{"text": "#include \"QuinticPolynomial.h\"\n\n#include \n#include \n\nusing namespace Eigen;\n\nQuinticPolynomial::QuinticPolynomial(double xs, double vxs, double axs,\n double xe, double vxe, double axe, double t):\n a0(xs), a1(vxs) {\n a2 = axs / 2.0;\n Matrix3d A;\n Vector3d B;\n A << pow(t, 3), pow(t, 4), pow(t, 5), 3 * pow(t, 2),\n 4 * pow(t, 3), 5 * pow(t, 4), 6 * t, 12 * pow(t, 2),\n 20 * pow(t, 3);\n B << xe - a0 - a1 * t - a2 * pow(t, 2), vxe - a1 - 2 * a2 * t,\n axe - 2 * a2;\n Matrix3d A_inv = A.inverse();\n Vector3d x = A_inv * B;\n a3 = x[0];\n a4 = x[1];\n a5 = x[2];\n}\n\ndouble QuinticPolynomial::calc_point(double t) {\n return a0 + a1 * t + a2 * pow(t, 2) + a3 * pow(t, 3) +\n a4 * pow(t, 4) + a5 * pow(t, 5);\n}\n\ndouble QuinticPolynomial::calc_first_derivative(double t) {\n return a1 + 2 * a2 * t + 3 * a3 * pow(t, 2) + 4 * a4 * pow(t, 3) +\n 5 * a5 * pow(t, 4);\n}\n\ndouble QuinticPolynomial::calc_second_derivative(double t) {\n return 2 * a2 + 6 * a3 * t + 12 * a4 * pow(t, 2) + 20 * a5 * pow(t, 3);\n}\n\ndouble QuinticPolynomial::calc_third_derivative(double t) {\n return 6 * a3 + 24 * a4 * t + 60 * a5 * pow(t, 2);\n}", "meta": {"hexsha": "5f5c16a5643727c6c3f4c4b5da1925a79ebba3cc", "size": 1189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Polynomials/QuinticPolynomial.cpp", "max_stars_repo_name": "shiveshkhaitan/frenet_optimal_trajectory_planner", "max_stars_repo_head_hexsha": "90443cf62c61f78ac0dde9507fc61e34a84136d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 66.0, "max_stars_repo_stars_event_min_datetime": "2020-04-11T16:44:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T04:56:27.000Z", "max_issues_repo_path": "src/Polynomials/QuinticPolynomial.cpp", "max_issues_repo_name": "shiveshkhaitan/frenet_optimal_trajectory_planner", "max_issues_repo_head_hexsha": "90443cf62c61f78ac0dde9507fc61e34a84136d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-05-16T11:57:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T07:54:17.000Z", "max_forks_repo_path": "src/Polynomials/QuinticPolynomial.cpp", "max_forks_repo_name": "shiveshkhaitan/frenet_optimal_trajectory_planner", "max_forks_repo_head_hexsha": "90443cf62c61f78ac0dde9507fc61e34a84136d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2020-04-28T06:02:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:13:23.000Z", "avg_line_length": 28.3095238095, "max_line_length": 75, "alphanum_fraction": 0.5449957948, "num_tokens": 482, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240194661945, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6999709165182003}} {"text": "/*\n DepSpawn: Data Dependent Spawn library\n Copyright (C) 2012-2021 Carlos H. Gonzalez, Basilio B. Fraguela. Universidade da Coruna\n \n Distributed under the MIT License. (See accompanying file LICENSE)\n*/\n\n///\n/// \\author Carlos H. Gonzalez \n/// \\author Basilio B. Fraguela \n///\n\n#include \n#include \n#include \n#include \n#include \"depspawn/depspawn.h\"\n#include \"common_io.cpp\" // This is only for serializing parallel prints\n\nusing namespace depspawn;\nusing namespace blitz;\n\ntypedef float Type;\n\n\n#define N 1000\n\nint CHUNKS;\n\nArray result(N,N), a(N, N), b(N,N);\n\n//template //IT DOES NOT WORK WITH A TEMPLATED FUNCTION; AND IT SHOULD!\nvoid mxm(Array& result, const Array& a, const Array& b)\n{\n const int nrows = result.rows();\n const int ncols = result.cols();\n const int kdim = a.cols();\n \n for(int i = 0; i < nrows; i++) {\n for(int j = 0; j < ncols; j++) {\n Type f = (Type)0;\n for(int k = 0; k < kdim; k++)\n\tf += a(i, k) * b(k, j);\n result(i, j) = f;\n }\n }\n}\n\nbool test()\n{\n const Type *ap = a.data();\n const Type *bp = b.data();\n const Type *rp = result.data();\n \n for (int i = 0; i < N; i++) {\n for(int j = 0; j < N; j++) {\n Type f = (Type)0;\n for(int k = 0; k < N; k++)\n\tf += ap[i * N + k] * bp[k * N + j];\n if (f != rp[i * N + j])\n\treturn false;\n }\n }\n \n return true;\n}\n\nint main(int argc, char **argv)\n{ int i, j;\n \n CHUNKS = (argc == 1) ? 4 : atoi(argv[1]);\n\n for (i = 0; i < N; i++) {\n for( j = 0; j < N; j++) {\n result(i, j) = (Type)0;\n a(i, j) = i + j;\n b(i, j) = (i > j) ? i - j : j - i;\n }\n }\n \n std::chrono::time_point t0 = std::chrono::high_resolution_clock::now();\n \n mxm(result, a, b);\n \n std::chrono::time_point t1 = std::chrono::high_resolution_clock::now();\n \n //matrix - vector product using CHUNKS chunks\n for(i = 0; i < N; i += N / CHUNKS) {\n int limi = (i + N / CHUNKS) >= N ? N : (i + N / CHUNKS);\n Range rows(i, limi - 1);\n for(j = 0; j < N; j += N / CHUNKS) {\n int limj = (j + N / CHUNKS) >= N ? N : (j + N / CHUNKS);\n Range cols(j, limj - 1);\n spawn(mxm, result(rows, cols), a(rows, Range::all()), b(Range::all(), cols));\n }\n }\n \n wait_for_all();\n \n std::chrono::time_point t2 = std::chrono::high_resolution_clock::now();\n \n double serial_time = std::chrono::duration(t1-t0).count();\n double parallel_time = std::chrono::duration(t2-t1).count();\n \n std::cout << \"Serial time: \" << serial_time << \"s. Parallel time: \" << parallel_time << \"s.\\n\";\n std::cout << \"Speedup (using \" << CHUNKS << \" X \" << CHUNKS << \" chunks): \" << (serial_time / parallel_time) << std::endl;\n \n const bool test_ok = test();\n \n std::cout << \"TEST \" << (test_ok ? \"SUCCESSFUL\" : \"UNSUCCESSFUL\") << std::endl;\n \n return !test_ok;\n}\n", "meta": {"hexsha": "084952f7fb27e25b0427a46bde611cc21c220e5f", "size": 3040, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/mxm.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "tests/mxm.cpp", "max_issues_repo_name": "fraguela/depspawn", "max_issues_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/mxm.cpp", "max_forks_repo_name": "fraguela/depspawn", "max_forks_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6666666667, "max_line_length": 125, "alphanum_fraction": 0.5723684211, "num_tokens": 993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.8056321843145404, "lm_q1q2_score": 0.6999548080591087}} {"text": "/*\n * Distributed under our modified Boost Software License.\n * Version 1.0 (see accompanying file LICENSE)\n */\n/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at https://mozilla.org/MPL/2.0/. */\n/**\n * @file Robot.cpp\n * @author Lydia Zoghbi, Ari Kupferberg, Ryan Bates\n * @copyright Copyright ARL 2019\n * @date 10/19/2019\n * @version 1.0\n *\n * @brief Definitions for Robot.hpp \n *\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"Robot.hpp\"\n#include \n#include \n#include \n#include \n\nRobot::Robot(const Point& startingPos): initialEEPosition(startingPos) {\n}\n\nboost::numeric::ublas::matrix Robot::computeATransform(std::vector dhRow) {\n\n // Initializing parameters\n double a = dhRow[0];\n double alpha = dhRow[1];\n double d = dhRow[2];\n double theta = dhRow[3];\n boost::numeric::ublas::matrix aTransform(4, 4);\n\n // Initialize 'A' matrix variables\n std::vector aTerms = {cos(theta), -sin(theta)*cos(alpha),\n sin(theta)*sin(alpha), a*cos(theta), sin(theta), cos(theta)*cos(alpha),\n -cos(theta)*sin(alpha), a*sin(theta), 0, sin(alpha), cos(alpha), d, 0,\n 0, 0, 1};\n\n int i = 0;\n int j = 0;\n\n // Populate the A transformation matrix\n for (auto& term: aTerms) {\n aTransform(i, j) = term;\n j++;\n if (j == 4) {\n i++;\n j = 0;\n }\n }\n return aTransform;\n}\n\nstd::vector Robot::computeFk(std::vector jointAngles) {\n int i = 0;\n for (auto& element : jointAngles) {\n dhParams[i][3] = element + dhParams[i][3];\n i++;\n }\n\n // Initialize Matrices\n boost::numeric::ublas::matrix aTransform(4, 4);\n boost::numeric::ublas::matrix tTransform(4, 4);\n boost::numeric::ublas::matrix previousTransform(4, 4);\n boost::numeric::ublas::identity_matrix identity(4, 4);\n previousTransform = identity;\n\n // Loop through A matrices to get T matrices\n std::vector> tTransforms;\n for (auto& row : dhParams) {\n aTransform = computeATransform(row);\n tTransform = prod(previousTransform, aTransform);\n previousTransform = tTransform;\n tTransforms.push_back(tTransform);\n }\n\n // Pull points from T matrices\n Point initialPoint(0.0, 0.0, 0.0);\n std::vector points = {initialPoint};\n for (auto& p : tTransforms) {\n Point point(p(0, 3), p(1, 3), p(2, 3));\n points.push_back(point);\n }\n return points;\n}\n\nboost::numeric::ublas::vector Robot::crossProduct(boost::numeric::ublas::vector vector1, boost::numeric::ublas::vector vector2) {\n\n // Cross product function because there was no easy way to get it done through Boost\n boost::numeric::ublas::vector resultVector(3);\n resultVector(0) = vector1(1)*vector2(2)-vector1(2)*vector2(1);\n resultVector(1) = vector1(2)*vector2(0)-vector1(0)*vector2(2);\n resultVector(2) = vector1(0)*vector2(1)-vector1(1)*vector2(0);\n return resultVector;\n}\n\nstd::vector> Robot::computeTransformationMatrices(std::vector jointAngles) {\n\n int i = 0;\n for (auto& element : jointAngles) {\n dhParams[i][3] = element + dhParams[i][3];\n i++;\n }\n\n // Initialize Matrices\n boost::numeric::ublas::matrix aTransform(4, 4);\n boost::numeric::ublas::matrix tTransform(4, 4);\n boost::numeric::ublas::matrix previousTransform(4, 4);\n boost::numeric::ublas::identity_matrix identity(4, 4);\n previousTransform = identity;\n\n // Loop through A matrices to get T matrices\n std::vector> tTransforms;\n tTransforms.push_back(identity);\n for (auto& row : dhParams) {\n aTransform = computeATransform(row);\n tTransform = prod(previousTransform, aTransform);\n previousTransform = tTransform;\n tTransforms.push_back(tTransform);\n }\n return tTransforms;\n}\n\nboost::numeric::ublas::matrix Robot::computeJacobian(RobotPosition robotPosition, std::vector> tTransforms) {\n\n // Get all the joint positions in Point\n std::vector joints = robotPosition.getJoints();\n boost::numeric::ublas::vector zAxes(3);\n zAxes(0) = 0;\n zAxes(1) = 0;\n zAxes(2) = 1;\n\n // Initialize some parameteres\n boost::numeric::ublas::matrix jacobian(6,6);\n std::vector iterator = {0, 1, 2};\n boost::numeric::ublas::matrix trans(3,3);\n\n int index = 0;\n Point robotEEPosition = joints[6];\n joints.pop_back();\n\n // Loop through the joints to compute the Jacobian\n for (auto& joint : joints) {\n Point robotJointPosition = joint;\n double differenceInX = robotEEPosition.getX() - robotJointPosition.getX();\n double differenceInY = robotEEPosition.getY() - robotJointPosition.getY();\n double differenceInZ = robotEEPosition.getZ() - robotJointPosition.getZ();\n boost::numeric::ublas::vector differenceVector(3);\n differenceVector(0) = differenceInX;\n differenceVector(1) = differenceInY;\n differenceVector(2) = differenceInZ;\n\n trans(0,0) = tTransforms[index](0,0); trans(0,1) = tTransforms[index](0,1);\n trans(0,2) = tTransforms[index](0,2); trans(1,0) = tTransforms[index](1,0);\n trans(1,1) = tTransforms[index](1,1); trans(1,2) = tTransforms[index](1,2);\n trans(2,0) = tTransforms[index](2,0); trans(2,1) = tTransforms[index](2,1);\n trans(2,2) = tTransforms[index](2,2);\n boost::numeric::ublas::vector transformedZAxes = prod(trans,zAxes);\n boost::numeric::ublas::vector crossProductVector = crossProduct(transformedZAxes, differenceVector);\n\n // Populate the Jacobian's columns iteratively\n for (auto& element : iterator) {\n jacobian(element, index) = crossProductVector(element);\n jacobian(element+3, index) = transformedZAxes(element);\n }\n index++;\n }\n return jacobian;\n}\n\n// https://gist.github.com/javidcf/25066cf85e71105d57b6 used as reference\nboost::numeric::ublas::matrix Robot::penroseInverseMatrix(boost::numeric::ublas::matrix mat) {\n boost::numeric::ublas::matrix result(mat.size1(), mat.size2());\n\n Eigen::MatrixXd convertedInput(mat.size1(), mat.size2());\n\n // Convert from boost matrix to eigen matrix\n // we permit ourselves to use int for loops\n // because the indexing is useful for referencing between datatypes\n for (unsigned int rowIndex = 0; rowIndex < mat.size1(); rowIndex++) {\n for (unsigned int columnIndex = 0; columnIndex < mat.size2(); columnIndex++) {\n convertedInput(rowIndex, columnIndex) = mat(rowIndex, columnIndex);\n }\n }\n\n // Now for the actual math\n Eigen::JacobiSVD svd(convertedInput, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n // We can safely use adjoint instead of transpose because this is a real matrix\n Eigen::MatrixXd sigma = svd.singularValues().asDiagonal();\n\n double tolerance = 0.001;\n // Take the reciprocal of each element, if possible,\n // as per https://en.wikipedia.org/wiki/Moore%E2%80%93Penrose_inverse\n // We only hit the diagonal, since this is a diagonal matrix.\n // We allow this loop type because the indexing is useful.\n for (int i = 0; i < sigma.rows(); i++) {\n if (fabs(sigma(i, i)) < tolerance) {\n sigma(i, i) = 0;\n } else {\n sigma(i, i) = 1 / sigma(i, i);\n }\n }\n\n Eigen::MatrixXd sigmaTransposed = sigma.transpose();\n Eigen::MatrixXd eigenResult = svd.matrixV() * sigmaTransposed * svd.matrixU().adjoint();\n\n // Convert eigen matrix to boost matrix\n // We permit ourselves to use int for loops\n // because the indexing is useful for referencing between datatypes\n for (unsigned int rowIndex = 0; rowIndex < mat.size1(); rowIndex++) {\n for (unsigned int columnIndex = 0; columnIndex < mat.size2(); columnIndex++) {\n result(rowIndex, columnIndex) = static_cast(eigenResult(rowIndex, columnIndex));\n }\n }\n return result;\n}\n\nstd::vector Robot::computeIK(Point targetPoint, Environment environment) {\n\n // Initialize the angles vector theta\n std::vector allRobotPositions;\n boost::numeric::ublas::vector velocity(6);\n boost::numeric::ublas::vector theta(6);\n theta(0) = initialJointAngles[0]; theta(1) = initialJointAngles[1]; theta(2) = initialJointAngles[2];\n theta(3) = initialJointAngles[3]; theta(4) = initialJointAngles[4]; theta(5) = initialJointAngles[5];\n\n std::vector jointAngles = initialJointAngles;\n\n std::vector robotJointPosition = computeFk(jointAngles);\n Point eePosition = robotJointPosition.back();\n PathPlanner pathPlanner;\n std::vector getPath = pathPlanner.findStraightPath(eePosition, targetPoint);\n\n double eeX; double eeY; double eeZ;\n double targetX; double targetY; double targetZ;\n double norm;\n int counter = 0;\n\n for(auto& pathPoints:getPath) {\n\n // Extact each point from a discretized path to find joint angles\n robotJointPosition = computeFk(jointAngles);\n eePosition = robotJointPosition.back();\n eeX = eePosition.getX(); eeY = eePosition.getY(); eeZ = eePosition.getZ();\n targetX = pathPoints.getX(); targetY = pathPoints.getY(); targetZ = pathPoints.getZ();\n velocity(0) = targetX - eeX; velocity(1) = targetY - eeY; velocity(2) = targetZ - eeZ;\n velocity(3) = 0.0; velocity(4) = 0.0; velocity(5) = 0.0;\n norm = norm_2(velocity);\n counter++;\n\n // Loop through each point to compute the inverse kinematics using the pseudo-inverse Jacobian\n while (norm > 0.01) {\n\n robotJointPosition = computeFk(jointAngles);\n RobotPosition robotPosition(robotJointPosition, jointAngles);\n std::vector> tTrans = computeTransformationMatrices(jointAngles);\n boost::numeric::ublas::matrix jacobian = computeJacobian(robotPosition, tTrans);\n boost::numeric::ublas::matrix pseudoInverse = penroseInverseMatrix(jacobian);\n Point eePosition = robotJointPosition.back();\n\n eeX = eePosition.getX(); eeY = eePosition.getY(); eeZ = eePosition.getZ();\n targetX = pathPoints.getX(); targetY = pathPoints.getY(); targetZ = pathPoints.getZ();\n velocity(0) = targetX - eeX; velocity(1) = targetY - eeY; velocity(2) = targetZ - eeZ;\n velocity(3) = 0.0; velocity(4) = 0.0; velocity(5) = 0.0;\n norm = norm_2(velocity);\n\n boost::numeric::ublas::vector deltaTheta = prod(pseudoInverse, velocity);\n theta = theta + 0.0000001*deltaTheta;\n jointAngles[0] = theta(0); jointAngles[1] = theta(1); jointAngles[2] = theta(2);\n jointAngles[3] = theta(3); jointAngles[4] = theta(4); jointAngles[5] = theta(5);\n\n }\n\n RobotPosition robotPosition(robotJointPosition, jointAngles);\n\n // Check for any collision\n if (robotPosition.checkCollision(environment)) {\n allRobotPositions.push_back(robotPosition);\n } else {break;}\n }\n\nreturn allRobotPositions;\n\n}\n\n", "meta": {"hexsha": "656585756f8b85b34f8ec3143fb5432f52d69d36", "size": 11176, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/Robot.cpp", "max_stars_repo_name": "akupferb/808xmidterm", "max_stars_repo_head_hexsha": "c8e3aff6165948d0b4cde48e685b65f516cef6a4", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/Robot.cpp", "max_issues_repo_name": "akupferb/808xmidterm", "max_issues_repo_head_hexsha": "c8e3aff6165948d0b4cde48e685b65f516cef6a4", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/Robot.cpp", "max_forks_repo_name": "akupferb/808xmidterm", "max_forks_repo_head_hexsha": "c8e3aff6165948d0b4cde48e685b65f516cef6a4", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-13T22:46:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-13T22:46:15.000Z", "avg_line_length": 37.6296296296, "max_line_length": 155, "alphanum_fraction": 0.6913922691, "num_tokens": 3129, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871157, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6999434759866942}} {"text": "//\n// seqols.cpp\n//\n//\n// Created by Jose V. Alcala Burgos on 7/30/13.\n// Copyright [2013] Jose V. Alcala Burgos\n//\n//\n\n#include \"base/seqols.h\"\n\n// System\n#include \n\n#include \n#include \n\nusing namespace arma;\nusing namespace std;\n\nvoid SeqOls::useObservations(mat X, mat Y // A n x p matrix with n responses,\n // one response per row\n ) {\n if (X.size() != Y.size()) {\n cout << \" The predictor/response matrices should have the same size\";\n cout << endl;\n }\n\n n = X.n_rows;\n p = X.n_cols;\n X = join_rows(X, ones(n, 1));\n P = inv((X.t()) * X);\n B = P * (X.t() * Y);\n G = inv(B.rows(0, p - 1));\n}\n\nvoid SeqOls::addObservation(mat x,\n mat y\n ) {\n if (x.size() != y.size()) {\n cout << \" The predictor/response matrices should have the same size\";\n cout << endl;\n }\n\n if (x.n_cols != p) {\n cout << \" The new observation should have \" << p << \"columns\" << endl;\n }\n\n if (x.n_rows != 1) {\n cout << \" Add only ONE observation. \" << endl;\n }\n\n n = n + 1;\n x = join_rows(x, ones(1, 1));\n double alpha;\n alpha = as_scalar((1.0 / (1.0 + x * P * x.t())));\n mat u = P * x.t();\n u = u.rows(0, p - 1);\n u = alpha * u;\n mat v = y - x * B;\n v = v.t();\n B = B + alpha * (P * x.t() * (y - x * B));\n P = P - alpha * (P * x.t() * x * P.t());\n double beta;\n beta = as_scalar(1.0 / (1.0 + v.t() * G * u));\n G = G - beta * (G * u * v.t() * G);\n}\n\n// Prints the Ols estimator\nvoid SeqOls::printEstimator() {\n B.print(\" B_estimator : \");\n G.print(\"G_estimator (Hessian inverse):\");\n}\n\n// Tests that the inverse of the first p rows of B is equal to G.\nvoid SeqOls::testInverse() {\n double tolerance = 0.00000001;\n mat error = (B.rows(0, p - 1) * G - eye(p, p));\n if (norm(error, 2) < tolerance) {\n cout << \"The inverse of the estimator is correct.\" << endl;\n } else {\n cout << \"The inverse of the estimator is incorrect.\" << endl;\n }\n}\n", "meta": {"hexsha": "59b9b59a9a1b1c976ed32ee2158753d2b897ec22", "size": 2129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/seqols.cpp", "max_stars_repo_name": "vidalalcala/sopt-ols", "max_stars_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/seqols.cpp", "max_issues_repo_name": "vidalalcala/sopt-ols", "max_issues_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/seqols.cpp", "max_forks_repo_name": "vidalalcala/sopt-ols", "max_forks_repo_head_hexsha": "ffc41ccdd0c523c39eebbada894c83533f92338d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0470588235, "max_line_length": 78, "alphanum_fraction": 0.4922498826, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.7931059462938815, "lm_q1q2_score": 0.6998587782514756}} {"text": "\r\n#include \r\n\r\n#include \r\n\r\nNTL_START_IMPL\r\n\r\n\r\n// This implements a variation of an algorithm in\r\n// [P. Domich, R. Kannan and L. Trotter, Math. Oper. Research 12:50-59, 1987].\r\n// I started with the description in Henri Cohen's book, but had to modify\r\n// that because Cohen does not actually keep the numbers reduced modulo\r\n// the determinant, which leads to larger than necessary numbers.\r\n// This modifiaction was put in place in v3.9b.\r\n\r\nstatic\r\nvoid EuclUpdate(vec_ZZ& u, vec_ZZ& v, \r\n const ZZ& a, const ZZ& b, const ZZ& c, const ZZ& d,\r\n const ZZ& M)\r\n\r\n{\r\n long m = u.length(); \r\n long i;\r\n\r\n ZZ M1;\r\n RightShift(M1, M, 1);\r\n\r\n ZZ t1, t2, t3;\r\n\r\n for (i = 1; i <= m; i++) {\r\n mul(t1, u(i), a);\r\n mul(t2, v(i), b);\r\n add(t1, t1, t2);\r\n rem(t1, t1, M);\r\n if (t1 > M1)\r\n sub(t1, t1, M);\r\n\r\n t3 = t1;\r\n\r\n mul(t1, u(i), c);\r\n mul(t2, v(i), d);\r\n add(t1, t1, t2);\r\n rem(t1, t1, M);\r\n if (t1 > M1)\r\n sub(t1, t1, M);\r\n\r\n u(i) = t3;\r\n v(i) = t1;\r\n }\r\n}\r\n\r\n\r\nstatic\r\nvoid FixDiag(vec_ZZ& u, const ZZ& a, const vec_ZZ& v, const ZZ& M, long m)\r\n{\r\n long i;\r\n ZZ t1;\r\n\r\n for (i = 1; i <= m; i++) {\r\n mul(t1, a, v(i));\r\n rem(u(i), t1, M);\r\n }\r\n}\r\n\r\n\r\nstatic\r\nvoid ReduceW(vec_ZZ& u, const ZZ& a, const vec_ZZ& v, const ZZ& M, long m)\r\n{\r\n long i;\r\n ZZ t1, t2;\r\n\r\n for (i = 1; i <= m; i++) {\r\n mul(t1, a, v(i));\r\n sub(t2, u(i), t1);\r\n rem(u(i), t2, M);\r\n }\r\n}\r\n \r\n\r\n\r\nvoid HNF(mat_ZZ& W, const mat_ZZ& A_in, const ZZ& D_in)\r\n{\r\n mat_ZZ A = A_in;\r\n\r\n long n = A.NumRows();\r\n long m = A.NumCols();\r\n\r\n ZZ D = D_in;\r\n if (D < 0)\r\n negate(D, D);\r\n\r\n if (n == 0 || m == 0 || D == 0)\r\n LogicError(\"HNF: bad input\");\r\n\r\n W.SetDims(m, m);\r\n clear(W);\r\n\r\n long i, j, k;\r\n ZZ d, u, v, c1, c2;\r\n\r\n k = n;\r\n\r\n for (i = m; i >= 1; i--) {\r\n for (j = k-1; j >= 1; j--) {\r\n if (A(j, i) != 0) {\r\n XGCD(d, u, v, A(k, i), A(j, i));\r\n div(c1, A(k, i), d);\r\n div(c2, A(j, i), d);\r\n negate(c2, c2);\r\n EuclUpdate(A(j), A(k), c1, c2, v, u, D);\r\n }\r\n }\r\n\r\n XGCD(d, u, v, A(k, i), D);\r\n FixDiag(W(i), u, A(k), D, i);\r\n if (W(i, i) == 0) W(i, i) = D;\r\n\r\n for (j = i+1; j <= m; j++) {\r\n div(c1, W(j, i), W(i, i));\r\n ReduceW(W(j), c1, W(i), D, i);\r\n }\r\n\r\n div(D, D, d);\r\n k--;\r\n }\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "0c3affdfd256b52dfaec4dfa46f1716236140252", "size": 2527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/HNF.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WinNTL-8_1_2/src/HNF.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WinNTL-8_1_2/src/HNF.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5891472868, "max_line_length": 79, "alphanum_fraction": 0.4309457855, "num_tokens": 927, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103777, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6997915034317642}} {"text": "#include \n#include \n#include \"Sundials.h\"\n#include \"Mooring.h\"\n\n\nnamespace Upp {\n\n\nMooringStatus Catenary(double rho_m, double rho_m3, double rho_water, double moorlen, double BL,\n\t\t\t double xanchorvessel, double zanchor, double zvessel, \n\t\t\t double &Fhanchorvessel, double &Fvanchor, double &Fvvessel, \n\t\t\t double &xonfloor, Vector &x, Vector &z, int num) {\n\tif (zanchor < 0 && zvessel < 0)\n\t\tthrow Exc(\"Catenary. Anchor and vessel z positions have to be positive\");\n\tif (xanchorvessel < 0)\n\t\tthrow Exc(\"Catenary. x distance between anchor and vessel has to be positive\");\n\t\n\tconst double g = 9.81; \t\t\n\n\tdouble lmb = rho_m*(rho_m3 - rho_water)/rho_m3;\n\t\n \tBuffer udata(1, 1);\t\n\tSolveNonLinearEquationsSun(udata, 1, [&](const double y[], double residuals[])->bool {\n\t\tdouble Blimit = y[0];\n\t\tresiduals[0] = sqrt(zanchor*(zanchor + 2*Blimit)) + sqrt(zvessel*(zvessel + 2*Blimit)) - moorlen; \n\t\treturn true;\n\t});\n\tdouble Blimit = udata[0];\n\n double xanchorvessel_limit = Blimit*(acosh(zanchor/Blimit + 1) + acosh(zvessel/Blimit + 1));\n\t\n\tdouble delta = xanchorvessel/(num - 1);\n\tx.SetCount(num);\n\tz.SetCount(num);\n\t\n\tMooringStatus status;\n\t\n\tif (xanchorvessel < moorlen - zanchor - zvessel) {\t\t\t\t\n\t\tstatus = LOOSE_ON_FLOOR;\n\t\t\n\t\tif (!IsNull(rho_m)) {\n\t Fhanchorvessel = 0;\n\t Fvanchor = lmb*g*zanchor;\n\t Fvvessel = lmb*g*zvessel;\n\t\t} else\n\t\t\tFhanchorvessel = Fvanchor = Fvvessel = Null;\n\t\t\n \txonfloor = xanchorvessel;\n \t\n\t\tx.SetCount(4);\n\t\tz.SetCount(4);\n\t\tx[0] = 0;\t\t\t\tz[0] = zanchor;\n\t\tx[1] = 0;\t\t\t\tz[1] = 0;\n\t\tx[2] = xanchorvessel;\tz[2] = 0;\n\t\tx[3] = xanchorvessel;\tz[3] = zvessel;\n\t} else if (xanchorvessel < xanchorvessel_limit) {\n status = CATENARY_ON_FLOOR;\n\t\n\t \tBuffer consdata(1, 2);\t\t// B > 0\n\t \t\n\t \tBuffer udata(1, Blimit/2.);\t\n\t\tSolveNonLinearEquationsSun(udata, 1, [&](const double y[], double residuals[])->bool {\n\t\t\tdouble B = y[0];\n\t\t\tresiduals[0] = xanchorvessel - B*acosh(zanchor/B + 1) - B*acosh(zvessel/B + 1) + sqrt(zanchor*(zanchor + 2*B)) + sqrt(zvessel*(zvessel + 2*B)) - moorlen; \n\t\t\treturn true;\n\t\t}, consdata);\t\t\n\t\tdouble B = udata[0];\n\n double xcatanchor = B*acosh(zanchor/B + 1);\n double xcatvessel = B*acosh(zvessel/B + 1);\n\t\txonfloor = xanchorvessel - xcatanchor - xcatvessel;\n\n\t\tif (!IsNull(rho_m)) {\n\t Fhanchorvessel = lmb*g*B; \n\t Fvanchor = Fhanchorvessel*sinh(xcatanchor/B); \n\t Fvvessel = Fhanchorvessel*sinh(xcatvessel/B); \n\t\t} else\n\t\t\tFhanchorvessel = Fvanchor = Fvvessel = Null;\n \n for (int i = 0; i < x.size(); ++i) {\n x[i] = i*delta;\n if (x[i] < xcatanchor)\n \t\tz[i] = B*(cosh((xcatanchor - x[i])/B) - 1);\n else if (x[i] > (xanchorvessel - xcatvessel))\n z[i] = B*(cosh((max(0., x[i] - (xanchorvessel - xcatvessel)))/B) - 1);\n else\n z[i] = 0;\n }\n } else if (xanchorvessel < sqrt(sqr(moorlen) - sqr(zvessel - zanchor))) {\n status = CATENARY;\n \n\t\tint neq = 2;\n double deltaz = zvessel - zanchor;\n\n\t \tBuffer udata(neq);\n\t \tBuffer consdata(2);\n\t \tconsdata[0] = 2;\t\t\t// B > 0\n\t \tconsdata[1] = 0;\n\t \t\n\t \tdouble x1_0, B_0, x1, B;\n\t \tbool done = false;\n\t \tfor (x1_0 = 0; x1_0 < abs(xanchorvessel) && !done; x1_0 += abs(xanchorvessel)/4) {\n\t \t\tfor (B_0 = abs(Blimit); B_0 < 10*B_0 && !done; B_0 += 5*abs(Blimit)/4) {\t\t\n\t\t \t\tudata[0] = B_0;\t\n\t\t \t\tudata[1] = x1_0;\n\t\t\t\tSolveNonLinearEquationsSun(udata, neq, [&](const double y[], double residuals[])->bool {\n\t\t\t\t\tdouble B = y[0];\n\t\t\t\t\tdouble x1 = y[1];\n\t\t\t\t\t\n\t\t\t\t\tresiduals[0] = B*(sinh((x1 + xanchorvessel)/B) - sinh(x1/B)) - moorlen;\n\t\t\t\t\tresiduals[1] = B*(cosh((x1 + xanchorvessel)/B) - cosh(x1/B)) - deltaz;\n\t\t\t\t\t\n\t\t\t\t\treturn true;\n\t\t\t\t}, consdata);\n\t\t\t\tB = udata[0];\n\t\t\t\tx1 = udata[1];\t\t\n\t\t\t\tif (abs((x1 + xanchorvessel)/B) < 3)\n\t\t\t\t\tdone = true;\n\t \t\t}\n\t \t}\n\t \tif (!done) \n\t\t\tthrow Exc(\"Catenary. Solving problem\");\n\n\t\tif (!IsNull(rho_m)) {\n\t Fhanchorvessel = lmb*g*abs(B); \n\t Fvanchor = -Fhanchorvessel*sinh(x1/B); \t\t\t\n\t Fvvessel = Fhanchorvessel*sinh((x1 + xanchorvessel)/B); \t\n\t\t} else\n\t\t\tFhanchorvessel = Fvanchor = Fvvessel = Null;\n\t\t\n xonfloor = 0;\n \n for (int i = 0; i < x.size(); ++i) {\n x[i] = i*delta;\n \tz[i] = B*(cosh((x[i] + x1)/B) - 1) - B*(cosh(x1/B) - 1) + zanchor;\n }\n } else {\n\t\tstatus = BROKEN;\n\t\tif (!IsNull(rho_m)) \n\t\t\tFhanchorvessel = Fvanchor = Fvvessel = xonfloor = 0;\n\t\telse\n\t\t\tFhanchorvessel = Fvanchor = Fvvessel = xonfloor = Null;\n\t\t\n\t\tx.Clear();\n\t\tz.Clear();\n }\n \n\tif (!IsNull(BL)) \n \tif (max(sqrt(sqr(Fhanchorvessel) + sqr(Fvanchor)), sqrt(sqr(Fhanchorvessel) + sqr(Fvvessel))) >= BL)\n \tstatus = BL_EXCEDEED;\n \n\treturn status;\n}\n\nMooringStatus Catenary(double rho_m, double rho_m3, double rho_water, double moorlen, double BL,\n\t\t\t double xanchorvessel, double zanchor, double zvessel, \n\t\t\t double &Fhanchorvessel, double &Fvanchor, double &Fvvessel, double &xonfloor) {\n\tVector x, z;\n\t\t\t\t \n\treturn Catenary(rho_m, rho_m3, rho_water, moorlen, BL, xanchorvessel, \n\t\t\tzanchor, zvessel, Fhanchorvessel, Fvanchor, Fvvessel, xonfloor, x, z, 0);\t\t\t\t \n}\n\nMooringStatus Catenary(double moorlen, double xanchorvessel, double zanchor, double zvessel, double &xonfloor,\n\t\t\t\tVector &x, Vector &z, int num) {\n\tdouble rho_m = Null, rho_m3 = Null, rho_water = Null, BL = Null, Fhanchorvessel, Fvanchor, Fvvessel;\t\t \n\n\treturn Catenary(rho_m, rho_m3, rho_water, moorlen, BL, xanchorvessel, \n\t\t\tzanchor, zvessel, Fhanchorvessel, Fvanchor, Fvvessel, xonfloor, x, z, num);\n}\n\nMooringStatus Catenary(double moorlen, double xanchorvessel, double zanchor, double zvessel, double &xonfloor) {\n\tdouble rho_m = Null, rho_m3 = Null, rho_water = Null, BL = Null, Fhanchorvessel, Fvanchor, Fvvessel;\t\t \n\tVector x, z;\n\treturn Catenary(rho_m, rho_m3, rho_water, moorlen, BL, xanchorvessel, \n\t\t\tzanchor, zvessel, Fhanchorvessel, Fvanchor, Fvvessel, xonfloor, x, z, 0);\n}\n\n\nbool CatenaryGetLen0(double xonfloor, double xanchorvessel, double zanchor, double zvessel, \n\t\t\t\t\tdouble &moorlen) {\n\tif (xonfloor >= xanchorvessel) {\n\t\tmoorlen = xanchorvessel + 2*(xonfloor - xanchorvessel) + zanchor + zvessel;\n\t\treturn false;\n\t} \n\t\n\tBuffer consdata(2, 2);\t\t// B > 0 && moorlen > 0\n \tBuffer udata(2);\t\n \tudata[0] = 1;\n \tudata[1] = sqrt(sqr(xanchorvessel) + sqr(zanchor - zvessel));\n\tSolveNonLinearEquationsSun(udata, 2, [&](const double y[], double residuals[])->bool {\n\t\tdouble B = y[0];\n\t\tdouble moorlen = y[1];\n\t\tresiduals[0] = xanchorvessel - B*acosh(zanchor/B + 1) - B*acosh(zvessel/B + 1) + sqrt(zanchor*(zanchor + 2*B)) + sqrt(zvessel*(zvessel + 2*B)) - moorlen; \n \tdouble xcatanchor = B*acosh(zanchor/B + 1);\n \tdouble xcatvessel = B*acosh(zvessel/B + 1);\n\t\tresiduals[1] = xanchorvessel - xcatanchor - xcatvessel - xonfloor;\n\t\treturn true;\n\t}, consdata);\t\t\n\t//double B = udata[0];\n\tmoorlen = udata[1];\n\n\treturn true;\n\t\t\t\t\t}\n\nMooringStatus CatenaryGetLen(double xonfloor, double xanchorvessel, double zanchor, double zvessel, \n\t\t\tdouble &moorlen) {\n\tif (!CatenaryGetLen0(xonfloor, xanchorvessel, zanchor, zvessel, moorlen))\n\t\treturn LOOSE_ON_FLOOR;\n\t\n\treturn Catenary(moorlen, xanchorvessel, zanchor, zvessel, xonfloor);\n}\n\nMooringStatus CatenaryGetLen(double rho_m, double rho_m3, double rho_water, double xonfloor, \n\t\t\tdouble BL, double xanchorvessel, double zanchor, double zvessel, \n\t\t\tdouble &Fhanchorvessel, double &Fvanchor, double &Fvvessel, double &moorlen) {\n\tif (!CatenaryGetLen0(xonfloor, xanchorvessel, zanchor, zvessel, moorlen))\n\t\treturn LOOSE_ON_FLOOR;\n\t\n\treturn Catenary(rho_m, rho_m3, rho_water, moorlen, BL, xanchorvessel, zanchor, zvessel, \n\t\t\t\t\tFhanchorvessel, Fvanchor, Fvvessel, xonfloor);\n}\n\nconst char *MooringStatusStr(MooringStatus status) {\n\tconst char *str[5] = {\"loose on floor\", \"catenary on floor\", \"catenary\", \n\t\t\t\t\t\t \"line length exceeded\", \"break load exdeeded\"};\n\tASSERT(int(status) < 5);\n\treturn str[int(status)];\n}\n\nbool IsOK(MooringStatus status) { \n\treturn status < BROKEN;\n}\n\n}", "meta": {"hexsha": "ee38705258508f5706e34b3dae762f214a184cdc", "size": 8178, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STEM4U/Mooring.cpp", "max_stars_repo_name": "XOULID/Anboto", "max_stars_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "STEM4U/Mooring.cpp", "max_issues_repo_name": "XOULID/Anboto", "max_issues_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "STEM4U/Mooring.cpp", "max_forks_repo_name": "XOULID/Anboto", "max_forks_repo_head_hexsha": "2743b066f23bf2db9cc062d3adedfd044bc69ec1", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6525423729, "max_line_length": 157, "alphanum_fraction": 0.6312056738, "num_tokens": 2904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.699791490279279}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef CGAL::Simple_cartesian K;\ntypedef K::Point_3 Point_3;\n\ntypedef std::array Facet;\n\nnamespace std {\n std::ostream&\n operator<<(std::ostream& os, const Facet& f)\n {\n os << \"3 \" << f[0] << \" \" << f[1] << \" \" << f[2];\n return os;\n }\n}\n\nstruct Perimeter {\n\n double bound;\n\n Perimeter(double bound)\n : bound(bound)\n {}\n\n template \n double operator() (const AdvancingFront& adv, Cell_handle& c,\n const int& index) const\n {\n // bound == 0 is better than bound < infinity\n // as it avoids the distance computations\n if(bound == 0){\n return adv.smallest_radius_delaunay_sphere (c, index);\n }\n\n // If perimeter > bound, return infinity so that facet is not used\n double d = 0;\n d = sqrt(squared_distance(c->vertex((index+1)%4)->point(),\n c->vertex((index+2)%4)->point()));\n if(d>bound) return adv.infinity();\n d += sqrt(squared_distance(c->vertex((index+2)%4)->point(),\n c->vertex((index+3)%4)->point()));\n if(d>bound) return adv.infinity();\n d += sqrt(squared_distance(c->vertex((index+1)%4)->point(),\n c->vertex((index+3)%4)->point()));\n if(d>bound) return adv.infinity();\n\n // Otherwise, return usual priority value: smallest radius of\n // delaunay sphere\n return adv.smallest_radius_delaunay_sphere (c, index);\n }\n};\n\nint main(int argc, char* argv[])\n{\n std::ifstream in((argc>1)?argv[1]:\"data/half.xyz\");\n double per = (argc>2)?boost::lexical_cast(argv[2]):0;\n std::vector points;\n std::vector facets;\n\n std::copy(std::istream_iterator(in),\n std::istream_iterator(),\n std::back_inserter(points));\n\n Perimeter perimeter(per);\n CGAL::advancing_front_surface_reconstruction(points.begin(),\n points.end(),\n std::back_inserter(facets),\n perimeter);\n\n std::cout << \"OFF\\n\" << points.size() << \" \" << facets.size() << \" 0\\n\";\n std::copy(points.begin(),\n points.end(),\n std::ostream_iterator(std::cout, \"\\n\"));\n std::copy(facets.begin(),\n facets.end(),\n std::ostream_iterator(std::cout, \"\\n\"));\n\n return 0;\n}\n", "meta": {"hexsha": "f3b259d80e47d61b8b315d02a5236ab6a8737085", "size": 2637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/Advancing_front_surface_reconstruction/reconstruction_fct.cpp", "max_stars_repo_name": "josuehfa/DAASystem", "max_stars_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T01:13:02.000Z", "max_issues_repo_path": "CoreSystem/lib/CGAL/examples/Advancing_front_surface_reconstruction/reconstruction_fct.cpp", "max_issues_repo_name": "josuehfa/DAASystem", "max_issues_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoreSystem/lib/CGAL/examples/Advancing_front_surface_reconstruction/reconstruction_fct.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 30.6627906977, "max_line_length": 74, "alphanum_fraction": 0.5798255593, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6996766868909073}} {"text": "#ifndef CANNON_MATH_FUNC_ROSENBROCK_H\n#define CANNON_MATH_FUNC_ROSENBROCK_H \n\n/*!\n * \\file cannon/math/func/rosenbrock.hpp\n * \\brief File containing Rosenbrock function and gradient definitions.\n */\n\n#include \n\nusing namespace Eigen;\n\nnamespace cannon {\n namespace math {\n\n /*!\n * \\brief Compute the value of the Rosenbrock function at the input point.\n * See https://en.wikipedia.org/wiki/Rosenbrock_function\n *\n * \\param x The point at which to evaluate the Rosenbrock function.\n *\n * \\returns The value of the Rosenbrock function at the input point.\n */\n double rosenbrock(const Vector2d& x);\n\n /*!\n * \\brief Compute the gradient of the Rosenbrock function at the input point.\n *\n * \\param x The point at which to compute the gradient.\n *\n * \\returns Rosenbrock function gradient at the input point.\n */\n Vector2d rosenbrock_grad(const Vector2d& x);\n\n } // namespace math\n} // namespace cannon\n\n\n#endif /* ifndef CANNON_MATH_FUNC_ROSENBROCK_H */\n", "meta": {"hexsha": "0ba09451e33248b0ef335be5cd749ffac82415f7", "size": 1028, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/math/func/rosenbrock.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/math/func/rosenbrock.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/math/func/rosenbrock.hpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7, "max_line_length": 81, "alphanum_fraction": 0.6974708171, "num_tokens": 255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951104066293, "lm_q2_score": 0.8289388040954683, "lm_q1q2_score": 0.6995374036024845}} {"text": "#include \"problemes.h\"\n#include \"numerique.h\"\n#include \"puissance.h\"\n\n#include \n\nENREGISTRER_PROBLEME(162, \"Hexadecimal numbers\") {\n // In the hexadecimal number system numbers are represented using 16 different digits:\n //\n // 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F\n //\n // The hexadecimal number AF when written in the decimal number system equals 10x16+15=175.\n //\n // In the 3-digit hexadecimal numbers 10A, 1A0, A10, and A01 the digits 0,1 and A are all present.\n // Like numbers written in base ten we write hexadecimal numbers without leading zeroes.\n //\n // How many hexadecimal numbers containing at most sixteen hexadecimal digits exist with all of the digits 0,1, and\n // A present at least once?\n // Give your answer as a hexadecimal number.\n //\n // (A,B,C,D,E and F in upper case, without any leading or trailing code that marks the number as hexadecimal and\n // without leading zeroes , e.g. 1A3F and not: 1a3f and not 0x1a3f and not $1A3F and not #1A3F and not 0000001A3F)\n uint128_t resultat = 0;\n for (size_t n = 3; n < 17; ++n) {\n resultat += 15 * puissance::puissance(16, n - 1);\n resultat += 41 * puissance::puissance(14, n - 1);\n resultat -= 43 * puissance::puissance(15, n - 1);\n resultat -= puissance::puissance(13, n);\n }\n\n std::ostringstream oss;\n oss << std::hex << resultat;\n\n std::string str = oss.str();\n boost::to_upper(str);\n\n return str;\n}\n", "meta": {"hexsha": "965918f1ea7ec54ea8dc19b9027ddef5d1bfcbd0", "size": 1560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme162.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme1xx/probleme162.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme1xx/probleme162.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0, "max_line_length": 119, "alphanum_fraction": 0.65, "num_tokens": 448, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6995266848691656}} {"text": "//============================================================================\n//\n// This file is part of the Thea toolkit.\n//\n// This software is distributed under the BSD license, as detailed in the\n// accompanying LICENSE.txt file. Portions are derived from other works:\n// their respective licenses and copyright information are reproduced in\n// LICENSE.txt and/or in the relevant source files.\n//\n// Author: Siddhartha Chaudhuri\n// First version: 2009\n//\n//============================================================================\n\n#ifndef __Thea_Algorithms_LinearLeastSquares3_hpp__\n#define __Thea_Algorithms_LinearLeastSquares3_hpp__\n\n#include \"../Common.hpp\"\n#include \"../Array.hpp\"\n#include \"../Line3.hpp\"\n#include \"../MatVec.hpp\"\n#include \"../Plane3.hpp\"\n#include \"CentroidN.hpp\"\n#include \"Iterators.hpp\"\n#include \"PointTraitsN.hpp\"\n#include \n\nnamespace Thea {\nnamespace Algorithms {\n\n/** Fitting linear models to 3D data by minimizing sum-of-squared-errors. */\ntemplate \nclass /* THEA_API */ LinearLeastSquares3\n{\n public:\n /**\n * Linear least-squares fitting of a line to a set of 3D objects. InputIterator must dereference to type T or pointer-to-T.\n *\n * @param begin The first object in the set.\n * @param end One position beyond the last object in the set.\n * @param line Used to return the best-fit line.\n * @param centroid If non-null, used to return the centroid of the objects, which is computed in the process of finding the\n * best-fit line.\n *\n * @return The sum of squared fitting errors.\n */\n template \n static double fitLine(InputIterator begin, InputIterator end, Line3 & line, Vector3 * centroid = nullptr);\n\n /**\n * Linear least-squares fitting of a plane to a set of 3D objects. InputIterator must dereference to type T or pointer-to-T.\n *\n * @param begin The first object in the set.\n * @param end One position beyond the last object in the set.\n * @param plane Used to return the best-fit plane.\n * @param centroid If non-null, used to return the centroid of the objects, which is computed in the process of finding\n * the best-fit plane.\n *\n * @return The fitting quality: 0 (worst) to 1 (perfect).\n */\n template \n static double fitPlane(InputIterator begin, InputIterator end, Plane3 & plane, Vector3 * centroid = nullptr);\n\n}; // class LinearLeastSquares3\n\n// Fitting linear models to sets of objects that map to single points in 3-space.\ntemplate \nclass LinearLeastSquares3::value >::type>\n{\n public:\n template \n static double fitLine(InputIterator begin, InputIterator end, Line3 & line, Vector3 * centroid = nullptr)\n {\n Vector3d center;\n Matrix3d cov = covMatrix(begin, end, center);\n\n double sum = 0;\n for (auto iter = makeRefIterator(begin); iter != makeRefIterator(end); ++iter)\n {\n Vector3d diff = PointTraitsN::getPosition(*iter).template cast() - center;\n sum += (diff[0] * diff[0] + diff[1] * diff[1] + diff[2] * diff[2]);\n }\n\n Matrix3d m = sum * Matrix3d::Identity() - cov;\n Eigen::SelfAdjointEigenSolver eigensolver;\n if (eigensolver.computeDirect(m).info() != Eigen::Success)\n throw Error(\"LinearLeastSquares3: Could not eigensolve matrix\");\n\n // Eigenvalues are in increasing order\n line = Line3::fromPointAndDirection(center.cast(), eigensolver.eigenvectors().col(0).cast());\n if (centroid) *centroid = center.cast();\n return eigensolver.eigenvalues()[0];\n }\n\n template \n static double fitPlane(InputIterator begin, InputIterator end, Plane3 & plane, Vector3 * centroid = nullptr)\n {\n Vector3d center;\n Matrix3d cov = covMatrix(begin, end, center);\n\n Eigen::SelfAdjointEigenSolver eigensolver;\n if (eigensolver.computeDirect(cov).info() != Eigen::Success)\n throw Error(\"LinearLeastSquares3: Could not eigensolve covariance matrix\");\n\n // Eigenvalues are non-negative (covariance matrix is non-negative definite) and in increasing order\n plane = Plane3::fromPointAndNormal(center.cast(), eigensolver.eigenvectors().col(0).cast());\n if (centroid) *centroid = center.cast();\n return eigensolver.eigenvalues()[0];\n }\n\n private:\n /** Compute the covariance matrix between the coordinates of a set of 3D points. */\n template \n static Matrix3d covMatrix(InputIterator begin, InputIterator end, Vector3d & centroid)\n {\n centroid = CentroidN::compute(begin, end).template cast();\n\n Matrix3d m = Matrix3d::Zero();\n for (auto iter = makeRefIterator(begin); iter != makeRefIterator(end); ++iter)\n {\n Vector3d diff = PointTraitsN::getPosition(*iter).template cast() - centroid;\n m += diff * diff.transpose(); // outer product\n }\n\n return m;\n }\n\n}; // class LinearLeastSquares3\n\n} // namespace Algorithms\n} // namespace Thea\n\n#endif\n", "meta": {"hexsha": "9adfd3bda0e43fa1f13cd16ccab389b68c0599fe", "size": 5244, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/Source/Algorithms/LinearLeastSquares3.hpp", "max_stars_repo_name": "sidch/Thea", "max_stars_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T17:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:34.000Z", "max_issues_repo_path": "Code/Source/Algorithms/LinearLeastSquares3.hpp", "max_issues_repo_name": "sidch/Thea", "max_issues_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-22T16:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-22T16:47:04.000Z", "max_forks_repo_path": "Code/Source/Algorithms/LinearLeastSquares3.hpp", "max_forks_repo_name": "sidch/Thea", "max_forks_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-10-17T20:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T09:56:27.000Z", "avg_line_length": 39.1343283582, "max_line_length": 128, "alphanum_fraction": 0.6702898551, "num_tokens": 1251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.923039160069787, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6994738900649674}} {"text": "// A simple quickref for Eigen. Add anything that's missing.\n// Main author: Keir Mierle\n\n#include \n\nMatrix A; // Fixed rows and cols. Same as Matrix3d.\nMatrix B; // Fixed rows, dynamic cols.\nMatrix C; // Full dynamic. Same as MatrixXd.\nMatrix E; // Row major; default is column-major.\nMatrix3f P, Q, R; // 3x3 float matrix.\nVector3f x, y, z; // 3x1 float matrix.\nRowVector3f a, b, c; // 1x3 float matrix.\nVectorXd v; // Dynamic column vector of doubles\ndouble s;\n\n// Basic usage\n// Eigen // Matlab // comments\nx.size() // length(x) // vector size\nC.rows() // size(C,1) // number of rows\nC.cols() // size(C,2) // number of columns\nx(i) // x(i+1) // Matlab is 1-based\nC(i,j) // C(i+1,j+1) //\n\nA.resize(4, 4); // Runtime error if assertions are on.\nB.resize(4, 9); // Runtime error if assertions are on.\nA.resize(3, 3); // Ok; size didn't change.\nB.resize(3, 9); // Ok; only dynamic cols changed.\n\nA << 1, 2, 3, // Initialize A. The elements can also be\n 4, 5, 6, // matrices, which are stacked along cols\n 7, 8, 9; // and then the rows are stacked.\nB << A, A, A; // B is three horizontally stacked A's.\nA.fill(10); // Fill A with all 10's.\n\n// Eigen // Matlab\nMatrixXd::Identity(rows,cols) // eye(rows,cols)\nC.setIdentity(rows,cols) // C = eye(rows,cols)\nMatrixXd::Zero(rows,cols) // zeros(rows,cols)\nC.setZero(rows,cols) // C = ones(rows,cols)\nMatrixXd::Ones(rows,cols) // ones(rows,cols)\nC.setOnes(rows,cols) // C = ones(rows,cols)\nMatrixXd::Random(rows,cols) // rand(rows,cols)*2-1 // MatrixXd::Random returns uniform random numbers in (-1, 1).\nC.setRandom(rows,cols) // C = rand(rows,cols)*2-1\nVectorXd::LinSpaced(size,low,high) // linspace(low,high,size)'\nv.setLinSpaced(size,low,high) // v = linspace(low,high,size)'\n\n\n// Matrix slicing and blocks. All expressions listed here are read/write.\n// Templated size versions are faster. Note that Matlab is 1-based (a size N\n// vector is x(1)...x(N)).\n// Eigen // Matlab\nx.head(n) // x(1:n)\nx.head() // x(1:n)\nx.tail(n) // x(end - n + 1: end)\nx.tail() // x(end - n + 1: end)\nx.segment(i, n) // x(i+1 : i+n)\nx.segment(i) // x(i+1 : i+n)\nP.block(i, j, rows, cols) // P(i+1 : i+rows, j+1 : j+cols)\nP.block(i, j) // P(i+1 : i+rows, j+1 : j+cols)\nP.row(i) // P(i+1, :)\nP.col(j) // P(:, j+1)\nP.leftCols() // P(:, 1:cols)\nP.leftCols(cols) // P(:, 1:cols)\nP.middleCols(j) // P(:, j+1:j+cols)\nP.middleCols(j, cols) // P(:, j+1:j+cols)\nP.rightCols() // P(:, end-cols+1:end)\nP.rightCols(cols) // P(:, end-cols+1:end)\nP.topRows() // P(1:rows, :)\nP.topRows(rows) // P(1:rows, :)\nP.middleRows(i) // P(:, i+1:i+rows)\nP.middleRows(i, rows) // P(:, i+1:i+rows)\nP.bottomRows() // P(:, end-rows+1:end)\nP.bottomRows(rows) // P(:, end-rows+1:end)\nP.topLeftCorner(rows, cols) // P(1:rows, 1:cols)\nP.topRightCorner(rows, cols) // P(1:rows, end-cols+1:end)\nP.bottomLeftCorner(rows, cols) // P(end-rows+1:end, 1:cols)\nP.bottomRightCorner(rows, cols) // P(end-rows+1:end, end-cols+1:end)\nP.topLeftCorner() // P(1:rows, 1:cols)\nP.topRightCorner() // P(1:rows, end-cols+1:end)\nP.bottomLeftCorner() // P(end-rows+1:end, 1:cols)\nP.bottomRightCorner() // P(end-rows+1:end, end-cols+1:end)\n\n// Of particular note is Eigen's swap function which is highly optimized.\n// Eigen // Matlab\nR.row(i) = P.col(j); // R(i, :) = P(:, i)\nR.col(j1).swap(mat1.col(j2)); // R(:, [j1 j2]) = R(:, [j2, j1])\n\n// Views, transpose, etc; all read-write except for .adjoint().\n// Eigen // Matlab\nR.adjoint() // R'\nR.transpose() // R.' or conj(R')\nR.diagonal() // diag(R)\nx.asDiagonal() // diag(x)\nR.transpose().colwise().reverse(); // rot90(R)\nR.conjugate() // conj(R)\n\n// All the same as Matlab, but matlab doesn't have *= style operators.\n// Matrix-vector. Matrix-matrix. Matrix-scalar.\ny = M*x; R = P*Q; R = P*s;\na = b*M; R = P - Q; R = s*P;\na *= M; R = P + Q; R = P/s;\n R *= Q; R = s*P;\n R += Q; R *= s;\n R -= Q; R /= s;\n\n// Vectorized operations on each element independently\n// Eigen // Matlab\nR = P.cwiseProduct(Q); // R = P .* Q\nR = P.array() * s.array();// R = P .* s\nR = P.cwiseQuotient(Q); // R = P ./ Q\nR = P.array() / Q.array();// R = P ./ Q\nR = P.array() + s.array();// R = P + s\nR = P.array() - s.array();// R = P - s\nR.array() += s; // R = R + s\nR.array() -= s; // R = R - s\nR.array() < Q.array(); // R < Q\nR.array() <= Q.array(); // R <= Q\nR.cwiseInverse(); // 1 ./ P\nR.array().inverse(); // 1 ./ P\nR.array().sin() // sin(P)\nR.array().cos() // cos(P)\nR.array().pow(s) // P .^ s\nR.array().square() // P .^ 2\nR.array().cube() // P .^ 3\nR.cwiseSqrt() // sqrt(P)\nR.array().sqrt() // sqrt(P)\nR.array().exp() // exp(P)\nR.array().log() // log(P)\nR.cwiseMax(P) // max(R, P)\nR.array().max(P.array()) // max(R, P)\nR.cwiseMin(P) // min(R, P)\nR.array().min(P.array()) // min(R, P)\nR.cwiseAbs() // abs(P)\nR.array().abs() // abs(P)\nR.cwiseAbs2() // abs(P.^2)\nR.array().abs2() // abs(P.^2)\n(R.array() < s).select(P,Q); // (R < s ? P : Q)\n\n// Reductions.\nint r, c;\n// Eigen // Matlab\nR.minCoeff() // min(R(:))\nR.maxCoeff() // max(R(:))\ns = R.minCoeff(&r, &c) // [s, i] = min(R(:)); [r, c] = ind2sub(size(R), i);\ns = R.maxCoeff(&r, &c) // [s, i] = max(R(:)); [r, c] = ind2sub(size(R), i);\nR.sum() // sum(R(:))\nR.colwise().sum() // sum(R)\nR.rowwise().sum() // sum(R, 2) or sum(R')'\nR.prod() // prod(R(:))\nR.colwise().prod() // prod(R)\nR.rowwise().prod() // prod(R, 2) or prod(R')'\nR.trace() // trace(R)\nR.all() // all(R(:))\nR.colwise().all() // all(R)\nR.rowwise().all() // all(R, 2)\nR.any() // any(R(:))\nR.colwise().any() // any(R)\nR.rowwise().any() // any(R, 2)\n\n// Dot products, norms, etc.\n// Eigen // Matlab\nx.norm() // norm(x). Note that norm(R) doesn't work in Eigen.\nx.squaredNorm() // dot(x, x) Note the equivalence is not true for complex\nx.dot(y) // dot(x, y)\nx.cross(y) // cross(x, y) Requires #include \n\n//// Type conversion\n// Eigen // Matlab\nA.cast(); // double(A)\nA.cast(); // single(A)\nA.cast(); // int32(A)\nA.real(); // real(A)\nA.imag(); // imag(A)\n// if the original type equals destination type, no work is done\n\n// Note that for most operations Eigen requires all operands to have the same type:\nMatrixXf F = MatrixXf::Zero(3,3);\nA += F; // illegal in Eigen. In Matlab A = A+F is allowed\nA += F.cast(); // F converted to double and then added (generally, conversion happens on-the-fly)\n\n// Eigen can map existing memory into Eigen matrices.\nfloat array[3];\nVector3f::Map(array).fill(10); // create a temporary Map over array and sets entries to 10\nint data[4] = {1, 2, 3, 4};\nMatrix2i mat2x2(data); // copies data into mat2x2\nMatrix2i::Map(data) = 2*mat2x2; // overwrite elements of data with 2*mat2x2\nMatrixXi::Map(data, 2, 2) += mat2x2; // adds mat2x2 to elements of data (alternative syntax if size is not know at compile time)\n\n// Solve Ax = b. Result stored in x. Matlab: x = A \\ b.\nx = A.ldlt().solve(b)); // A sym. p.s.d. #include \nx = A.llt() .solve(b)); // A sym. p.d. #include \nx = A.lu() .solve(b)); // Stable and fast. #include \nx = A.qr() .solve(b)); // No pivoting. #include \nx = A.svd() .solve(b)); // Stable, slowest. #include \n// .ldlt() -> .matrixL() and .matrixD()\n// .llt() -> .matrixL()\n// .lu() -> .matrixL() and .matrixU()\n// .qr() -> .matrixQ() and .matrixR()\n// .svd() -> .matrixU(), .singularValues(), and .matrixV()\n\n// Eigenvalue problems\n// Eigen // Matlab\nA.eigenvalues(); // eig(A);\nEigenSolver eig(A); // [vec val] = eig(A)\neig.eigenvalues(); // diag(val)\neig.eigenvectors(); // vec\n// For self-adjoint matrices use SelfAdjointEigenSolver<>\n", "meta": {"hexsha": "a755c302168a23917adb5f4b3c47d2a76c5a8463", "size": 9644, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ekf/matlab/Eigen_Matlab_ref.cpp", "max_stars_repo_name": "KerryWu16/src", "max_stars_repo_head_hexsha": "bed672dc1732cd6af1752bb54ab0abde015bb93a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-12-17T11:07:56.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-19T09:35:11.000Z", "max_issues_repo_path": "ekf/matlab/Eigen_Matlab_ref.cpp", "max_issues_repo_name": "KerryWu16/src", "max_issues_repo_head_hexsha": "bed672dc1732cd6af1752bb54ab0abde015bb93a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ekf/matlab/Eigen_Matlab_ref.cpp", "max_forks_repo_name": "KerryWu16/src", "max_forks_repo_head_hexsha": "bed672dc1732cd6af1752bb54ab0abde015bb93a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-19T07:41:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-19T07:41:48.000Z", "avg_line_length": 46.3653846154, "max_line_length": 133, "alphanum_fraction": 0.4813355454, "num_tokens": 2858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.699350583606021}} {"text": "/*\nCopyright (C) 2015-present CompatibL\n\nPerformance test results and finance-specific examples are available at:\n\nhttp://www.tapescript.org\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n#ifndef cl_tape_examples_impl_polynomial_regression_hpp\n#define cl_tape_examples_impl_polynomial_regression_hpp\n\n#define CL_BASE_SERIALIZER_OPEN\n#include \n#include \n#include \n#include \n\nnamespace cl\n{\n // Class for polynomial regression calculation.\n class polynomial_regression\n {\n private:\n // Order of polynomial regression.\n const int order_;\n // Size of matrixes m = order + 1.\n const int m_;\n\n // Input data vectors.\n const tobject data_x_;\n const tobject data_y_;\n\n // Intermediate regression struuctures:\n // Vectors of powers of x from 0 to 2 * (order + 1).\n std::vector x_power_;\n // Matrix X * X^T\n std::vector> mat_X_XT_;\n // Inverse matrix (X * X^T)^-1\n std::vector> mat_X_XT_inv_;\n // Vector X^T * y.\n std::vector vec_XT_y_;\n\n // Regression coefficients and their derivatives.\n std::vector coef_;\n\n // Status of calculation.\n bool is_coef_calculated;\n bool is_estim_calculated;\n\n public:\n // Construct using provided data and order of polynomial regression.\n polynomial_regression(tobject& x, tobject& y, int order) : data_x_(x), data_y_(y), order_(order), m_(order + 1)\n {\n is_coef_calculated = false;\n is_estim_calculated = false;\n }\n\n // Calculate polynomial regression coefficients.\n std::vector calculate_coefficients()\n {\n // Create vectors of powers of x from 0 to 2m.\n x_power_.resize(2 * m_);\n x_power_[0] = 1 + data_x_ - data_x_;\n std::vector x_power_sum_vec(2 * m_);\n x_power_sum_vec[0] = tapescript::sum_vec(x_power_[0]);\n for (int i = 1; i < 2 * m_; i++)\n {\n x_power_[i] = x_power_[i - 1] * data_x_;\n x_power_sum_vec[i] = tapescript::sum_vec(x_power_[i]);\n }\n\n // Calculate matrix X * X^T.\n mat_X_XT_.resize(m_);\n for (int i = 0; i < m_; i++)\n mat_X_XT_[i].resize(m_);\n\n // Calculate lower triangular matrix elements.\n for (int i = 0; i < m_; i++)\n for (int j = 0; j <= i; j++)\n mat_X_XT_[i][j] = x_power_sum_vec[i + j];\n\n // Calculate the rest of matrix elements using symmetry.\n for (int i = 0; i < m_; i++)\n for (int j = i + 1; j < m_; j++)\n mat_X_XT_[i][j] = mat_X_XT_[j][i];\n\n // Calculate inverse matrix (X * X^T)^-1.\n mat_X_XT_inv_ = invert_sym_matrix_boost(mat_X_XT_);\n\n // Calculate vector X^T * y.\n vec_XT_y_.resize(m_);\n for (int i = 0; i < m_; i++)\n vec_XT_y_[i] = tapescript::sum_vec(x_power_[i] * data_y_);\n\n // Calculate regression coefficients.\n coef_.resize(m_);\n for (int i = 0; i < m_; i++)\n {\n coef_[i] = 0;\n for (int j = 0; j < m_; j++)\n coef_[i] += mat_X_XT_inv_[i][j] * vec_XT_y_[j];\n }\n\n is_coef_calculated = true;\n return coef_;\n }\n\n // Calculate polynomial regression coefficients.\n tobject calculate_estimation()\n {\n if (!is_coef_calculated)\n throw std::runtime_error(\"Regression coefficients are not calculated.\");\n tobject estim_y = tobject(0);\n for (int i = 0; i < m_; i++)\n estim_y += coef_[i] * x_power_[i];\n is_estim_calculated = true;\n return estim_y;\n }\n\n // Calculate polynomial regression coefficients derivatives w.r.t data points (y).\n std::vector> calculate_coefficients_derivatives()\n {\n if (!is_coef_calculated)\n throw std::runtime_error(\"Regression coefficients are not calculated.\");\n std::vector> d_coef_d_y(m_);\n std::vector x_power_tvalue(m_);\n for (int i = 0; i < m_; i++)\n x_power_tvalue[i] = (tvalue)x_power_[i];\n int npoints = x_power_tvalue[0].size();\n for (int i = 0; i < m_; i++)\n {\n d_coef_d_y[i].resize(npoints);\n for (int j = 0; j < npoints; j++)\n for (int k = 0; k < m_; k++)\n d_coef_d_y[i][j] += ((tvalue)mat_X_XT_inv_[i][k]).scalar_value_ * x_power_tvalue[k].element_at(j);\n }\n return d_coef_d_y;\n }\n\n // Calculate polynomial regression coefficients derivatives w.r.t data points (y).\n std::vector> calculate_estimation_derivatives()\n {\n std::vector> d_coef_d_y = calculate_coefficients_derivatives();\n std::vector x_power_tvalue(m_);\n for (int i = 0; i < m_; i++)\n x_power_tvalue[i] = (tvalue)x_power_[i];\n int npoints = x_power_tvalue[0].size();\n std::vector> estim_y_deriv(npoints);\n for (int i = 0; i < npoints; i++)\n {\n estim_y_deriv[i].resize(npoints);\n for (int j = 0; j < npoints; j++)\n for (int k = 0; k < m_; k++)\n estim_y_deriv[i][j] += d_coef_d_y[k][i] * x_power_tvalue[k].element_at(j);\n }\n return estim_y_deriv;\n }\n\n // Invert symmetric matrix using Cholesky decomposition from the Boost library.\n // This template method works with both element_type = tobject and element_type = tdouble.\n template\n static std::vector> invert_sym_matrix_boost(const std::vector>& mat)\n {\n // Matrix size.\n int m = mat.size();\n boost::numeric::ublas::matrix input(m, m);\n for (int i = 0; i < m; i++)\n for (int j = 0; j < m; j++)\n input.operator ()(i, j) = mat[i][j];\n // Create a permutation matrix for the LU-factorization\n boost::numeric::ublas::permutation_matrix pm(m);\n // Perform LU-factorization\n if(boost::numeric::ublas::lu_factorize(input, pm))\n throw std::runtime_error(\"Singular matrix\");\n // Create identity matrix of for inverse\n boost::numeric::ublas::matrix inverse(m, m);\n inverse.assign(boost::numeric::ublas::identity_matrix(m));\n boost::numeric::ublas::lu_substitute(input, pm, inverse);\n std::vector> mat_inv = mat;\n for (int i = 0; i < m; i++)\n for (int j = 0; j < m; j++)\n mat_inv[i][j] = inverse(i, j);\n return mat_inv;\n }\n };\n}\n\n#endif // cl_tape_examples_impl_polynomial_regression_hpp\n", "meta": {"hexsha": "f2820a9576aef761497c20e756f89f9cdf62e925", "size": 7898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tapescript/cpp/cl/tape/examples/impl/polynomial_regression.hpp", "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 41.0, "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_issues_repo_path": "tapescript/cpp/cl/tape/examples/impl/polynomial_regression.hpp", "max_issues_repo_name": "fduffy/QuantLibAdjoint", "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tapescript/cpp/cl/tape/examples/impl/polynomial_regression.hpp", "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "avg_line_length": 39.2935323383, "max_line_length": 128, "alphanum_fraction": 0.566599139, "num_tokens": 1926, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834277, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6992823567261756}} {"text": "/** @file\n * @brief NPDE ZienkiewiczZhuEstimator\n * @author Erick Schulz\n * @date 25/07/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \n#include \n#include \n#include \n\n#include \"zienkiewiczzhuestimator.h\"\n// Eigen includes\n#include \n#include \n#include \n// Lehrfem++ includes\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace ZienkiewiczZhuEstimator;\n\nint main(int /*argc*/, const char ** /*argv*/) {\n std::cout << \"\\n\" << std::endl;\n std::cout << \"PROBLEM - ZienkiewiczZhuEstimator \" << std::endl;\n progress_bar progress{std::clog, 70u, \"Computing\"};\n double progress_pourcentage;\n // Tools and data\n int N_meshes = 4; // num. of meshes\n Eigen::VectorXd approx_sol; // basis ceoff expansion of scalar approx sol\n Eigen::VectorXd approx_grad; // basis ceoff expansion of approx grad\n Eigen::VectorXd L2errors(N_meshes); // L2 errors of scalar approx sol\n Eigen::VectorXd H1errors(N_meshes); // H1 errors of scalar approx sol\n Eigen::VectorXd errors_grad(N_meshes); // deviation of grad (delta error)\n Eigen::VectorXd errors_diff(N_meshes); // error difference (epsilon error)\n Eigen::VectorXd mesh_sizes(N_meshes);\n Eigen::VectorXd interpolated_uExact;\n std::shared_ptr> fe_space_p;\n std::shared_ptr mesh_p;\n\n // Analytic solution\n auto uExact = [](coord_t x) -> double {\n return (0.2 / (M_PI * M_PI)) * sin(M_PI * x[0]) * sin(2 * M_PI * x[1]);\n };\n lf::mesh::utils::MeshFunctionGlobal mf_uExact{uExact};\n auto grad_uExact = [](coord_t x) -> Eigen::Vector2d {\n return Eigen::Vector2d(\n (0.2 / M_PI) * cos(M_PI * x[0]) * sin(2 * M_PI * x[1]),\n (0.4 / M_PI) * sin(M_PI * x[0]) * cos(2 * M_PI * x[1]));\n };\n lf::mesh::utils::MeshFunctionGlobal mf_grad_uExact{grad_uExact};\n\n for (int i = 0; i < N_meshes; i++) { // for each mesh\n std::string idx_str = std::to_string(i);\n // Load mesh into a Lehrfem++ object\n auto mesh_factory = std::make_unique(2);\n const lf::io::GmshReader reader(\n std::move(mesh_factory),\n CURRENT_SOURCE_DIR \"/../meshes/unitsquare\" + idx_str + \".msh\");\n mesh_p = reader.mesh();\n mesh_sizes[i] = getMeshSize(mesh_p);\n fe_space_p =\n std::make_shared>(mesh_p);\n // Obtain reference to scalar dofh\n const lf::assemble::DofHandler &dofh{fe_space_p->LocGlobMap()};\n // Produce a dof handler for the vector-valued finite element space\n lf::assemble::UniformFEDofHandler vec_dofh(\n mesh_p, {{lf::base::RefEl::kPoint(), 2},\n {lf::base::RefEl::kSegment(), 0},\n {lf::base::RefEl::kTria(), 0},\n {lf::base::RefEl::kQuad(), 0}});\n\n LF_VERIFY_MSG(2 * dofh.NumDofs() == vec_dofh.NumDofs(),\n \"Number of degrees of freedom mismatch!\");\n\n // Solve Poisson BVP with essential BCs\n approx_sol = solveBVP(fe_space_p);\n // Compute L2 and H1 errors\n auto mf_approx_sol = lf::fe::MeshFunctionFE(fe_space_p, approx_sol);\n L2errors[i] = std::sqrt(lf::fe::IntegrateMeshFunction(\n *mesh_p, lf::uscalfe::squaredNorm(mf_uExact - mf_approx_sol), 2));\n auto mf_approx_grad_sol =\n lf::fe::MeshFunctionGradFE(fe_space_p, approx_sol);\n H1errors[i] = std::sqrt(lf::fe::IntegrateMeshFunction(\n *mesh_p, lf::uscalfe::squaredNorm(mf_grad_uExact - mf_approx_grad_sol),\n 2));\n\n // Solve gradient VP and compute L2 deviation\n approx_grad = solveGradVP(fe_space_p, approx_sol, vec_dofh);\n // approx_grad = computeLumpedProjection(dofh, approx_sol, vec_dofh);\n // Compute deviation error (delta error)\n errors_grad[i] =\n computeL2Deviation(dofh, approx_sol, vec_dofh, approx_grad);\n\n // Compute difference error (epsilon error)\n errors_diff[i] = std::abs(H1errors[i] - errors_grad[i]);\n\n progress_pourcentage = ((double)i + 1.0) / N_meshes * 100.0;\n progress.write(progress_pourcentage / 100.0);\n }\n\n // Computing rates of convergence of approx solutions to BVP and gradient VP\n double ratesL2[N_meshes - 1];\n double ratesH1[N_meshes - 1];\n double rates_grad[N_meshes - 1];\n double rates_diff[N_meshes - 1];\n double log_denum;\n for (int k = 0; k < N_meshes - 1; k++) {\n log_denum = log(mesh_sizes[k] / mesh_sizes[k + 1]);\n ratesL2[k] = log(L2errors[k] / L2errors[k + 1]) / log_denum;\n ratesH1[k] = log(H1errors[k] / H1errors[k + 1]) / log_denum;\n rates_grad[k] = log(errors_grad[k] / errors_grad[k + 1]) / log_denum;\n rates_diff[k] = log(errors_diff[k] / errors_diff[k + 1]) / log_denum;\n }\n\n std::cout << \"\\n Done.\" << std::endl;\n std::cout << \"Outputing results.\" << std::endl;\n\n std::cout << \"\\n\" << std::endl;\n std::cout << \"*********************************************************\"\n << std::endl;\n std::cout << \" ERRORS AND CONVERGENCE RATES FOR PROBLEM \"\n << std::endl;\n std::cout << \" ZIENKIEWICZ ZHU ESTIMATOR \"\n << std::endl;\n std::cout << \"*********************************************************\"\n << std::endl;\n\n std::cout << \"\\n\" << std::endl;\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n std::cout << \" L2 errors of approximate scalar solutions to the \"\n << std::endl;\n std::cout << \" Poisson Problem with essential boundary conditions \"\n << std::endl;\n std::cout << \"--------------------- RESULTS ---------------------------\"\n << std::endl;\n std::cout << \"Iteration\"\n << \"\\t| L2 error\"\n << \"\\t\\t| rates\" << std::endl;\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n for (int k = 0; k < N_meshes; k++) {\n std::cout << k << \"\\t\"\n << \"\\t|\" << L2errors[k];\n if (k > 0) {\n std::cout << \"\\t \\t|\" << ratesL2[k - 1];\n }\n std::cout << \"\\n\";\n }\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n\n std::cout << \"\\n\" << std::endl;\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n std::cout << \" H1 errors of approximate scalar solutions to the \"\n << std::endl;\n std::cout << \" Poisson Problem with essential boundary conditions \"\n << std::endl;\n std::cout << \"--------------------- RESULTS ---------------------------\"\n << std::endl;\n std::cout << \"Iteration\"\n << \"\\t| H1 error\"\n << \"\\t\\t| rates\" << std::endl;\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n for (int k = 0; k < N_meshes; k++) {\n std::cout << k << \"\\t\"\n << \"\\t|\" << H1errors[k];\n if (k > 0) {\n std::cout << \"\\t \\t|\" << ratesH1[k - 1];\n }\n std::cout << \"\\n\";\n }\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n\n std::cout << \"\\n\" << std::endl;\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n std::cout << \" Convergence rates of the approximate gradients \"\n << std::endl;\n std::cout << \" (delta error) \"\n << std::endl;\n std::cout << \"--------------------- RESULTS ---------------------------\"\n << std::endl;\n std::cout << \"Iteration\"\n << \"\\t| delta\"\n << \"\\t\\t| rates\" << std::endl;\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n for (int k = 0; k < N_meshes; k++) {\n std::cout << k << \"\\t\"\n << \"\\t|\" << errors_grad[k];\n if (k > 0) {\n std::cout << \"\\t\\t|\" << rates_grad[k - 1];\n }\n std::cout << \"\\n\";\n }\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n\n std::cout << \"\\n\" << std::endl;\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n std::cout << \" Difference error between the H1 error of the \"\n << std::endl;\n std::cout << \" approximate solution to the BVP and the deviation \"\n << std::endl;\n std::cout << \" (epsilon error) \"\n << std::endl;\n std::cout << \"--------------------- RESULTS ---------------------------\"\n << std::endl;\n std::cout << \"Iteration\"\n << \"\\t| epsilon\"\n << \"\\t\\t| rates\" << std::endl;\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n for (int k = 0; k < N_meshes; k++) {\n std::cout << k << \"\\t\"\n << \"\\t|\" << errors_diff[k];\n if (k > 0) {\n std::cout << \"\\t \\t|\" << rates_diff[k - 1];\n }\n std::cout << \"\\n\";\n }\n std::cout << \"---------------------------------------------------------\"\n << std::endl;\n\n // Output results for epsilon and delta errors to csv file\n const static Eigen::IOFormat CSVFormat(Eigen::StreamPrecision,\n Eigen::DontAlignCols, \", \", \"\\n\");\n std::string errors_file_name_delta = \"delta_errors.csv\";\n std::ofstream file_delta(errors_file_name_delta.c_str());\n if (file_delta.is_open()) {\n file_delta << errors_grad.format(CSVFormat);\n }\n std::string errors_file_name_epsilon = \"epsilon_errors.csv\";\n std::ofstream file_epsilon(errors_file_name_epsilon.c_str());\n if (file_epsilon.is_open()) {\n file_epsilon << errors_diff.format(CSVFormat);\n }\n\n std::cout << \"\\n The delta and epsilon errors were written to:\" << std::endl;\n std::cout << \">> delta_errors.csv and epsilon_errors.csv\\n\" << std::endl;\n\n // Save approximate solution in VTK format\n // Output results to vtk file\n const lf::assemble::DofHandler &dofh{fe_space_p->LocGlobMap()};\n const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n lf::io::VtkWriter vtk_writer(mesh_p, \"ZienkiewiczZhuEstimator_solution.vtk\");\n // Write nodal data taking the values of the discrete solution at the\n // vertices\n auto nodal_data = lf::mesh::utils::make_CodimMeshDataSet(mesh_p, 2);\n for (int global_idx = 0; global_idx < N_dofs; global_idx++) {\n nodal_data->operator()(dofh.Entity(global_idx)) = approx_sol[global_idx];\n };\n vtk_writer.WritePointData(\"ZienkiewiczZhuEstimator_solution\", *nodal_data);\n\n std::cout << \"\\n The ZienkiewiczZhuEstimator_solution was written to:\"\n << std::endl;\n std::cout << \">> ZienkiewiczZhuEstimator_solution.vtk\\n\" << std::endl;\n\n} // main\n", "meta": {"hexsha": "363b68875865eeed949c42195812bae851e45c0a", "size": 10885, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ZienkiewiczZhuEstimator/templates/zienkiewiczzhuestimator_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/ZienkiewiczZhuEstimator/templates/zienkiewiczzhuestimator_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/ZienkiewiczZhuEstimator/templates/zienkiewiczzhuestimator_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 40.1660516605, "max_line_length": 79, "alphanum_fraction": 0.5257694074, "num_tokens": 2977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6992823530940874}} {"text": "// Modified from NetKet source for YANNQ Project\n// (chae.yeun.park@gmail.com)\n// Copyright 2018 The Simons Foundation, Inc. - All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef YANNQ_ACTIVATIONS_HPP\n#define YANNQ_ACTIVATIONS_HPP\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nnamespace yannq {\n\n/**\n Abstract class for Activations.\n*/\nnamespace activation\n{\ntemplate\nclass Identity \n{\npublic:\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\n\t// A = Z\n\tinline void operator()(VectorConstRef Z, VectorRef A) const {\n\t\tA.noalias() = Z;\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = Z\n\t// J = dA / dZ = I\n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef /*Z*/, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const {\n\t\tG.noalias() = F;\n\t}\n\n\tstd::string name() const {\n\t\treturn \"Identity\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\n\ntemplate\nclass LnCosh \n{\npublic:\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\n\t// A = Lncosh(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const {\n\t\tfor (int i = 0; i < A.size(); ++i) {\n\t\t\tA(i) = logCosh(Z(i));\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = Lncosh(Z)\n\t// J = dA / dZ\n\t// G = J * F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const {\n\t\tG.array() = F.array() * Z.array().tanh();\n\t}\n\n\tstd::string name() const {\n\t\treturn \"LnCosh\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\ntemplate\nclass Tanh \n{\npublic:\t\n\tusing Scalar = T;\n\tusing RealScalar = remove_complex_t;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\nprivate:\n\tRealScalar constant_;\n\npublic:\n\n\texplicit Tanh(const RealScalar constant = 1.0) //constant*tanh(z/constant)\n\t\t: constant_{constant}\n\t{\n\t}\n\n\t// A = a*Tanh(Z/a)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const {\n\t\tA.array() = constant_ * (Z.array() / constant_).tanh();\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = a*Tanh(Z/a)\n\t// J = dA / dZ\n\t// G = J * F\n\tinline void ApplyJacobian(VectorConstRef /*Z*/, VectorConstRef A,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const {\n\t\tG.array() = F.array() * (1. - A.array() * A.array() / (constant_*constant_));\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"Tanh\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& ar)\n\t{\n\t\tar(constant_);\n\t}\n};\n\ntemplate\nclass WeakTanh\n{\npublic:\t\n\tusing Scalar = T;\n\tusing RealScalar = remove_complex_t;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\nprivate:\n\npublic:\n\n\texplicit WeakTanh() //x - tanh(x)/2\n\t{\n\t}\n\n\t// A = a*Tanh(Z/a)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const {\n\t\tA.array() = Z.array();\n\t\tA.array() -= Z.array().tanh()/2.0;\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = Tanh(Z)\n\t// J = dA / dZ\n\t// G = J * F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const {\n\t\tEigen::Array tanh = Z.array().tanh();\n\t\tG.array() = F.array() * (1.0 + tanh * tanh)/2.0;\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"WeakTanh\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\n\ntemplate\nclass Sigmoid\n{\n\tstatic_assert(!is_complex_type::value, \"Sigmoid now only supports real parameters\");\npublic:\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\n\t// A = Sigmoid(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const {\n\t\tA.array() = Z.array().exp();\n\t\tA.array().inverse();\n\t\tA.array() += 1.;\n\t\tA.array().inverse();\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = Sigmoid(Z)\n\t// J = dA / dZ\n\t// G = J * F\n\tinline void ApplyJacobian(VectorConstRef /*Z*/, VectorConstRef A,\n\t\t\tVectorConstRef /*F*/,\n\t\t\tVectorRef G) const {\n\t\tG.array() = (1. - A.array() ) * A.array();\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"Sigmoid\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\ntemplate\nclass ReLU;\n\n//for complex T\ntemplate\nclass ReLU::value>::type > \n{\npublic:\n\tusing Scalar = T;\n\tusing RealScalar = remove_complex_t;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\n\tconstexpr static RealScalar theta1_ = 3*M_PI/4;\n\tconstexpr static RealScalar theta2_ = -M_PI/4;\n\n\t// A = ReLU(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const {\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tA(i) =\n\t\t\t\t(std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? Z(i) : 0.0;\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = ReLU(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const {\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) =\n\t\t\t\t(std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? F(i) : 0.0;\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"ReLU\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n//For real T\ntemplate\nclass ReLU::value>::type >\n{\npublic:\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\n\t// A = ReLU(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const {\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tA(i) = std::max(Z(i), T{0.0});\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = ReLU(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const \n\t{\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) = Z(i)>0?F(i):T{0.0};\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"ReLU\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\ntemplate\nclass LeakyReLU;\n\n//for complex T\ntemplate\nclass LeakyReLU::value>::type>\n{\npublic:\n\tusing Scalar = T;\n\tusing RealScalar = remove_complex_t;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\n\tconstexpr static RealScalar theta1_ = 3*M_PI/4;\n\tconstexpr static RealScalar theta2_ = -M_PI/4;\n\tRealScalar negativeSlope_;\n\n\tLeakyReLU(const RealScalar negativeSlope = 0.1)\n\t\t: negativeSlope_{negativeSlope}\n\t{\n\t}\n\n\t// A = LeakyReLU(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const {\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tA(i) =\n\t\t\t\t(std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? Z(i) : negativeSlope_*Z(i);\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = LeakyReLU(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const \n\t{\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) =\n\t\t\t\t(std::arg(Z(i)) < theta1_) && (std::arg(Z(i)) > theta2_) ? F(i) : negativeSlope_*F(i);\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"LeakyReLU\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& ar)\n\t{\n\t\tar(negativeSlope_);\n\t}\n};\n\n//For real T\ntemplate\nclass LeakyReLU::value>::type>\n{\npublic:\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\t\n\tScalar negativeSlope_;\n\n\tLeakyReLU(const Scalar negativeSlope = 0.1)\n\t\t: negativeSlope_{negativeSlope}\n\t{\n\t}\n\t// A = LeakyReLU(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const {\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tA(i) = Z(i)>0?Z(i):T{negativeSlope_*Z(i)};\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = LeakyReLU(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F,\n\t\t\tVectorRef G) const \n\t{\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) = Z(i)>0?F(i):T{negativeSlope_*F(i)};\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"LeakyReLU\";\n\t}\n\ttemplate\n\tvoid serialize(Archive& ar)\n\t{\n\t\tar(negativeSlope_);\n\t}\n};\n\n\n//For real T\ntemplate\nclass HardTanh\n{\npublic:\n\tstatic_assert(!is_complex_type::value, \"T must be a real type for HardTanh\");\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\t\n\tHardTanh()\n\t{\n\t}\n\n\t// A = hardtanh(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const \n\t{\n\t\tusing std::abs;\n\t\tfor (int i = 0; i < Z.size(); ++i) \n\t\t{\n\t\t\tA(i) = abs(Z(i))>1.0?copysign(1.0, Z(i)):Z(i);\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = hardtanh(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F, VectorRef G) const \n\t{\n\t\tusing std::abs;\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) = abs(Z(i))>1.0?0.0:F(i);\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"HardTanh\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\ntemplate\nclass SoftShrink\n{\npublic:\n\tstatic_assert(!is_complex_type::value, \"T must be a real type for SoftShrink\");\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\t\n\tSoftShrink()\n\t{\n\t}\n\n\t// A = softshrink(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const \n\t{\n\t\tusing std::abs;\n\t\tfor (int i = 0; i < Z.size(); ++i) \n\t\t{\n\t\t\tA(i) = abs(Z(i))<1.0?0.0:(Z(i)-copysign(1.0,Z(i)));\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = softshrink(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F, VectorRef G) const \n\t{\n\t\tusing std::abs;\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) = abs(Z(i))<1.0?0.0:F(i);\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"SoftShrink\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n\n};\n\ntemplate\nclass LeakyHardTanh\n{\npublic:\n\tstatic_assert(!is_complex_type::value, \"T must be a real type for LeakyHardTanh\");\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\n\tScalar outsideSlope_;\n\t\n\tLeakyHardTanh(Scalar outsideSlope = 0.01)\n\t\t: outsideSlope_{outsideSlope}\n\t{\n\t}\n\n\t// A = leakyhardtanh(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const \n\t{\n\t\tusing std::abs;\n\t\tfor (int i = 0; i < Z.size(); ++i) \n\t\t{\n\t\t\tT val = abs(Z(i))>1.0?copysign(1.0, Z(i)):Z(i);\n\t\t\tval += abs(Z(i))<1.0?0.0:outsideSlope_*(Z(i)-copysign(1.0,Z(i)));\n\t\t\tA(i) = val;\n\t\t}\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = leakyhardtanh(Z)\n\t// J = dA / dZ \n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F, VectorRef G) const \n\t{\n\t\tusing std::abs;\n\t\tfor (int i = 0; i < Z.size(); ++i) {\n\t\t\tG(i) = abs(Z(i))>1.0?outsideSlope_*F(i):F(i);\n\t\t}\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"LeakyHardTanh\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& ar)\n\t{\n\t\tar(outsideSlope_);\n\t}\n};\n\n\ntemplate\nclass SoftSign\n{\npublic:\n\tstatic_assert(!is_complex_type::value, \"T must be a real type for SoftSign\");\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\t\n\tSoftSign()\n\t{\n\t}\n\n\t// A = softsign(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const \n\t{\n\t\tA.array() = Z.array()/(Z.array().abs()+1.0);\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = softsign(Z)\n\t// J = dA / dZ = I\n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F, VectorRef G) const \n\t{\n\t\tG.array() = (1.0+Z.array().abs()).square().inverse()*F.array();\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"SoftSign\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& /*ar*/)\n\t{\n\t}\n};\n\ntemplate\nclass Cos\n{\nprivate:\n\tT a_;\npublic:\n\tstatic_assert(!is_complex_type::value, \"T must be a real type for Cos\");\n\tusing Scalar = T;\n\tusing Vector = Eigen::Matrix;\n\tusing VectorRef = Eigen::Ref;\n\tusing VectorConstRef = Eigen::Ref;\n\n\t\n\tCos(T a = 1.0)\n\t\t: a_{a}\n\t{\n\t}\n\n\t// A = cos(Z)\n\tinline void operator()(VectorConstRef Z, VectorRef A) const \n\t{\n\t\tA.array() = a_*cos(Z.array()*M_PI/a_);\n\t}\n\n\t// Apply the (derivative of activation function) matrix J to a vector F\n\t// A = a*cos(\\pi Z/a)\n\t// J = dA / dZ = \\pi sin(\\pi Z/ a)\n\t// G = J * F = F\n\tinline void ApplyJacobian(VectorConstRef Z, VectorConstRef /*A*/,\n\t\t\tVectorConstRef F, VectorRef G) const \n\t{\n\t\tG.array() = -M_PI*sin(M_PI*Z.array()/a_)*F.array();\n\t}\n\n\tstd::string name() const\n\t{\n\t\treturn \"Cos\";\n\t}\n\n\ttemplate\n\tvoid serialize(Archive& ar)\n\t{\n\t\tar(a_);\n\t}\n};\n}//namsepace activation\n\n}// namespace yannq\n\n#endif\n", "meta": {"hexsha": "2e0d9f7efabdb0d9f3defaf2bb48089937efd734", "size": 14850, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Yannq/Machines/layers/activations.hpp", "max_stars_repo_name": "cecri/yannq", "max_stars_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Yannq/Machines/layers/activations.hpp", "max_issues_repo_name": "cecri/yannq", "max_issues_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Yannq/Machines/layers/activations.hpp", "max_forks_repo_name": "cecri/yannq", "max_forks_repo_head_hexsha": "b78c1f86a255059f06b34dd5e538449e7261d0ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.8382352941, "max_line_length": 90, "alphanum_fraction": 0.6422895623, "num_tokens": 4619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.6992409165079084}} {"text": "#include \n#include \n#include \n \nusing Eigen::MatrixXd;\nusing namespace Eigen;\nusing namespace std;\n \nint main()\n{\n string name = \"Juan pablo mallarino \\n github.com\";\n int n = 0, m = 0;\n // Bloque de codigo que lee el archivo y determina filas y columnas\n MatrixXd A(n,m);\n // Bloque de codigo que carga el archivo a la matriz\n MatrixXd m = MatrixXd::Random(10,10); // # reales PSEUDO-aleatorios entre -1 y 1\n cout << \"Checkpoint 1: \\n\" << m << endl;\n cout << \"Determinant of m:\\n\" << m.determinant() << endl;\n MatrixXd u_m = m.inverse();\n cout << \"Inverse of m:\\n\" << u_m << endl;\n cout << \"Test de valicez m^-1*m:\\n\" << u_m*m << endl;\n // No existe tal cosa como exactitud en computacion -> decimales\n // el cero en precision doble (double) -> 10^-15\n // -> es un reto!\n // LISP + Mathematica\n m = (m + MatrixXd::Constant(10,10,1.2)) * 50; // # reales aleatorios entre 10 y 110\n cout << \"Checkpoint 2: m =\\n\" << m << endl; // endl hace flush...\n VectorXd v(10);\n v << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;\n cout << \"Checkpoint 3: v =\" << v << endl;\n cout << \"m * v =\" << endl << m * v << endl;\n cout << \"terminando... \"<\n\n#include \n#include \n\n#include \n\n//! \\brief One step of autonomous IVP y'' + y' + y = 0, [y(0), y'(0)] = z0 using SDIRK method\n//! Use SDIRK method for first order ode z' = f(z). Steps of size h.\n//! \\tparam StateType type of solution space y and initial data y0\n//! \\param[in] z0 initial data z(0)\n//! \\param[in] h size of the step\n//! \\param[in] gamma parameter\n//! \\return next step z1\ntemplate \nStateType sdirkStep(const StateType & z0, double h, double gamma) {\n // TODO: implement one step of SDIRK method\n}\n\n//! \\brief Solve autonomous IVP y'' + y' + y = 0, [y(0), y'(0)] = z0 using SDIRK method\n//! Use SDIRK method for first order ode z' = f(z), with N equidistant steps\n//! \\tparam StateType type of solution space z = [y,y']! and initial data z0 = [y(0), y'(0)]\n//! \\param[in] z0 initial data z(0)\n//! \\param[in] N number of equidistant steps\n//! \\param[in] T final time of simulation\n//! \\param[in] gamma parameter\n//! \\return vector containing each step of z_k (y and y')\ntemplate \nstd::vector sdirkSolve(const StateType & z0, unsigned int N, double T, double gamma) {\n // TODO: implement solution with SDIRK method\n}\n\nint main() {\n // Initial data z0 = [y(0), y'(0)]\n Eigen::Vector2d z0;\n z0 << 1,0;\n // Final time\n const double T = 10;\n // Parameter \n const double gamma = (3.+std::sqrt(3.)) / 6.;\n // Mesh sizes\n std::vector N = {20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240};\n // Exact solution (only y(t)) given z0 = [y(0), y'(0)] and t\n auto yex = [&z0] (double t) {\n return 1./3.*std::exp(-t/2.) * ( 3.*z0(0) * std::cos( std::sqrt(3.)*t/2. ) + \n std::sqrt(3.)*z0(0) * std::sin( std::sqrt(3.)*t/2. ) + \n 2.*std::sqrt(3.)*z0(1) * std::sin( std::sqrt(3.)*t/2. ) );\n };\n \n // TODO: compute solution and output error/approximate order\n}\n", "meta": {"hexsha": "09f47763b6961a85e84f95ecef9f784fa7ee64a9", "size": 1926, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS14/templates_ps14/sdirk_template.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS14/templates_ps14/sdirk_template.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS14/templates_ps14/sdirk_template.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.0384615385, "max_line_length": 97, "alphanum_fraction": 0.6100726895, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.865224070413529, "lm_q1q2_score": 0.6991592036778402}} {"text": "#include \n#include \n#include \n#include \n#include \"common.h\"\n\n#define TINYEXR_IMPLEMENTATION\n#include \"tinyexr.h\"\n\nusing namespace std;\n\n\nfloat L(float cosTheta, float rough, float f0, int s)\n{\n\tif (rough == 0) return schlick(cosTheta, f0);\n\tcosTheta = std::max(cosTheta, 0.001f); // avoid issues at exact grazing\n\n\tfloat sinTheta = std::sqrt(1 - sqr(cosTheta));\n\tVector3 incoming(sinTheta, 0, cosTheta);\n\tfloat alpha = sqr(rough);\n\tMicrofacetLobe lobe(alpha, f0, incoming);\n\tfloat total = 0;\n\n\tfor (int i = 0; i < s; i++)\n\t\tfor (int j = 0; j < s; j++)\n\t\t{\n\t\t\t// stratified sampling\n\t\t\tfloat r1 = (randf() + i) / s;\n\t\t\tfloat r2 = (randf() + j) / s;\n\t\t\tVector3 dir;\n\t\t\tfloat weight;\n\t\t\tbool ok = lobe.sample(r1, r2, dir, weight);\n\t\t\tif (!ok) continue;\n\t\t\ttotal += weight;\n\t\t}\n\n\ttotal /= s * s;\n\treturn total;\n}\n\nfloat T(int i, const FloatImage& img)\n{\n\t// computing the hemispherical integral in solid angle measure:\n\t// I = 1/pi * int[f(cos theta) * cos theta d omega]\n\n\t// this is turned into spherical coordinates, resulting in:\n\t// I = 2 int[f(cos theta) * cos theta * sin theta d theta] from 0 to pi/2\n\n\t// substitute t := cos theta, obtaining\n\t// I = 2 int[f(t) * t dt] from 0 to 1\n\t// compute the latter using trapezoid rule\n\n\tint n = img.cols();\n\tfloat total = 0;\n\n\tfor (int j = 0; j < n; j++)\n\t{\n\t\tfloat t = float(j) / (n - 1);\n\t\tfloat w = j == 0 || j == n-1 ? 0.5f : 1;\n\t\ttotal += 2 * t * img(i, j) * w / (n - 1);\n\t}\n\n\treturn total;\n}\n\nvoid writeExr(FloatImage& img, string filename)\n{\n\tint m = img.rows(), n = img.cols();\n\tColorImage tmp(m, n);\n\tfor (int i = 0; i < m; i++)\n\t\tfor (int j = 0; j < n; j++)\n\t\t\ttmp(i, j) = Color::Constant(img(i, j));\n\tSaveEXR((float*) &tmp(0,0), n, m, 3, 1, filename.c_str(), 0);\n}\n\nint main(int argc, char** argv)\n{\n\tint s = 100; // use s^2 stratified samples\n\tint n = 256; // result table size n x n\n\tfloat f0 = 0; // Schlick Fresnel normal incidence\n\n\tint tmp;\n\twhile ((tmp = getopt(argc, argv, \"n:s:f:\")) != -1)\n\t{\n\t\tswitch (tmp)\n\t\t{\n\t\t\tcase 'n': n = atoi(optarg); break;\n\t\t\tcase 's': s = atoi(optarg); break;\n\t\t\tcase 'f': f0 = atof(optarg); break;\n\t\t}\n\t}\n\n\tFloatImage Limg(n, n);\n\n\t#pragma omp parallel for\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 0; j < n; j++)\n\t\t{\n\t\t\tfloat rough = float(i) / (n - 1);\n\t\t\tfloat cosTheta = float(j) / (n - 1);\n\t\t\tLimg(i, j) = L(cosTheta, rough, f0, s);\n\t\t}\n\n\tFloatImage Timg(1, n);\n\tfor (int i = 0; i < n; i++) Timg(0, i) = T(i, Limg);\n\n\twriteExr(Limg, \"L.exr\");\n\twriteExr(Timg, \"T.exr\");\n\treturn 0;\n}\n\n", "meta": {"hexsha": "4bdc8487f00695731b046323e5eb757ba6e8ff46", "size": 2527, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "aps.cpp", "max_stars_repo_name": "miloshasan/aps", "max_stars_repo_head_hexsha": "e64eaecb076ca92d35495470eef6cae9d7d2b729", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aps.cpp", "max_issues_repo_name": "miloshasan/aps", "max_issues_repo_head_hexsha": "e64eaecb076ca92d35495470eef6cae9d7d2b729", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aps.cpp", "max_forks_repo_name": "miloshasan/aps", "max_forks_repo_head_hexsha": "e64eaecb076ca92d35495470eef6cae9d7d2b729", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5625, "max_line_length": 74, "alphanum_fraction": 0.5856747131, "num_tokens": 894, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788076, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6991556816715239}} {"text": "/*****************************************************************************\n*\n* Copyright (C) 2021 by Synge Todo \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 \n#include \n#include \n#include \n#include \n\ntemplate\nclass func {\npublic:\n typedef T real_t;\n func(real_t t) : t_(t) {}\n real_t operator()(real_t x, real_t xc) const {\n using std::abs; using std::cos; using std::log;\n if (x < t_ && xc > 0) {\n return cos(2 * x) * log(abs(2 * sin(xc / 2) * sin((t_ + x) / 2)));\n } else if (x > t_ && xc < 0) {\n return cos(2 * x) * log(abs(2 * sin(-xc / 2) * sin((t_ + x) / 2)));\n } else {\n real_t s = abs(cos(x) - cos(t_));\n return s > 0 ? cos(2 * x) * log(s) : real_t(0);\n }\n }\n real_t result() const {\n using std::cos;\n return -boost::math::constants::pi() * cos(2 * t_) / 2;\n }\nprivate:\n real_t t_;\n};\n\nint main() {\n using std::abs; using std::sqrt;\n typedef double real_t;\n const real_t pi = boost::math::constants::pi();\n\n boost::math::quadrature::tanh_sinh integrator;\n real_t termination = sqrt(std::numeric_limits::epsilon());\n \n real_t t = pi / 8;\n func f(t);\n real_t error, L1;\n size_t levels;\n real_t q1 = integrator.integrate(f, 0, t, termination, &error, &L1, &levels);\n std::cout << std::scientific << std::setprecision(std::numeric_limits::digits10)\n << \"lower part: \" << q1 << std::endl\n << \"estimated error: \" << error << std::endl\n << \"L1 * error: \" << L1 * error << std::endl\n << \"levels: \" << levels << std::endl;\n real_t q2 = integrator.integrate(f, t, pi, termination, &error, &L1, &levels);\n std::cout << \"upper part: \" << q2 << std::endl\n << \"estimated error: \" << error << std::endl\n << \"L1 * error: \" << L1 * error << std::endl\n << \"levels: \" << levels << std::endl;\n std::cout << \"result: \" << (q1 + q2) << std::endl\n << \"real error: \" << abs(q1 + q2 - f.result()) << std::endl;\n}\n", "meta": {"hexsha": "41964491125f74938aab56bf1b7f2bf7a74ea9d3", "size": 2337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tanh_sinh/example2.cpp", "max_stars_repo_name": "wistaria/boost-examples", "max_stars_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tanh_sinh/example2.cpp", "max_issues_repo_name": "wistaria/boost-examples", "max_issues_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tanh_sinh/example2.cpp", "max_forks_repo_name": "wistaria/boost-examples", "max_forks_repo_head_hexsha": "48a9f2fd50290a6be11a8dd68ef936da5d5e8a86", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4090909091, "max_line_length": 90, "alphanum_fraction": 0.5353016688, "num_tokens": 711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045847699186, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6990561692576199}} {"text": "//\n// neuralnetwork.h\n// NeuralNetwork\n//\n// Created by Nikhil Joshi on 10/15/14.\n// Copyright (c) 2014 Nikhil Joshi. All rights reserved.\n//\n\n#ifndef __NeuralNetwork__neuralnetwork__\n#define __NeuralNetwork__neuralnetwork__\n\n#define EIGEN_DEFAULT_TO_ROW_MAJOR\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"utility/utility.hpp\"\n#include \"utility/functionalitysuite.hpp\"\n\nnamespace NNetwork {\n \n class Network {\n public:\n // constructor\n Network(std::vector&& topology) {\n _topology = Eigen::toEigen(topology);\n initialize();\n }\n \n Network(std::initializer_list& ls)\n : Network(std::vector(ls))\n {\n }\n \n // Destructor\n ~Network(){\n for (int i = 0; i < _numLayers; i++)\n delete _functions[i];\n }\n \n \n // member functions\n // Setters/Getters\n // network topology\n void setTopology(const std::vector& topology);\n void setTopology(const std::initializer_list& topology);\n std::vector getTopology(void) const { return Eigen::toStdVector(_topology); }\n size_t numInputs(void) const { return _numInputs; }\n size_t numOutputs(void) const { return _numOutputs; }\n size_t numLayers(void) const { return _numLayers; }\n // weights\n std::vector> getWeightsAfterLayer(const unsigned int layer) const;\n Eigen::MatrixXd getWeightsAfterLayerEigen(const unsigned int layer) const;\n void printWeights(void) const;\n void setRandomWeights(void);\n void setRandomWeightsForLayer(unsigned int layer);\n void setWeightsAfterLayer(const unsigned int layer, const std::vector>& weights);\n void setWeightsAfterLayer(const unsigned int layer, const Eigen::Ref& weights);\n\n // activation function\n void setFunctionalityAtLayer(const unsigned int layer, FunctionalitySuite& suit);\n // make it a softmax output\n void setSoftmaxAtOutputLayer(void);\n bool isSoftmaxAtOutputLayer(void) { return _isSoftmax; }\n \n \n // Train the network on given examples\n // Data is assumed given in standard format :\n // One row = one (training) example n input/feature columns followed by m output/label columns\n double train(const char* dataFileName, const double regularizer,\n const bool verbose = true);\n double train(const Eigen::MatrixXd& data, const double regularizer,\n const bool verbose = true);\n \n // Predict\n unsigned int predict(const std::vector& input);\n \n \n // Test methods\n friend bool isValidNetworkImplementation(Network& testNet);\n \n \n private:\n\n Eigen::VectorXu _topology;\n std::vector _weights;\n std::vector _functions;\n size_t _numInputs, _numOutputs, _numLayers;\n bool _isSoftmax;\n \n // Member functions\n // initializers\n void initialize(void);\n void scaleWeightVectors(void);\n void setupDefaultNetwork(void);\n \n // Process input to produce output\n void processInput(const Eigen::Ref& input,\n std::vector& inputs,\n std::vector& activations);\n // Calculate loss for the given input - label pair\n double calculateLoss(const Eigen::Ref& data,\n const double regularizer = 0);\n double calculateLoss(const Eigen::Ref& input,\n const Eigen::Ref& label,\n const double regularizer = 0);\n \n // Calculate Error Delta by back Propagation\n void unregularizedLossAndWeightCorrectionsForExample(const Eigen::Ref& input,\n const Eigen::Ref& label,\n double& loss,\n std::vector& weightCorrections);\n void lossAndWeightCorrections(const Eigen::Ref& data,\n const double regularizer,\n double& loss,\n std::vector& weightCorrections);\n };\n \n\n // Network implementation checks\n bool isValidNetworkImplementation(Network& testNet);\n \n \n // include implementation file\n#include \"network.ipp\"\n \n}\n\n\n#endif /* defined(__NeuralNetwork__neuralnetwork__) */\n", "meta": {"hexsha": "4f221edb33abe9ff0f0f82b9aac07f774392b609", "size": 5154, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NeuralNetwork/network.hpp", "max_stars_repo_name": "nikhiljjoshi/neuralNetwork", "max_stars_repo_head_hexsha": "6c5df9e2fb1edac8c28d8bd191972d5f574fba83", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NeuralNetwork/network.hpp", "max_issues_repo_name": "nikhiljjoshi/neuralNetwork", "max_issues_repo_head_hexsha": "6c5df9e2fb1edac8c28d8bd191972d5f574fba83", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NeuralNetwork/network.hpp", "max_forks_repo_name": "nikhiljjoshi/neuralNetwork", "max_forks_repo_head_hexsha": "6c5df9e2fb1edac8c28d8bd191972d5f574fba83", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4626865672, "max_line_length": 110, "alphanum_fraction": 0.5871168025, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404077216355, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6989508628357679}} {"text": "#ifndef MPI_PI_PI_INCLUDED\n#define MPI_PI_PI_INCLUDED\n\n#include \"../include/common.hpp\"\n#include \"../include/random.hpp\"\n#include \n#include \n\nnamespace mpi_pi {\n\nnamespace area_integral {\n\ntemplate \nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n common::Division division(comm, terms);\n Number nterms = terms;\n Number delta = Number(1) / nterms;\n Number local_sum = 0;\n Number fxdx = 0;\n for (std::size_t i = division.first; i != division.last; ++i) {\n Number ni = i;\n Number x = ni / nterms;\n Number x1 = (ni + Number(1)) / nterms;\n Number fxdx1 = delta / (x1 * x1 + Number(1));\n if (i == division.first) {\n fxdx = delta / (x * x + Number(1));\n }\n local_sum += (fxdx + fxdx1) / Number(2);\n fxdx = fxdx1;\n }\n local_sum *= Number(4);\n Number result = 0;\n boost::mpi::reduce(comm, local_sum, result, std::plus(), root);\n return result;\n}\n\n} // namespace area_integral\n\nnamespace power_series {\n\ntemplate \nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n common::Division division(comm, terms);\n Number local_sum = 0;\n for (std::size_t i = division.first; i != division.last; ++i) {\n Number ni = i;\n Number term = Number(1) / (Number(2) * ni + Number(1));\n if (i % 2 == 1)\n term = -term;\n local_sum += term;\n }\n local_sum *= Number(4);\n Number result = 0;\n boost::mpi::reduce(comm, local_sum, result, std::plus(), root);\n return result;\n}\n\n} // namespace power_series\n\nnamespace improved_power_series {\n\ntemplate \nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n using boost::multiprecision::pow;\n using std::pow;\n\n common::Division division(comm, terms);\n Number local_sum = 0;\n for (std::size_t i = division.first; i != division.last; ++i) {\n Number ni = i;\n Number x = ni * Number(2) + Number(1);\n Number term5 = Number(4) / (x * pow(Number(5), x));\n Number term239 = Number(-1) / (x * pow(Number(239), x));\n if (i % 2 == 1) {\n term5 = -term5;\n term239 = -term239;\n }\n local_sum += term5 + term239;\n }\n local_sum *= Number(4);\n Number result = 0;\n boost::mpi::reduce(comm, local_sum, result, std::plus(), root);\n return result;\n}\n\n} // namespace improved_power_series\n\nnamespace monte_carlo {\n\ntemplate \nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n common::Division division(comm, terms);\n random::MinimunStandardEngine random_engine(comm, root);\n std::uniform_real_distribution dist(-1.0, 1.0);\n std::size_t local_hit = 0;\n for (std::size_t i = division.first; i != division.last; ++i) {\n auto x = dist(random_engine);\n auto y = dist(random_engine);\n if ((x * x + y * y) <= 1.0)\n local_hit += 1;\n }\n std::size_t total_hit = 0;\n boost::mpi::reduce(comm, local_hit, total_hit, std::plus(),\n root);\n Number result = 0;\n if (comm.rank() == root) {\n result = Number(total_hit) * Number(4) / Number(terms);\n }\n return result;\n}\n\n} // namespace monte_carlo\n\nnamespace monte_carlo_integral {\n\ntemplate \nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n common::Division division(comm, terms);\n random::MinimunStandardEngine random_engine(comm, root);\n std::uniform_real_distribution dist(0, 1.0);\n std::size_t local_hit = 0;\n for (std::size_t i = division.first; i != division.last; ++i) {\n auto x = dist(random_engine);\n auto y = dist(random_engine);\n double fx = 1.0 / (1.0 + x * x);\n if (y <= fx)\n local_hit += 1;\n }\n std::size_t total_hit = 0;\n boost::mpi::reduce(comm, local_hit, total_hit, std::plus(),\n root);\n Number result = 0;\n if (comm.rank() == root) {\n result = Number(total_hit) * Number(4) / Number(terms);\n }\n return result;\n}\n\n} // namespace monte_carlo_integral\n\nnamespace random_integral {\n\ntemplate \nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n common::Division division(comm, terms);\n random::MinimunStandardEngine random_engine(comm, root);\n std::uniform_real_distribution dist(0, 1.0);\n Number nterms = terms;\n Number delta = Number(1) / nterms;\n Number local_sum = 0;\n for (std::size_t i = division.first; i != division.last; ++i) {\n Number x = dist(random_engine);\n Number x1 = x + delta;\n Number fxdx = delta / (x * x + Number(1));\n Number fxdx1 = delta / (x1 * x1 + Number(1));\n local_sum += (fxdx + fxdx1) / Number(2);\n }\n local_sum *= Number(4);\n Number result = 0;\n boost::mpi::reduce(comm, local_sum, result, std::plus(), root);\n return result;\n}\n\n} // namespace random_integral\n\nnamespace borwein1987 {\n\ntemplate \nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n using boost::multiprecision::pow;\n using boost::multiprecision::sqrt;\n using std::pow;\n using std::sqrt;\n\n if (comm.rank() == root) {\n std::cerr << \"borwein1987 is an iterative method, will not run parallelized\"\n << std::endl;\n }\n Number x = sqrt(Number(2.0));\n Number p = Number(2) + sqrt(Number(2.0));\n Number y = pow(Number(2.0), Number(1.0) / Number(4.0));\n for (std::size_t i = 0; i != terms; ++i) {\n x = Number(0.5) * (sqrt(x) + Number(1) / sqrt(x));\n p *= (x + Number(1)) / (y + Number(1));\n y = (y * sqrt(x) + Number(1) / sqrt(x)) / (y + Number(1));\n }\n return p;\n}\n\n} // namespace borwein1987\n\nnamespace yasumasa2002 {\n\ntemplate \nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n using boost::multiprecision::pow;\n using std::pow;\n\n common::Division division(comm, terms);\n Number local_sum = 0;\n for (std::size_t i = division.first; i != division.last; ++i) {\n Number ni = i;\n Number x = ni * Number(2) + Number(1);\n Number term49 = Number(12) / (x * pow(Number(49), x));\n Number term57 = Number(32) / (x * pow(Number(57), x));\n Number term239 = Number(-5) / (x * pow(Number(239), x));\n Number term110443 = Number(12) / (x * pow(Number(110443), x));\n if (i % 2 == 1) {\n term49 = -term49;\n term57 = -term57;\n term239 = -term239;\n term110443 = -term110443;\n }\n local_sum += term49 + term57 + term239 + term110443;\n }\n local_sum *= Number(4);\n Number result = 0;\n boost::mpi::reduce(comm, local_sum, result, std::plus(), root);\n return result;\n}\n\n} // namespace yasumasa2002\n\nnamespace chudnovsky {\n\ntemplate \nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n using boost::multiprecision::pow;\n using boost::multiprecision::sqrt;\n using std::pow;\n using std::sqrt;\n\n if (comm.rank() == root) {\n std::cerr << \"this implementation of chudnovsky is iterative, will not run \"\n \"parallelized\"\n << std::endl;\n }\n\n Number K = 6;\n Number M = 1;\n Number L = 13591409;\n Number X = 1;\n Number x_multiplier = -pow(Number(640320), 3);\n Number sum = 13591409;\n for (std::size_t k = 0; k != terms; ++k) {\n M = (pow(K, Number(3)) - Number(16) * K) * M /\n pow(k + Number(1), Number(3));\n L += 545140134;\n X *= x_multiplier;\n sum += M * L / X;\n K += 12;\n }\n Number result = Number(426880) * sqrt(Number(10005)) / sum;\n return result;\n}\n\n} // namespace chudnovsky\n\nnamespace bbp {\n\ntemplate \nNumber pi(const boost::mpi::communicator &comm, int root, std::size_t terms) {\n using boost::multiprecision::pow;\n using std::pow;\n\n common::Division division(comm, terms);\n Number local_sum = 0;\n for (std::size_t i = division.first; i != division.last; ++i) {\n Number ni = Number(i);\n Number ni8 = Number(8) * ni;\n Number t1 = Number(4) / (ni8 + Number(1));\n Number t2 = Number(-2) / (ni8 + Number(4));\n Number t3 = Number(-1) / (ni8 + Number(5));\n Number t4 = Number(-1) / (ni8 + Number(6));\n Number term = (t1 + t2 + t3 + t4) / pow(Number(16), ni);\n local_sum += term;\n }\n Number result = 0;\n boost::mpi::reduce(comm, local_sum, result, std::plus(), root);\n return result;\n}\n\n} // namespace bbp\n\n} // namespace mpi_pi\n\n#endif", "meta": {"hexsha": "fa2e6b0fe0d158f254279ee1f01c8f1be3d2c9c0", "size": 8329, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pi.hpp", "max_stars_repo_name": "linyinfeng/mpi-pi", "max_stars_repo_head_hexsha": "661f2c7c55a5daedfa81503f780a6d0306a6a8c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/pi.hpp", "max_issues_repo_name": "linyinfeng/mpi-pi", "max_issues_repo_head_hexsha": "661f2c7c55a5daedfa81503f780a6d0306a6a8c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/pi.hpp", "max_forks_repo_name": "linyinfeng/mpi-pi", "max_forks_repo_head_hexsha": "661f2c7c55a5daedfa81503f780a6d0306a6a8c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0209059233, "max_line_length": 80, "alphanum_fraction": 0.6276863969, "num_tokens": 2515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7905303087996143, "lm_q1q2_score": 0.6988598512200584}} {"text": "/**\n * @file sdirk.cc\n * @brief NPDE homework SDIRK code\n * @author Unknown, Oliver Rietmann\n * @date 31.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"sdirk.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"polyfit.h\"\n\nnamespace SDIRK {\n\n/* SAM_LISTING_BEGIN_0 */\nEigen::Vector2d sdirkStep(const Eigen::Vector2d &z0, double h, double gamma) {\n Eigen::Vector2d res;\n // TO DO (13-3.f): compute one timestep of the ODE\n#if SOLUTION\n // Matrix A for evaluation of f\n Eigen::Matrix2d A;\n A << 0., 1., -1., -1.;\n // Reuse factorization\n auto A_lu = (Eigen::Matrix2d::Identity() - h * gamma * A).partialPivLu();\n Eigen::Vector2d az = A * z0;\n\n // Increments\n Eigen::Vector2d k1 = A_lu.solve(az);\n Eigen::Vector2d k2 = A_lu.solve(az + h * (1 - 2 * gamma) * A * k1);\n\n // Next step\n res = z0 + h * 0.5 * (k1 + k2);\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return res;\n}\n/* SAM_LISTING_END_0 */\n\n/* SAM_LISTING_BEGIN_1 */\nstd::vector sdirkSolve(const Eigen::Vector2d &z0,\n unsigned int N, double T,\n double gamma) {\n // Solution vector\n std::vector res(N + 1);\n // TO DO (13-3.g): solve the ODE with uniform timesteps using the SDIRK method\n#if SOLUTION\n // Equidistant step size\n const double h = T / N;\n // Push initial data\n res.at(0) = z0;\n // Main loop\n for (unsigned int i = 1; i <= N; ++i) {\n res.at(i) = sdirkStep(res.at(i - 1), h, gamma);\n }\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return res;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\ndouble cvgSDIRK() {\n double conv_rate;\n // TO DO (13-3.g) study the convergence rate of the method.\n#if SOLUTION\n // Initial data z0 = [y(0), y'(0)]\n Eigen::Vector2d z0;\n z0 << 1, 0;\n // Final time\n const double T = 10;\n // Parameter\n const double gamma = (3. + std::sqrt(3.)) / 6.;\n // Mesh sizes\n Eigen::ArrayXd err(10);\n Eigen::ArrayXd N(10);\n N << 20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240;\n\n // Exact solution (only y(t)) given z0 = [y(0), y'(0)] and t\n auto yex = [&z0](double t) {\n return 1. / 3. * std::exp(-t / 2.) *\n (3. * z0(0) * std::cos(std::sqrt(3.) * t / 2.) +\n std::sqrt(3.) * z0(0) * std::sin(std::sqrt(3.) * t / 2.) +\n 2. * std::sqrt(3.) * z0(1) * std::sin(std::sqrt(3.) * t / 2.));\n };\n\n // Store old error for rate computation\n double errold = 0;\n std::cout << std::setw(15) << \"n\" << std::setw(15) << \"maxerr\"\n << std::setw(15) << \"rate\" << std::endl;\n // Loop over all meshes\n for (unsigned int i = 0; i < N.size(); ++i) {\n int n = N(i);\n // Get solution\n auto sol = sdirkSolve(z0, n, T, gamma);\n // Compute error\n err(i) = std::abs(sol.back()(0) - yex(T));\n\n // Print table\n std::cout << std::setw(15) << n << std::setw(15) << err(i);\n if (i > 0) std::cout << std::setw(15) << std::log2(errold / err(i));\n std::cout << std::endl;\n\n // Store old error\n errold = err(i);\n }\n // Eigen::VectorXd Neig(N.data());\n // Eigen::VectorXd erreig (err.data());\n Eigen::VectorXd coeffs = polyfit(N.log(), err.log(), 1);\n conv_rate = -coeffs(0);\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return conv_rate;\n}\n/* SAM_LISTING_END_2 */\n\n} // namespace SDIRK\n", "meta": {"hexsha": "c25bcb83929e9fb0ce15a4c81d3df907de27ed1c", "size": 3487, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/SDIRK/mastersolution/sdirk.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "developers/SDIRK/mastersolution/sdirk.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "developers/SDIRK/mastersolution/sdirk.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4166666667, "max_line_length": 80, "alphanum_fraction": 0.5468884428, "num_tokens": 1186, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891435927269, "lm_q2_score": 0.8499711737573763, "lm_q1q2_score": 0.6988370714300821}} {"text": "//\n// hough3dlines.cpp\n// Main program implementing the iterative Hough transform\n//\n// Author: Tilman Schramke, Christoph Dalitz\n// Date: 2020-01-15\n// License: see License-BSD2\n//\n\n#include \"vector3d.h\"\n#include \"pointcloud.h\"\n#include \"hough.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing Eigen::MatrixXf;\nusing namespace std;\n\n// usage message\nconst char* usage = \"Usage:\\n\"\n \"\\though3dlines [options] \\n\"\n \"Options (defaults in brackets):\\n\"\n \"\\t-o write results to [stdout]\\n\"\n \"\\t-dx step width in x'y'-plane [0]\\n\"\n \"\\t when =0, it is set to 1/64 of total width\\n\"\n \"\\t-nlines maximum number of lines returned [0]\\n\"\n \"\\t when =0, all lines are returned\\n\"\n \"\\t-minvotes only lines with at least points are returned [0]\\n\"\n \"\\t-gnuplot print result as a gnuplot command\\n\"\n \"\\t-raw print plot data in easily machine-parsable format\\n\"\n \"\\t-delim use as field delimiter in input file [,]\\n\"\n \"\\t-v be verbose and print Hough space size to stdout\\n\"\n \"\\t-vv be even more verbose and print Hough lines (before LSQ)\\n\"\n \"Version:\\n\"\n \"\\t1.2 from 2020-01-15\\n\";\n\n//--------------------------------------------------------------------\n// utility functions\n//--------------------------------------------------------------------\n\n//\n// orthogonal least squares fit with libeigen\n// rc = largest eigenvalue\n//\ndouble orthogonal_LSQ(const PointCloud &pc, Vector3d* a, Vector3d* b){\n double rc = 0.0;\n\n // anchor point is mean value\n *a = pc.meanValue();\n\n // copy points to libeigen matrix\n Eigen::MatrixXf points = Eigen::MatrixXf::Constant(pc.points.size(), 3, 0);\n for (int i = 0; i < points.rows(); i++) {\n points(i,0) = pc.points.at(i).x;\n points(i,1) = pc.points.at(i).y;\n points(i,2) = pc.points.at(i).z;\n }\n\n // compute scatter matrix ...\n MatrixXf centered = points.rowwise() - points.colwise().mean();\n MatrixXf scatter = (centered.adjoint() * centered);\n\n // ... and its eigenvalues and eigenvectors\n Eigen::SelfAdjointEigenSolver eig(scatter);\n Eigen::MatrixXf eigvecs = eig.eigenvectors();\n\n // we need eigenvector to largest eigenvalue\n // libeigen yields it as LAST column\n b->x = eigvecs(0,2); b->y = eigvecs(1,2); b->z = eigvecs(2,2);\n rc = eig.eigenvalues()(2);\n\n return (rc);\n}\n\n\n//--------------------------------------------------------------------\n// main program\n//--------------------------------------------------------------------\n\nint main(int argc, char ** argv) {\n\n // default values for command line options\n double opt_dx = 0.0;\n int opt_nlines = 0;\n int opt_minvotes = 0;\n enum Outformat { format_normal, format_gnuplot, format_raw };\n Outformat opt_outformat = format_normal;\n char opt_delim = ',';\n int opt_verbose = 0;\n char* infile_name = NULL;\n char* outfile_name = NULL;\n\n // number of icosahedron subdivisions for direction discretization\n int granularity = 4;\n int num_directions[7] = {12, 21, 81, 321, 1281, 5121, 20481};\n\n // IO files\n //FILE* infile = NULL;\n FILE* outfile = stdout;\n\n // bounding box of point cloud\n Vector3d minP, maxP, minPshifted, maxPshifted;\n // diagonal length of point cloud\n double d;\n\n // parse command line\n for (int i=1; i= d) {\n fprintf(stderr, \"Error: dx too large\\n\");\n return 1;\n }\n double num_x = floor(d / opt_dx + 0.5);\n double num_cells = num_x * num_x * num_directions[granularity];\n if (opt_verbose) {\n printf(\"info: x'y' value range is %f in %.0f steps of width dx=%f\\n\",\n d, num_x, opt_dx);\n printf(\"info: Hough space has %.0f cells taking %.2f MB memory space\\n\",\n num_cells, num_cells * sizeof(unsigned int) / 1000000.0);\n }\n#ifdef WEBDEMO\n if (num_cells > 1E8) {\n fprintf(stderr, \"Error: program was compiled in WEBDEMO mode, \"\n \"which does not permit %.0f cells in Hough space\\n\", num_cells);\n return 2;\n }\n#endif\n\n // first Hough transform\n Hough* hough;\n try {\n hough = new Hough(minPshifted, maxPshifted, opt_dx, granularity);\n } catch (const std::exception &e) {\n fprintf(stderr, \"Error: cannot allocate memory for %.0f Hough cells\"\n \" (%.2f MB)\\n\", num_cells, \n (double(num_cells) / 1000000.0) * sizeof(unsigned int));\n return 2;\n }\n hough->add(X);\n\n // print header info if necessary\n if (opt_outformat == format_gnuplot) {\n fprintf(outfile, \"set datafile separator '%c'\\n\"\n \"set parametric\\n\"\n \"set xrange [%f:%f]\\n\"\n \"set yrange [%f:%f]\\n\"\n \"set zrange [%f:%f]\\n\"\n \"set urange [%f:%f]\\n\"\n \"splot '%s' using 1:2:3 with points palette\",\n opt_delim,\n minP.x, maxP.x, minP.y, maxP.y, minP.z, maxP.z,\n -d, d, infile_name);\n }\n else if (opt_outformat == format_raw) {\n fprintf(outfile, \"%f %f %f %f %f %f\\n%f %f\\n\",\n minP.x, maxP.x, minP.y, maxP.y, minP.z, maxP.z, -d, d);\n }\n \n // iterative Hough transform\n // (Algorithm 1 in IPOL paper)\n PointCloud Y;\t// points close to line\n double rc;\n unsigned int nvotes;\n int nlines = 0;\n do {\n Vector3d a; // anchor point of line\n Vector3d b; // direction of line\n\n hough->subtract(Y); // do it here to save one call\n\n nvotes = hough->getLine(&a, &b);\n if (opt_verbose > 1) {\n Vector3d p = a + X.shift;\n printf(\"info: highest number of Hough votes is %i for the following \"\n \"line:\\ninfo: a=(%f,%f,%f), b=(%f,%f,%f)\\n\",\n nvotes, p.x, p.y, p.z, b.x, b.y, b.z);\n }\n\n X.pointsCloseToLine(a, b, opt_dx, &Y);\n\n rc = orthogonal_LSQ(Y, &a, &b);\n if (rc==0.0) break;\n\n X.pointsCloseToLine(a, b, opt_dx, &Y);\n nvotes = Y.points.size();\n if (nvotes < (unsigned int)opt_minvotes) break;\n\n rc = orthogonal_LSQ(Y, &a, &b);\n if (rc==0.0) break;\n\n a = a + X.shift;\n\n nlines++;\n if (opt_outformat == format_normal) {\n fprintf(outfile, \"npoints=%lu, a=(%f,%f,%f), b=(%f,%f,%f)\\n\",\n Y.points.size(), a.x, a.y, a.z, b.x, b.y, b.z);\n }\n else if (opt_outformat == format_gnuplot) {\n fputs(\", \\\\\\n \", outfile);\n fprintf(outfile, \"%f + u * %f, %f + u * %f, %f + u * %f \"\n \"with lines notitle lc rgb 'black'\",\n a.x, b.x, a.y, b.y, a.z, b.z);\n }\n else {\n fprintf(outfile, \"%f %f %f %f %f %f %lu\\n\",\n a.x, a.y, a.z, b.x, b.y, b.z, Y.points.size());\n }\n\n X.removePoints(Y);\n\n } while ((X.points.size() > 1) && \n ((opt_nlines == 0) || (opt_nlines > nlines)));\n\n // final newline in gnuplot command\n if (opt_outformat == format_gnuplot)\n fputs(\"\\n\", outfile);\n \n // clean up\n delete hough;\n if (outfile_name) fclose(outfile);\n\n return 0;\n}\n", "meta": {"hexsha": "912eedab04b43a0e48aa840195b5be3b1e57f1c6", "size": 9381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hough3dlines.cpp", "max_stars_repo_name": "estebanrdo/hough-3d-lines", "max_stars_repo_head_hexsha": "15e886a8c0ede648a2a7154d096a06020861fb07", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2020-04-25T14:06:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T09:14:27.000Z", "max_issues_repo_path": "hough3dlines.cpp", "max_issues_repo_name": "estebanrdo/hough-3d-lines", "max_issues_repo_head_hexsha": "15e886a8c0ede648a2a7154d096a06020861fb07", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hough3dlines.cpp", "max_forks_repo_name": "estebanrdo/hough-3d-lines", "max_forks_repo_head_hexsha": "15e886a8c0ede648a2a7154d096a06020861fb07", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-04-20T13:35:24.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-04T10:35:43.000Z", "avg_line_length": 28.5136778116, "max_line_length": 79, "alphanum_fraction": 0.5630529794, "num_tokens": 2908, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.8499711775577736, "lm_q1q2_score": 0.6988370634449442}} {"text": "#include \"triangle.hpp\"\n\n#include \n#include \n#include \n\n#include \n\n#include \"base-types.hpp\"\n\nnamespace\n{\n bool areValidVertices(const yakovlev::point_t vertices[3]);\n}\n\nyakovlev::Triangle::Triangle(\n const point_t & vertice1,\n const point_t & vertice2,\n const point_t & vertice3,\n double rotation\n) :\n vertices_{ vertice1, vertice2, vertice3 },\n pos_{ (vertice1.x + vertice2.x + vertice3.x) / 3.0, (vertice1.y + vertice2.y + vertice3.y) / 3.0 }\n{\n if (!areValidVertices(vertices_)) {\n throw std::invalid_argument{ \"Triangle must not be degenerate\" };\n }\n rotate(rotation);\n}\n\nbool yakovlev::Triangle::operator==(const Triangle & other) const noexcept\n{\n for (const point_t & vert : vertices_) {\n bool hasEqual = false;\n for (const point_t & othervert : other.vertices_) {\n if (vert == othervert) {\n hasEqual = true;\n }\n }\n if (!hasEqual) {\n return false;\n }\n }\n return true;\n}\n\nbool yakovlev::Triangle::operator!=(const Triangle & other) const noexcept\n{\n return !(*this == other);\n}\n\nyakovlev::point_t yakovlev::Triangle::getCenter() const noexcept\n{\n return pos_;\n}\n\ndouble yakovlev::Triangle::getArea() const noexcept\n{\n return std::abs(vertices_[0].x * (vertices_[1].y - vertices_[2].y)\n + vertices_[1].x * (vertices_[2].y - vertices_[0].y)\n + vertices_[2].x * (vertices_[0].y - vertices_[1].y))\n / 2.0;\n}\n\nyakovlev::rectangle_t yakovlev::Triangle::getFrameRect() const noexcept\n{\n double maxX = vertices_[0].x, maxY = vertices_[0].y;\n double minX = vertices_[0].x, minY = vertices_[0].y;\n for (int i = 1; i < 3; ++i) {\n minX = std::min(vertices_[i].x, minX);\n maxX = std::max(vertices_[i].x, maxX);\n minY = std::min(vertices_[i].y, minY);\n maxY = std::max(vertices_[i].y, maxY);\n }\n \n double width = maxX - minX, height = maxY - minY;\n return { width, height, { minX + (width / 2.0), minY + (height / 2.0) } };\n}\n\nvoid yakovlev::Triangle::move(const point_t & pos) noexcept\n{\n move(pos.x - pos_.x, pos.y - pos_.y);\n}\n\nvoid yakovlev::Triangle::move(double x, double y) noexcept\n{\n for (point_t &vert : vertices_) {\n vert.x += x;\n vert.y += y;\n }\n pos_.x += x;\n pos_.y += y;\n}\n\nvoid yakovlev::Triangle::rotate(double rotation) noexcept\n{\n double rad = rotation * M_PI / 180.0;\n double rotSin = sin(rad);\n double rotCos = cos(rad);\n for (point_t & vert : vertices_) {\n point_t local = { vert.x - pos_.x, vert.y - pos_.y };\n vert = {\n pos_.x + local.x * rotCos - local.y * rotSin,\n pos_.y + local.x * rotSin + local.y * rotCos\n };\n }\n}\n\nvoid yakovlev::Triangle::scale(double coef)\n{\n if (coef <= 0.0) {\n throw std::invalid_argument{ (boost::format(\"Invalid rectangle scale coefficient %1% - can not be negative or zero\") % coef ).str() };\n }\n for (point_t & vert : vertices_) {\n vert = {\n pos_.x + (vert.x - pos_.x) * coef,\n pos_.y + (vert.y - pos_.y) * coef\n };\n }\n}\n\nvoid yakovlev::Triangle::print(std::ostream & os) const\n{\n os << \"Triangle with verticies on \" << vertices_[0] << \", \" << vertices_[1]\n << \", \" << vertices_[2] << '\\n';\n}\n\nnamespace\n{\n bool areValidVertices(const yakovlev::point_t vertices[3])\n {\n double sides[3] = { \n yakovlev::getDistanceBetweenPoints(vertices[0], vertices[1]),\n yakovlev::getDistanceBetweenPoints(vertices[1], vertices[2]),\n yakovlev::getDistanceBetweenPoints(vertices[0], vertices[2])\n };\n return ((sides[0] + sides[1]) > sides[2]) \n && ((sides[0] + sides[2]) > sides[1]) \n && ((sides[1] + sides[2]) > sides[0]); \n }\n}\n", "meta": {"hexsha": "6449f6b0e54102d646b45fb79e4de5f18aeff433", "size": 3629, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/triangle.cpp", "max_stars_repo_name": "NekoSilverFox/CPP", "max_stars_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-02-08T20:57:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-23T06:24:41.000Z", "max_issues_repo_path": "508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/triangle.cpp", "max_issues_repo_name": "NekoSilverFox/CPP", "max_issues_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-03-02T14:44:55.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-11T16:25:33.000Z", "max_forks_repo_path": "508 - A4-spbspu-labs-2020-904-3/spbspu-labs-2020-904-3-master-yakovlev.alexey/3/common/triangle.cpp", "max_forks_repo_name": "NekoSilverFox/CPP", "max_forks_repo_head_hexsha": "c6797264fceda4a65ac3452acca496e468d1365a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-27T17:30:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-16T09:48:23.000Z", "avg_line_length": 25.5563380282, "max_line_length": 138, "alphanum_fraction": 0.612565445, "num_tokens": 1109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178969328287, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6988000771980137}} {"text": "/*\n * trajectory_factory.hpp\n *\n * Author(s): Tamas D. Nagy\n *\tCreated on: 2016-10-25\n *\n * Static class to generate simple trajectories\n * built of any corresponding data type.\n *\n */\n\n#ifndef DVRK_TRAJECTORY_FACTORY_HPP_\n#define DVRK_TRAJECTORY_FACTORY_HPP_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"irob_utils/trajectory.hpp\"\n#include \"irob_utils/utils.hpp\"\n#include \"irob_utils/tool_pose.hpp\"\n\n\nnamespace saf {\n\nclass TrajectoryFactory\n{\n\nprivate:\n TrajectoryFactory() {}\npublic:\n\n\n /**\n *\tUniform ramp between x1 and x2.\n */\n static Trajectory uniformRamp(int N,\n double x1=0.0, double x2=1.0)\n {\n Trajectory v;\n for (int i = 0; i < N; i++)\n {\n v.addPoint(interpolate(((double)i)/(N-1), x1, x2));\n }\n return v;\n }\n\n\n /**\n *\tAccelerating ramp between x1 and x2.\n *\tFor decceleration: acceleratingRamp(N, x2, x1).reverse().\n */\n static Trajectory acceleratingRamp(int N,\n double x1=0.0, double x2=1.0)\n {\n Trajectory v, steps;\n double maxStep = (2.0*(x2-x1))/N;\n steps = uniformRamp(N, 0.0, maxStep);\n\n double a = x1;\n for (int i = 0; i < N; i++)\n {\n a += steps[i];\n v.addPoint(interpolate(a, x1, x2));\n }\n return v;\n }\n\n\n /**\n *\tSmooth ramp between x1 and x2.\n */\n static Trajectory smoothenedRamp(int Nfull, int Nacc, int Ndecc,\n double x1=0.0, double x2=1.0)\n {\n Trajectory v, stepsAcc, stepsDecc;\n\n if (Nfull < Nacc || Nfull < Ndecc)\n throw std::runtime_error(\"Trajectory Nacc > Nfull\");\n\n double accRatio = ((double)Nacc) / Nfull;\n double deccRatio = ((double)Ndecc) / Nfull;\n double maxStep = (x2-x1)/(Nfull-((Nacc+Ndecc)/2.0));\n stepsAcc = uniformRamp(Nacc, 0.0, maxStep);\n stepsDecc = uniformRamp(Ndecc, maxStep, 0.0);\n\n double a = x1;\n for (int i = 0; i < Nacc; i++)\n {\n a += stepsAcc[i];\n v.addPoint(interpolate(a, x1, x2));\n }\n\n for (int i = 0; i < Nfull-(Nacc + Ndecc); i++)\n {\n a += maxStep;\n v.addPoint(interpolate(a, x1, x2));\n }\n\n for (int i = 0; i < Ndecc; i++)\n {\n a += stepsDecc[i];\n v.addPoint(interpolate(a, x1, x2));\n }\n return v;\n }\n\n\n /**\n * Linear trajectory between start and end, with constant speed.\n */\n template \n static Trajectory

linearTrajectory(P start,P end,\n double speed, double dt)\n {\n Trajectory

tr(dt);\n double stepSize = speed * dt;\n int N = (int)round(distanceEuler(start, end) / stepSize)+1;\n Trajectory ramp = uniformRamp(N);\n for (int i = 0; i < ramp.size(); i++)\n {\n tr.addPoint(interpolate(ramp[i], start, end));\n }\n return tr;\n }\n\n /**\n *\tSmoothly accelerationg trajectory between 2 points.\n */\n template \n static Trajectory

linearTrajectoryWithSmoothAcceleration(\n P start,\n P end,\n double speed,\n double acc,\n double dt)\n {\n Trajectory

tr(dt);\n double s_full = distanceEuler(start, end);\n if (s_full < 0.00001)\n return tr;\n\n double t_acc = speed / acc;\n double s_acc = 0.5 * acc * t_acc * t_acc;\n\n double t_full = (2.0 * t_acc) + ((s_full-(2.0 * s_acc)) / speed);\n\n int N_full = (int)round(t_full / dt)+1;\n int N_acc = (int)round(t_acc / dt)+1;\n\n Trajectory ramp = smoothenedRamp(N_full, N_acc, N_acc);\n\n for (int i = 0; i < ramp.size(); i++)\n {\n tr.addPoint(interpolate(ramp[i], start, end));\n }\n return tr;\n }\n\n\n /**\n *\tSmoothly accelerationg trajectory between 2 points with waypoints.\n */\n template \n static Trajectory

linearTrajectoryWithSmoothAcceleration(\n P start,\n std::vector

waypoints,\n P end,\n double speed,\n double acc,\n double dt)\n {\n if (waypoints.empty())\n return linearTrajectoryWithSmoothAcceleration(\n start, end, speed, acc, dt);\n Trajectory

tr(dt);\n\n // To first waypoints\n double s_full = distanceEuler(start, waypoints[0]);\n double t_acc = speed / acc;\n double s_acc = 0.5 * acc * t_acc * t_acc;\n double t_full = t_acc + ((s_full-s_acc) / speed);\n\n int N_full = (int)round(t_full / dt)+1;\n int N_acc = (int)round(t_acc / dt)+1;\n Trajectory acc_ramp = smoothenedRamp(N_full, N_acc, 0);\n\n for (int i = 0; i < acc_ramp.size(); i++)\n {\n tr.addPoint(interpolate(acc_ramp[i], start, waypoints[0]));\n }\n\n // Between waypoints\n for(typename std::vector

::size_type i = 0;\n i < waypoints.size()-1; i++)\n {\n s_full = distanceEuler(waypoints[i],waypoints[i+1]);\n t_full = s_full / speed;\n\n N_full = (int)round(t_full / dt)+1;\n Trajectory ramp = uniformRamp(N_full);\n for (int j = 0; j < ramp.size(); j++)\n {\n tr.addPoint(interpolate(ramp[j],\n waypoints[i],\n waypoints[i+1]));\n }\n }\n\n // To endpoint\n s_full = distanceEuler(waypoints.back(), end);\n t_acc = speed / acc;\n s_acc = 0.5 * acc * t_acc * t_acc;\n t_full = t_acc + ((s_full-s_acc) / speed);\n\n N_full = (int)round(t_full / dt)+1;\n N_acc = (int)round(t_acc / dt)+1;\n\n Trajectory decc_ramp = smoothenedRamp(N_full, 0, N_acc);\n for (int i = 0; i < decc_ramp.size(); i++)\n {\n tr.addPoint(interpolate(decc_ramp[i],\n waypoints.back(),\n end));\n }\n\n return tr;\n }\n\n\n /**\n * Horizontal circular trajectory around center.\n */\n static Trajectory circleTrajectoryHorizontal(\n Eigen::Vector3d start,\n double toAngle, Eigen::Vector3d center,\n double T, double dt)\n {\n Trajectory tr(dt);\n int N = (int)round(T / dt)+1;\n Trajectory ramp = uniformRamp(N, 0.0, toAngle);\n for (int i = 0; i < ramp.size(); i++)\n {\n Eigen::Vector3d p = start-center;\n Eigen::Vector3d p1(p.x()*cos(ramp[i])-p.y()*sin(ramp[i]),\n p.y()*cos(ramp[i])+p.x()*sin(ramp[i]), p.z());\n Eigen::Vector3d p2 = p1+center;\n tr.addPoint(p2);\n }\n return tr;\n }\n\n\n /**\n * Horizontal circular trajectory around center.\n */\n static Trajectory circleTrajectoryHorizontal(\n ToolPose start,\n double toAngle, Eigen::Vector3d center,\n double T, double dt)\n {\n Trajectory tr(dt);\n int N = (int)round(T / dt)+1;\n Trajectory ramp = uniformRamp(N, 0.0, toAngle);\n for (int i = 0; i < ramp.size(); i++)\n {\n Eigen::Vector3d p = start.transform.translation()-center;\n Eigen::Vector3d p1(p.x()*cos(ramp[i])-p.y()*sin(ramp[i]),\n p.y()*cos(ramp[i])+p.x()*sin(ramp[i]), p.z());\n Eigen::Vector3d p2 = p1+center;\n ToolPose po2(p2, Eigen::Quaterniond(start.transform.rotation()), start.jaw);\n tr.addPoint(po2);\n }\n return tr;\n }\n\n\n /**\n * Vertical circular trajectory around center in Y plane.\n */\n static Trajectory circleTrajectoryVerticalY(\n Eigen::Vector3d start,\n double toAngle, Eigen::Vector3d center,\n double T, double dt)\n {\n Trajectory tr(dt);\n int N = (int)round(T / dt)+1;\n Trajectory ramp = uniformRamp(N, 0.0, toAngle);\n for (int i = 0; i < ramp.size(); i++)\n {\n Eigen::Vector3d p = start-center;\n Eigen::Vector3d p1(p.x(),\n p.y()*cos(ramp[i])+p.z()*sin(ramp[i]), p.z()*cos(ramp[i])-p.y()*sin(ramp[i]));\n Eigen::Vector3d p2 = p1+center;\n tr.addPoint(p2);\n }\n return tr;\n }\n\n\n /**\n * Vertical circular trajectory around center in X plane.\n */\n static Trajectory circleTrajectoryVerticalX(\n Eigen::Vector3d start,\n double toAngle, Eigen::Vector3d center,\n double T, double dt)\n {\n Trajectory tr(dt);\n int N = (int)round(T / dt)+1;\n Trajectory ramp = uniformRamp(N, 0.0, toAngle);\n for (int i = 0; i < ramp.size(); i++)\n {\n Eigen::Vector3d p = start-center;\n Eigen::Vector3d p1(p.x()*cos(ramp[i])+p.z()*sin(ramp[i]),\n p.y(), p.z()*cos(ramp[i])-p.x()*sin(ramp[i]));\n Eigen::Vector3d p2 = p1+center;\n tr.addPoint(p2);\n }\n return tr;\n }\n\n};\n\n}\n\n#endif\n", "meta": {"hexsha": "5df761be236ae18537532931d744304e05d0bf60", "size": 8534, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "irob_utils/include/irob_utils/trajectory_factory.hpp", "max_stars_repo_name": "ABC-iRobotics/irob-saf", "max_stars_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-06-07T22:56:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T14:56:36.000Z", "max_issues_repo_path": "irob_utils/include/irob_utils/trajectory_factory.hpp", "max_issues_repo_name": "ABC-iRobotics/irob-saf", "max_issues_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-12-19T10:04:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-19T13:45:25.000Z", "max_forks_repo_path": "irob_utils/include/irob_utils/trajectory_factory.hpp", "max_forks_repo_name": "ABC-iRobotics/irob-saf", "max_forks_repo_head_hexsha": "27832e1657912f7ad7e9812bb5020d6254137454", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-05-24T23:45:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T23:33:43.000Z", "avg_line_length": 25.8606060606, "max_line_length": 103, "alphanum_fraction": 0.5701898289, "num_tokens": 2542, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218327098193, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6986271654969143}} {"text": "#ifndef DZNL_BFGS_OPTIMIZER_HPP_INCLUDED\n#define DZNL_BFGS_OPTIMIZER_HPP_INCLUDED\n\n// C++ standard library headers\n#include // for std::size_t\n#include // for std::function\n\n// Eigen linear algebra library headers\n#include \n\n// Project-specific headers\n#include \"QuadraticLineSearcher.hpp\"\n\nnamespace dznl {\n\n enum class StepType { NONE, GRAD, BFGS };\n\n template \n class BFGSOptimizer {\n private: // ========================================== INTERNAL TYPE ALIASES\n typedef std::function objective_function_t;\n typedef std::function objective_gradient_t;\n\n typedef Eigen::Matrix MatrixXT;\n typedef Eigen::Matrix VectorXT;\n\n private: // =============================================== MEMBER VARIABLES\n const std::size_t n;\n const objective_function_t f;\n const objective_gradient_t g;\n\n VectorXT x;\n T fx;\n VectorXT gx;\n VectorXT dg;\n\n T step_size;\n VectorXT step_dir;\n VectorXT grad_dir;\n MatrixXT hess_inv;\n\n VectorXT temp;\n std::size_t iter_count;\n StepType last_step_type;\n\n public: // ===================================================== CONSTRUCTOR\n BFGSOptimizer(std::size_t num_dimensions,\n const objective_function_t &objective_function,\n const objective_gradient_t &objective_gradient)\n : n(num_dimensions),\n f(objective_function),\n g(objective_gradient),\n x(n),\n fx(0),\n gx(n),\n dg(n),\n step_size(0),\n step_dir(n),\n grad_dir(n),\n hess_inv(n, n),\n temp(n),\n iter_count(0),\n last_step_type(StepType::NONE) {\n hess_inv.setIdentity();\n }\n\n public: // ======================================================= ACCESSORS\n const VectorXT &get_current_point() { return x; }\n\n T get_current_objective_value() { return fx; }\n\n const VectorXT &get_current_gradient() { return gx; }\n\n std::size_t get_iteration_count() { return iter_count; }\n\n T get_last_step_size() { return step_size; }\n\n StepType get_last_step_type() { return last_step_type; }\n\n public: // ======================================================== MUTATORS\n void set_current_point(const VectorXT &p) {\n x = p;\n fx = f(p.data());\n g(gx.data(), p.data());\n }\n\n void set_iteration_count(std::size_t k) { iter_count = k; }\n\n void set_step_size(const T &h) { step_size = h; }\n\n private: // ==================================== OPTIMIZATION HELPER METHODS\n void reset_hessian() { hess_inv.setIdentity(); }\n\n void update_inverse_hessian() {\n temp = hess_inv.template selfadjointView() * dg;\n const T lambda = step_size * dg.dot(step_dir);\n const T sigma = (lambda + dg.dot(temp)) / (lambda * lambda);\n temp -= (step_size * lambda * sigma / 2) * step_dir;\n hess_inv.template selfadjointView().rankUpdate(\n temp, step_dir, -step_size / lambda);\n }\n\n T competitive_line_search() {\n dznl::QuadraticLineSearcher grad_searcher(f, x, grad_dir);\n grad_searcher.search(step_size);\n dznl::QuadraticLineSearcher bfgs_searcher(f, x, step_dir);\n bfgs_searcher.search(step_size);\n if (grad_searcher.get_best_objective_value() <\n bfgs_searcher.get_best_objective_value()) {\n last_step_type = StepType::GRAD;\n step_dir = grad_dir;\n reset_hessian();\n fx = grad_searcher.get_best_objective_value();\n return grad_searcher.get_best_step_size();\n } else {\n last_step_type = StepType::BFGS;\n fx = bfgs_searcher.get_best_objective_value();\n return bfgs_searcher.get_best_step_size();\n }\n }\n\n public: // ============================================ OPTIMIZATION METHODS\n bool step() {\n grad_dir = -gx.normalized();\n step_dir =\n -(hess_inv.template selfadjointView() * gx);\n step_dir.normalize();\n const T new_step_size = competitive_line_search();\n if (new_step_size == 0) { return false; }\n ++iter_count;\n step_size = new_step_size;\n x += step_size * step_dir;\n g(temp.data(), x.data());\n dg = temp - gx;\n gx.swap(temp);\n update_inverse_hessian();\n return true;\n }\n\n }; // class BFGSOptimizer\n\n} // namespace dznl\n\n#endif // DZNL_BFGS_OPTIMIZER_HPP_INCLUDED\n", "meta": {"hexsha": "daf65c1237d2c0603dd285f6ce910cfed155403a", "size": 5049, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "legacy/dznl/BFGSOptimizer.hpp", "max_stars_repo_name": "dzhang314/dznl", "max_stars_repo_head_hexsha": "69b592bc38e5d0d8584723c266116c7a53a1086e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "legacy/dznl/BFGSOptimizer.hpp", "max_issues_repo_name": "dzhang314/dznl", "max_issues_repo_head_hexsha": "69b592bc38e5d0d8584723c266116c7a53a1086e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "legacy/dznl/BFGSOptimizer.hpp", "max_forks_repo_name": "dzhang314/dznl", "max_forks_repo_head_hexsha": "69b592bc38e5d0d8584723c266116c7a53a1086e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8206896552, "max_line_length": 80, "alphanum_fraction": 0.5284214696, "num_tokens": 1069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6986127610972518}} {"text": "//-----------------------------------------------------------------------------\n// Copyright (c) 2016 Benjamin Buch\n//\n// https://github.com/bebuch/mitrax\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n//-----------------------------------------------------------------------------\n#ifndef _mitrax__Eigen__convolution__hpp_INCLUDED_\n#define _mitrax__Eigen__convolution__hpp_INCLUDED_\n\n#include \n\n\nnamespace Eigen{\n\n\n\ttemplate < typename DerivedM, typename DerivedK >\n\tinline auto convolution(\n\t\tMatrixBase< DerivedM > const& m,\n\t\tMatrixBase< DerivedK > const& k\n\t){\n\t\tusing ScalarK = typename DerivedK::Scalar;\n\n\t\tusing ResultType = Matrix< ScalarK, Eigen::Dynamic, Eigen::Dynamic >;\n\n\t\tint kr = k.rows();\n\t\tint kc = k.cols();\n\n\t\tint res_r = m.rows() - kr + 1;\n\t\tint res_c = m.cols() - kc + 1;\n\n\t\tResultType res(res_r, res_c);\n\n\t\tfor(int my = 0; my < res_r; ++my){\n\t\t\tfor(int mx = 0; mx < res_c; ++mx){\n\t\t\t\tScalarK b = 0;\n\n\t\t\t\tfor(int ky = 0; ky < kr; ++ky){\n\t\t\t\t\tfor(int kx = 0; kx < kc; ++kx){\n\t\t\t\t\t\tb += m(my + ky, mx + kx) * k(ky, kx);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tres.coeffRef(my, mx) = b;\n\t\t\t}\n\t\t}\n\n\t\treturn res;\n\t}\n\n\ttemplate < typename DerivedM, typename DerivedKC, typename DerivedKR >\n\tinline auto convolution(\n\t\tMatrixBase< DerivedM > const& m,\n\t\tMatrixBase< DerivedKC > const& vc,\n\t\tMatrixBase< DerivedKR > const& vr\n\t){\n\t\treturn convolution(convolution(m, vr), vc);\n\t}\n\n}\n\n\n#endif\n", "meta": {"hexsha": "cbda56c21ac67fccd92976e95511b5e7c57e7b92", "size": 1505, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmark/include/Eigen/convolution.hpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmark/include/Eigen/convolution.hpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmark/include/Eigen/convolution.hpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1538461538, "max_line_length": 79, "alphanum_fraction": 0.5813953488, "num_tokens": 413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6986127610972518}} {"text": "\n#include \n#include \n\n#include \n#include \n\n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char **argv)\n{\n\tint mag_data_counter = 1000;\n\tFILE * fp;\n\tdouble mag_x, mag_y, mag_z;\n\n\tMatrixXd mat_D(mag_data_counter, 9);\n\tMatrixXd mat_DT;\n\tfp = fopen(\"magdata\", \"r\");\n\n\tfor (int i = 0; i < mag_data_counter; i++)\n\t{\n\n\t\tfscanf(fp, \"%lf %lf %lf\\n\", &mag_x, &mag_y, &mag_z);\n\t\tmat_D(i, 0) = mag_x * mag_x;\n\t\tmat_D(i, 1) = mag_y * mag_y;\n\t\tmat_D(i, 2) = mag_z * mag_z;\n\t\tmat_D(i, 3) = 2 * mag_x * mag_y;\n\t\tmat_D(i, 4) = 2 * mag_x * mag_z;\n\t\tmat_D(i, 5) = 2 * mag_y * mag_z;\n\t\tmat_D(i, 6) = 2 * mag_x;\n\t\tmat_D(i, 7) = 2 * mag_y;\n\t\tmat_D(i, 8) = 2 * mag_z;\n\t}\n\tfclose(fp);\n\tmat_DT = mat_D.transpose();\n\n\tMatrixXd mat_Ones = MatrixXd::Ones(mag_data_counter, 1);\n\n\tMatrixXd mat_Result = (mat_DT * mat_D).inverse() * (mat_DT * mat_Ones);\n\n\tMatrix mat_A_4x4;\n\n\tmat_A_4x4(0, 0) = mat_Result(0, 0);\n\tmat_A_4x4(0, 1) = mat_Result(3, 0);\n\tmat_A_4x4(0, 2) = mat_Result(4, 0);\n\tmat_A_4x4(0, 3) = mat_Result(6, 0);\n\n\tmat_A_4x4(1, 0) = mat_Result(3, 0);\n\tmat_A_4x4(1, 1) = mat_Result(1, 0);\n\tmat_A_4x4(1, 2) = mat_Result(5, 0);\n\tmat_A_4x4(1, 3) = mat_Result(7, 0);\n\n\tmat_A_4x4(2, 0) = mat_Result(4, 0);\n\tmat_A_4x4(2, 1) = mat_Result(5, 0);\n\tmat_A_4x4(2, 2) = mat_Result(2, 0);\n\tmat_A_4x4(2, 3) = mat_Result(8, 0);\n\n\tmat_A_4x4(3, 0) = mat_Result(6, 0);\n\tmat_A_4x4(3, 1) = mat_Result(7, 0);\n\tmat_A_4x4(3, 2) = mat_Result(8, 0);\n\tmat_A_4x4(3, 3) = -1.0;\n\n\n\tMatrixXd mat_Center = -((mat_A_4x4.block(0, 0, 3, 3)).inverse() * mat_Result.block(6, 0, 3, 1));\n\n\tMatrix mat_T_4x4;\n\tmat_T_4x4.setIdentity();\n\tmat_T_4x4.block(3, 0, 1, 3) = mat_Center.transpose();\n\n\tMatrixXd mat_R = mat_T_4x4 * mat_A_4x4 * mat_T_4x4.transpose();\n\n\tEigenSolver eig(mat_R.block(0, 0, 3, 3) / -mat_R(3, 3));\n\t//mat_T_4x4(3,0)=mat_Center()\n\tMatrixXd mat_Eigval(3, 1) ;\n\tMatrixXd mat_Evecs(3, 3) ;\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tmat_Evecs(i, j) = (eig.eigenvectors())(i, j).real();\n\t\t}\n\t}\n\tmat_Eigval(0, 0) = (eig.eigenvalues())(0, 0).real();\n\tmat_Eigval(1, 0) = (eig.eigenvalues())(1, 0).real();\n\tmat_Eigval(2, 0) = (eig.eigenvalues())(2, 0).real();\n\tMatrixXd mat_Radii = (1.0 / mat_Eigval.array()).cwiseSqrt();\n\tMatrixXd mat_Scale = MatrixXd::Identity(3, 3) ;\n\tmat_Scale(0, 0) = mat_Radii(0, 0);\n\tmat_Scale(1, 1) = mat_Radii(1, 0);\n\tmat_Scale(2, 2) = mat_Radii(2, 0);\n\tdouble min_Radii = mat_Radii.minCoeff();\n\n\tmat_Scale = mat_Scale.inverse().array() * min_Radii;\n\tMatrixXd mat_Correct = mat_Evecs * mat_Scale * mat_Evecs.transpose();\n\n\n\tcout << \"The Ellipsoid center is:\" << endl << mat_Center << endl;\n\tcout << \"The Ellipsoid radii is:\" << endl << mat_Radii << endl;\n\tcout << \"The scale matrix is:\" << endl << mat_Scale << endl;\n\tcout << \"The correct matrix is:\" << endl << mat_Correct << endl;\n\n}", "meta": {"hexsha": "0fdc01a6587d8805621135e52d2cfc3f64bf7338", "size": 2894, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RTEllipsoidFit/ellipsoid_fit.cpp", "max_stars_repo_name": "mfkiwl/RTIMULib2", "max_stars_repo_head_hexsha": "8cbb128570568eacbf238d7424bd39f07b540d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-03-03T10:15:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T12:17:29.000Z", "max_issues_repo_path": "RTEllipsoidFit/ellipsoid_fit.cpp", "max_issues_repo_name": "mfkiwl/RTIMULib2", "max_issues_repo_head_hexsha": "8cbb128570568eacbf238d7424bd39f07b540d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2021-03-31T03:58:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-27T14:53:58.000Z", "max_forks_repo_path": "RTEllipsoidFit/ellipsoid_fit.cpp", "max_forks_repo_name": "mfkiwl/RTIMULib2", "max_forks_repo_head_hexsha": "8cbb128570568eacbf238d7424bd39f07b540d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2020-02-27T13:50:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T04:50:39.000Z", "avg_line_length": 27.8269230769, "max_line_length": 97, "alphanum_fraction": 0.6264685556, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.967899295134923, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6985747406438644}} {"text": "#ifndef PROPAGATION_HPP\n#define PROPAGATION_HPP\n\n#include \n\n#include \n\n#include \"../utility/activation.hpp\"\n\n/*! \\file propagation.hpp\n \\brief collection of propagation algorithms\n*/\n\n/*!\n * \\addtogroup ocv\n * @{\n */\nnamespace ocv{\n\n/*!\n * \\addtogroup ml\n * @{\n */\nnamespace ml{\n\n/**\n *@brief forward propagation of neural network, this function\\n\n *Assume this is a three layers neural network, this function\\n\n *will compute the output of the layer 2\n *@param input The input of the neurals(input of layer 2)\n *@param weight The weight of the input\n *@param bias bias of the input\n *@param output The output of the neurals(output of layer 2).\\n\n * After computation, output.rows == weight.rows && output.cols == input.cols\n *@param func unary functor which apply the activation on\\n\n * the output\n *@pre input, weight and bias cannot be empty, the type of the\\n\n * input, weight, bias and output should be double(CV_64F).\\n\n * weight.cols == input.rows && bias.rows == weight.rows\n */\ntemplate\nvoid forward_propagation(cv::Mat const &input,\n cv::Mat const &weight,\n cv::Mat const &bias,\n cv::Mat &output,\n UnaryFunc func = UnaryFunc())\n{\n if(!input.empty() && !weight.empty() &&\n !bias.empty()){\n //output = weight * input;\n cv::gemm(weight, input, 1.0, cv::Mat(),\n 0.0, output);\n for(int i = 0; i != output.cols; ++i){\n output.col(i) += bias;\n }\n func(output);\n }\n}\n\n/**\n *@brief forward propagation of neural network, this function\\n\n *Assume this is a three layers neural network, this function\\n\n *will compute the output of the layer 2\n *@param input The input of the neurals(input of layer 2)\n *@param weight The weight of the input\n *@param bias bias of the input\n *@param output The output of the neurals(output of layer 2).\\n\n * After computation, output.rows == weight.rows && output.cols == input.cols\n *@param func unary functor which apply the activation on\\n\n * the output\n *@pre input, weight and bias cannot be empty.\\n\n * weight.cols == input.rows && bias.rows == weight.rows\n */\ntemplate\nvoid forward_propagation(Eigen::MatrixBase const &input,\n Eigen::MatrixBase const &weight,\n Eigen::MatrixBase const &bias,\n Eigen::MatrixBase &output,\n bool no_overlap = true,\n UnaryFunc func = UnaryFunc())\n{\n static_assert(std::is_same::value &&\n std::is_same::value &&\n std::is_same::value,\n \"Data type of matrix input, weight, bias and output should be the same\");\n\n if(input.rows() != 0 && weight.rows() != 0 &&\n bias.rows() != 0){ \n if(no_overlap){\n output.noalias() = weight * input;\n }else{\n output = weight * input;\n }\n\n using Scalar = typename Derived3::Scalar;\n using MatType = Eigen::Matrix;\n using Mapper = Eigen::Map;\n Mapper Map(&bias(0, 0), bias.size());\n output.colwise() += Map;\n func(output);\n }\n}\n\n} /*! @} End of Doxygen Groups*/\n\n} /*! @} End of Doxygen Groups*/\n\n#endif // PROPAGATION_HPP\n\n", "meta": {"hexsha": "7ce6c903ac620a6a025f732d29d0252c0170cb45", "size": 3694, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ml/deep_learning/propagation.hpp", "max_stars_repo_name": "stereomatchingkiss/ocv_libs", "max_stars_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2015-12-17T05:28:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T02:59:29.000Z", "max_issues_repo_path": "ml/deep_learning/propagation.hpp", "max_issues_repo_name": "stereomatchingkiss/ocv_libs", "max_issues_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ml/deep_learning/propagation.hpp", "max_forks_repo_name": "stereomatchingkiss/ocv_libs", "max_forks_repo_head_hexsha": "1424ac2f8a2c034513483b3050d8138ca0a0ae3f", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-05-10T11:20:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T17:06:06.000Z", "avg_line_length": 32.4035087719, "max_line_length": 91, "alphanum_fraction": 0.60584732, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6985120173113334}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n// vertex: 3d vector\nclass CurveFittingVertex : public g2o::BaseVertex<3, Eigen::Vector3d> {\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n // override the reset function\n virtual void setToOriginImpl() override {\n _estimate << 0, 0, 0;\n }\n\n // override the plus operator, just plain vector addition\n virtual void oplusImpl(const double *update) override {\n _estimate += Eigen::Vector3d(update);\n }\n\n // the dummy read/write function\n virtual bool read(istream &in) {}\n\n virtual bool write(ostream &out) const {}\n};\n\n// edge: 1D error term, connected to exactly one vertex\nclass CurveFittingEdge : public g2o::BaseUnaryEdge<1, double, CurveFittingVertex> {\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n CurveFittingEdge(double x) : BaseUnaryEdge(), _x(x) {}\n\n // define the error term computation\n virtual void computeError() override {\n const CurveFittingVertex *v = static_cast (_vertices[0]);\n const Eigen::Vector3d abc = v->estimate();\n _error(0, 0) = _measurement - std::exp(abc(0, 0) * _x * _x + abc(1, 0) * _x + abc(2, 0));\n }\n\n // the jacobian\n virtual void linearizeOplus() override {\n const CurveFittingVertex *v = static_cast (_vertices[0]);\n const Eigen::Vector3d abc = v->estimate();\n double y = exp(abc[0] * _x * _x + abc[1] * _x + abc[2]);\n _jacobianOplusXi[0] = -_x * _x * y;\n _jacobianOplusXi[1] = -_x * y;\n _jacobianOplusXi[2] = -y;\n }\n\n virtual bool read(istream &in) {}\n\n virtual bool write(ostream &out) const {}\n\npublic:\n double _x; // x data, note y is given in _measurement\n};\n\nint main(int argc, char **argv) {\n double ar = 1.0, br = 2.0, cr = 1.0; // ground−truth values\n double ae = 2.0, be = -1.0, ce = 5.0; // initial estimation\n int N = 100; // num of data points\n double w_sigma = 1.0; // sigma of the noise\n double inv_sigma = 1.0 / w_sigma;\n cv::RNG rng; // Random number generator\n\n vector x_data, y_data; // the data\n for (int i = 0; i < N; i++) {\n double x = i / 100.0;\n x_data.push_back(x);\n y_data.push_back(exp(ar * x * x + br * x + cr) + rng.gaussian(w_sigma * w_sigma));\n }\n\n // set g2o\n // Each error term optimizer has a dimension of 3, and the error value has a dimension of 1.\n typedef g2o::BlockSolver> BlockSolverType;\n typedef g2o::LinearSolverDense LinearSolverType; // linear solver\n\n // choose the optimizatoin method from GN, LM, DogLeg\n auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n g2o::make_unique(g2o::make_unique()));\n g2o::SparseOptimizer optimizer; // graph optimizer\n optimizer.setAlgorithm(solver); // set the algorithm\n optimizer.setVerbose(true); // print the results\n\n // add vertex\n CurveFittingVertex *v = new CurveFittingVertex();\n v->setEstimate(Eigen::Vector3d(ae, be, ce));\n v->setId(0);\n optimizer.addVertex(v);\n\n // add edges\n for (int i = 0; i < N; i++) {\n CurveFittingEdge *edge = new CurveFittingEdge(x_data[i]);\n edge->setId(i);\n edge->setVertex(0, v); // connect to the vertex\n edge->setMeasurement(y_data[i]); // measurement\n edge->setInformation(Eigen::Matrix::Identity() * 1 / (w_sigma * w_sigma)); // set the information matrix\n optimizer.addEdge(edge);\n }\n\n // carry out the optimization\n cout << \"start optimization\" << endl;\n chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n optimizer.initializeOptimization();\n optimizer.optimize(10);\n chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n chrono::duration time_used = chrono::duration_cast>(t2 - t1);\n cout << \"solve time cost = \" << time_used.count() << \" seconds. \" << endl;\n\n // print the results\n Eigen::Vector3d abc_estimate = v->estimate();\n cout << \"estimated model: \" << abc_estimate.transpose() << endl;\n\n return 0;\n}", "meta": {"hexsha": "a29ca6d589536a0b3058da5ed124fe5bf6c027b7", "size": 4559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/g2oCurveFitting.cpp", "max_stars_repo_name": "SNU-SF4/slambook2", "max_stars_repo_head_hexsha": "eba0c28882fb6c78a9c81644f01fe93a80f83c7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch6/g2oCurveFitting.cpp", "max_issues_repo_name": "SNU-SF4/slambook2", "max_issues_repo_head_hexsha": "eba0c28882fb6c78a9c81644f01fe93a80f83c7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch6/g2oCurveFitting.cpp", "max_forks_repo_name": "SNU-SF4/slambook2", "max_forks_repo_head_hexsha": "eba0c28882fb6c78a9c81644f01fe93a80f83c7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8976377953, "max_line_length": 122, "alphanum_fraction": 0.6711998245, "num_tokens": 1327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.698510416808155}} {"text": "/*\n * oper_matrix.cpp\n *\n * Created on: 2017. 6. 6.\n * Author: cho\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n//#include \"io.hpp\"\n\nusing namespace std;\nnamespace ublas = boost::numeric::ublas;\n\n/// number of data\nconst unsigned int N = 5;\n\nint main() {\n\tcout << \"==== START \" << endl;\n\trandom_device rd; // seed, rd()\n\tmt19937_64 gen(4); // random number generator\n\n\tublas::vector t (N); // time vector, sec\n\tfor (unsigned i = 0; i < t.size(); ++i) t(i) = i+1;\n\tcout << \"t(\"< dis_y( 0, 10 );\n\tublas::vector y (N); // measured value\n\tfor (unsigned i = 0; i < y.size(); ++i) y(i) = dis_y(gen);\n\tcout << \"y(\"< m( N, N );\n\tfor (unsigned i = 0; i < m.size1 (); ++ i)\n\t\tfor (unsigned j = 0; j < m.size2 (); ++ j)\n\t\t\tm (i, j) = i*2 + j + 1;\n\t\t\t//m(i,j) = m_init[i][j];\n\tm(N-1,N-1) = 3;\n\tcout << \"matrix = \" << m << endl;\n\n\tcout << \"\\n==== standard operation : +, -, *(scalar), /(scalar) \" << endl;\n\t{\n\t\tcout << \"t+y = \" << t+y << endl;\n\t\tcout << \"t-y = \" << t-y << endl;\n\t\tcout << \"2*t = \" << 2*t << endl;\n\t\tcout << \"t*3 = \" << t*3 << endl;\n\t\tcout << \"t/2 = \" << t/3 << endl;\n\t\tcout << \"-t = \" << -t << endl;\n\t}\n\n\tcout << \"\\n==== inner, outer and other products \" << endl;\n\t{\n\t\tcout << \"inner_prod(t, y) = \" << inner_prod( t, y ) << endl;\n\t\tcout << \"inner_prod(y, t) = \" << inner_prod( y, t ) << endl;\n\t\tcout << \"outer_prod(t, y) = \" << outer_prod( t, y ) << endl;\n\t\tcout << \"outer_prod(y, t) = \" << outer_prod( y, t ) << endl;\n\t\tcout << \"element_prod(t, y) = \" << element_prod(t, y) << endl;\n\t\tcout << \"element_prod(y, t) = \" << element_prod(y, t) << endl;\n\t\tcout << \"element_div(t, y) = \" << element_div(t, y) << endl;\n\t\tcout << \"element_div(y, t) = \" << element_div(y, t) << endl;\n\t\tcout << \"prod(m, t) = \" << prod(m, t) << endl;\n\t\tcout << \"prod(t, m) = \" << prod(t, m) << endl;\n\t\tcout << \"prec_prod(t, m) = \" << prec_prod(t, m) << endl;\n\t\tcout << \"prec_prod(m, t) = \" << prec_prod(m, t) << endl;\n\t}\n\n\tcout << \"\\n==== transformations \" << endl;\n\t{\n\t\tcout << \"trans(m) = \" << ublas::trans(m) << endl;\n\t}\n\n\tcout << \"\\n==== triangular matrix \" << endl;\n\t{\n\t\tauto L = ublas::triangular_adaptor, ublas::lower> (m);\n\t\tauto SL = ublas::triangular_adaptor, ublas::strict_lower> (m);\n\t\tauto UL = ublas::triangular_adaptor, ublas::unit_lower> (m);\n\t\tcout << \"lower L = \" << L << endl;\n\t\tcout << \"strict lower SL = \" << SL << endl;\n\t\tcout << \"unit lower UL = \" << UL << endl;\n\n\t\tauto U = ublas::triangular_adaptor, ublas::upper> (m);\n\t\tauto SU = ublas::triangular_adaptor, ublas::strict_upper> (m);\n\t\tauto UU = ublas::triangular_adaptor, ublas::unit_upper> (m);\n\t\tcout << \"upper U = \" << U << endl;\n\t\tcout << \"strict upper SU = \" << SU << endl;\n\t\tcout << \"unit upper UU = \" << UU << endl;\n\n\t\tcout << \"prod( U, m ) = \" << prod(U, m) << endl;\n\n\t\tublas::vector x(m.size1());\n\t\tublas::vector b(m.size1(), 1);\n\t\tcout << \"inplace_solve(UL, b, ) : b = \" << b << endl;\n\t\tinplace_solve( UL, b, ublas::unit_lower_tag() );\n\t\tcout << \"inplace_solve(UL, b, ) : b = \" << b << endl;\n\t\tcout << \"prod( UL, b ) = \" << prod( UL, b ) << endl;\n\t}\n\n\tcout << \"\\n==== pumutation matrix \" << endl;\n\t{\n\t\tublas::permutation_matrix pm(N);\n\t\tpm(0) = 1;\n\t\tcout << \"-- pm = \" << pm << endl;\n\t\tublas::swap_rows( pm, m);\n\t\tcout << \"-- swap_rows( pm, m) = \" << m << endl;\n\t\tpm(0) = 0; pm(1) = 0;\n\t\tcout << \"-- pm = \" << pm << endl;\n\t\tublas::swap_rows( pm, m);\n\t\tcout << \"-- swap_rows( pm, m) = \" << m << endl;\n\t\tpm(0) = 0; pm(1) = 1; pm(2) = 0;\n\t\tcout << \"-- pm = \" << pm << endl;\n\t\tublas::swap_rows( pm, m);\n\t\tcout << \"-- swap_rows( pm, m) = \" << m << endl;\n\t}\n\n\tcout << \"\\n==== LU factorization\" << endl;\n\t{\n\t\tublas::matrix A(m);\n\t\tublas::permutation_matrix pm(N);\n\t\tcout << \"-- pm = \" << pm << endl;\n\t\tbool singular = ublas::lu_factorize( A, pm);\n\t\tcout << \"-- return = \" << singular << endl;\n\t\tcout << \"-- A = \" << A << endl;\n\t\tcout << \"-- pm = \" << pm << endl;\n\n\t\tauto L = ublas::triangular_adaptor, ublas::unit_lower>(A);\n\t\tcout << \"-- L = \" << L << endl;\n\t\tauto U = ublas::triangular_adaptor, ublas::upper>(A);\n\t\tcout << \"-- U = \" << U << endl;\n\t\tcout << \"-- LU = \" << prod(L,U) << endl;\n\t\tublas::matrix pmA( m ); // pmA means pm*A, at first init as m\n\t\tswap_rows(pm, pmA);\n\t\tcout << \"-- swap_rows(pm,A) = \" << pmA << endl;\n\n\t\tcout << \"-- solve Lz = b -------------\" << endl;\n\t\tublas::vector b( N ); b(0) = 1; b(1) = 2; b(2) = 3;\n\t\tublas::vector z( b );\n\t\tcout << \"-- L \" << L << endl;\n\t\tcout << \"-- b \" << b << endl;\n\t\tublas::inplace_solve( A, z, ublas::unit_lower_tag() );\n\t\tcout << \"-- z = \" << z << endl;\n\t\tcout << \"-- confirm Lz = \" << prod( L, z ) << endl;\n\n\t\tcout << \"-- solve Ux = z -------------\" << endl;\n\t\tublas::vector x( z );\n\t\tcout << \"-- U \" << U << endl;\n\t\tcout << \"-- z \" << z << endl;\n\t\tinplace_solve( A, x, ublas::upper_tag() );\n\t\tcout << \"-- x = \" << x << endl;\n\t\tcout << \"-- confirm Ux = \" << prod( U, x ) << endl;\n\t}\n\n\tcout << \"==== END \" << endl;\n}\n", "meta": {"hexsha": "bda7363d360c1808e9ee524cbe49726de2c86bfd", "size": 5526, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost_ublas/oper_matrix.cpp", "max_stars_repo_name": "batangr00t/cppLab", "max_stars_repo_head_hexsha": "3946e702692dffb53f92c776e9e8c4a073d68bc9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost_ublas/oper_matrix.cpp", "max_issues_repo_name": "batangr00t/cppLab", "max_issues_repo_head_hexsha": "3946e702692dffb53f92c776e9e8c4a073d68bc9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost_ublas/oper_matrix.cpp", "max_forks_repo_name": "batangr00t/cppLab", "max_forks_repo_head_hexsha": "3946e702692dffb53f92c776e9e8c4a073d68bc9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7547169811, "max_line_length": 86, "alphanum_fraction": 0.5200868621, "num_tokens": 1963, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6982486178861433}} {"text": "#ifndef MATHTOOLBOX_BACKTRACKING_LINE_SEARCH_HPP\n#define MATHTOOLBOX_BACKTRACKING_LINE_SEARCH_HPP\n\n#include \n#include \n#include \n\nnamespace mathtoolbox\n{\n namespace optimization\n {\n /// \\brief Run the backtracking line search.\n ///\n /// \\details The algorithm is described in the book (Algorithm 3.1: Backtracking Line Search).\n ///\n /// This algorithm tries to find an appropriate step size that satisfies the Armijo condition (i.e., the\n /// safficient decreasing condition). This algorithm runs faster than the line search algorithm for the strong\n /// Wolfe conditions, but it does not guarantee the curvature condition, which is required to stabilize the\n /// overall optimization.\n inline double RunBacktrackingLineSearch(const std::function& f,\n const Eigen::VectorXd& grad,\n const Eigen::VectorXd& x,\n const Eigen::VectorXd& p,\n const double alpha_init,\n const double rho,\n const double c = 1e-04)\n {\n constexpr unsigned int max_num_iters = 50;\n\n assert(p.size() == x.size());\n\n double alpha = alpha_init;\n\n for (int iter = 0; iter < max_num_iters; ++iter)\n {\n // Equation 3.4\n const bool armijo_condition = f(x + alpha * p) <= f(x) + c * alpha * grad.transpose() * p;\n\n if (armijo_condition)\n {\n return alpha;\n }\n\n alpha *= rho;\n }\n\n std::cerr << \"Warning: The line search did not converge.\" << std::endl;\n return alpha;\n }\n\n /// \\brief Run the backtracking line search with bound constraints\n ///\n /// \\details This function should be slightly slower than the unbounded one since it evaluates bound conditions\n /// every step.\n ///\n /// \\param lower_bound Lower bound of the search space. It can also be a zero-sized vector when there is no\n /// lower bound condition.\n ///\n /// \\param upper_bound Upper bound of the search space. It can also be a zero-sized vector when there is no\n /// upper bound condition.\n inline double RunBacktrackingBoundedLineSearch(const std::function& f,\n const Eigen::VectorXd& grad,\n const Eigen::VectorXd& x,\n const Eigen::VectorXd& p,\n const Eigen::VectorXd& lower_bound,\n const Eigen::VectorXd& upper_bound,\n const double alpha_init,\n const double rho,\n const double c = 1e-04)\n {\n constexpr unsigned int max_num_iters = 50;\n\n assert(p.size() == x.size());\n\n double alpha = alpha_init;\n\n for (int iter = 0; iter < max_num_iters; ++iter)\n {\n const Eigen::VectorXd x_new = x + alpha * p;\n\n // Equation 3.4\n const bool armijo_condition = f(x_new) <= f(x) + c * alpha * grad.transpose() * p;\n\n // Bound conditions\n const bool lower_bound_condition = lower_bound.size() == 0 || (x_new - lower_bound).minCoeff() >= 0.0;\n const bool upper_bound_condition = upper_bound.size() == 0 || (upper_bound - x_new).minCoeff() >= 0.0;\n\n if (armijo_condition && lower_bound_condition && upper_bound_condition)\n {\n return alpha;\n }\n\n alpha *= rho;\n }\n\n std::cerr << \"Warning: The line search did not converge.\" << std::endl;\n return alpha;\n }\n } // namespace optimization\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_BACKTRACKING_LINE_SEARCH_HPP\n", "meta": {"hexsha": "687042cded4ee473c3b3017783194088cee4dcb7", "size": 4898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/backtracking-line-search.hpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "include/mathtoolbox/backtracking-line-search.hpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "include/mathtoolbox/backtracking-line-search.hpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 47.5533980583, "max_line_length": 120, "alphanum_fraction": 0.4501837485, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6981715195229788}} {"text": "#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"NumpySaver.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef double type;\n\nconst char* divider = \"#####################################################\";\n\n// copied from https://gist.github.com/lorenzoriano/5414671\ntemplate \nstd::vector linspace(T start, T end, size_t N) {\n T h = (end - start) / static_cast(N - 1);\n std::vector xs(N);\n typename std::vector::iterator x;\n T val;\n for (x = xs.begin(), val = start; x != xs.end(); ++x, val += h) *x = val;\n return xs;\n}\n\nSparseMatrix get_5_point_schroedinger_matrix(\n double xmin, double xmax, unsigned int N,\n function potential) {\n // cout << \"Hello from the Beginning of building the matrix\" << endl;\n SparseMatrix mat(N, N);\n mat.reserve(5 * N - 6);\n\n double h = (xmax - xmin) / N;\n double prefac = 1. / 12. / h / h;\n\n double x = xmin;\n for (unsigned int i = 0; i < N; i++, x += h) {\n if (i >= 2) mat.insert(i, i - 2) = prefac;\n if (i >= 1) mat.insert(i, i - 1) = -prefac * 16;\n mat.insert(i, i) = prefac * 30 + potential(x);\n if (i < N - 1) mat.insert(i, i + 1) = -prefac * 16;\n if (i < N - 2) mat.insert(i, i + 2) = prefac;\n }\n // cout << \"Hello from the End of building the matrix\" << endl;\n\n return mat;\n}\n\ndouble harmonic_oszi_potential(double x) { return x * x; }\ndouble disturbed_harmonic_oszi_potential(double x, double c1, double c2) {\n return x * x + c1 * exp(-x * x * c2);\n}\n\nfunction get_potential(YAML::Node potential_conf) {\n auto pot_name = potential_conf[\"name\"].as();\n\n if (pot_name == \"harmonic\") {\n return harmonic_oszi_potential;\n } else if (pot_name == \"disturbed\") {\n double c1 = potential_conf[\"c1\"].as();\n double c2 = potential_conf[\"c2\"].as();\n return bind(disturbed_harmonic_oszi_potential, std::placeholders::_1, c1,\n c2);\n } else {\n throw runtime_error(\n \"Potential needs to be either 'harmonic' or 'disturbed'!\");\n }\n}\n\ntemplate \nvector get_values(YAML::Node& node) {\n auto type = node.Type();\n // single value\n if (type == YAML::NodeType::Scalar) {\n vector ret = {node.as()};\n return ret;\n } else if (type == YAML::NodeType::Sequence) {\n return node.as>();\n } else if (type == YAML::NodeType::Map) {\n auto start = node[\"start\"].as();\n auto end = node[\"end\"].as();\n auto N = node[\"N\"].as();\n return linspace(start, end, N);\n } else {\n throw std::runtime_error(\n \"Range node must either be list, scalar or a map defining \"\n \"'start','end' and 'N'.\");\n }\n}\n\ntuple eigenvector_inverse_power_iteration(\n SparseMatrix& matrix, VectorXd& start_vector, double shift = 0,\n double tol = 1e-4, unsigned int max_iterations = 10000) {\n // apply shift\n // cout << \"Matrix=\\n\" << matrix;\n SparseMatrix mat(matrix.rows(), matrix.cols());\n mat.setIdentity();\n mat = matrix - shift * mat;\n // cout << \"Shifted Matrix\\n\" << mat;\n\n // first do the (sparse) LU decomposition\n Eigen::SparseLU, Eigen::COLAMDOrdering> solver;\n solver.analyzePattern(mat);\n solver.factorize(mat);\n\n // now the iteration\n VectorXd y_now(start_vector);\n VectorXd y_last;\n\n // not the best init value, but should work ok\n type lambda_now = numeric_limits::max();\n type lambda_last;\n\n // keep track of iterations\n unsigned int i = 0;\n\n do {\n // normalize vector\n y_now.normalize();\n y_last = y_now;\n\n // iteration\n y_now = solver.solve(y_last);\n\n // calculate eigenvector\n lambda_last = lambda_now;\n lambda_now = 1 / (y_last.dot(y_now)) + shift;\n\n } while ((abs(lambda_last - lambda_now) > tol) && i++ < max_iterations);\n\n return {y_now, lambda_now, i};\n}\n\nvoid test_inverse_power_iteration(YAML::Node& test_configs) {\n auto size = test_configs.size();\n for (std::size_t i = 0; i < size; i++) {\n auto conf = test_configs[i];\n\n auto N = conf[\"dim\"].as();\n auto max_iteartions = conf[\"max_iter\"].as();\n auto tol = conf[\"tol\"].as();\n\n MatrixXd matrix = MatrixXd::Random(N, N);\n matrix = matrix.selfadjointView();\n VectorXd start_vector = VectorXd::Random(N);\n SparseMatrix sparse_view = matrix.sparseView();\n\n cout << divider << \"# Test Power Iteration \" << i + 1 << \"/\" << size << endl\n << divider;\n cout << \"Matrix=\\n\" << matrix;\n cout << \"\\nStart vector=\\n\" << start_vector;\n cout << \"\\nTolerance=\" << tol << endl << endl;\n\n YAML::Node shift_node = conf[\"shift\"];\n auto shifts = get_values(shift_node);\n\n // Eigen solution for comparison:\n EigenSolver es(matrix);\n cout << \"Eigen-Eigenvalues:\" << endl << es.eigenvalues() << endl;\n cout << \"Eigen-Eigenvectors:\" << endl << es.eigenvectors() << endl << endl;\n\n for (auto& shift : shifts) {\n cout << divider << \"Shift=\" << shift << endl;\n\n auto [eigenvector, eigenvalue, iterations] =\n eigenvector_inverse_power_iteration(sparse_view, start_vector, shift,\n tol, max_iteartions);\n cout << \"Iterations needed to reach tolerance: \" << iterations << endl;\n cout << \"Inverse power Iteration eigenvector is:\\n\" << eigenvector;\n cout << \"\\nInverse power Iteration eigenvalue is:\\n\" << eigenvalue;\n if (iterations >= max_iteartions)\n cerr\n << \"\\nWarning! Exceeded maximum number of iterations! Solution did \"\n \"not converge!\"\n << endl;\n cout << endl;\n }\n cout << endl;\n }\n}\n\nvoid test_harmonic(YAML::Node& test_configs) {\n auto size = test_configs.size();\n for (std::size_t i = 0; i < size; i++) {\n cout << divider << \"\\n# Test Harmonic Oscillator \" << i + 1 << \"/\" << size\n << endl\n << divider << endl\n << endl;\n auto conf = test_configs[i];\n\n auto N = conf[\"N\"].as();\n auto max_iteartions = conf[\"max_iter\"].as();\n auto tol = conf[\"tol\"].as();\n auto xmin = conf[\"xmin\"].as();\n auto xmax = conf[\"xmax\"].as();\n\n function pot = get_potential(conf[\"potential\"]);\n auto matrix = get_5_point_schroedinger_matrix(xmin, xmax, N, pot);\n\n bool has_name = false;\n string file_name;\n if (conf[\"name\"]) {\n has_name = true;\n file_name = \"build/output/\" + conf[\"name\"].as() + \".npy\";\n cout << \"Name to save to: \" << file_name << endl;\n }\n\n NumpySaver saver(file_name);\n\n if (has_name) {\n VectorXd x_space(N);\n VectorXd pot_space(N);\n double h = (xmax - xmin) / N;\n\n double x = xmin;\n for (size_t i = 0; i < N; i++, x += h) {\n x_space[i] = x;\n pot_space[i] = pot(x);\n }\n\n saver << \"x\" << x_space << \"pot\" << pot_space;\n }\n\n VectorXd start_vector = VectorXd::Ones(N);\n\n YAML::Node shift_node = conf[\"shift\"];\n auto shifts = get_values(shift_node);\n\n cout << \"Tolerance=\" << tol << endl;\n\n // Eigen solution for comparison:\n SelfAdjointEigenSolver> es(matrix);\n if (N < 10) {\n cout << \"Eigen-Eigenvalues:\" << endl << es.eigenvalues() << endl;\n cout << \"Eigen-Eigenvectors:\" << endl\n << es.eigenvectors() << endl\n << endl;\n cout << \"Matrix=\\n\" << matrix << endl;\n cout << \"Start vector=\\n\" << start_vector << endl;\n }\n\n for (auto& shift : shifts) {\n cout << divider << \"Shift=\" << shift << endl;\n\n auto [eigenvector, eigenvalue, iterations] =\n eigenvector_inverse_power_iteration(matrix, start_vector, shift, tol,\n max_iteartions);\n\n if (has_name) saver << \"ev\" << eigenvector;\n\n cout << \"Iterations=\" << iterations << endl;\n\n if (N < 10)\n cout << \"Inverse power Iteration eigenvector = \\n\"\n << eigenvector << endl;\n\n cout << \"Inverse power Iteration eigenvalue = \" << eigenvalue << endl;\n\n if (iterations >= max_iteartions)\n cerr << \"Warning! Exceeded maximum number of iterations! Solution did \"\n \"not converge!\"\n << endl;\n\n cout << endl;\n }\n cout << endl;\n }\n}\n\nvoid run_tests() {\n cout << divider << divider << \"## RUNNING TESTS\\n\"\n << divider << divider << endl\n << endl;\n\n YAML::Node config = YAML::LoadFile(\"test.yaml\");\n\n auto config_power_iter = config[\"inverse_iteration\"];\n test_inverse_power_iteration(config_power_iter);\n\n auto config_harmonic = config[\"harmonic\"];\n test_harmonic(config_harmonic);\n}\n\nvoid run_program() {\n YAML::Node configs = YAML::LoadFile(\"config.yaml\");\n auto size = configs.size();\n\n for (std::size_t i = 0; i < size; i++) {\n cout << divider << divider << \"\\n# Running Simulation \" << i + 1 << \"/\"\n << size << endl\n << divider << divider << endl;\n auto conf = configs[i];\n\n auto N = conf[\"N\"].as();\n auto max_iteartions = conf[\"max_iter\"].as();\n auto tol = conf[\"tol\"].as();\n auto xmin = conf[\"xmin\"].as();\n auto xmax = conf[\"xmax\"].as();\n\n function pot = get_potential(conf[\"potential\"]);\n auto matrix = get_5_point_schroedinger_matrix(xmin, xmax, N, pot);\n VectorXd start_vector = VectorXd::Ones(N);\n\n bool has_name = false;\n string file_name;\n if (conf[\"name\"]) {\n has_name = true;\n file_name = \"build/output/\" + conf[\"name\"].as() + \".npy\";\n cout << \"Save to:\\t\" << file_name << endl;\n }\n\n NumpySaver saver(file_name);\n\n if (has_name) {\n VectorXd x_space(N);\n VectorXd pot_space(N);\n double h = (xmax - xmin) / N;\n\n double x = xmin;\n for (size_t i = 0; i < N; i++, x += h) {\n x_space[i] = x;\n pot_space[i] = pot(x);\n }\n\n saver << \"x\" << x_space << \"pot\" << pot_space;\n }\n\n YAML::Node shift_node = conf[\"shift\"];\n auto shifts = get_values(shift_node);\n\n cout << \"N=\\t\\t\" << N << endl;\n cout << \"Tolerance=\\t\" << tol << endl;\n cout << \"xmin=\\t\\t\" << xmin << endl;\n cout << \"xmax=\\t\\t\" << xmax << endl;\n cout << \"function=\\t\" << conf[\"potential\"][\"name\"] << endl << endl;\n\n // to time the methods\n chrono::steady_clock::time_point start;\n chrono::duration elapsed_seconds;\n\n // Eigen solution for comparison:\n if (N <= 1000) {\n start = chrono::steady_clock::now();\n\n SelfAdjointEigenSolver> es(matrix);\n auto ev_ref = es.eigenvalues();\n\n elapsed_seconds = chrono::steady_clock::now() - start;\n cout << \"Eigen::SelfAdjointEigenSolver took \"\n << elapsed_seconds.count() * 1e3 << \"ms\" << endl;\n\n cout << \"eigenvalues=\" << ev_ref(seq(0, shifts.size())).transpose()\n << endl\n << endl;\n\n auto evec_ref = es.eigenvectors();\n\n if (has_name)\n NumpySaver(\"build/output/\" + conf[\"name\"].as() +\n \"_reference.npy\")\n << evec_ref;\n\n if (N < 10) {\n cout << \"Eigen-Eigenvalues:\" << endl << ev_ref << endl;\n cout << \"Eigen-Eigenvectors:\" << endl << evec_ref << endl << endl;\n cout << \"Matrix=\\n\" << matrix << endl;\n cout << \"Start vector=\\n\" << start_vector << endl;\n }\n } else {\n cout << \"Not going to test SelfAdjointEigenSolver, since it would take \"\n \"too long.\"\n << endl;\n }\n\n start = std::chrono::steady_clock::now();\n for (auto& shift : shifts) {\n cout << divider << \"\\nShift=\\t\\t\" << shift << endl;\n\n auto [eigenvector, eigenvalue, iterations] =\n eigenvector_inverse_power_iteration(matrix, start_vector, shift, tol,\n max_iteartions);\n\n elapsed_seconds = chrono::steady_clock::now() - start;\n\n if (has_name) saver << \"ev\" << eigenvector;\n\n cout << \"elapsed time=\\t\" << elapsed_seconds.count() * 1e3 << \"ms\"\n << endl;\n\n cout << \"Iterations=\\t\" << iterations << endl;\n if (N < 10)\n cout << \"Inverse power Iteration eigenvector = \\n\"\n << eigenvector << endl;\n\n cout << \"eigenvalue=\\t\" << eigenvalue << endl;\n\n if (iterations >= max_iteartions)\n cerr << \"Warning! Exceeded maximum number of iterations! Solution did \"\n \"not converge!\"\n << endl;\n }\n cout << endl;\n }\n}\n\nint main(int argc, char const* argv[]) {\n // uncomment this to run the test\n // run_tests();\n run_program();\n return 0;\n}\n", "meta": {"hexsha": "69962b63220b9885603358819bad436f8ba9200a", "size": 12779, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project02-Eigenvalues/eigenvalues.cpp", "max_stars_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_stars_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Project02-Eigenvalues/eigenvalues.cpp", "max_issues_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_issues_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Project02-Eigenvalues/eigenvalues.cpp", "max_forks_repo_name": "The-Ludwig/ComputationalPhysicsSU22", "max_forks_repo_head_hexsha": "67cd47b1adf42087a300bcaa97f6ea5c6df691f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6450839329, "max_line_length": 80, "alphanum_fraction": 0.5816574067, "num_tokens": 3463, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.8333245994514082, "lm_q1q2_score": 0.6980093069257037}} {"text": "// TODO : Dimention Agnosticism\n\n#include \n#include \n#include \n\nnamespace bg = boost::geometry;\nnamespace ublas = boost::numeric::ublas;\n\n// Make vector from 2 points\ntemplate\nublas::vector make_vector(const Point& a, const Point& b)\n{\n\tublas::vector v(2);\n\tv[0] = bg::get<0>(b) - bg::get<0>(a);\n\tv[1] = bg::get<1>(b) - bg::get<1>(a);\n\treturn v;\n}\n\n// Calculate cos from 2 vectors\ndouble cos_from_vecs(const ublas::vector& v1, \n\t\t\t\t\t const ublas::vector& v2) {\n\treturn ublas::inner_prod(v1, v2)/(ublas::norm_2(v1)*ublas::norm_2(v2));\n}\n\n// Calculate cos from 3 points\ntemplate\ndouble cos_from_dots(const Point& a, const Point& b, const Point& c) {\n\treturn cos_from_vecs(make_vector(b,a), make_vector(b,c));\n}\n\ntemplate\nvoid convex_hull(const MultiPoint& in, MultiPoint& out) {\n\n\ttypedef bg::model::point point_t;\n\tpoint_t min_coordinate;\n\n\tbool flag = false;\n\n\t// TODO : Remove points which cannot be a part of a convex hull\n\tfor (const auto &point : in) {\n\t\tif (!flag) {\n\t\t\tbg::set<0>(min_coordinate, bg::get<0>(point));\n\t\t\tbg::set<1>(min_coordinate, bg::get<1>(point));\n\t\t\tflag = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (bg::get<0>(point) < bg::get<0>(min_coordinate) || \n\t\t\t\t(bg::get<0>(point) == bg::get<0>(min_coordinate) &&\n\t\t\t\t bg::get<1>(point) < bg::get<1>(min_coordinate))) {\n\t\t\t\n\t\t\tbg::set<0>(min_coordinate, bg::get<0>(point));\n\t\t\tbg::set<1>(min_coordinate, bg::get<1>(point));\n\t\t}\n\t}\n\t\n\tpoint_t B(bg::get<0>(min_coordinate), bg::get<1>(min_coordinate)-1.0);\t// Before\n\tpoint_t S(bg::get<0>(min_coordinate), bg::get<1>(min_coordinate));\t// Start\n\tpoint_t T;\t// To\n\n\tbg::append(out, S);\n\n\twhile(1) {\n\t\tdouble min_cos_value = 1.0;\n\t\tpoint_t p;\n\t\tfor (const auto &point : in) {\n\t\t\tbg::set<0>(T, bg::get<0>(point));\n\t\t\tbg::set<1>(T, bg::get<1>(point));\n\n\t\t\tif (bg::get<0>(S)==bg::get<0>(T) && bg::get<1>(S)==bg::get<1>(T)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdouble cos_value = cos_from_dots(B,S,T);\n\n\t\t\tif (cos_value < min_cos_value) {\n\t\t\t\tmin_cos_value = cos_value;\n\t\t\t\tbg::set<0>(p, bg::get<0>(T));\n\t\t\t\tbg::set<1>(p, bg::get<1>(T));\n\t\t\t}\n\t\t}\n\t\tbg::append(out, p);\n\t\tif (bg::get<0>(p)==bg::get<0>(min_coordinate) &&\n\t\t\tbg::get<1>(p)==bg::get<1>(min_coordinate)) {\n\t\t\t// Break because Pi+1 == P0 \n\t\t\tbreak;\n\t\t}\n\n\t\t// B = S\n\t\tbg::set<0>(B, bg::get<0>(S));\n\t\tbg::set<1>(B, bg::get<1>(S));\n\n\t\t// S = p\n\t\tbg::set<0>(S, bg::get<0>(p));\n\t\tbg::set<1>(S, bg::get<1>(p));\n\t}\n}\n\n\n\n", "meta": {"hexsha": "37eae7193f487d9559a0945510664a7982a96232", "size": 2553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "convex_hull.hpp", "max_stars_repo_name": "rika77/boost", "max_stars_repo_head_hexsha": "4dd09da3173ee7fda0a1bc8ad3f53aff95327a6e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-07T00:17:47.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-07T00:17:47.000Z", "max_issues_repo_path": "convex_hull.hpp", "max_issues_repo_name": "rika77/convex_hull_with_boost", "max_issues_repo_head_hexsha": "4dd09da3173ee7fda0a1bc8ad3f53aff95327a6e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "convex_hull.hpp", "max_forks_repo_name": "rika77/convex_hull_with_boost", "max_forks_repo_head_hexsha": "4dd09da3173ee7fda0a1bc8ad3f53aff95327a6e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2772277228, "max_line_length": 81, "alphanum_fraction": 0.6153544849, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642804, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6979870412896301}} {"text": "#pragma once\n\n#include \n#include \n#include \n\n#include \"boundary.hpp\"\n#include \"mass_matrix_assembly.hpp\"\n#include \"neumann_boundary_assemble.hpp\"\n#include \"stiffness_matrix_assembly.hpp\"\n\n//! Evolves the solution in time using the explicit Forward Euler scheme\n//!\n//! @param vertices the list of vertices that build the triangular mesh\n//! @param triangles the list of indices that represent the triangular mesh\n//! @param u0 the initial data\n//! @param gamma the parameter gamma (has to do with the boundary conditions)\n//! @param m number of timesteps to perform\n//! @returns a pair which contains as first parameter the solution at time = 1,\n//! and second parameter the energy evolving over time.\nstd::pair> radiativeTimeEvolutionExplicit(const Eigen::MatrixXd &vertices,\n const Eigen::MatrixXi &triangles,\n const Eigen::VectorXd &u0,\n const double gamma,\n const int m) {\n\tstd::vector energy;\n\tEigen::VectorXd u(u0.size());\n\tu = u0;\n\n\tdouble dt = 1.0 / m;\n\n\t// Get the edges, this is used to compute the neumann boundary matrix\n\tEigen::MatrixXi edges = getBoundaryEdges(vertices, triangles);\n\n\t// Define the needed matrices and solvers\n\tSparseMatrix M = assembleMassMatrix(vertices, triangles);\n\tSparseMatrix A = assembleStiffnessMatrix(vertices, triangles);\n\tSparseMatrix B = assembleBoundaryMatrix(vertices, edges, gamma);\n\tA += B;\n\n\tEigen::SimplicialLDLT SolverM;\n\tSolverM.compute(M);\n\n\tif (SolverM.info() != Eigen::Success) {\n\t\tthrow std::runtime_error(\"Could not decompose matrix M\");\n\t}\n\n\t// (write your solution here)\n\tfor (int timestep = 0; timestep < m; ++timestep) {\n\t\t// Step the solution forward in time\n\t\t// (write your solution here)\n\t\tu += SolverM.solve(-1.0 * dt * A * u).eval();\n\n\t\tenergy.push_back(u.sum() / u.rows());\n\t}\n\n\treturn std::make_pair(u, energy);\n}\n", "meta": {"hexsha": "fda557867a736ad373b7591c381ac0c49cf1cd40", "size": 2229, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series4/2d-rad-cooling/time_evolution_explicit.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series4/2d-rad-cooling/time_evolution_explicit.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series4/2d-rad-cooling/time_evolution_explicit.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7796610169, "max_line_length": 112, "alphanum_fraction": 0.6173171826, "num_tokens": 472, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6979499093450098}} {"text": "/*\n * @Description: utils for ceres residual block analytic Jacobians\n * @Author: Ge Yao\n * @Date: 2020-11-29 15:47:49\n */\n#ifndef LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_UTILS_HPP_\n#define LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_UTILS_HPP_\n\n#include \n#include \n#include \n\n#include \n\nnamespace sliding_window {\n\nEigen::Matrix3d JacobianRInv(const Eigen::Vector3d &w) {\n Eigen::Matrix3d J_r_inv = Eigen::Matrix3d::Identity();\n\n double theta = w.norm();\n\n if ( theta > 1e-5 ) {\n Eigen::Vector3d k = w.normalized();\n Eigen::Matrix3d K = Sophus::SO3d::hat(k);\n \n J_r_inv = J_r_inv \n + 0.5 * K\n + (1.0 - (1.0 + std::cos(theta)) * theta / (2.0 * std::sin(theta))) * K * K;\n }\n\n return J_r_inv;\n}\n\n} // namespace sliding_window\n\n#endif // LIDAR_LOCALIZATION_MODELS_SLIDING_WINDOW_UTILS_HPP_", "meta": {"hexsha": "92dfdb5826f14dc400df6e486a2e4fce33a46112", "size": 916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/utils/utils.hpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/utils/utils.hpp", "max_issues_repo_name": "lanqing30/SensorFusionCourse", "max_issues_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GraphOptimize/09-sliding-window/src/lidar_localization/include/lidar_localization/models/sliding_window/utils/utils.hpp", "max_forks_repo_name": "lanqing30/SensorFusionCourse", "max_forks_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T01:05:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T01:05:31.000Z", "avg_line_length": 25.4444444444, "max_line_length": 94, "alphanum_fraction": 0.6517467249, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588052782736, "lm_q2_score": 0.7853085708384735, "lm_q1q2_score": 0.6979499071931902}} {"text": "/**\n * @file visual_ekf.hpp\n * @author Ziyou Zhang (ziyou.zhang@outlook.com)\n * @brief Design of visual-based EKF estimation of dynamic object state.\n * @version 0.1\n * @date 2020-09-18\n * \n * @copyright Copyright (c) 2020\n * \n */\n\n#ifndef VISUAL_EKF_HPP_\n#define VISUAL_EKF_HPP_\n\n#include \n#include \n\n#include \n#include \n\nstruct ObjectState\n{\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n double mass;\n double timestamp; // Time stamp in seconds.\n Eigen::Vector3d r_W; // The position relative to the W frame.\n Eigen::Quaterniond q_WO; // The quaternion of rotation W-O.\n Eigen::Vector3d v_O; // The velocity expressed in object frame.\n Eigen::Vector3d omega_O; // The angular velocity expressed in object frame.\n Eigen::Matrix inertia; //The moment of inertia.\n Eigen::Matrix inertia_inverse; // The inverse of moment of inertia, stored for better efficiency.\n\n ObjectState()\n {\n inertia << 0.5 / 12, 0, 0,\n 0, 0.5 / 12, 0,\n 0, 0, 0.5 / 12;\n\n inertia_inverse = inertia.inverse();\n }\n};\n\nstruct ObjectStateDerivative\n{\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n double timestamp; // Time stamp in seconds.\n Eigen::Vector3d r_W_dot; // The position relative to the W frame.\n Eigen::Quaterniond q_WO_dot; // The quaternion of rotation W-O.\n Eigen::Vector3d v_O_dot; // The velocity expressed in object frame.\n Eigen::Vector3d omega_O_dot; // The angular velocity expressed in object frame.\n};\n\nstruct ApriltagMeasurement\n{\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n double timestamp; // Time stamp in seconds.\n Eigen::Vector3d r_W; // The position relative to the W frame.\n Eigen::Quaterniond q_WO; // The quaternion of rotation W-O.\n};\n\nclass VisualEKF\n{\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n VisualEKF();\n ~VisualEKF();\n\n /**\n * @brief The initialisation state.\n * \n * @return true if initialised\n * @return false if not initialised\n */\n bool isInitialsed();\n\n /**\n * @brief Initialise the EKF with the initial state.\n * \n * @param initialState Initial object state.\n * @return true if successfully executed.\n */\n bool initialise(const ObjectState initialState);\n\n /**\n * @brief The predict step in EKF.\n * \n * @param dt The time difference.\n * @param fromState The previous state.\n * @param toState The predicted state.\n * @return true if successfully executed.\n */\n bool predict(const double dt,\n const ObjectState &fromState,\n ObjectState &toState);\n\n /**\n * @brief The update step in EKF.\n * \n * @param apriltagMeasurement The apriltag measurement (pose and oritation of the object).\n * @return true if successfully executed.\n */\n bool update(const ApriltagMeasurement apriltagMeasurement);\n\n /**\n * @brief The state transition using trapezoidal numerical integration.\n * \n * @param object_state_k_minues_1 The state at previous step.\n * @param object_state_1 The resulting state after trapezoidal numerical integration.\n * @param dt The time difference.\n * @param jacobian The jacobian matrix to be calculated.\n * @return true if successfully executed.\n */\n bool stateTransition(const ObjectState &object_state_k_minues_1,\n ObjectState &object_state_1,\n const double dt,\n Eigen::Matrix &jacobian);\n\n /**\n * @brief Calculate the derivatives based on the motion model.\n * \n * @param state The object state.\n * @return ObjectStateDerivative The object state derivatives.\n */\n ObjectStateDerivative calcStateDerivative(const ObjectState &state);\n\n /**\n * @brief Calculate the jacobian matrix.\n * \n * @param state The object state.\n * @param dt The time difference.\n * @param jacobian The jacobian matrix to be calculated.\n * @return true if successfully executed.\n */\n bool calcJacobian(const ObjectState &state,\n const double &dt,\n Eigen::Matrix &jacobian);\n\nprivate:\n // The object states.\n ObjectState x_;\n ObjectState x_predicted_;\n ObjectState x_temp_;\n\n // The initialsation information.\n bool initialised = false;\n\n // The error matrix and jacobian matrix.\n Eigen::Matrix P_;\n Eigen::Matrix jacobian;\n\n // Process noise params.\n double sigma_c_r_W = 0.2; // m, location error\n double sigma_c_q_WO = 0.4; // N/A, for quoternion error\n double sigma_c_v_O = 3; // m/s, velocity error\n double sigma_c_omega_O = 10; // rad/s, amgular velocity error\n\n //Measurement noise params.\n double sigma_z_r_W = 0.02; // m, pose measurement error\n double sigma_z_q_WO = 0.02; // N/A, quaternion measurement error\n\n friend class PoseDetector;\n};\n\n#endif // VISUAL_EKF_HPP_", "meta": {"hexsha": "48364d9ec8fbaa068468cd237ba44201afdb0132", "size": 5161, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/visual_ekf.hpp", "max_stars_repo_name": "ZiyouZhang/rotors_datmo", "max_stars_repo_head_hexsha": "b18a79b6b580f41efc0c12628cc471d673b83a67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-06T23:28:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-14T06:34:30.000Z", "max_issues_repo_path": "include/visual_ekf.hpp", "max_issues_repo_name": "ZiyouZhang/rotors_datmo", "max_issues_repo_head_hexsha": "b18a79b6b580f41efc0c12628cc471d673b83a67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/visual_ekf.hpp", "max_forks_repo_name": "ZiyouZhang/rotors_datmo", "max_forks_repo_head_hexsha": "b18a79b6b580f41efc0c12628cc471d673b83a67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4695121951, "max_line_length": 115, "alphanum_fraction": 0.6365045534, "num_tokens": 1261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6979499024033824}} {"text": "// 以下代码参考\n// Eigen提取block:https://blog.csdn.net/jiahao62/article/details/80655542\n// Eigen提取block:https://www.cnblogs.com/newneul/p/8306430.html\n// 求解Ax=b:https://www.cnblogs.com/newneul/p/8306442.html\n\n#include \nusing namespace std;\n#include \n#include \n\n#define MATRIX_SIZE 50\n\n#define EQUATION_NUM 3\n#define VARIABLE_NUM 3\n\nint main( int argc, char** argv )\n{\n // Eigen提取block\n Eigen::Matrix matrix_NN = Eigen::MatrixXd::Random( MATRIX_SIZE, MATRIX_SIZE );\n cout << \"before assign \\n\" << matrix_NN.block(0, 0, 3, 3) << endl;\n Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Identity();\n matrix_NN.block(0, 0, 3, 3) = matrix_33;\n cout << \"after assign \\n\" << matrix_NN.block(0, 0, 3, 3) << endl;\n\n //-------------------------------------------------------------------------------------\n // 求解Ax=b\n Eigen::Matrix A = Eigen::MatrixXd::Random(EQUATION_NUM, VARIABLE_NUM);\n Eigen::Matrix b = Eigen::MatrixXd::Random(EQUATION_NUM, 1);\n // 测试用例\n A << 10,3,1,2,-10,3,1,3,10;\n b << 14,-5,14;\n // 设置解变量\n Eigen::Matrix x;\n\n clock_t time_stt = clock(); // 计时\n \n // 方法一:直接求逆,适用条件:方阵\n x = A.inverse()*b;\n cout <<\"time use in normal inverse is \" << 1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC << \"ms\"<< endl;\n \n\t // 方法二:QR分解,适用条件:方阵和非方阵\n // 当方程组有解时的出的是真解,若方程组无解得出的是近似解\n time_stt = clock();\n x = A.colPivHouseholderQr().solve(b);\n cout << \"x^T = \" << x.transpose() <\n#include \n//#include \n#include \n#include \n#include \n\nclass Poly1d\n{\n protected:\n std::vector coefficients_;\n public:\n //============================================================================\n // Method Description:\n Poly1d() = default;\n\n //============================================================================\n // Method Description:\n std::vector getCoeffs()\n {\n return coefficients_;\n }\n\n void init (const std::vector& inValues)\n {\n // std::vector coefficients_;\n for (auto value : inValues)\n {\n coefficients_.push_back(value);\n }\n }\n \n std::vector evaluate (std::vector inValues)\n {\n std::vector result;\n \n for (int i = 0; i < inValues.size(); i++)\n {\n double polyValue = 0.0;\n int power = inValues.size() - 1;\n for (auto coeff : coefficients_)\n {\n polyValue += coeff * pow(inValues[i], power);\n power--;\n }\n result.push_back(polyValue);\n }\n \n return result;\n }\n \n void fit (std::vector &x_data, std::vector &y_data, std::vector &coeff, int order)\n {\n Eigen::MatrixXd W(x_data.size(), order + 1); \n Eigen::VectorXd I = Eigen::VectorXd::Map(&y_data.front(), y_data.size());\n Eigen::VectorXd result;\n\n assert(x_data.size() == y_data.size());\n assert(x_data.size() >= order + 1);\n\n for(std::size_t i = 0; i < x_data.size(); ++i)\n {\n for (std::size_t j = 0; j < order + 1; ++j)\n {\n W(i, j) = std::pow(x_data.at(i), j);\n }\n }\n\n// std::cout<< W << std::endl;\n\n result = W.householderQr().solve(I);\n coeff.resize(order + 1);\n\n for(std::size_t k = 0; k < order + 1; k++)\n {\n coeff[k] = result[k];\n }\n }\n};\n\n", "meta": {"hexsha": "ae3b9c529b4ca6e9f44bec785f256fa82b701314", "size": 2324, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/poly1d.cpp", "max_stars_repo_name": "anva-kn/ramanflow", "max_stars_repo_head_hexsha": "0a8852a0a8d57d97e5ccd011bc6bc8659ecd666c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "utils/poly1d.cpp", "max_issues_repo_name": "anva-kn/ramanflow", "max_issues_repo_head_hexsha": "0a8852a0a8d57d97e5ccd011bc6bc8659ecd666c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-05T06:40:27.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-07T07:18:18.000Z", "max_forks_repo_path": "utils/poly1d.cpp", "max_forks_repo_name": "anva-kn/ramanflow", "max_forks_repo_head_hexsha": "0a8852a0a8d57d97e5ccd011bc6bc8659ecd666c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6913580247, "max_line_length": 114, "alphanum_fraction": 0.4083476764, "num_tokens": 484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6978188906985098}} {"text": "#include \n\n#include \n\ntypedef boost::multiprecision::number> Precise_Decimal;\n\n/*\n Solves two conic sections equations simultaneously.\n\n It is used to find the intersection points of two conic sections.\n\n An arbitrary conic section (equation) is of the following form:\n\n Ax^2 + Bxy + Cy^2 + Dx + Ey + F = 0\n\n where A, B, C, D, and E are arbitrary coefficients, and F is an arbitrary constant.\n\n - by Melwyn Francis Carlo \n\n - Written for LibreCAD software.\n*/\nRS_VectorSolutions RS_Math::simultaneousQuadraticSolverFull(const std::vector>& input_conicSections)\n{\n RS_VectorSolutions intersectionPoints;\n\n if (input_conicSections.size() != 2) return intersectionPoints;\n\n if ((input_conicSections[0].size() == 3) || (input_conicSections[1].size() == 3))\n {\n return simultaneousQuadraticSolverMixed(input_conicSections);\n }\n\n if ((input_conicSections[0].size() != 6) || (input_conicSections[1].size() != 6))\n {\n return intersectionPoints;\n }\n\n std::vector> conicSections = input_conicSections;\n\n for (int i = 0; i < 2; i++)\n {\n unsigned int max_orderOfMagnitudeFactor = 0;\n\n for (int j = 0; j < 6; j++)\n {\n if (std::fabs(conicSections[i][j]) < RS_TOLERANCE15)\n {\n conicSections[i][j] = 0.0;\n }\n\n if (conicSections[i][j] < 1.0)\n {\n const unsigned int orderOfMagnitudeFactor = (unsigned int) std::trunc(std::fabs(std::log10(conicSections[i][j]))) + 1;\n\n if (orderOfMagnitudeFactor > max_orderOfMagnitudeFactor)\n {\n max_orderOfMagnitudeFactor = orderOfMagnitudeFactor;\n }\n }\n }\n\n for (int j = 0; j < 6; j++)\n {\n const double orderOfMagnitude = std::pow(10, max_orderOfMagnitudeFactor);\n\n conicSections[i][j] = std::trunc(conicSections[i][j] * orderOfMagnitude * 1.0E+10) * 1.0E-10;\n }\n }\n\n const Precise_Decimal a1 = conicSections[0][0];\n const Precise_Decimal b1 = conicSections[0][1];\n const Precise_Decimal c1 = conicSections[0][2];\n const Precise_Decimal d1 = conicSections[0][3];\n const Precise_Decimal e1 = conicSections[0][4];\n const Precise_Decimal f1 = conicSections[0][5];\n\n const Precise_Decimal a2 = conicSections[1][0];\n const Precise_Decimal b2 = conicSections[1][1];\n const Precise_Decimal c2 = conicSections[1][2];\n const Precise_Decimal d2 = conicSections[1][3];\n const Precise_Decimal e2 = conicSections[1][4];\n const Precise_Decimal f2 = conicSections[1][5];\n\n if ((a1 == 0.0) || (a2 == 0.0) || (c1 == 0.0) || (c2 == 0.0)) return intersectionPoints;\n\n const Precise_Decimal a1_sq = a1 * a1;\n const Precise_Decimal b1_sq = b1 * b1;\n const Precise_Decimal c1_sq = c1 * c1;\n const Precise_Decimal d1_sq = d1 * d1;\n const Precise_Decimal e1_sq = e1 * e1;\n const Precise_Decimal f1_sq = f1 * f1;\n\n const Precise_Decimal a2_sq = a2 * a2;\n const Precise_Decimal b2_sq = b2 * b2;\n const Precise_Decimal c2_sq = c2 * c2;\n const Precise_Decimal d2_sq = d2 * d2;\n const Precise_Decimal e2_sq = e2 * e2;\n const Precise_Decimal f2_sq = f2 * f2;\n\n const Precise_Decimal c1_cu = c1_sq * c1;\n\n std::vector x_n_terms(5, 0.0);\n\n /* The x^4 term. */\n x_n_terms[4] = ((a1_sq * c1 * c2_sq) + (a2_sq * c1_cu) - (2.0 * a1 * a2 * c1_sq * c2) \n + (a2 * b1_sq * c1 * c2) - (a2 * b1 * b2 * c1_sq) \n + (a1 * b2_sq * c1_sq) - (a1 * b1 * b2 * c1 * c2)).convert_to();\n\n /* The x^3 term. */\n x_n_terms[3] = ((2.0 * a1 * c1 * c2_sq * d1) + (2.0 * a2 * c1_cu * d2) - (2.0 * a1 * c1_sq * c2 * d2) - (2.0 * a2 * c1_sq * c2 * d1) \n + (2.0 * a2 * b1 * c1 * c2 * e1) + (b1_sq * c1 * c2 * d2) - (a2 * b1 * c1_sq * e2) - (a2 * b2 * c1_sq * e1) - (b1 * b2 * c1_sq * d2) \n + (2.0 * a1 * b2 * c1_sq * e2) + (b2_sq * c1_sq * d1) - (a1 * b1 * c1 * c2 * e2) - (a1 * b2 * c1 * c2 * e1) - (b1 * b2 * c1 * c2 * d1)).convert_to();\n\n /* The x^2 term. */\n x_n_terms[2] = ((2.0 * a1 * c1 * c2_sq * f1) + (2.0 * a2 * c1_cu * f2) + (c1_cu * d2_sq) + (c1 * c2_sq * d1_sq) - (2.0 * a1 * c1_sq * c2 * f2) - (2.0 * a2 * c1_sq * c2 * f1) - (2.0 * c1_sq * c2 * d1 * d2) \n + (a2 * c1 * c2 * e1_sq) + (2.0 * b1 * c1 * c2 * d2 * e1) + (b1_sq * c1 * c2 * f2) - (a2 * c1_sq * e1 * e2) - (b1 * b2 * c1_sq * f2) - (b1 * c1_sq * d2 * e2) - (b2 * c1_sq * d2 * e1) \n + (a1 * c1_sq * e2_sq) + (b2_sq * c1_sq * f1) + (2.0 * b2 * c1_sq * d1 * e2) - (a1 * c1 * c2 * e1 * e2) - (b1 * b2 * c1 * c2 * f1) - (b1 * c1 * c2 * d1 * e2) - (b2 * c1 * c2 * d1 * e1)).convert_to();\n\n /* The x term. */\n x_n_terms[1] = ((2.0 * c1_cu * d2 * f2) + (2.0 * c1 * c2_sq * d1 * f1) - (2.0 * c1_sq * c2 * d1 * f2) - (2.0 * c1_sq * c2 * d2 * f1) \n + (2.0 * b1 * c1 * c2 * e1 * f2) + (c1 * c2 * d2 * e1_sq) - (b1 * c1_sq * e2 * f2) - (b2 * c1_sq * e1 * f2) - (c1_sq * d2 * e1 * e2) \n + (c1_sq * d1 * e2_sq) + (2.0 * b2 * c1_sq * e2 * f1) - (b1 * c1 * c2 * e2 * f1) - (b2 * c1 * c2 * e1 * f1) - (c1 * c2 * d1 * e1 * e2)).convert_to();\n\n /* The constant term. */\n x_n_terms[0] = ((c1_cu * f2_sq) + (c1 * c2_sq * f1_sq) - (2.0 * c1_sq * c2 * f1 * f2) \n + (c1 * c2 * e1_sq * f2) - (c1_sq * e1 * e2 * f2) \n + (c1_sq * e2_sq * f1) - (c1 * c2 * e1 * e2 * f1)).convert_to();\n\n if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)\n {\n DEBUG_HEADER\n std::cout << std::endl << std::endl \n << \" (\" << x_n_terms[4] << \")x^4 + \" \n << \"(\" << x_n_terms[3] << \")x^3 + \" \n << \"(\" << x_n_terms[2] << \")x^2 + \" \n << \"(\" << x_n_terms[1] << \")x + \" \n << \"(\" << x_n_terms[0] << \") = 0\" \n << std::endl << std::endl;\n\n const double a = x_n_terms[4];\n const double b = x_n_terms[3];\n const double c = x_n_terms[2];\n const double d = x_n_terms[1];\n const double e = x_n_terms[0];\n\n const double a_sq = a * a;\n const double b_sq = b * b;\n const double c_sq = c * c;\n const double d_sq = d * d;\n const double e_sq = e * e;\n\n const double a_cu = a * a * a;\n const double b_cu = b * b * b;\n const double c_cu = c * c * c;\n const double d_cu = d * d * d;\n const double e_cu = e * e * e;\n\n std::cout << \" Discriminant (Delta) = \" \n << (256.0 * a_cu * e_cu) - (192.0 * a_sq * b * d * e_sq) - (128.0 * a_sq * c_sq * e_sq) \n + (144.0 * a_sq * c * d_sq * e) - (27.0 * a_sq * d_cu * d) + (144.0 * a * b_sq * c * e_sq) \n - (6.0 * a * b_sq * d_sq * e) - (80.0 * a * b * c_sq * d * e) + (18.0 * a * b * c * d_cu) \n + (16.0 * a * c_cu * c * e) - (4.0 * a * c_cu * d_sq) - (27.0 * b_cu * b * e_sq) \n + (18.0 * b_cu * c * d * e) - (4.0 * b_cu * d_cu) - (4.0 * b_sq * c_cu * e) + (b_sq * c_sq * d_sq) \n << std::endl << std::endl;\n\n std::cout << \" P Factor = \" \n << (8.0 * a * c) - (3.0 * b_sq) \n << std::endl << std::endl;\n\n std::cout << \" D Factor = \" \n << (64.0 * a_cu * e) - (16.0 * a_sq * c_sq) + (16.0 * a * b_sq * c) - (16.0 * a_sq * b * d) - (3 * b_cu * b) \n << std::endl << std::endl;\n }\n\n\tstd::vector rootsAbscissae = quarticSolverFull(x_n_terms);\n\n if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)\n {\n std::cout << \" Number of quartic roots = \" << rootsAbscissae.size() \n << std::endl << std::endl;\n }\n\n for (double& rootX : rootsAbscissae)\n {\n const Precise_Decimal rootXPrecise = rootX;\n\n const Precise_Decimal sqrtTerm1 = boost::multiprecision::trunc(((((b1 * rootXPrecise) + e1) * ((b1 * rootXPrecise) + e1)) \n - (4.0 * c1 * ((a1 * rootXPrecise * rootXPrecise) + (d1 * rootXPrecise) + f1))) * 1.0E+4) * 1.0E-4;\n\n const Precise_Decimal sqrtTerm2 = boost::multiprecision::trunc(((((b2 * rootXPrecise) + e2) * ((b2 * rootXPrecise) + e2)) \n - (4.0 * c2 * ((a2 * rootXPrecise * rootXPrecise) + (d2 * rootXPrecise) + f2))) * 1.0E+4) * 1.0E-4;\n\n if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)\n {\n std::cout << \" RootX square root terms : \" \n << sqrtTerm1 << \", \" << sqrtTerm2 \n << std::endl << std::endl;\n }\n\n if ((sqrtTerm1 < 0.0) || (sqrtTerm2 < 0.0)) continue;\n\n const Precise_Decimal numeratorTerm1 = (-b1 * rootXPrecise) - e1;\n const Precise_Decimal numeratorTerm2 = (-b2 * rootXPrecise) - e2;\n\n const Precise_Decimal denominatorTerm1 = 2.0 * c1;\n const Precise_Decimal denominatorTerm2 = 2.0 * c2;\n\n const RS_Vector conic_1_points[2] = \n {\n RS_Vector(rootX, ((numeratorTerm1 + boost::multiprecision::sqrt(sqrtTerm1)) / denominatorTerm1).convert_to()), \n RS_Vector(rootX, ((numeratorTerm1 - boost::multiprecision::sqrt(sqrtTerm1)) / denominatorTerm1).convert_to()) \n };\n\n const RS_Vector conic_2_points[2] = \n {\n RS_Vector(rootX, ((numeratorTerm2 + boost::multiprecision::sqrt(sqrtTerm2)) / denominatorTerm2).convert_to()), \n RS_Vector(rootX, ((numeratorTerm2 - boost::multiprecision::sqrt(sqrtTerm2)) / denominatorTerm2).convert_to()) \n };\n\n if (((fabs(conic_1_points[0].x - conic_2_points[0].x) < 1.0E-4) \n && (fabs(conic_1_points[0].y - conic_2_points[0].y) < 1.0E-4)) \n || ((fabs(conic_1_points[0].x - conic_2_points[1].x) < 1.0E-4) \n && (fabs(conic_1_points[0].y - conic_2_points[1].y) < 1.0E-4)))\n {\n intersectionPoints.push_back(conic_1_points[0]);\n }\n\n\n if (((fabs(conic_1_points[1].x - conic_2_points[0].x) < 1.0E-4) \n && (fabs(conic_1_points[1].y - conic_2_points[0].y) < 1.0E-4)) \n || ((fabs(conic_1_points[1].x - conic_2_points[1].x) < 1.0E-4) \n && (fabs(conic_1_points[1].y - conic_2_points[1].y) < 1.0E-4)))\n {\n intersectionPoints.push_back(conic_1_points[1]);\n }\n\n if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)\n {\n std::cout << \" Available roots : \" << std::endl \n << \" 1.1. \" << conic_1_points[0] << std::endl \n << \" 1.2. \" << conic_1_points[1] << std::endl \n << \" 2.1. \" << conic_2_points[0] << std::endl \n << \" 2.2. \" << conic_2_points[1] << std::endl << std::endl;\n\n std::cout << \" Chosen root : \" << intersectionPoints [intersectionPoints.size() - 1] \n << std::endl << std::endl;\n }\n }\n\n if (RS_DEBUG->getLevel() >= RS_Debug::D_INFORMATIONAL)\n {\n std::cout << \" Number of intersection points = \" << intersectionPoints.size() \n << std::endl << std::endl;\n }\n\n return intersectionPoints;\n}\n\n", "meta": {"hexsha": "eaa9dbb171deacd49dd0ddaa6a9553878e493219", "size": 11412, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CPP/Biconics_Sections_Intersections_Solver/biconics_sections_intersections_solver.cpp", "max_stars_repo_name": "melwyncarlo/Personal_Libraries_and_Code", "max_stars_repo_head_hexsha": "b04dcf03405e85c72796273f703bd293d934f7aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CPP/Biconics_Sections_Intersections_Solver/biconics_sections_intersections_solver.cpp", "max_issues_repo_name": "melwyncarlo/Personal_Libraries_and_Code", "max_issues_repo_head_hexsha": "b04dcf03405e85c72796273f703bd293d934f7aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CPP/Biconics_Sections_Intersections_Solver/biconics_sections_intersections_solver.cpp", "max_forks_repo_name": "melwyncarlo/Personal_Libraries_and_Code", "max_forks_repo_head_hexsha": "b04dcf03405e85c72796273f703bd293d934f7aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.0617760618, "max_line_length": 225, "alphanum_fraction": 0.5171749036, "num_tokens": 4050, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6977784326908261}} {"text": "//\n// Created by alex on 26/05/20.\n//\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"Utils.h\"\n\nusing namespace std;\n\nvector> Utils::loadGEucSpace(const string &file_path) {\n auto vertices = readVList(file_path);\n int n = vertices.size();\n vector> D(n, vector(n));\n\n for (size_t i = 0; i < n; ++i) {\n for (size_t j = i + 1; j < n; ++j) {\n\n auto v1 = vertices[i];\n auto v2 = vertices[j];\n\n // computing euclidean distance\n vector subtracted;\n subtracted.reserve(v1.size());\n transform(v1.begin(), v1.end(), v2.begin(), back_inserter(subtracted),\n [](float a, float b) { return pow(a - b, 2); });\n double d = sqrt(accumulate(subtracted.begin(), subtracted.end(), 0.0));\n D[j][i] = D[i][j] = (int)(d+0.5);\n }\n }\n return D;\n}\n\nstd::vector> Utils::readVList(const std::string &file_path) {\n\n std::vector> vertices;\n std::string line;\n std::ifstream file(file_path);\n\n if (file.is_open()) {\n\n getline(file, line);\n boost::trim_right(line);\n boost::trim_left(line);\n\n std::vector line_vec;\n boost::split(line_vec, line, boost::is_any_of(\" \"));\n\n if (line_vec.size() != 1 && line_vec.size() != 3) {\n std::cerr << \"Error in line \" << line << std::endl;\n throw;\n }\n\n std::vector xy(2);\n if (line_vec.size() == 1) {\n int n = stoi(line);\n vertices.reserve(n);\n } else {\n std::transform(line_vec.begin() + 1, line_vec.end(), xy.begin(),\n [](std::string const &val) { return stof(val); });\n vertices.push_back(xy);\n }\n\n while (getline(file, line)) {\n boost::trim_right(line);\n boost::trim_left(line);\n boost::split(line_vec, line, boost::is_any_of(\" \"));\n\n if (line_vec.size() != 3) {\n std::cerr << \"Error in line \" << line << std::endl;\n throw;\n }\n\n std::transform(line_vec.begin() + 1, line_vec.end(), xy.begin(),\n [](std::string const &val) { return stof(val); });\n vertices.push_back(xy);\n }\n file.close();\n } else {\n std::cerr << \"Unable to open file\" << std::endl;\n }\n return vertices;\n}\n\nstd::vector> Utils::loadGMetricSpace(int n, const std::string &file_path) {\n std::vector> G(n, std::vector(n));\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n G[i][j] = i != j ? +INFINITY : 0;\n }\n }\n\n std::string line;\n std::ifstream file(file_path);\n\n if (file.is_open()) {\n\n std::vector line_vec;\n while (getline(file, line)) {\n boost::trim_right(line);\n boost::trim_left(line);\n boost::split(line_vec, line, boost::is_any_of(\" \"));\n\n if (line_vec.size() != 3) {\n std::cerr << \"Error in line \" << line << std::endl;\n throw;\n }\n\n int v1 = stoi(line_vec[0]) - 1;\n int v2 = stoi(line_vec[1]) - 1;\n float w = stof(line_vec[2]);\n\n G[v1][v2] = w;\n G[v2][v1] = w;\n }\n file.close();\n } else {\n std::cerr << \"Unable to open file\" << std::endl;\n }\n floydWarshall(G);\n return G;\n}\n\nvoid Utils::floydWarshall(std::vector> &G) {\n int n = G.size();\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n for (int l = 0; l < n; ++l) {\n float cost = (G[i][j] == +INFINITY || G[i][l] == +INFINITY) ?\n +INFINITY : G[i][j] + G[i][l];\n if (cost < G[j][l]) {\n G[j][l] = cost;\n }\n }\n }\n }\n}\n\nfloat Utils::stdDev(std::vector &items, float average) {\n float std = 0;\n for (float item : items) {\n std += pow(item - average, 2);\n }\n int n = items.size() > 2 ? items.size() - 1 : items.size();\n return sqrt(std / n);\n}\n\nbool Utils::save(std::string &output_path, std::string &content) {\n std::ofstream output_file(output_path);\n// output_file.write(&content, content.size());\n output_file << content;\n output_file.close();\n return true;\n}\n", "meta": {"hexsha": "cbdaf5da47d492c0aa525cac1d1079b07debfde6", "size": 4608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/util/Utils.cpp", "max_stars_repo_name": "alex-cornejo/ckc-heuristic", "max_stars_repo_head_hexsha": "7190df6bc4410c99313a21cb5d656640fc993209", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-09-02T17:24:35.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-04T14:20:22.000Z", "max_issues_repo_path": "src/util/Utils.cpp", "max_issues_repo_name": "alex-cornejo/ckc-heuristic", "max_issues_repo_head_hexsha": "7190df6bc4410c99313a21cb5d656640fc993209", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util/Utils.cpp", "max_forks_repo_name": "alex-cornejo/ckc-heuristic", "max_forks_repo_head_hexsha": "7190df6bc4410c99313a21cb5d656640fc993209", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8, "max_line_length": 94, "alphanum_fraction": 0.4928385417, "num_tokens": 1230, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026528034425, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6977468615575466}} {"text": "#include \n#include \"zeroSumGame.h\"\n#include \"gurobi_c++.h\"\n\nusing namespace arma;\nusing namespace std;\n\n\nbool ZeroSumGame::solveGame(const Mat &payoffMat, double &gameValue, Col &p, Col &q, double diffThreshold, bool checkNonnegative)\n{\n double maximumGain = 0;\n double minimumLoss = 0;\n if(!maximizePayoff(payoffMat,maximumGain,p,checkNonnegative)) return false;\n if(!minimizePayoff(payoffMat,minimumLoss,q,checkNonnegative)) return false;\n \n Col absValues(2);\n absValues(0) = abs(maximumGain);\n absValues(1) = abs(minimumLoss);\n \n double abs_gain_loss_diff = abs(maximumGain-minimumLoss);\n double diff_portion = abs_gain_loss_diff/max(absValues);\n if (diff_portion < diffThreshold) {\n gameValue = (maximumGain+minimumLoss)/2;\n return true;\n }\n return false;\n}\n\nbool ZeroSumGame::maximizePayoff(const Mat &payoffMat, double &maximumGain, Col &p, bool checkNonnegative)\n{\n if (checkNonnegative==true) {\n double minValuePayoffMat = min(min(payoffMat));\n if (minValuePayoffMat <= 0) {\n cout << \"all elements of the payoffMat must be positive!\" << endl;\n throw 2;\n }\n }\n \n int numRows = payoffMat.n_rows;\n int numCols = payoffMat.n_cols;\n \n bool success = false;\n GRBEnv* env = 0;\n try{\n env = new GRBEnv();\n GRBModel model = GRBModel(*env);\n /* No solving information printed */\n model.getEnv().set(GRB_IntParam_OutputFlag, 0);\n /* Add varialbe to the model */\n /* first NULL means low bound is 0.0 and seconde NULL means up bound is infinite by default */\n GRBVar* vars = model.addVars(NULL,NULL,NULL,NULL,NULL,numRows);\n model.update();\n \n /* Populate payoffMat matrix */\n for (int j = 0; j < numCols; j++) {\n GRBLinExpr lhs = 0;\n for (int i = 0; i < numRows; i++)\n if(payoffMat(i,j) != 0)\n lhs += payoffMat(i,j)*vars[i];\n model.addConstr(lhs,GRB_GREATER_EQUAL,1.0);\n }\n \n GRBLinExpr obj = 0;\n \n for (int i = 0; i >(numRows);\n for (int i = 0; i < numRows; i++)\n p(i) = vars[i].get(GRB_DoubleAttr_X)*maximumGain;\n success = true;\n }\n \n //cout << \"maximum gain:\" << maximumGain << endl;\n delete [] vars;\n \n }catch(GRBException e) {\n cout << \"Error code = \" << e.getErrorCode() << endl;\n cout << e.getMessage() << endl;\n } catch(...) {\n cout << \"Exception during optimization\" << endl;\n }\n delete env;\n return success;\n}\n\nbool ZeroSumGame::minimizePayoff(const Mat &payoffMat, double &minimumLoss, Col &q, bool checkNonnegative)\n{\n if (checkNonnegative==true) {\n double minValuePayoffMat = min(min(payoffMat));\n if (minValuePayoffMat <= 0) {\n cout << \"all elements of the payoffMat must be positive!\" << endl;\n throw 2;\n }\n }\n int numRows = payoffMat.n_rows;\n int numCols = payoffMat.n_cols;\n \n bool success = false;\n GRBEnv* env = 0;\n try{\n env = new GRBEnv();\n GRBModel model = GRBModel(*env);\n /* No solving information printed */\n model.getEnv().set(GRB_IntParam_OutputFlag, 0);\n /* Add varialbe to the model */\n /* first NULL means low bound is 0.0 and seconde NULL means up bound is infinite by default */\n GRBVar* vars = model.addVars(NULL,NULL,NULL,NULL,NULL,numCols);\n model.update();\n \n /* Populate A matrix */\n for (int i = 0; i < numRows; i++) {\n GRBLinExpr lhs = 0;\n for (int j = 0; j < numCols; j++)\n if(payoffMat(i,j) != 0)\n lhs += payoffMat(i,j)*vars[j];\n model.addConstr(lhs,GRB_LESS_EQUAL,1.0);\n }\n \n GRBLinExpr obj = 0;\n \n for (int j = 0; j >(numCols);\n for (int j = 0; j < numCols; j++)\n q(j) = vars[j].get(GRB_DoubleAttr_X)*minimumLoss;\n success = true;\n }\n \n //cout << \"minimum loss:\" << minimumLoss << endl;\n \n delete [] vars;\n \n }catch(GRBException e) {\n cout << \"Error code = \" << e.getErrorCode() << endl;\n cout << e.getMessage() << endl;\n } catch(...) {\n cout << \"Exception during optimization\" << endl;\n }\n delete env;\n return success;\n}\n", "meta": {"hexsha": "791a8c32e97376cb5b199ed357daddd6e98409e8", "size": 5002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gurobi_C++/src/ZeroSumGame.cpp", "max_stars_repo_name": "xiangli-chen/two-person-zero-sum-game", "max_stars_repo_head_hexsha": "53e9a7a53009d9483b31d96cb0171d57819676fd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gurobi_C++/src/ZeroSumGame.cpp", "max_issues_repo_name": "xiangli-chen/two-person-zero-sum-game", "max_issues_repo_head_hexsha": "53e9a7a53009d9483b31d96cb0171d57819676fd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gurobi_C++/src/ZeroSumGame.cpp", "max_forks_repo_name": "xiangli-chen/two-person-zero-sum-game", "max_forks_repo_head_hexsha": "53e9a7a53009d9483b31d96cb0171d57819676fd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0641025641, "max_line_length": 153, "alphanum_fraction": 0.5757696921, "num_tokens": 1348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625012602593, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6977466387547238}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \"Derivative.h\"\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nusing Eigen::Derivative;\n\nusing std::function;\nusing std::vector;\n\ntypedef function FuncDV;\ntypedef function FuncVV;\ntypedef function FuncMV;\n\nMatrixXd MakePositiveSemidefinite(MatrixXd mat, int dim){\n double left = 0, right = std::max(-mat.minCoeff(), .0) + 1;\n while(right - left >= 1e-4){\n double mid = (left+right)/2;\n auto test = mat + mid*MatrixXd::Identity(dim, dim);\n // From https://stackoverflow.com/questions/35227131/eigen-check-if-matrix-is-positive-semi-definite\n\n Eigen::LLT lltOfA(test);\n if(lltOfA.info() == Eigen::NumericalIssue)\n left = mid;\n else\n right = mid;\n }\n return mat + right*MatrixXd::Identity(dim, dim);\n}\n\nVectorXd doIPM(\n FuncDV F, FuncVV DelF, FuncMV LaplaceF,\n FuncVV H, FuncMV DelH, vector LaplaceH,\n int dimX, int dimH, VectorXd initX\n){\n double mu = 0.0001;\n\n std::function feasible = [dimH](VectorXd _f){\n for(int lx = 0;lx < dimH;lx++)\n if(_f[lx] < 0)\n return false;\n return true; \n };\n\n std::function \n L = [mu, F, H, dimH](VectorXd x, VectorXd y, VectorXd w){\n double barrier = 0;\n for(int lx = 0;lx < dimH;lx++)\n barrier += log(w[lx]);\n return F(x) - mu*barrier - y.transpose()*(H(x) - w);\n };\n\n VectorXd x = initX, y, w = H(initX);\n\n { \n MatrixXd A = DelH(x).transpose();\n MatrixXd invA = A.completeOrthogonalDecomposition().pseudoInverse();\n y = invA*DelF(x);\n }\n \n for(;;){\n VectorXd h = H(x), e = VectorXd::Ones(dimH);\n MatrixXd W = w.asDiagonal(), invY = y.asDiagonal().inverse();\n\n MatrixXd Hess = LaplaceF(x);\n for(int lx = 0;lx < dimH;lx++)\n Hess -= y[lx]*LaplaceH[lx](x);\n\n // Find ~H = H + lambda * I\n Hess = MakePositiveSemidefinite(Hess, dimX);\n\n MatrixXd A = DelH(x);\n MatrixXd M1(dimX + dimH, dimX + dimH);\n\n M1 << -Hess, A.transpose(),\n A, W*invY ;\n\n VectorXd V1(dimX + dimH);\n \n V1 << DelF(x) - A.transpose()*y,\n - h + mu*invY*e ;\n\n VectorXd dxy = M1.inverse()*V1;\n VectorXd dx, dy, dw;\n\n dx = dxy.head(dimX);\n dy = dxy.tail(dimH);\n dw = invY*mu*e - W*e - invY*W*dy;\n\n x += dx, y += dy, w += dw;\n\n if(dx.norm() <= 0.001)\n break;\n }\n\n return x;\n}\n\n// Solve : min obj_f\n// sub con_hs >= 0 \n\nVectorXd Derivative_IPM(Derivative obj_f, vector con_hs, VectorXd start_guess){\n int x_size = start_guess.size(), h_size = con_hs.size();\n\n vector v1w(x_size);\n vector< vector > v2w(x_size, v1w);\n\n vector f_gradient = v1w;\n vector< vector > f_hess = v2w;\n\n vector< vector > hs_gradient(h_size, v1w);\n vector< vector< vector > > hs_hess(h_size, v2w);\n\n // Prebuild differiential function\n \n for(int lx = 0;lx < x_size;lx++)\n f_gradient[lx] = obj_f.diffPartial(lx);\n\n for(int lx = 0;lx < x_size;lx++)\n for(int ly = 0;ly < x_size;ly++)\n f_hess[lx][ly] = f_gradient[lx].diffPartial(ly);\n \n for(int lh = 0;lh < h_size;lh++){\n for(int lx = 0;lx < x_size;lx++)\n hs_gradient[lh][lx] = con_hs[lh].diffPartial(lx);\n\n for(int lx = 0;lx < x_size;lx++)\n for(int ly = 0;ly < x_size;ly++)\n hs_hess[lh][lx][ly] = hs_gradient[lh][lx].diffPartial(ly);\n }\n\n FuncDV F = [obj_f](VectorXd x){\n return obj_f(x);\n };\n\n FuncVV DelF = [f_gradient, x_size](VectorXd x){\n VectorXd ret(x_size);\n for(int lx = 0;lx < x_size;lx++)\n ret[lx] = f_gradient[lx](x);\n return ret;\n };\n\n FuncMV LaplaceF = [f_hess, x_size](VectorXd x){ \n MatrixXd ret(x_size, x_size);\n for(int lx = 0;lx < x_size;lx++)\n for(int ly = 0;ly < x_size;ly++)\n ret(lx, ly) = f_hess[lx][ly](x);\n return ret; \n };\n\n FuncVV H = [con_hs, h_size](VectorXd x){\n VectorXd ret(h_size);\n for(int lx = 0;lx < h_size;lx++)\n ret[lx] = con_hs[lx](x);\n return ret;\n };\n\n FuncMV DelH = [hs_gradient, h_size, x_size](VectorXd x){\n MatrixXd A(h_size, x_size);\n for(int lh = 0;lh < h_size;lh++)\n for(int lx = 0;lx < x_size;lx++)\n A(lh, lx) = hs_gradient[lh][lx](x);\n return A;\n };\n \n vector LaplaceH(h_size);\n \n for(int lh = 0;lh < h_size;lh++){\n LaplaceH[lh] = [hs_hess, lh, x_size](VectorXd x){\n MatrixXd ret(x_size, x_size);\n for(int lx = 0;lx < x_size;lx++)\n for(int ly = 0;ly < x_size;ly++)\n ret(lx, ly) = hs_hess[lh][lx][ly](x);\n return ret;\n };\n };\n \n return doIPM(F, DelF, LaplaceF, H, DelH, LaplaceH, start_guess.size(), con_hs.size(), start_guess); \n}\n\nint main(){\n // Reference : http://www.princeton.edu/~rvdb/tex/talks/MLSS_LaPalma/LaPalma3.pdf\n // Solve : min x+y\n // sub xx + yy >= 1 \n // x >= 0 \n // y >= 0 \n\n Derivative par_x = Derivative::Variable(0), par_y = Derivative::Variable(1);\n Derivative obj_f = par_x + par_y;\n\n Derivative con_h1 = par_x*par_x + par_y*par_y - 1,\n con_h2 = par_x,\n con_h3 = par_y;\n\n // Multiple initial value\n VectorXd x(2);\n \n x << 1, 1;\n std::cout << \"x initial as \" << x.transpose() << std::endl;\n std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n\n x << 1, 2;\n std::cout << \"x initial as \" << x.transpose() << std::endl;\n std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n\n x << 2, 1;\n std::cout << \"x initial as \" << x.transpose() << std::endl;\n std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n \n x << 4, -1;\n std::cout << \"x initial as \" << x.transpose() << std::endl;\n std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n\n x << -1, 4;\n std::cout << \"x initial as \" << x.transpose() << std::endl;\n std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n\n x << 0.2, 0.7;\n std::cout << \"x initial as \" << x.transpose() << std::endl;\n std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n\n x << 0.5, 0.5;\n std::cout << \"x initial as \" << x.transpose() << std::endl;\n std::cout << Derivative_IPM(obj_f, {con_h1, con_h2, con_h3}, x).transpose() << std::endl;\n return 0;\n}\n", "meta": {"hexsha": "55ee171f3727f76c71ad3e290159f3a536dca781", "size": 7026, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/interior-point-method.cpp", "max_stars_repo_name": "mudream4869/eigen-derivative", "max_stars_repo_head_hexsha": "c45c9bd1fe781831aaf42fe798c7d6c1a3d568ad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/interior-point-method.cpp", "max_issues_repo_name": "mudream4869/eigen-derivative", "max_issues_repo_head_hexsha": "c45c9bd1fe781831aaf42fe798c7d6c1a3d568ad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/interior-point-method.cpp", "max_forks_repo_name": "mudream4869/eigen-derivative", "max_forks_repo_head_hexsha": "c45c9bd1fe781831aaf42fe798c7d6c1a3d568ad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1545064378, "max_line_length": 108, "alphanum_fraction": 0.5461144321, "num_tokens": 2214, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6976485146247153}} {"text": "#ifndef TRIUMF_SRIM_PDF_HPP\n#define TRIUMF_SRIM_PDF_HPP\n\n#include \n// #include \n// #include \n#include \n\n#include \n\n#include \n\n// TRIUMF: Canada's accelerator centre\nnamespace triumf {\n\n// Stopping and Range of Ions in Matter (SRIM)\nnamespace srim {\n\n// probability density functions (PDF)\nnamespace pdf {\n\n/// see Eq. (5.6) in Md Masrur Hossain's MSc thesis, UBC, 2006, p. 52.\ntemplate T custom(T x, T alpha, T beta, T sigma, T x_max, T N) {\n T y = x / x_max;\n return y < 0.0 or y > 1.0 ? 0.0\n : N * std::pow(y, alpha) * std::pow(1.0 - y, beta) *\n std::exp(-std::pow((x - x_max) / sigma, 2));\n}\n\n/// see Eq. (5.6) in Md Masrur Hossain's MSc thesis, UBC, 2006, p. 52.\ntemplate T custom(const T *x, const T *par) {\n // parameters\n T alpha = par[0];\n T beta = par[1];\n T sigma = par[2];\n T x_max = par[3];\n T N = par[4];\n T y = *x / x_max;\n\n // ensure function is always properly normalized!\n boost::math::quadrature::tanh_sinh integrator;\n auto integrand = [&](T z) { return custom(z, alpha, beta, sigma, x_max, N); };\n T I = integrator.integrate(integrand, 0.0, x_max);\n\n // return the normalized function\n return custom(*x, alpha, beta, sigma, x_max, N) / I;\n}\n\n/// beta distribution - x in [0, 1]\ntemplate T _beta(T x, T alpha, T beta) {\n if ((x < 0.0) or (x > 1.0)) {\n return 0.0;\n } else {\n return std::pow(x, alpha - 1.0) * std::pow(1.0 - x, beta - 1.0) /\n boost::math::beta(alpha, beta);\n }\n}\n\n/// modified beta distribution - x in [0, x_max]\ntemplate T modified_beta(T x, T alpha, T beta, T x_max) {\n T y = x / x_max;\n return _beta(y, alpha, beta) / x_max;\n}\n\n/// modified beta distribution - x in [0, x_max]\n/// interface for ROOT TF1\ntemplate 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(*x, alpha, beta, x_max);\n}\n\n} // namespace pdf\n\n} // namespace srim\n\n} // namespace triumf\n\n#endif // TRIUMF_SRIM_PDF_HPP\n", "meta": {"hexsha": "128cfc3cef818f52de6f8b0e51f679981248c63e", "size": 2276, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/srim/pdf.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/triumf/srim/pdf.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/triumf/srim/pdf.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0987654321, "max_line_length": 80, "alphanum_fraction": 0.6234622144, "num_tokens": 749, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.92414182206801, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6976485114702979}} {"text": "#include \n#include \n#include \n\nnamespace rct_optimizations\n{\nEigen::VectorXd calculateHomographyError(const Correspondence2D3D::Set &correspondences,\n const CorrespondenceSampler &correspondence_sampler)\n{\n /* There is a 3x3 homography matrix, H, that can transform a point from one plane onto a different plane\n * | u | = k * | H00 H01 H02 | * | x |\n * | v | | H10 H11 H12 | | y |\n * | 1 | | H20 H12 1 | | 1 |\n *\n * In our case we have 2 sets of known corresponding planar points: points on the planar target, and points in the image plane\n * Therefore, there is some matrix, H, which can transform target points into the image plane.\n * If the target points and camera points actually match, we should be able to:\n * 1. Calculate H for a subset of corresponding points\n * 2. Transform the remaining target points by H to obtain estimates of their locations in the image plane\n * 3. Compare the calculated estimations to the actual image points to make sure they are very close. If they are not close, we know that the correspondences are not valid\n *\n * The matrix H has 8 unique values.\n * These 8 values of the homography matrix can be solved for, given a set of (at least) 8 corresponding planar vectors, by rearranging the above equations:\n *\n * A * H = b, where\n * H = inv(A) * b\n * - A is matrix (size 2*n x 8), where n is the number of corresponding vectors\n * - H is a vector (size 8 x 1) of the unknown elements of the homography matrix\n * - B is a vector (size 2*n x 1) representing the elements of one set of planar vectors\n *\n * A * H = b\n * |-x0 -y0 -1 0 0 0 u0*x0 u0*y0 | * | H00 | = | -u0 |\n * | 0 0 0 -x0 -y0 -1 v0*x0 v0*y0 | * | H01 | = | -v0 |\n * ...\n * |-x7 -y7 -1 0 0 0 u7*x7 u7*y7 | * | H20 | = | -u7 |\n * | 0 0 0 -x7 -y7 -1 v7*x7 v7*y7 | * | H21 | = | -v7 |\n *\n */\n\n // Select the points that we want to use to create the H matrix\n std::vector sample_correspondence_indices = correspondence_sampler\n .getSampleCorrespondenceIndices();\n std::size_t n_samples = sample_correspondence_indices.size();\n\n // Ensure that there are enough points for testing outside of the sampled set\n if (correspondences.size() < 2 * n_samples)\n {\n std::stringstream ss;\n ss << \"Correspondences size is not more than 2x sample size (\" << correspondences.size()\n << \" correspondences vs. \" << n_samples << \")\";\n throw std::runtime_error(ss.str());\n }\n\n // Create the A and b matrices\n Eigen::MatrixXd A(2 * n_samples, 8);\n Eigen::MatrixXd b(2 * n_samples, 1);\n\n // Fill the A and B matrices with data from the selected correspondences\n for (std::size_t i = 0; i < n_samples; ++i)\n {\n std::size_t corr_idx = sample_correspondence_indices.at(i);\n const Correspondence2D3D &corr = correspondences.at(corr_idx);\n\n //assign A row-th row:\n const double x = corr.in_target.x();\n const double y = corr.in_target.y();\n const double u = corr.in_image.x();\n const double v = corr.in_image.y();\n A.row(2 * i) << -x, -y, -1.0, 0.0, 0.0, 0.0, u * x, u * y;\n A.row(2 * i + 1) << 0.0, 0.0, 0.0, -x, -y, -1.0, v * x, v * y;\n\n b.block<2, 1>(2 * i, 0) = -1.0 * corr.in_image;\n }\n\n // Create the homography matrix\n Eigen::Matrix H = Eigen::Matrix3d::Ones();\n\n // Map the elements of the H matrix into a column vector and solve for the first 8\n {\n Eigen::Map hv(H.data(), 9);\n hv.head<8>() = A.fullPivLu().solve(b);\n }\n\n // Estimate the image locations of all the target observations and compare to the actual image locations\n Eigen::VectorXd error(correspondences.size());\n for (std::size_t i = 0; i < correspondences.size(); ++i)\n {\n const Correspondence2D3D &corr = correspondences[i];\n\n // Calculate the scaling factor\n double ki = 1.0 / (H(2, 0) * corr.in_target.x() + H(2, 1) * corr.in_target.y() + 1.0);\n\n // Replace the z-element of the point with 1\n Eigen::Vector3d xy(corr.in_target);\n xy(2) = 1.0;\n\n // Estimate the point in the image plane\n Eigen::Vector3d in_image_estimate = ki * H * xy;\n\n // Calculate the error\n Eigen::Vector2d image_error = corr.in_image - in_image_estimate.head<2>();\n error(i) = image_error.norm();\n }\n\n return error;\n}\n\n} // namespace rct_optimizations\n\n", "meta": {"hexsha": "b6a349b1af8d959a0d6e3e60f95d58ac17a83e80", "size": 4651, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rct_optimizations/src/rct_optimizations/validation/homography_validation.cpp", "max_stars_repo_name": "jaberkebile/robot_cal_tools", "max_stars_repo_head_hexsha": "2bd3d8719974c324868d0aed00377640e85c7097", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rct_optimizations/src/rct_optimizations/validation/homography_validation.cpp", "max_issues_repo_name": "jaberkebile/robot_cal_tools", "max_issues_repo_head_hexsha": "2bd3d8719974c324868d0aed00377640e85c7097", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rct_optimizations/src/rct_optimizations/validation/homography_validation.cpp", "max_forks_repo_name": "jaberkebile/robot_cal_tools", "max_forks_repo_head_hexsha": "2bd3d8719974c324868d0aed00377640e85c7097", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.2818181818, "max_line_length": 175, "alphanum_fraction": 0.6196516878, "num_tokens": 1398, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6976485102571586}} {"text": "#ifndef LINEAR_ELASTICITY_HPP\n#define LINEAR_ELASTICITY_HPP\n\n#include \"C0_triangles.hpp\"\n#include \"Galerkin/Galerkin.hpp\"\n#include \"mesh_traits.hpp\"\n#include \"SymSparse.hpp\"\n\nusing Galerkin::get;\n\n#include \n\n#include \n\nnamespace Elasticity\n{\n\nnamespace TwoD\n{\n\ntemplate \nEigen::Matrix2d pair_stiffness_integral(const Element &el, const U &u, const V &v,\n double lambda, double mu)\n{\n auto uxvx = el.integrate(el.template partial<0>(u) * el.template partial<0>(v));\n auto uxvy = el.integrate(el.template partial<0>(u) * el.template partial<1>(v));\n auto uyvy = el.integrate(el.template partial<1>(u) * el.template partial<1>(v));\n auto uyvx = el.integrate(el.template partial<1>(u) * el.template partial<0>(v));\n\n Eigen::Matrix2d K;\n K(0, 0) = (lambda + 2*mu) * uxvx + mu * uyvy;\n K(1, 0) = lambda * uyvx + mu * uxvy;\n K(0, 1) = lambda * uxvy + mu * uyvx;\n K(1, 1) = (lambda + 2*mu) * uyvy + mu * uxvx;\n\n return K;\n}\n\ntemplate \nconstexpr size_t basis_size = Element::basis.size();\n\ntemplate \nvoid add_contribution(const Element &el, double lambda, double mu,\n Eigen::Matrix, 2*basis_size> &K)\n{\n constexpr auto u = get(Element::basis);\n constexpr auto v = get(Element::basis);\n auto local_K = pair_stiffness_integral(el, u, v, lambda, mu);\n auto row = I*2;\n auto col = J*2;\n K.block(row, col, 2, 2) = local_K;\n K.block(col, row, 2, 2) = local_K.transpose();\n}\n\ntemplate \nEigen::Matrix, 2*basis_size>\nelement_stiffness_matrix(const Element &el, double lambda, double mu)\n{\n Eigen::Matrix, 2*basis_size> K;\n Galerkin::static_for<0, basis_size, 1>(\n [&](auto I)\n {\n Galerkin::static_for, 1>(\n [&](auto J)\n {\n add_contribution(el, lambda, mu, K);\n }\n );\n }\n );\n return K;\n}\n\ntemplate \nauto instantiate_element(const Mesh &mesh, size_t which)\n{\n constexpr int order = msh::element_order;\n const auto &el = mesh.element(which);\n return fem::c0::C0Triangle(\n mesh.coord(el.control_nodes[0]),\n mesh.coord(el.control_nodes[1]),\n mesh.coord(el.control_nodes[2])\n );\n}\n\nconstexpr auto lame_parameters(double E, double nu) noexcept\n{\n double lambda = E * nu / ((1+nu) * (1-nu));\n double mu = E / (2 * (1+nu));\n return std::make_pair(lambda, mu);\n}\n\ntemplate \nauto assemble_stiffness(const Mesh &mesh, double E, double nu)\n{\n SymSparse::SymmetricSparseMatrix> K(mesh.num_nodes() * 2);\n auto [lambda, mu] = lame_parameters(E, nu);\n\n for (size_t i = 0; i < mesh.num_elements(); ++i)\n {\n const auto &el_info = mesh.element(i);\n const auto nn = el_info.node_numbers();\n const auto el = instantiate_element(mesh, i);\n const auto local_K = element_stiffness_matrix(el, lambda, mu);\n for (size_t j = 0; j < nn.size(); ++j)\n {\n for (size_t k = j; k < nn.size(); ++k)\n {\n K.insert_entry(nn[j]*2, nn[k]*2, local_K(2*j, 2*k));\n if (k != j)\n {\n K.insert_entry(nn[j]*2+1, nn[k]*2, local_K(2*j+1, 2*k));\n }\n K.insert_entry(nn[j]*2, nn[k]*2+1, local_K(2*j, 2*k+1));\n K.insert_entry(nn[j]*2+1, nn[k]*2+1, local_K(2*j+1, 2*k+1));\n }\n }\n }\n return K;\n}\n\ntemplate \nusing StiffnessType = decltype(assemble_stiffness(std::declval(), 1.0, 1.0));\n\n/*\n * Add a homogeneous Dirichlet condition on the boundary segment of the mesh\n * indexed by `which`. K is the stiffness matrix obtained from `assemble_stiffness`,\n * and `rhs` is the forcing vector.\n */\ntemplate \nvoid impose_homogeneous_condition(const Mesh &mesh, StiffnessType &K, RHS &rhs, size_t which,\n double scale = 1.0)\n{\n std::vector adjacent;\n adjacent.reserve(2 * msh::max_node_adjacencies);\n const auto &boundary = mesh.boundary(which);\n\n for (auto n: boundary.nodes)\n {\n adjacent.clear();\n // Get all of the adjacent DOFs to this one; since there are two components\n // of displacement there are 2 degrees of freedom (2*n, 2*n+1) corresponding\n // to each node.\n for (auto n2: mesh.adjacent_nodes(n))\n {\n adjacent.push_back(2*n2);\n adjacent.push_back(2*n2+1);\n }\n K.eliminate_dof(2*n, 0.0, scale, rhs, adjacent);\n K.eliminate_dof(2*n+1, 0.0, scale, rhs, adjacent);\n }\n}\n\ntemplate \nvoid impose_homogeneous_condition(\n const Mesh &mesh, StiffnessType &K, size_t which, double scale = 1.0)\n{\n std::vector adjacent;\n adjacent.reserve(2 * msh::max_node_adjacencies);\n const auto &boundary = mesh.boundary(which);\n\n for (auto n : boundary.nodes)\n {\n adjacent.clear();\n // Get all of the adjacent DOFs to this one; since there are two components\n // of displacement there are 2 degrees of freedom (2*n, 2*n+1) corresponding\n // to each node.\n for (auto n2 : mesh.adjacent_nodes(n))\n {\n adjacent.push_back(2 * n2);\n adjacent.push_back(2 * n2 + 1);\n }\n K.eliminate_dof(2 * n, 0.0, scale, adjacent);\n K.eliminate_dof(2 * n + 1, 0.0, scale, adjacent);\n }\n}\n\nstruct OutOfBoundsIndex : public std::exception\n{\n const char *msg;\n OutOfBoundsIndex(const char *m) : msg(m) {}\n const char *what() const noexcept\n {\n return msg;\n }\n};\n\ntemplate \nvoid impose_dirichlet_condition(const Mesh &mesh, StiffnessType &K, RHS &rhs, size_t which,\n const Vector &value, double scale = 1.0)\n{\n std::vector adjacent;\n adjacent.reserve(2 * msh::max_node_adjacencies);\n const auto &boundary = mesh.boundary(which);\n\n if (value.size() != 2*boundary.nodes.size())\n {\n throw OutOfBoundsIndex(\"Vector given for Dirichlet condition has wrong number of values\");\n }\n\n size_t i = 0;\n for (auto n: boundary.nodes)\n {\n adjacent.clear();\n for (auto n2: mesh.adjacent_nodes(n))\n {\n adjacent.push_back(2*n2);\n adjacent.push_back(2*n2+1);\n }\n K.eliminate_dof(2*n, value[2*i], scale, rhs, adjacent);\n K.eliminate_dof(2*n+1, value[2*i+1], scale, rhs, adjacent);\n i += 1;\n }\n}\n\ntemplate \nvoid add_point_force(const Force &force, size_t node, RHS &F)\n{\n if (2*node+1 > F.size())\n {\n throw OutOfBoundsIndex(\"Node is out of bounds for given forcing vector\");\n }\n F[2*node] += force[0];\n F[2*node+1] += force[1];\n}\n\ntemplate \nvoid add_point_forces(const Eigen::Matrix &force, const IndexContainer &nodes,\n RHS &F)\n{\n static_assert(sizeof...(Options) == 3);\n size_t col = 0;\n for (size_t n: nodes)\n {\n add_point_force(force.col(col), n, F);\n col += 1;\n }\n}\n\n} // namespace 2D\n\n} // namespace Elasticity\n\n#endif // LINEAR_ELASTICITY_HPP\n", "meta": {"hexsha": "307f895d2da05bf5a869182ba79dfabe525f8bb0", "size": 7566, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "2d.hpp", "max_stars_repo_name": "slmcbane/Le-TO", "max_stars_repo_head_hexsha": "d8fb0378fb687bb6dd56ed302072b59e5cdfb92f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2d.hpp", "max_issues_repo_name": "slmcbane/Le-TO", "max_issues_repo_head_hexsha": "d8fb0378fb687bb6dd56ed302072b59e5cdfb92f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2d.hpp", "max_forks_repo_name": "slmcbane/Le-TO", "max_forks_repo_head_hexsha": "d8fb0378fb687bb6dd56ed302072b59e5cdfb92f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8816326531, "max_line_length": 106, "alphanum_fraction": 0.6037536347, "num_tokens": 2122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159727, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6975771930285403}} {"text": "// Copyright (C) Microsoft. All rights reserved.\n// Licensed under the MIT License. See LICENSE in the project root for license information.\n\n#include \n#include \n\n////////////////////////////////////////////////////////////////////////////////\n// File: jacobi_cyclic_method.c //\n// Routines: //\n// Jacobi_Cyclic_Method //\n////////////////////////////////////////////////////////////////////////////////\n////////////////////////////////////////////////////////////////////////////////\n// void Jacobi_Cyclic_Method //\n// (double eigenvalues[], double *eigenvectors, double *A, int n) //\n// //\n// Description: //\n// Find the eigenvalues and eigenvectors of a symmetric n x n matrix A //\n// using the Jacobi method. Upon return, the input matrix A will have //\n// been modified. //\n// The Jacobi procedure for finding the eigenvalues and eigenvectors of a //\n// symmetric matrix A is based on finding a similarity transformation //\n// which diagonalizes A. The similarity transformation is given by a //\n// product of a sequence of orthogonal (rotation) matrices each of which //\n// annihilates an off-diagonal element and its transpose. The rotation //\n// effects only the rows and columns containing the off-diagonal element //\n// and its transpose, i.e. if a[i][j] is an off-diagonal element, then //\n// the orthogonal transformation rotates rows a[i][] and a[j][], and //\n// equivalently it rotates columns a[][i] and a[][j], so that a[i][j] = 0 //\n// and a[j][i] = 0. //\n// The cyclic Jacobi method considers the off-diagonal elements in the //\n// following order: (0,1),(0,2),...,(0,n-1),(1,2),...,(n-2,n-1). If the //\n// the magnitude of the off-diagonal element is greater than a treshold, //\n// then a rotation is performed to annihilate that off-diagnonal element. //\n// The process described above is called a sweep. After a sweep has been //\n// completed, the threshold is lowered and another sweep is performed //\n// with the new threshold. This process is completed until the final //\n// sweep is performed with the final threshold. //\n// The orthogonal transformation which annihilates the matrix element //\n// a[k][m], k != m, is Q = q[i][j], where q[i][j] = 0 if i != j, i,j != k //\n// i,j != m and q[i][j] = 1 if i = j, i,j != k, i,j != m, q[k][k] = //\n// q[m][m] = cos(phi), q[k][m] = -sin(phi), and q[m][k] = sin(phi), where //\n// the angle phi is determined by requiring a[k][m] -> 0. This condition //\n// on the angle phi is equivalent to //\n// cot(2 phi) = 0.5 * (a[k][k] - a[m][m]) / a[k][m] //\n// Since tan(2 phi) = 2 tan(phi) / (1.0 - tan(phi)^2), //\n// tan(phi)^2 + 2cot(2 phi) * tan(phi) - 1 = 0. //\n// Solving for tan(phi), choosing the solution with smallest magnitude, //\n// tan(phi) = - cot(2 phi) + sgn(cot(2 phi)) sqrt(cot(2phi)^2 + 1). //\n// Then cos(phi)^2 = 1 / (1 + tan(phi)^2) and sin(phi)^2 = 1 - cos(phi)^2 //\n// Finally by taking the sqrts and assigning the sign to the sin the same //\n// as that of the tan, the orthogonal transformation Q is determined. //\n// Let A\" be the matrix obtained from the matrix A by applying the //\n// similarity transformation Q, since Q is orthogonal, A\" = Q'AQ, where Q'//\n// is the transpose of Q (which is the same as the inverse of Q). Then //\n// a\"[i][j] = Q'[i][p] a[p][q] Q[q][j] = Q[p][i] a[p][q] Q[q][j], //\n// where repeated indices are summed over. //\n// If i is not equal to either k or m, then Q[i][j] is the Kronecker //\n// delta. So if both i and j are not equal to either k or m, //\n// a\"[i][j] = a[i][j]. //\n// If i = k, j = k, //\n// a\"[k][k] = //\n// a[k][k]*cos(phi)^2 + a[k][m]*sin(2 phi) + a[m][m]*sin(phi)^2 //\n// If i = k, j = m, //\n// a\"[k][m] = a\"[m][k] = 0 = //\n// a[k][m]*cos(2 phi) + 0.5 * (a[m][m] - a[k][k])*sin(2 phi) //\n// If i = k, j != k or m, //\n// a\"[k][j] = a\"[j][k] = a[k][j] * cos(phi) + a[m][j] * sin(phi) //\n// If i = m, j = k, a\"[m][k] = 0 //\n// If i = m, j = m, //\n// a\"[m][m] = //\n// a[m][m]*cos(phi)^2 - a[k][m]*sin(2 phi) + a[k][k]*sin(phi)^2 //\n// If i= m, j != k or m, //\n// a\"[m][j] = a\"[j][m] = a[m][j] * cos(phi) - a[k][j] * sin(phi) //\n// //\n// If X is the matrix of normalized eigenvectors stored so that the ith //\n// column corresponds to the ith eigenvalue, then AX = X Lamda, where //\n// Lambda is the diagonal matrix with the ith eigenvalue stored at //\n// Lambda[i][i], i.e. X'AX = Lambda and X is orthogonal, the eigenvectors //\n// are normalized and orthogonal. So, X = Q1 Q2 ... Qs, where Qi is //\n// the ith orthogonal matrix, i.e. X can be recursively approximated by //\n// the recursion relation X\" = X Q, where Q is the orthogonal matrix and //\n// the initial estimate for X is the identity matrix. //\n// If j = k, then x\"[i][k] = x[i][k] * cos(phi) + x[i][m] * sin(phi), //\n// if j = m, then x\"[i][m] = x[i][m] * cos(phi) - x[i][k] * sin(phi), and //\n// if j != k and j != m, then x\"[i][j] = x[i][j]. //\n// //\n// Arguments: //\n// double eigenvalues //\n// Array of dimension n, which upon return contains the eigenvalues of //\n// the matrix A. //\n// double* eigenvectors //\n// Matrix of eigenvectors, the ith column of which contains an //\n// eigenvector corresponding to the ith eigenvalue in the array //\n// eigenvalues. //\n// double* A //\n// Pointer to the first element of the symmetric n x n matrix A. The //\n// input matrix A is modified during the process. //\n// int n //\n// The dimension of the array eigenvalues, number of columns and rows //\n// of the matrices eigenvectors and A. //\n// //\n// Return Values: //\n// Function is of type void. //\n// //\n// Example: //\n// #define N //\n// double A[N][N], double eigenvalues[N], double eigenvectors[N][N] //\n// //\n// (your code to initialize the matrix A ) //\n// //\n// Jacobi_Cyclic_Method(eigenvalues, (double*)eigenvectors, //\n// (double *) A, N); //\n////////////////////////////////////////////////////////////////////////////////\n// //\n\n#define VAL_FLT_EPSILON 2.2204460492503131e-016f//1.0e-4f//1.192092896e-07F /* smallest such that 1.0+FLT_EPSILON != 1.0 */\n\nvoid Jacobi_Cyclic_Method(float eigenvalues[], float *eigenvectors,float *A, int n)\n{\n int i, j, k, m;\n float *pAk, *pAm, *p_r, *p_e;\n double threshold_norm;\n double threshold;\n double tan_phi, sin_phi, cos_phi, tan2_phi, sin2_phi, cos2_phi;\n double sin_2phi, cos_2phi, cot_2phi;\n double dum1;\n double dum2;\n double dum3;\n double max;\n\n\t\t\t\t // Take care of trivial cases\n\n if ( n < 1) return;\n if ( n == 1) {\n\t eigenvalues[0] = *A;\n\t *eigenvectors = 1.f;\n\t return;\n }\n\n\t\t // Initialize the eigenvalues to the identity matrix.\n\n for (p_e = eigenvectors, i = 0; i < n; i++)\n\t for (j = 0; j < n; p_e++, j++)\n\t\t if (i == j) *p_e = 1.f; else *p_e = 0.f;\n \n\t\t\t// Calculate the threshold and threshold_norm.\n \n for (threshold = 0.f, pAk = A, i = 0; i < ( n - 1 ); pAk += n, i++) \n\t for (j = i + 1; j < n; j++) threshold += *(pAk + j) * *(pAk + j);\n threshold = sqrt(threshold + threshold);\n threshold_norm = threshold * VAL_FLT_EPSILON;\n max = threshold + 1.f;\n while (threshold > threshold_norm)\n {\n// for (int il=0; il<100; il++) {\n\t threshold /= 10.f;\n\t if (max < threshold)\n\t\t continue;\n\t max = 0.f;\n\t for (pAk = A, k = 0; k < (n-1); pAk += n, k++) {\n\t\t for (pAm = pAk + n, m = k + 1; m < n; pAm += n, m++) {\n\t\t\tdouble fabspAkpm=fabs(*(pAk + m));\n\t\t\tif ( fabspAkpm < threshold )\n\t\t\t\tcontinue;\n\n\t\t\t\t // Calculate the sin and cos of the rotation angle which\n\t\t\t\t // annihilates A[k][m].\n\n\t\t\tcot_2phi = 0.5f * ( *(pAk + k) - *(pAm + m) ) / *(pAk + m);\n\t\t\tdum1 = sqrt( cot_2phi * cot_2phi + 1.f);\n\t\t\tif (cot_2phi < 0.f) dum1 = -dum1;\n\t\t\ttan_phi = -cot_2phi + dum1;\n\t\t\ttan2_phi = tan_phi * tan_phi;\n\t\t\tsin2_phi = tan2_phi / (1.f + tan2_phi);\n\t\t\tcos2_phi = 1.f - sin2_phi;\n\t\t\tsin_phi = sqrt(sin2_phi);\n\t\t\tif (tan_phi < 0.f) sin_phi = - sin_phi;\n\t\t\tcos_phi = sqrt(cos2_phi); \n\t\t\tsin_2phi = 2.f * sin_phi * cos_phi;\n\t\t\tcos_2phi = cos2_phi - sin2_phi;\n\n\t\t\t\t\t // Rotate columns k and m for both the matrix A \n\t\t\t\t\t // and the matrix of eigenvectors.\n\n\t\t\tp_r = A;\n\t\t\tdum1 = *(pAk + k);\n\t\t\tdum2 = *(pAm + m);\n\t\t\tdum3 = *(pAk + m);\n\t\t\t*(pAk + k) = dum1 * cos2_phi + dum2 * sin2_phi + dum3 * sin_2phi;\n\t\t\t*(pAm + m) = dum1 * sin2_phi + dum2 * cos2_phi - dum3 * sin_2phi;\n\t\t\t*(pAk + m) = 0.f;\n\t\t\t*(pAm + k) = 0.f;\n\t\t\tfor (i = 0; i < n; p_r += n, i++) {\n\t\t\t if ( (i == k) || (i == m) ) continue;\n\t\t\t if ( i < k ) dum1 = *(p_r + k); else dum1 = *(pAk + i);\n\t\t\t if ( i < m ) dum2 = *(p_r + m); else dum2 = *(pAm + i);\n\t\t\t dum3 = dum1 * cos_phi + dum2 * sin_phi;\n\t\t\t if ( i < k ) *(p_r + k) = dum3; else *(pAk + i) = dum3;\n\t\t\t dum3 = - dum1 * sin_phi + dum2 * cos_phi;\n\t\t\t if ( i < m ) *(p_r + m) = dum3; else *(pAm + i) = dum3;\n\t\t\t}\n\t\t\tfor (p_e = eigenvectors, i = 0; i < n; p_e += n, i++) {\n\t\t\t dum1 = *(p_e + k);\n\t\t\t dum2 = *(p_e + m);\n\t\t\t *(p_e + k) = dum1 * cos_phi + dum2 * sin_phi;\n\t\t\t *(p_e + m) = - dum1 * sin_phi + dum2 * cos_phi;\n\t\t\t}\n\t\t }\n\t\t for (i = 0; i < n; i++)\n\t\t\tif ( i == k ) continue;\n\t\t\telse if ( max < fabs(*(pAk + i))) max = fabs(*(pAk + i));\n\t }\n }\n for (pAk = A, k = 0; k < n; pAk += n, k++) eigenvalues[k] = *(pAk + k); \n}\n\nvoid GenericEigen3D(const Vec3f *vectors,S32 nbvectors,Vec3f eigenvectors[3],Float eigenvalues[3])\n{\n\tint\t\ti;\n\n\tif (nbvectors<1)\n\t\treturn;\n\n\tVec3f\tBaryCentre=VEC4F_NULL;\n\n\t// Calculate mean (barycentre)\n\tfor (i=0; i\n#include \n#include \n\n\nclass LinearRegressionFunction\n{\n public:\n \n LinearRegressionFunction(arma::mat& X, arma::vec& y) : X(X), y(y) { }\n \n double EvaluateWithGradient(const arma::mat& theta, arma::mat& gradient)\n {\n const arma::vec tmp = X.t() * theta - y;\n gradient = 2 * X * tmp;\n return arma::dot(tmp,tmp);\n }\n \n private:\n \n const arma::mat& X;\n const arma::vec& y;\n};\n\n\nint main(int argc, char** argv)\n{\n if (argc < 3)\n {\n std::cout << \"usage: \" << argv[0] << \" n_dims n_points\" << std::endl;\n return -1;\n }\n \n int n_dims = atoi(argv[1]);\n int n_points = atoi(argv[2]);\n \n // generate noisy dataset with a slight linear pattern\n arma::mat X(n_dims, n_points, arma::fill::randu);\n arma::vec y( n_points, arma::fill::randu);\n \n for (size_t i = 0; i < n_points; ++i)\n {\n double a = arma::randu();\n X(1, i) += a;\n y(i) += a;\n }\n \n LinearRegressionFunction lrf(X, y);\n \n // create a Limited-memory BFGS optimizer object with default parameters\n ens::L_BFGS opt;\n opt.MaxIterations() = 10;\n \n // initial point (uniform random)\n arma::vec theta(n_dims, arma::fill::randu);\n \n opt.Optimize(lrf, theta);\n \n // theta now contains the optimized parameters\n theta.print(\"theta:\");\n \n return 0;\n}\n", "meta": {"hexsha": "264f137bd065720338b65fa43b77eff47a7ef45c", "size": 1498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example.cpp", "max_stars_repo_name": "ElianeBriand/ensmallen", "max_stars_repo_head_hexsha": "0f634056d054d100b2a70cb8f15ea9fa38680d10", "max_stars_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example.cpp", "max_issues_repo_name": "ElianeBriand/ensmallen", "max_issues_repo_head_hexsha": "0f634056d054d100b2a70cb8f15ea9fa38680d10", "max_issues_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example.cpp", "max_forks_repo_name": "ElianeBriand/ensmallen", "max_forks_repo_head_hexsha": "0f634056d054d100b2a70cb8f15ea9fa38680d10", "max_forks_repo_licenses": ["BSL-1.0", "BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-16T16:21:59.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-16T16:21:59.000Z", "avg_line_length": 21.0985915493, "max_line_length": 78, "alphanum_fraction": 0.6194926569, "num_tokens": 451, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070084811307, "lm_q2_score": 0.7662936430859598, "lm_q1q2_score": 0.697255956398453}} {"text": "#include \n#include \n#include \n#include \n#include \"/Users/drewlewis/software/install/tiledarray/sparse_new_summa_debug/include/tiledarray.h\"\n\nusing Tensor = TiledArray::Tensor;\nusing Perm = TiledArray::Permutation;\nusing Range = TiledArray::Range;\nusing Matrix =\n Eigen::Matrix;\n\ntemplate \nTiledArray::Range make_range(Args... args) {\n return TiledArray::Range(args...);\n}\n\nTensor vectors(Tensor const &a) {\n auto const &size = a.range().size();\n Eigen::Map map(a.data(), size[0], size[1] * size[2]);\n\n Eigen::JacobiSVD svd(map,\n Eigen::ComputeThinU | Eigen::ComputeThinV);\n auto const &vals = svd.singularValues();\n\n auto rank = 0;\n for (auto i = 0; i < vals.size(); ++i) {\n if (1e-12 < vals[i]) {\n ++rank;\n }\n }\n\n auto matrixU = svd.matrixU().leftCols(rank);\n Tensor U{Range(matrixU.rows(), matrixU.cols())};\n\n for (auto i = 0; i < matrixU.size(); ++i) {\n U[i] = *(matrixU.data() + i);\n }\n\n return U;\n}\n\nTensor Kron(Tensor const &a, Tensor const &b) {\n auto const &asize = a.range().size();\n auto const &bsize = b.range().size();\n const auto ab0 = asize[0] * bsize[0];\n const auto ab1 = asize[1] * bsize[1];\n\n Tensor out(Range(ab0, ab1));\n\n Eigen::Map outm(out.data(), ab0, ab1);\n Eigen::Map am(a.data(), asize[0], asize[1]);\n Eigen::Map bm(b.data(), bsize[0], bsize[1]);\n\n outm = Matrix::Zero(ab0, ab1);\n std::cout << \"outm = \\n\" << outm << std::endl;\n\n auto row_start = 0;\n for (auto i = 0; i < am.rows(); ++i) {\n auto col_start = 0;\n for (auto j = 0; j < am.cols(); ++j) {\n outm.block(row_start, col_start, bsize[0], bsize[1]) = am(i, j) * bm;\n col_start += bsize[1];\n }\n row_start += bsize[0];\n std::cout << \"outm = \\n\" << std::endl;\n }\n\n return out;\n}\n\nTensor FormS(Tensor const &U1, Tensor const &A, Tensor const &K) {\n auto const &usize = U1.range().size();\n auto const &asize = A.range().size();\n auto const &ksize = K.range().size();\n Eigen::Map um(U1.data(), usize[0], usize[1]);\n Eigen::Map am(A.data(), asize[0], asize[1] * asize[2]);\n Eigen::Map km(K.data(), ksize[0], ksize[1]);\n\n Matrix outtemp(usize[1], asize[1] * asize[2]);\n outtemp = um.transpose() * am;\n\n Tensor out{Range(usize[1], asize[1], asize[2])};\n Eigen::Map outm(out.data(), usize[1], asize[1] * asize[2]);\n outm = outtemp * km;\n return out;\n}\n\nTensor FormA(Tensor const &U1, Tensor const &S, Tensor const &K) {\n auto const &usize = U1.range().size();\n auto const &ssize = S.range().size();\n auto const &ksize = K.range().size();\n Eigen::Map um(U1.data(), usize[0], usize[1]);\n Eigen::Map sm(S.data(), ssize[0], ssize[1] * ssize[2]);\n Eigen::Map km(K.data(), ksize[0], ksize[1]);\n\n Matrix outtemp(usize[0], ssize[1] * ssize[2]);\n outtemp = um * sm;\n std::cout << outtemp << std::endl;\n\n Tensor out{Range(usize[0], ssize[1], ssize[2])};\n Eigen::Map outm(out.data(), usize[0], ssize[1] * ssize[2]);\n outm = outtemp * km.transpose();\n return out;\n}\n\nint main(int argc, char **argv) {\n auto tensor = Tensor{make_range(3, 2, 2)};\n for (auto i = 1; i <= 12; ++i) {\n tensor[i - 1] = i;\n }\n auto u1 = vectors(tensor);\n auto u2 = vectors(Tensor{tensor, Perm{1, 0, 2}});\n auto u3 = vectors(Tensor{tensor, Perm{2, 1, 0}});\n\n std::cout << tensor << std::endl;\n std::cout << u1 << std::endl;\n std::cout << u2 << std::endl;\n std::cout << u3 << std::endl;\n\n auto K = Kron(u3,u2);\n std::cout << \"K = \\n\" << K << std::endl;\n auto S = FormS(u1, tensor, K);\n std::cout << \"S = \\n\" << S << std::endl;\n auto Tapprox = FormA(u1, S, K);\n std::cout << \"Aapprox = \\n\" << Tapprox << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "ddcf337f2de894bb5849a490ed80a48ffde920ae", "size": 4079, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code_tests/hosvd/hosvd.cpp", "max_stars_repo_name": "calewis/SmallProjectsAndDev", "max_stars_repo_head_hexsha": "0d7a7ddc123150507efac1f130fe1691aff65e75", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code_tests/hosvd/hosvd.cpp", "max_issues_repo_name": "calewis/SmallProjectsAndDev", "max_issues_repo_head_hexsha": "0d7a7ddc123150507efac1f130fe1691aff65e75", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code_tests/hosvd/hosvd.cpp", "max_forks_repo_name": "calewis/SmallProjectsAndDev", "max_forks_repo_head_hexsha": "0d7a7ddc123150507efac1f130fe1691aff65e75", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3769230769, "max_line_length": 99, "alphanum_fraction": 0.5685216965, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6972017505987161}} {"text": "\n// Adapted from:\n// * http://www.stanford.edu/~acoates/quaternion.h\n// * http://www.euclideanspace.com/maths/geometry/rotations/conversions\n\n#pragma once\n\n#include \"vector-2.hpp\"\n#include \"vector-3.hpp\"\n#include \"vector-4.hpp\"\n#include \n#include \n\n#include \n\nnamespace perceive\n{\n#pragma pack(push, 1)\ntemplate class QuaternionT\n{\n public:\n using value_type = T;\n\n T x, y, z, w;\n\n QuaternionT() noexcept\n : x(0.0)\n , y(0.0)\n , z(0.0)\n , w(1.0)\n {}\n\n QuaternionT(const Vector3T& v, T w_) noexcept\n : x(v.x)\n , y(v.y)\n , z(v.z)\n , w(w_)\n {}\n\n QuaternionT(const Vector4T& v) noexcept { from_axis_angle(v); }\n\n QuaternionT(const T array[4]) noexcept\n {\n x = array[0];\n y = array[1];\n z = array[2];\n w = array[3];\n }\n\n QuaternionT(T x_, T y_, T z_, T w_) noexcept\n : x(x_)\n , y(y_)\n , z(z_)\n , w(w_)\n {}\n\n QuaternionT(const Vector3T& a, const Vector3T& b) noexcept\n {\n *this = between_vectors(a, b);\n }\n\n bool operator==(const QuaternionT& rhs) const noexcept\n {\n const auto o = this->normalised();\n const auto p = rhs.normalised();\n const auto cos_phi = p.x * o.x + p.y * o.y + p.z * o.z + p.w * o.w;\n return fabs(cos_phi) > 1.0 - 1e-9;\n }\n\n bool operator!=(const QuaternionT& rhs) const noexcept\n {\n return !(*this == rhs);\n }\n\n static inline QuaternionT identity() noexcept\n {\n return QuaternionT(0.0, 0.0, 0.0, 1.0);\n }\n\n static QuaternionT nan() noexcept\n {\n constexpr T val = T(NAN);\n return QuaternionT(val, val, val, val);\n }\n\n // Create from between vectors\n static inline QuaternionT between_vectors(const Vector3T& a,\n const Vector3T& b) noexcept\n {\n auto u = a.normalised();\n auto v = b.normalised();\n auto n = cross(u, v);\n auto cos_t = dot(u, v);\n if(cos_t < (1e-6 - 1.0)) {\n // 180 degree rotation... about arbitrary axis\n Vector3T axis;\n axis = cross(Vector3T(1, 0, 0), u);\n if(axis.quadrance() < 1e-3) axis = cross(Vector3T(0, 1, 0), u);\n axis.normalise();\n return QuaternionT(axis, 0);\n } else if(cos_t >= 1.0 - 1e-6) {\n return QuaternionT(0, 0, 0, 1);\n }\n QuaternionT q(n, 1.0 + cos_t);\n q.normalise();\n return q;\n }\n\n // Create from between rotations: r * a = b\n static inline QuaternionT between_rotations(const QuaternionT& a,\n const QuaternionT& b) noexcept\n {\n return b * a.conjugate();\n }\n\n Vector3T& complex() noexcept\n {\n return *(reinterpret_cast*>(this));\n }\n const Vector3T& complex() const noexcept\n {\n return *(reinterpret_cast*>(this));\n }\n T& real() noexcept { return w; }\n const T& real() const noexcept { return w; }\n QuaternionT conjugate() const noexcept { return QuaternionT(-x, -y, -z, w); }\n\n QuaternionT inverse() const noexcept { return conjugate().normalised(); }\n QuaternionT& invert() const noexcept\n {\n x = -x;\n y = -y;\n z = -z;\n return normalise();\n }\n\n T quadrance() const noexcept { return x * x + y * y + z * z + w * w; }\n T norm() const noexcept { return std::sqrt(quadrance()); }\n\n QuaternionT normalised(T epsilon = T(1e-9)) const noexcept\n {\n QuaternionT ret(*this);\n ret.normalise(epsilon);\n return ret;\n }\n\n QuaternionT& normalise(T epsilon = T(1e-9)) noexcept\n {\n auto mag2 = quadrance();\n if(std::fabs(mag2 - T(1.0)) > epsilon) {\n auto inv = T(1.0) / T(std::sqrt(mag2));\n x *= inv;\n y *= inv;\n z *= inv;\n w *= inv;\n }\n return *this;\n }\n\n unsigned size() const noexcept { return 4; }\n\n T* copy_to(T a[4]) const noexcept\n {\n a[0] = x;\n a[1] = y;\n a[2] = z;\n a[3] = w;\n return a;\n }\n\n T* ptr() noexcept { return &x; }\n const T* ptr() const noexcept { return &x; }\n T& operator[](int idx) noexcept\n {\n#ifdef DEBUG_BUILD\n assert(idx >= 0 && idx < 4);\n#endif\n return ptr()[idx];\n }\n\n const T& operator[](int idx) const noexcept\n {\n#ifdef DEBUG_BUILD\n assert(idx >= 0 && idx < 4);\n#endif\n return ptr()[idx];\n }\n\n T& operator()(int idx) noexcept\n {\n#ifdef DEBUG_BUILD\n assert(idx >= 0 && idx < 4);\n#endif\n return ptr()[idx];\n }\n\n const T& operator()(int idx) const noexcept\n {\n#ifdef DEBUG_BUILD\n assert(idx >= 0 && idx < 4);\n#endif\n return ptr()[idx];\n }\n\n static void product(const QuaternionT& a,\n const QuaternionT& b,\n QuaternionT& c) noexcept\n {\n c.x = a.y * b.z - a.z * b.y + a.x * b.w + a.w * b.x;\n c.y = a.z * b.x - a.x * b.z + a.y * b.w + a.w * b.y;\n c.z = a.x * b.y - a.y * b.x + a.z * b.w + a.w * b.z;\n c.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\n }\n\n QuaternionT operator*(const QuaternionT& rhs) const noexcept\n {\n QuaternionT q;\n product(*this, rhs, q);\n return q;\n }\n QuaternionT& operator*=(const QuaternionT& rhs) noexcept\n {\n *this = *this * rhs;\n return *this;\n }\n\n QuaternionT operator*(T s) const noexcept\n {\n auto q = *this;\n q *= s;\n return q;\n }\n QuaternionT& operator*=(T s) noexcept\n {\n x *= s;\n y *= s;\n z *= s;\n w *= s;\n return *this;\n }\n QuaternionT operator/(T s) const noexcept { return *this * T(1.0) /= s; }\n QuaternionT& operator/=(T s) noexcept { return *this *= T(1.0) / s; }\n\n QuaternionT operator+(const QuaternionT& o) const noexcept\n {\n auto q = *this;\n q += o;\n return q;\n }\n QuaternionT& operator+=(const QuaternionT& o) noexcept\n {\n x += o.x;\n y += o.y;\n z += o.z;\n w += o.w;\n return *this;\n }\n QuaternionT operator-(const QuaternionT& o) const noexcept\n {\n auto q = *this;\n q -= o;\n return q;\n }\n QuaternionT& operator-=(const QuaternionT& o) noexcept\n {\n x -= o.x;\n y -= o.y;\n z -= o.z;\n w -= o.w;\n return *this;\n }\n\n // Same as rotation-maxtrix3x3 * v\n Vector3T rotate(const Vector3T& v) const noexcept\n {\n return (((*this) * QuaternionT(v, 0)) * inverse()).complex();\n }\n\n Vector3T inverse_rotate(const Vector3T& v) const noexcept\n {\n return conjugate().rotate(v);\n }\n\n Vector3T apply(const Vector3T& v) const noexcept { return rotate(v); }\n Vector3T inverse_apply(const Vector3T& v) const noexcept\n {\n return inverse_rotate(v);\n }\n\n // -- spherical-axis-angle\n Vector3T to_spherical_axis_angle() const noexcept\n {\n Vector3T a;\n auto aa = to_axis_angle();\n a.x = std::acos(aa.z); // inclination\n a.y = std::atan2(aa.y, aa.x); // azimuth\n a.z = aa.w; // theta\n return a;\n }\n\n QuaternionT& from_spherical_axis_angle(const Vector3T& a) noexcept\n {\n // a(inclination, azimuth, amount-of-rotation)\n const T half_theta = T(0.5) * a.z;\n const T sin_half_theta = std::sin(half_theta);\n x = std::sin(a.x) * std::cos(a.y) * sin_half_theta;\n y = std::sin(a.x) * std::sin(a.y) * sin_half_theta;\n z = std::cos(a.x) * sin_half_theta;\n w = std::cos(half_theta);\n return *this;\n }\n\n QuaternionT& from_axis_angle(const Vector3T& a,\n const double theta) noexcept\n {\n const T sin_t = std::sin(0.5 * theta);\n const T cos_t = std::cos(0.5 * theta);\n auto b = a.normalised();\n x = b.x * sin_t;\n y = b.y * sin_t;\n z = b.z * sin_t;\n w = cos_t;\n normalise();\n return *this;\n }\n\n QuaternionT& from_axis_angle(const Vector4T& a) noexcept\n {\n return from_axis_angle(a.xyz(), a.d());\n }\n\n Vector4T to_axis_angle() const noexcept\n {\n if(!is_finite()) return Vector4T::nan();\n auto mag = quadrance();\n if(std::fabs(mag) < T(1e-9)) return Vector4T(1, 0, 0, 0);\n T n_inv = T(1.0) / std::sqrt(mag);\n\n Vector4T a;\n if(std::fabs(w - T(1.0)) < T(1e-9)) {\n // There is no rotation, so set the axis\n // to an arbitrary value, and theta to 0\n a = Vector4T(1, 0, 0, 0);\n } else {\n auto ww = w * n_inv;\n T theta = T(2.0) * std::acos(ww); // angle of rotation\n T s_inv = T(1.0) / std::sqrt(T(1.0) - ww * ww);\n a.xyz() = complex() * s_inv * n_inv;\n a.w = T(2.0) * std::acos(ww);\n }\n return a;\n }\n\n T theta() const noexcept { return to_axis_angle().w; }\n Vector3T axis() const noexcept { return to_axis_angle().xyz(); }\n\n void set_theta(T f) noexcept { from_axis_angle(axis(), f); }\n void set_axis(const Vector3T& a) noexcept { from_axis_angle(a, theta()); }\n\n bool is_nan() const noexcept\n {\n return std::isnan(x) || std::isnan(y) || std::isnan(z) || std::isnan(w);\n }\n bool is_finite() const noexcept\n {\n return std::isfinite(x) && std::isfinite(y) && std::isfinite(z)\n && std::isfinite(w);\n }\n bool is_unit_quaternion(T epsilon = 1e-9) const noexcept\n {\n return is_finite() && fabs(quadrance() - 1.0) < epsilon;\n }\n\n // -- String shim --\n std::string to_string(const char* fmt = \"[{}, {}, {}, {}]\") const\n {\n return format(fmt, x, y, z, w);\n }\n std::string to_str() const { return to_string(\"[{}, {}, {}, {}]\"); }\n\n void print(const char* msg = NULL, bool newline = true) const\n {\n printf(\"{}{}{}{}\",\n (msg == NULL ? \"\" : msg),\n (msg == NULL ? \"\" : \" \"),\n to_string().c_str(),\n (newline ? \"\\n\" : \"\"));\n fflush(stdout);\n }\n\n std::string to_readable_str() const\n {\n auto aa = to_axis_angle();\n return format(\"aa = [{:7.5f}, {:7.5f}, {:7.5f}], theta = {:7.3f} degrees\",\n aa(0),\n aa(1),\n aa(2),\n to_degrees(aa(3)));\n }\n};\n#pragma pack(pop)\n\n// Scalar multiplication\ntemplate QuaternionT operator*(float a, const QuaternionT& v)\n{\n return v * a;\n}\ntemplate QuaternionT operator/(float a, const QuaternionT& v)\n{\n return v / a;\n}\ntemplate QuaternionT operator*(double a, const QuaternionT& v)\n{\n return v * a;\n}\ntemplate QuaternionT operator/(double a, const QuaternionT& v)\n{\n return v / a;\n}\n\n// ------------------- String shim\ntemplate std::string str(const QuaternionT& v)\n{\n return v.to_string();\n}\ntemplate\nstd::ostream& operator<<(std::ostream& out, const QuaternionT& v)\n{\n out << v.to_string();\n return out;\n}\n\n} // namespace perceive\n", "meta": {"hexsha": "577f89b79abff065598c6f8401818cec05b9fbf5", "size": 11134, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "multiview/multiview_cpp/src/perceive/geometry/quaternion.hpp", "max_stars_repo_name": "prcvlabs/multiview", "max_stars_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-09-03T23:12:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-04T21:43:32.000Z", "max_issues_repo_path": "multiview/multiview_cpp/src/perceive/geometry/quaternion.hpp", "max_issues_repo_name": "prcvlabs/multiview", "max_issues_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T02:57:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T05:33:02.000Z", "max_forks_repo_path": "multiview/multiview_cpp/src/perceive/geometry/quaternion.hpp", "max_forks_repo_name": "prcvlabs/multiview", "max_forks_repo_head_hexsha": "1a03e14855292967ffb0c0ec7fff855c5abbc9d2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-26T03:14:40.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-26T06:42:52.000Z", "avg_line_length": 25.6543778802, "max_line_length": 80, "alphanum_fraction": 0.523890785, "num_tokens": 3284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941962904955, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6972017473019031}} {"text": "// neural_network.cpp example program using posit arithmetic for a neural network simulation\n//\n// Copyright (C) 2017-2018 Stillwater Supercomputing, Inc.\n//\n// This file is part of the universal numbers project, which is released under an MIT Open Source license.\n#include \"common.hpp\"\n// include the posit number system\n#include \n#define MTL_WITH_INITLIST 1\n#include \n\n#undef NOW\n#ifdef NOW\ntemplate\nsw::unum::posit Sigmoid_(sw::unum::posit& x, bool derivative = false) {\n\tif (derivative) return x*(1-x);\n\treturn (1);\n}\n\n\ntemplate\nScalar sigmoid(Scalar x) {\n\treturn (1.0f / (1.0f + exp(-x)));\n}\n\ntemplate\nScalar f_theta(Scalar x, Scalar b, const Vector& V, const Vector& W) {\n\tdouble result = b;\n\tfor (int i = 0; i < N; ++i) {\n\t\tresult += V[i] * sigmoid(c[i] + W[i] * x);\n\t}\n\treturn result;\n}\n\ntemplate\nvoid train(Scalar x, Scalar y, Vector& W, Vector& V, Vector& c) {\n\tfor (int i = 0; i < size(W); ++i) {\n\t\tW[i] = W[i] - epsilon * 2 * (f_theta(x) - y) * V[i] * x *\n\t\t\t(1 - sigmoid(c[i] + W[i] * x)) * sigmoid(c[i] + W[i] * x);\n\t}\n\tfor (int i = 0; i < size(V); ++i) {\n\t\tV[i] = V[i] - epsilon * 2 * (f_theta(x) - y) * sigmoid(c[i] + W[i] * x);\n\t}\n\tb = b - epsilon * 2 * (f_theta(x) - y);\n\tfor (int i = 0; i < size(c); ++i) {\n\t\tc[i] = c[i] - epsilon * 2 * (f_theta(x) - y) * V[i] *\n\t\t\t(1 - sigmoid(c[i] + W[i] * x)) * sigmoid(c[i] + W[i] * x);\n\t}\n}\n\n// Multi-Level Perceptron\n// one input layer\n// one hidden layer with NrOfNeurons. \n// A \\(sigmoid\\\\) function as activation function\n// one output layer\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing namespace sw::unum;\n\n\tconst size_t nbits = 16;\n\tconst size_t es = 1;\n\tconst size_t vecSize = 32;\n\n\tusing Scalar = float;\n\tusing Matrix = mtl::dense2D;\n\tusing Vector = mtl::dense_vector;\n\tusing Pair = std::pair;\n\tusing VoP = mtl::dense_vector;\n\n#if defined(MTL_WITH_INITLIST) && defined(MTL_WITH_AUTO) && defined(MTL_WITH_RANGEDFOR)\n\tMatrix X = {\n\t\t{0,0,1},\n\t\t{0,1,1},\n\t\t{1,0,1},\n\t\t{1,1,1}\n\t};\n#endif\n\n\tconstexpr int NrOfTrainingSamples = 20;\n\tconstexpr int NrOfNeurons = 5;\n\tconstexpr float epsilon = 0.05f;\n\tconstexpr int epoch = 50000;\n\n\tVector c(NrOfNeurons), W(NrOfNeurons), V(NrOfNeurons);\n\tc = W = V = 0;\n\tScalar b = 0;\n\n\t// fill initial state with random values\n\tsrand((unsigned int)time(NULL));\n\tfor (int i = 0; i < NrOfNeurons; i++) {\n\t\tW[i] = Scalar(2 * rand() / RAND_MAX - 1);\n\t\tV[i] = Scalar(2 * rand() / RAND_MAX - 1);\n\t\tc[i] = Scalar(2 * rand() / RAND_MAX - 1);\n\t}\n\tVoP trainingSet(NrOfTrainingSamples);\n\n\tfor (int i = 0; i < NrOfTrainingSamples; i++) {\n\t\ttrainingSet[i] = make_pair(i * 2 * m_pi / NrOfTrainingSamples, sin(i * m_2_pi / NrOfTrainingSamples));\n\t}\n\n\t// train for epoch number of cycles\n\tfor (int k = 0; k < epoch; ++k) {\n\t\tfor (int i = 0; i < NrOfTrainingSamples; i++) {\n\t\t\tauto x = trainingSet[i].first;\n\t\t\tauto y = trainingSet[i].second;\n\t\t\ttrain(x,y, W, V, c);\n\t\t}\n\t\tstd::cout << k << \"\\r\";\n\t}\n\n\t// Plot the results\n\tint nrVisualSamples = 1000;\n\tVector x(nrVisualSamples);\n\tVector y1(nrVisualSamples), y2(nrVisualSamples);\n\n\tauto scaling_factor = m_2pi / nrVisualSamples;\n\tfor (int i = 0; i < nrVisualSamples; i++) {\n\t\tx[i] = i * scaling_factor;\n\t\ty1[i] = sin(i * scaling_factor);\n\t\ty2[i] = f_theta(Scalar(i * scaling_factor), b, V, W);\n\t}\n\n\tFILE * gp = _popen(\"gnuplot\", \"w\");\n\tfprintf(gp, \"set terminal wxt size 600,400 \\n\");\n\tfprintf(gp, \"set grid \\n\");\n\tfprintf(gp, \"set title '%s' \\n\", \"f(x) = sin (x)\");\n\tfprintf(gp, \"set style line 1 lt 3 pt 7 ps 0.1 lc rgb 'green' lw 1 \\n\");\n\tfprintf(gp, \"set style line 2 lt 3 pt 7 ps 0.1 lc rgb 'red' lw 1 \\n\");\n\tfprintf(gp, \"plot '-' w p ls 1, '-' w p ls 2 \\n\");\n\n\t// Exact f(x) = sin(x) -> Green Graph\n\tfor (int k = 0; k < nrVisualSamples; ++k) {\n\t\tfprintf(gp, \"%f %f \\n\", x[k], y1[k]);\n\t}\n\tfprintf(gp, \"e\\n\");\n\n\t//Neural Network Approximate f(x) = sin(x) -> Red Graph\n\tfor (int k = 0; k < nrVisualSamples; ++k) {\n\t\tfprintf(gp, \"%f %f \\n\", x[k], y2[k]);\n\t}\n\tfprintf(gp, \"e\\n\");\n\n\tfflush(gp);\n\n\treturn EXIT_SUCCESS;\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_internal_exception& err) {\n\tstd::cerr << \"Uncaught posit internal exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (std::runtime_error& err) {\n\tstd::cerr << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tstd::cerr << \"Caught unknown exception\" << std::endl;\n\treturn EXIT_FAILURE;\n}\n\n#else\nint main() {}\n#endif\n", "meta": {"hexsha": "9315fadf769e1a1ccc204fe543a4480b26acc00c", "size": 4949, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/mlp/neural_network.cpp", "max_stars_repo_name": "fossabot/hpr-blas", "max_stars_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/mlp/neural_network.cpp", "max_issues_repo_name": "fossabot/hpr-blas", "max_issues_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/mlp/neural_network.cpp", "max_forks_repo_name": "fossabot/hpr-blas", "max_forks_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9604519774, "max_line_length": 106, "alphanum_fraction": 0.6280056577, "num_tokens": 1623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.805632181981183, "lm_q1q2_score": 0.6970523655492106}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"Sampling_functions.h\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace arma;\nusing namespace boost;\n\n//boost::random::mt19937 gen(0);\nboost::random::mt19937 gen(time(0));\n//distributions\ndouble runif(double lower, double higher)\n{\n\tboost::random::uniform_real_distribution<> dist(lower, higher);\n\treturn dist(gen);\n}\n\ndouble rnorm(double mean, double sd)\n{\n\tboost::random::normal_distribution<> dist(mean, sd);\n\treturn dist(gen);\n}\n\ndouble rgamma(double alpha, double beta)\n{\n\n\tboost::math::gamma_distribution<> dist(alpha, beta);\n\tdouble q = quantile(dist, runif(0,1));\n\n\treturn(q);\n}\n\ndouble rbeta(double alpha, double beta)\n{\n\n\tboost::math::beta_distribution<> dist(alpha, beta);\n\tdouble q = quantile(dist, runif(0,1));\n\n\treturn(q);\n}\n\ndouble rinvchisq(double df, double scale)\n{\n\n\tboost::math::inverse_chi_squared_distribution<> dist(df, scale);\n\tdouble q = quantile(dist, runif(0,1));\n\n\treturn(q);\n}\nint rbernoulli(double p)\n{\n\tstd::bernoulli_distribution dist(p);\n\treturn dist(gen);\n}\n\n//switch between armadillo and eigen\nEigen::MatrixXd cast_eigen(arma::mat arma_A)\n{\n\tEigen::MatrixXd eigen_B = Eigen::Map(arma_A.memptr(),\n\t\t\tarma_A.n_rows,\n\t\t\tarma_A.n_cols);\n\n\treturn eigen_B;\n}\n\narma::mat cast_arma(Eigen::MatrixXd& eigen_A)\n{\n\tarma::mat arma_B = arma::mat(eigen_A.data(), eigen_A.rows(), eigen_A.cols(),false, false);\n\treturn arma_B;\n}\n\n\n//sampling functions\ndouble sample_hyper(const MatrixXd& w1_M1_sample, const MatrixXd& WI_m, double b0_m, const VectorXd& mu0_m, int df_m,VectorXd& mu_m,MatrixXd& lambda_m)\n{\n\t//Sample from individual or SNP hyperparams (equation 14)\n\tint N = w1_M1_sample.rows();\n\tint num_feat=w1_M1_sample.cols();\n\tVectorXd u_bar(num_feat);\n\tMatrixXd S_bar(num_feat,num_feat);\n\n\tu_bar = w1_M1_sample.colwise().mean().transpose();\n\t//covariance to correlation\n\tS_bar = (w1_M1_sample.transpose()*w1_M1_sample)/N;\n\n\t//Gaussian-Wishard sampling\n\t//1.sample lambda from wishard distribution (lambda_m or lambda_u)\n\t//2.sample mu (mu_m or mu_u) from multivariate normal distribution with mean mu_0 (mu_temp) and variance (lambda*Lambda)^-1\n\n\t//Wishard-covariance matrix\n\tMatrixXd WI_post(num_feat,num_feat);\n\tWI_post = WI_m.inverse() + N*S_bar+((N*b0_m)/(b0_m+N))*((mu0_m - u_bar)*(mu0_m - u_bar).transpose());\n\n\t//WI_post = (WI_post + WI_post.transpose())/2;\n\n\tWI_post=WI_post.inverse();\n\n\t//Wishard-degrees of freedom\n\tint df_mpost = df_m+N;\n\n\t//Wishard draw, using the armadillo function. So I cast to an armadillo matrix, draw wishart then cast back to eigen matrix.\n\t//should just code the wishart function.\n\tmat arma_lambda =cast_arma(WI_post);\n\tmat W = wishrnd(arma_lambda, df_mpost);\n\tlambda_m=cast_eigen(W);\n\n\t//multivariate normal mean\n\tVectorXd mu_temp(num_feat);\n\tmu_temp = (b0_m*mu0_m + N*u_bar)/(b0_m+N);\n\n\t//Multivariate normal with mean mu_temp and cholesky decomposed covariance lam\n\tMatrixXd lam = (((b0_m+N)*lambda_m).inverse());\n\n\tlam=lam.llt().matrixU();\n\tlam.transposeInPlace();\n\n\tMatrixXd normV(num_feat,1);\n\tfor (int i=0;i I;\n\tfor (int i=0; i I;\n\tfor (int i=0; i I;\n\tfor (int i=0; i I;\n\tfor (int i=0; i I;\n\tfor (int i=0; i J;\n\tfor (int i=0; i\n#include \n#include // Eigen 部分\n#include // 稠密矩阵的代数运算\nusing namespace std;\n\n#define MATRIX_SIZE 50\n\n/********************************************\n * 本程序演示Eigen的基本类型的使用\n * *****************************************/\n\nint main(int argc, char** argv)\n{\n Eigen::Matrix matrix_23;\n Eigen::Vector3d v_3d;\n Eigen::Matrix vd_3d;\n\n Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero();\n Eigen::Matrix matrix_dynamic;\n Eigen::MatrixXd matrix_x;\n\n matrix_23 << 1, 2, 3, 4, 5, 6;\n cout<< matrix_23< result = matrix_23.cast() * v_3d;\n cout << result << endl;\n\n // Eigen::Matrix result2 = matrix_23 * vd_3d;\n // cout << result2 << endl;\n\n // 四则运算直接用+-*/\n // 下面为其他矩阵运算\n matrix_33 = Eigen::Matrix3d::Random();\n cout << matrix_33 << endl;\n\n cout << matrix_33.transpose() << endl;\n cout << matrix_33.sum() << endl;\n cout << matrix_33.trace() << endl;\n cout << 10*matrix_33 < eigen_solver\n (matrix_33.transpose()*matrix_33);\n cout << \"Eigen values = \\n\"<< eigen_solver.eigenvalues()< matrix_NN;\n matrix_NN = Eigen::MatrixXd::Random(MATRIX_SIZE,MATRIX_SIZE);\n Eigen::Matrix v_Nd;\n v_Nd = Eigen::MatrixXd::Random(MATRIX_SIZE,1);\n\n clock_t time_stt = clock(); // start\n \n\n // 直接求逆\n Eigen::Matrix x = matrix_NN.inverse()*v_Nd;\n cout << \"time use in normal inverse is \" << 1000*(clock()-time_stt)/\n (double)CLOCKS_PER_SEC << \"ms\" <\n#include \n\nint main(int, char**)\n{\n using namespace mtl;\n\n double array[][3]= {{1., 0., 3.}, {4., 0., 6.}, {7., 0., 9.}, {0., 0., 0.}};\n dense2D A(array), B2, B3;\n\n // Creating a compression (reordering) matrix from a vector (or an array respectively)\n int non_zero_rows[]= {0, 1, 2}, non_zero_columns[]= {0, 2};\n // To be sure, we give the number of columns for a consistent size!\n mat::traits::reorder<>::type RR= mat::reorder(non_zero_rows, 4), RC= mat::reorder(non_zero_columns);\n std::cout << \"A =\\n\" << A << \"\\nRR =\\n\" << RR << \"\\nRC =\\n\" << RC; \n\n // Compress rows\n B2= RR * A;\n std::cout << \"\\nRR * A, i.e. compress row of A =\\n\" << B2;\n \n // Compress columns\n B3= B2 * trans(RC);\n std::cout << \"\\nB2 * trans(RC), i.e. compress columns of B2 =\\n\" << B3;\n \n // Decompress rows\n dense2D C1(trans(RR) * B3);\n std::cout << \"\\ntrans(RR) * B3, i.e. row decompression of B3 =\\n\" << C1;\n\n // Decompress columns\n dense2D C2(C1 * RC);\n std::cout << \"\\nC1 * RC, i.e. column decompression of C1 (should be A) =\\n\" << C2;\n\n return 0;\n}\n", "meta": {"hexsha": "087e5bfd741b961a039356558135ae0c3ce9e300", "size": 1187, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/reorder3.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/reorder3.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/reorder3.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 33.9142857143, "max_line_length": 104, "alphanum_fraction": 0.5543386689, "num_tokens": 427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.8104789178257654, "lm_q1q2_score": 0.6967393578633362}} {"text": "#include \n#include \n#include \n#include \"linear_algebra_addon.hpp\"\nusing namespace Eigen;\nusing namespace std;\n\nMatrixXcd bl_cocg_rq(const MatrixXcd& A, const MatrixXcd& B, const double& tol, const int& itermax)\n{\n// only for complex-symmetric matrix\n// Gu et al 2016, arXiv, Block variants of COCG and COCR methods\n// for solving complex symmetric linear systems with multiple right-hand sides\n\n double Bnorm= B.norm();\n MatrixXcd X= MatrixXcd::Zero(B.rows(),B.cols()); // Initial guess of X (zeros)\n\n MatrixXcd Q;\n MatrixXcd xi;\n tie(Q,xi)= qr_reduced(B-A*X);\n MatrixXcd S= Q;\n\n for(int k= 0; k < itermax; ++k){\n MatrixXcd AS= A*S;\n MatrixXcd alpha= (S.transpose()*AS).fullPivLu().solve(Q.transpose()*Q);\n X= X+S*alpha*xi;\n MatrixXcd Qnew;\n MatrixXcd tau;\n tie(Qnew,tau)= qr_reduced(Q-AS*alpha);\n xi= tau*xi;\n double err= xi.norm()/Bnorm;\n cout << \"bl_cocg_rq: \" << \"iter= \" << k << \" relative err= \" << err << endl;\n if(err < tol) break;\n MatrixXcd beta= (Q.transpose()*Q).fullPivLu().solve(tau.transpose()*Qnew.transpose()*Qnew);\n Q= Qnew;\n S= Q+S*beta;\n }\n\n if((A*X-B).norm()/Bnorm > 10*tol){\n cerr << \"bl_cocg_rq did not converge to solution within error tolerance !\" << endl;\n // exit(EXIT_FAILURE);\n }\n\n return X;\n}\n", "meta": {"hexsha": "d1c86ed450a125d97a66f17039902d203033d0c2", "size": 1338, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bl_cocg_rq.cpp", "max_stars_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_stars_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-27T08:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T08:44:06.000Z", "max_issues_repo_path": "bl_cocg_rq.cpp", "max_issues_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_issues_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bl_cocg_rq.cpp", "max_forks_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_forks_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7333333333, "max_line_length": 99, "alphanum_fraction": 0.6382660688, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6966301992577538}} {"text": "#include \n#include \n#include \n\nusing namespace std;\nusing namespace mtl;\n\ntypedef dense2D Matrix;\n// using Matrix= dense2D; // C++11\n\ndense_vector unit_vector(unsigned k, unsigned n)\n{\n dense_vector e_k(n, 0.0);\n e_k[k]= 1.0;\n\n // for (unsigned i= 0; i < n; ++i)\n // \t e_k[k]= static_cast(i == k);\n // for (unsigned i= 0; i < n; ++i)\n // \t e_k[k]= i == k; \n\n return e_k;\n}\n\n\nMatrix inverse_upper(const Matrix& U)\n{\n const unsigned n= num_rows(U);\n Matrix Inv(n, n);\n Inv= 0.0;\n for (unsigned k= 0; k < n; k++) { \n\tirange r(0,k+1);\n\tInv[r][k]= upper_trisolve(U[r][r], unit_vector(k, k+1));\n }\n return Inv;\n}\n\nMatrix inverse_lower(const Matrix& L)\n{\n Matrix T(trans(L));\n return Matrix(trans(inverse_upper(T)));\n}\n\n\nMatrix inverse(const Matrix& A)\n{\n const unsigned n= num_rows(A);\n if (num_cols(A) != n)\n\tthrow \"Matrix must be square\";\n\n Matrix Inv(n, n);\n\n Matrix LU(A); // Kopie von A\n dense_vector Pv(n);\n lu(LU, Pv);\n compressed2D P(permutation(Pv));\n Matrix I(mat::identity(n, n)), L(I + strict_lower(LU)), U(upper(LU));\n Inv= inverse_upper(U) * inverse_lower(L) * P;\n\n return Inv;\n}\n\n\nint main (int argc, char* argv[]) \n{\n const unsigned size= 3;\n const double eps= 0.001; // C++11: constexpr double eps= 0.001; \n Matrix A(size, size);\n A= 4, 1, 2,\n 1, 5, 3,\n 2, 6, 9;\n\n cout << \"A ist\\n\" << A;\n\n Matrix LU(A); // Kopie von A\n dense_vector Pv(size);\n lu(LU, Pv);\n Matrix P(permutation(Pv));\n\n cout << \"LU ist\\n\" << LU;\n cout << \"Permutation vector is \" << Pv << \"\\nPermutationsmatrix ist\\n\" << P;\n\n Matrix I(mat::identity(size, size)), L(I + strict_lower(LU)), U(upper(LU));\n cout << \"L ist\\n\" << L << \"U ist\\n\" << U;\n\n Matrix UI(inverse_upper(U));\n cout << \"Inverse von U ist\\n\" << UI << \"UI * U ist\\n\" << Matrix(UI * U);\n assert(one_norm(Matrix(UI * U - I)) < eps);\n\n Matrix LI(inverse_lower(L));\n cout << \"Inverse von L ist\\n\" << LI << \"LI * L ist\\n\" << Matrix(LI * L);\n assert(one_norm(Matrix(LI * L - I)) < eps);\n\n\n Matrix AI(UI * LI * P);\n cout << \"Inverse von A ist\\n\" << AI << \"AI * A ist\\n\" << Matrix(AI * A);\n assert(one_norm(Matrix(AI * A - I)) < eps);\n \n Matrix A_inverse(inverse(A));\n cout << \"Inverse von A ist\\n\" << A_inverse << \"A_inverse * A ist\\n\" << Matrix(A_inverse * A);\n assert(one_norm(Matrix(A_inverse * A - I)) < eps);\n\n return 0 ;\n}\n", "meta": {"hexsha": "baa969a34426b88000832c7a22e7585421cd03f5", "size": 2562, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "DiscoveringModernCpp/c++03/inverse.cpp", "max_stars_repo_name": "SebastianTirado/Cpp-Learning-Archive", "max_stars_repo_head_hexsha": "fb83379d0cc3f9b2390cef00119464ec946753f4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 19.0, "max_stars_repo_stars_event_min_datetime": "2019-09-15T12:23:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-18T08:31:26.000Z", "max_issues_repo_path": "DiscoveringModernCpp/c++03/inverse.cpp", "max_issues_repo_name": "SebastianTirado/Cpp-Learning-Archive", "max_issues_repo_head_hexsha": "fb83379d0cc3f9b2390cef00119464ec946753f4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2021-12-07T06:46:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-31T07:55:32.000Z", "max_forks_repo_path": "DiscoveringModernCpp/c++03/inverse.cpp", "max_forks_repo_name": "SebastianTirado/Cpp-Learning-Archive", "max_forks_repo_head_hexsha": "fb83379d0cc3f9b2390cef00119464ec946753f4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2019-06-29T02:58:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-07T08:52:22.000Z", "avg_line_length": 24.6346153846, "max_line_length": 97, "alphanum_fraction": 0.5671350507, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6966301803473822}} {"text": "#include \"triangulation.h\"\n\n#include \"defines.h\"\n\n#include \n\n// Используем DLT метод, составляем систему уравнений. Система похожа на систему для гомографии, там пары уравнений получались из выражений вида x (cross) Hx = 0, а здесь будет x (cross) PX = 0\n// (см. Hartley & Zisserman p.312)\ncv::Vec4d phg::triangulatePoint(const cv::Matx34d *Ps, const cv::Vec3d *ms, int count)\n{\n using mat = Eigen::MatrixXd;\n using vec = Eigen::VectorXd;\n\n mat A(2 * count, 4);\n\n for (int i = 0; i < count; ++i) {\n\n const matrix34d &P = Ps[i];\n const vector3d &m = ms[i];\n\n double x = m[0];\n double y = m[1];\n double z = m[2];\n\n auto p0 = P.row(0);\n auto p1 = P.row(1);\n auto p2 = P.row(2);\n\n auto row0 = x * p2 - z * p0;\n auto row1 = y * p2 - z * p1;\n\n A.row(i * 2 + 0) << row0(0), row0(1), row0(2), row0(3);\n A.row(i * 2 + 1) << row1(0), row1(1), row1(2), row1(3);\n }\n\n Eigen::JacobiSVD svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n Eigen::VectorXd null_space = svd.matrixV().col(3);\n\n vector4d result;\n for (int i = 0; i < 4; ++i) {\n result(i) = null_space(i);\n }\n\n return result;\n}\n", "meta": {"hexsha": "7492480e0002dafff07da7d71b1e1fdaa22e9c53", "size": 1228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phg/sfm/triangulation.cpp", "max_stars_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_stars_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/phg/sfm/triangulation.cpp", "max_issues_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_issues_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/phg/sfm/triangulation.cpp", "max_forks_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_forks_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6956521739, "max_line_length": 193, "alphanum_fraction": 0.5602605863, "num_tokens": 450, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037221561135, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6965920410336649}} {"text": "//=============================================================================\n// Daniel J. Greenhoe\n// normed linear space R^2\n//=============================================================================\n//=====================================\n// headers\n//=====================================\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"r1.h\"\n#include \"r2.h\"\n#include \"r2op.h\"\n\n//-----------------------------------------------------------------------------\n//! List value of opair\n//! \\param[in] str1 : string to print before the sequence\n//! \\param[in] str2 : string to print after the sequence\n//! \\param[out] ptr : output string\n//-----------------------------------------------------------------------------\nvoid opair::list(const char *str1, const char *str2, FILE *ptr) const\n{\n if( strlen(str1)>0 ) fprintf(ptr,\"%s\",str1);\n fprintf(ptr,\"(%9.6lf,%9.6lf)\",getx(),gety());\n if( strlen(str2)>0 ) fprintf(ptr,\"%s\",str2);\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief polar rotation coordinate of opair point (x,y)\n//! \\returns Return value is in the half open interval [0:2pi), \n//! -1 on error\n//-----------------------------------------------------------------------------\ndouble vectR2::theta(void) const\n{\n const double x = getx();\n const double y = gety();\n if(x==0){\n if( y == 0 ) return -1 ;\n else if(y > 0 ) return 1 * M_PI / 2;\n else return 3 * M_PI / 2;\n }\n if(y==0){\n if( x>0 ) return 0;\n else return M_PI;\n }\n if( x>0 && y>0 ) return atan( y/x); // 1st quadrant\n if( x>0 && y<0 ) return 2*M_PI-atan(-y/x); // 4th quadrant\n if( x<0 && y>0 ) return M_PI-atan(-y/x); // 2nd quadrant\n if( x<0 && y<0 ) return M_PI+atan( y/x); // 3rd quadrant\n else return -1;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Operator to rotate vector R2 [x,y] counter-clockwise by radians\n//! \\param[in] phi: angle to rotate vector by\n//-----------------------------------------------------------------------------\nvoid vectR2::operator&=(const double phi)\n{\n vectR2 p(getx(),gety());\n p = p & phi;\n put(p.getx(),p.gety());\n}\n\n//=====================================\n// seqR2\n//=====================================\n//-----------------------------------------------------------------------------\n//! \\brief Constructor initializing seqR1 to 0s\n//! \\param[in] M: Length of sequence\n//-----------------------------------------------------------------------------\nseqR2::seqR2(const long M)\n{\n N = M;\n xy = new vectR2[N];\n clear();\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief constructor initializing seqR1 to u\n//! \\param[in] M: Length of sequence\n//! \\param[in] u: Initialization value\n//-----------------------------------------------------------------------------\nseqR2::seqR2(long M, double u)\n{\n long n;\n N=M;\n xy = new vectR2[N];\n for(n=0; n\n//-----------------------------------------------------------------------------\nvoid seqR2::fill(double u)\n{\n long n;\n for(n=0; n=N){\n fprintf(stderr,\"n=%ld larger than seqR1 size N=%ld\\n\",n,N);\n retval=-1;\n }\n else xy[n].put(u,v);\n return retval;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Put an R2 vector xyz into the sequence x at location n\n//-----------------------------------------------------------------------------\nint seqR2::put(long n, vectR2 xya)\n{\n int retval=0;\n if(n>=N){\n fprintf(stderr,\"n=%ld larger than seqR1 size N=%ld\\n\",n,N);\n retval=-1;\n }\n else xy[n]=xya;\n return retval;\n}\n\n//-----------------------------------------------------------------------------\n//! Get a single value from the sequence x at location n\n//-----------------------------------------------------------------------------\nvectR2 seqR2::get(const long n) const\n{\n vectR2 xya(0,0);\n if(n0)fprintf(ptr,\"%s\",str1);\n for(n=start,m=1; n<=end; n++,m++){\n x=get(n);\n fprintf(ptr,\" \");\n x.list(ptr);\n if(m%3==0)fprintf(ptr,\"\\n\");\n }\n if(strlen(str2)>0)fprintf(ptr,\"%s\",str2);\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief List contents of seqC1 using 1 digit per element\n//-----------------------------------------------------------------------------\nvoid seqR2::list1(void) const\n{\n long n,m;\n for(n=0,m=1; nmaxnorm){maxnorm=norm(n); maxn=n;}\n maxpair=get(maxn);\n if(verbose)\n {\n for(n=0; n=(maxnorm*0.999))\n printf(\"max=(%lf,%lf) at n=%ld\\n\",maxpair.getx(),maxpair.gety(),n);\n }\n }\n return maxpair;\n}\n\n//=====================================\n// external operations\n//=====================================\n//-----------------------------------------------------------------------------\n//! \\brief Operator: return p+q\n//-----------------------------------------------------------------------------\nvectR2 operator+(const vectR2 p, const vectR2 q)\n{\n const Eigen::Map< const Eigen::Vector2d > a( p.getdata() );\n const Eigen::Map< const Eigen::Vector2d > b( q.getdata() );\n const Eigen::Vector2d c = a + b;\n const vectR2 r( c(0), c(1) );\n return r;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Operator: return p-q\n//-----------------------------------------------------------------------------\nvectR2 operator-(const vectR2 p, const vectR2 q)\n{\n const Eigen::Map< const Eigen::Vector2d > a( p.getdata() );\n const Eigen::Map< const Eigen::Vector2d > b( q.getdata() );\n const Eigen::Vector2d c = a - b;\n const vectR2 r( c(0), c(1) );\n return r;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Operator: return -p\n//-----------------------------------------------------------------------------\nvectR2 operator-(const vectR2 p)\n{\n const Eigen::Map< const Eigen::Vector2d > a( p.getdata() );\n const Eigen::Vector2d b = -a;\n const vectR2 c( b(0), b(1) );\n return c;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief operator: return

rotated counter-clockwise by radians\n//! \\details\n//! https://stackoverflow.com/questions/17036818/\n//! https://eigen.tuxfamily.org/dox/group__TopicStorageOrders.html\n//! https://stackoverflow.com/questions/28722899/\n//-----------------------------------------------------------------------------\nvectR2 operator&(const vectR2 p, const double phi)\n{\n double cosphi, sinphi;\n if(phi==0){ cosphi = 1; sinphi = 0; }\n else { cosphi = cos(phi); sinphi = sin(phi); }\n const std::vector rr = { cosphi, -sinphi, \n sinphi, cosphi };\n const Eigen::Matrix R(rr.data()); \n//printf(\" _ _\\n\");\n//printf(\"R = | %9.6lf %9.6lf |\\n\", R(0,0), R(0,1) );\n//printf(\" |_%9.6lf %9.6lf _|\\n\", R(1,0), R(1,1) );\n//const Eigen::Map< const Eigen::Vector2d > x( p.pairxy.data() );\n const Eigen::Map< const Eigen::Vector2d > x( p.getdata() );\n const Eigen::Vector2d y = R * x;\n const vectR2 q( y(0), y(1) );\n return q;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Return the angle theta in radians between the two vectors induced by\n//! the points

and in the plane R^2\n//! \\returns On SUCCESS return theta in the closed interval [0:M_PI];\n//! On ERROR exit with value EXIT_FAILURE\n//-----------------------------------------------------------------------------\ndouble pqtheta(const vectR2 p, const vectR2 q)\n{\n const double rp=p.mag(), rq=q.mag();\n double y;\n if(rp==0) return -1;\n if(rq==0) return -2;\n y = (p^q)/(rp*rq);\n if( y > +1.0 )\n {\n if(y-1 < 1e-13 ) y = 1.0;\n else{\n fprintf(stderr,\"\\nERROR using pqtheta(vectR2 p, vectR2 q): (p^q)/(rp*rq)=%.12lf>+1\\n\",y);\n exit(EXIT_FAILURE);\n }\n }\n if(y<(-1.0))\n {\n if(y+1> -1e-13 ) y = -1.0;\n else{\n fprintf(stderr,\"\\nERROR using pqtheta(vectR2 p, vectR2 q): (p^q)/(rp*rq)=%.12lf<-1\\n\",y);\n exit(EXIT_FAILURE);\n }\n }\n const double theta = acos(y);\n return theta;\n}\n\n", "meta": {"hexsha": "7d520f2b45b97c4b2996d5b0b33d21abe713a79f", "size": 12033, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "r2.cpp", "max_stars_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_stars_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r2.cpp", "max_issues_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_issues_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r2.cpp", "max_forks_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_forks_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5181058496, "max_line_length": 103, "alphanum_fraction": 0.3928363667, "num_tokens": 2806, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.787931190663057, "lm_q1q2_score": 0.6965621286735617}} {"text": "#include \n#include \"../matplotlibcpp.h\"\nnamespace plt = matplotlibcpp;\n\n#ifdef WITH_EIGEN\n #include \n#endif\n\ntypedef std::vector> nested_vectors;\n\ntemplate \nvoid get_data(Matrix& x, Matrix& y, Matrix& z) {\n // check the sizes\n const unsigned ncols = x.cols(),\n nrows = x.rows();\n assert(ncols == y.cols() && ncols == z.cols());\n assert(nrows == y.rows() && nrows == z.rows());\n\n // write data\n const double a = -5,\n b = 5;\n const double col_incr = (b - a) / ncols,\n row_incr = (b - a) / nrows;\n for (unsigned i = 0; i < nrows; ++i) {\n for (unsigned j = 0; j < ncols; ++j) {\n x(i, j) = i;\n y(i, j) = j;\n z(i, j) = ::std::sin(::std::hypot(a + i * col_incr, a + j * row_incr));\n }\n }\n}\n\ntemplate <>\nvoid get_data(nested_vectors& x, nested_vectors& y, nested_vectors& z) {\n for (double i = -5; i <= 5; i += 0.25) {\n std::vector x_row, y_row, z_row;\n for (double j = -5; j <= 5; j += 0.25) {\n x_row.push_back(i);\n y_row.push_back(j);\n z_row.push_back(::std::sin(::std::hypot(i, j)));\n }\n x.push_back(x_row);\n y.push_back(y_row);\n z.push_back(z_row);\n }\n}\n\n\nint main() {\n std::vector> x, y, z;\n get_data(x, y, z);\n plt::plot_surface(x, y, z);\n plt::show();\n\n #ifdef WITH_EIGEN\n const unsigned n = 100; // resolution of hypot function\n Eigen::MatrixXd X(n,n), Y(n,n), Z(n,n);\n get_data(X, Y, Z);\n plt::plot_surface(X, Y, Z);\n plt::show();\n #endif\n}\n", "meta": {"hexsha": "d597708cc066f108f333915ed2a2f27b410bf4aa", "size": 1630, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulation_code/src/matplotlib-cpp/examples/surface.cpp", "max_stars_repo_name": "lottegr/project_simulation", "max_stars_repo_head_hexsha": "b95d88114a3d2611073d1977393884062f63bdab", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2019-12-30T19:39:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T15:55:10.000Z", "max_issues_repo_path": "simulation_code/src/matplotlib-cpp/examples/surface.cpp", "max_issues_repo_name": "lottegr/project_simulation", "max_issues_repo_head_hexsha": "b95d88114a3d2611073d1977393884062f63bdab", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-08-25T13:22:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T18:26:01.000Z", "max_forks_repo_path": "simulation_code/src/matplotlib-cpp/examples/surface.cpp", "max_forks_repo_name": "lottegr/project_simulation", "max_forks_repo_head_hexsha": "b95d88114a3d2611073d1977393884062f63bdab", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2020-02-26T11:37:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T09:50:24.000Z", "avg_line_length": 25.873015873, "max_line_length": 77, "alphanum_fraction": 0.5319018405, "num_tokens": 504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7879311931529758, "lm_q1q2_score": 0.6965621260602517}} {"text": "#include // Eigen is required\n\ntemplate\nstatic inline void pseudoInverse(float A[], float B[])\n{\n\ttypedef Eigen::Matrix t_A;\n\n\tt_A mA(R, C);\n\n\tfor (int i = 0; i < R; i++)\n\t{\n\t\tfor (int j = 0; j < C; j++)\n\t\t{\n\t\t\tmA(i, j) = A[i + j * R];\n\t\t}\n\t}\n\n\tEigen::JacobiSVD svd(mA, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n\tauto U = svd.matrixU();\n\tauto S = svd.singularValues();\n\tauto V = svd.matrixV();\n\n\tfloat Vt[C * C];\n\n\tfor (int i = 0; i < C; i++)\n\t{\n\t\tfloat s = S(i);\n\n\t\tif (s != 0.f)\n\t\t\ts = 1.f / s;\n\n\t\tfor (int j = 0; j < C; j++)\n\t\t{\n\t\t\tVt[j * C + i] = V(j, i) * s;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < C; i++)\n\t{\n\t\tfor (int j = 0; j < R; j++)\n\t\t{\n\t\t\tfloat v = 0.f;\n\n\t\t\tfor (int k = 0; k < C; k++)\n\t\t\t{\n\t\t\t\tv += Vt[i * C + k] * U(j, k);\n\t\t\t}\n\n\t\t\tB[i * R + j] = v;\n\t\t}\n\t}\n}\n\nvoid svd_routine_49_2(float A[], float B[])\n{\n\tpseudoInverse<49, 2>(A, B);\n}\n\nvoid svd_routine_121_8(float A[], float B[])\n{\n\tpseudoInverse<121, 8>(A, B);\n}\n", "meta": {"hexsha": "618a0db1a757a19ead6ab94446511b1d913e241c", "size": 1078, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PvrtcCompress/eigen_svd.cpp", "max_stars_repo_name": "pps83/playrix", "max_stars_repo_head_hexsha": "759fe85487760ee737bcbc7596cb7be3c259bb0e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PvrtcCompress/eigen_svd.cpp", "max_issues_repo_name": "pps83/playrix", "max_issues_repo_head_hexsha": "759fe85487760ee737bcbc7596cb7be3c259bb0e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PvrtcCompress/eigen_svd.cpp", "max_forks_repo_name": "pps83/playrix", "max_forks_repo_head_hexsha": "759fe85487760ee737bcbc7596cb7be3c259bb0e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.84375, "max_line_length": 116, "alphanum_fraction": 0.5222634508, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308165850442, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6964691348198766}} {"text": "/**\n * @author : adamlamson (adamlamson@LamsonMacbookPro)\n * @file : two_step_prob\n * @created : Wednesday Jan 29, 2020 14:05:35 MST\n */\n\n#ifndef TWO_STEP_PROB_HPP\n\n#define TWO_STEP_PROB_HPP\n#include \n#include \n#include \n\n// Solve the for the time that maximizes the probability of two events occuring\ntemplate \nclass MaxTimeOfTwoStepProbFunctor {\n public:\n // Constructor just stores values find root of function.\n MaxTimeOfTwoStepProbFunctor(T const &rate1, T const &rate2,\n T const &total_time)\n : k_ab(rate1), k_bc(rate2), tot_time(total_time) {}\n\n T operator()(T const &t) {\n T fx = k_ab * (exp(k_bc * (tot_time - t)) - 1.) -\n k_bc * (exp(k_ab * t) - 1.);\n return fx;\n }\n\n private:\n T k_ab;\n T k_bc;\n T tot_time;\n};\n\ntemplate \nT max_time_of_two_step_prob(T const &rate1, T const &rate2,\n T const &total_time) {\n\n T guess = .5 * total_time;\n T factor = 2; // How big steps to take when searching.\n\n const boost::uintmax_t maxit = 20; // Limit to maximum iterations.\n boost::uintmax_t it =\n maxit; // Initally our chosen max iterations, but updated with actual.\n bool is_rising =\n false; // So if guess is too low, then try increasing guess.\n int digits = std::numeric_limits::digits; // Maximum possible binary\n // digits accuracy for type T.\n // Some fraction of digits is used to control how accurate o try to make the\n // result.\n int get_digits =\n digits - 3; // We have to have a non-zero interval at each step, so\n // maximum accuracy is digits - 1. But we also have to\n // allow for inaccuracy in f(x), otherwise the last few\n // iterations just thrash around.\n boost::math::tools::eps_tolerance rel_tol(\n get_digits); // Set the tolerance.\n std::pair t = boost::math::tools::bracket_and_solve_root(\n MaxTimeOfTwoStepProbFunctor(rate1, rate2, total_time), guess, factor,\n is_rising, rel_tol, it);\n return t.first + (t.second - t.first) * .5;\n};\n\ntemplate \nT two_step_prob(T const &rate1, T const &rate2, T const &total_time,\n T const &t) {\n assert(total_time >= t);\n T prob = (1. - exp(-1. * rate1 * t)) *\n (1. - exp(-1. * rate2 * (total_time - t)));\n return prob;\n};\n\ntemplate \nT two_step_max_prob(T const &rate1, T const &rate2, T const &total_time) {\n T t_max = max_time_of_two_step_prob(rate1, rate2, total_time);\n T prob = two_step_prob(rate1, rate2, total_time, t_max);\n return prob;\n};\n\n#endif /* end of include guard TWO_STEP_PROB_HPP */\n\n", "meta": {"hexsha": "f3f5e7617a6bfebba4fc566bff08a058608a5c84", "size": 2814, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "KMC/two_step_prob.hpp", "max_stars_repo_name": "lamsoa729/KMC", "max_stars_repo_head_hexsha": "53ae6f392db369ee5fc5ea16711787bf4020d8d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-04-15T22:02:53.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-01T22:06:52.000Z", "max_issues_repo_path": "KMC/two_step_prob.hpp", "max_issues_repo_name": "lamsoa729/KMC", "max_issues_repo_head_hexsha": "53ae6f392db369ee5fc5ea16711787bf4020d8d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-09-27T17:05:07.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T15:59:17.000Z", "max_forks_repo_path": "KMC/two_step_prob.hpp", "max_forks_repo_name": "lamsoa729/KMC", "max_forks_repo_head_hexsha": "53ae6f392db369ee5fc5ea16711787bf4020d8d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-04-18T20:17:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-18T20:17:58.000Z", "avg_line_length": 34.3170731707, "max_line_length": 80, "alphanum_fraction": 0.6112295665, "num_tokens": 752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.867035752930664, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.696380397258486}} {"text": "#pragma once\n#include \n#include \n#include \n#include \n#include \n\n#define EPSILON 1e-6f\n#define DELTA 1e-4f\n#define PI 3.14159265358979323846f\n#define PI_INV 0.31830988618f\n\n\nnamespace mathext {\n std::default_random_engine random_generator;\n\n std::vector unif(float a, float b, int N = 1)\n {\n std::vector res;\n std::uniform_real_distribution dis(a, b);\n\n for (int i = 0; i < N; i++) {\n res.push_back(dis(random_generator));\n }\n return res;\n }\n\n Eigen::Vector2f disk(float r)\n {\n std::vector u = unif(0.0f, 1.0f, 2);\n\n return Eigen::Vector2f(r * sqrt(u[0]), 2 * PI * u[1]);\n }\n\n Eigen::Matrix3f rot_from_two_vectors(Eigen::Vector3f src, Eigen::Vector3f des)\n {\n return Eigen::Quaternionf::FromTwoVectors(src, des).toRotationMatrix();\n }\n\n Eigen::Matrix3f rot_align_normal(Eigen::Vector3f n)\n {\n return rot_from_two_vectors(Eigen::Vector3f(0.0f, 0.0f, 1.0f), n);\n }\n\n Eigen::Vector3f reflect(Eigen::Vector3f v1, Eigen::Vector3f n)\n {\n return 2 * n.dot(v1) * n - v1;\n }\n\n Eigen::Vector3f refract(Eigen::Vector3f v1, Eigen::Vector3f n, float ior = 1.0f)\n {\n float cos_theta_i = v1.dot(n); \n float eta = 1 / ior;\n if (cos_theta_i < 0) {\n eta = 1 / eta;\n n *= -1;\n cos_theta_i *= -1;\n }\n float c = sqrt(1 - eta * eta * (1 - cos_theta_i * cos_theta_i));\n return c < 0 ? Eigen::Vector3f(0, 0, 0) : (eta * (-v1) + (eta * cos_theta_i - c) * n);\n }\n\n float power_heuristic(int n_f, float p_f, int n_g, float p_g, float beta = 2)\n {\n float c_f = (float)n_f * p_f, c_g = (float)n_g * p_g;\n return pow(c_f, beta) / (pow(c_f, beta) + pow(c_g, beta));\n }\n}\n", "meta": {"hexsha": "084ead4fa3bda6b5f4084ee3f87ec345a745513a", "size": 1857, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "global_illumination/head/mathext.hpp", "max_stars_repo_name": "yuehaowang/learn_openGL", "max_stars_repo_head_hexsha": "1fdd0d4aea6196e272e8eea8459cfd371e98831a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-05T15:03:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-09T06:33:38.000Z", "max_issues_repo_path": "global_illumination/head/mathext.hpp", "max_issues_repo_name": "yuehaowang/lets_CG", "max_issues_repo_head_hexsha": "1fdd0d4aea6196e272e8eea8459cfd371e98831a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "global_illumination/head/mathext.hpp", "max_forks_repo_name": "yuehaowang/lets_CG", "max_forks_repo_head_hexsha": "1fdd0d4aea6196e272e8eea8459cfd371e98831a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9130434783, "max_line_length": 94, "alphanum_fraction": 0.577275175, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359876, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6962967975110155}} {"text": "#include \n#include \n\nint main(int argc, char **argv) \n{\n // exploit namespaces to shorten code\n using namespace boost::numeric::ublas;\n using std::cout; \n using std::endl;\n\n // declare three 3x3 matrices of complex elements\n matrix > m(3, 3), n(3, 3), o(3, 3);\n\n // iterate over 3x3 matrix entries\n // r : row index\n // c : column index\n for (unsigned r = 0; r < m.size1(); r++) {\n for (unsigned c = 0; c < m.size2(); c++) {\n // enumerated matrix entries\n m(r,c) = 3 * r + c;\n\n // complex numbers designating rows and cols\n n(r,c) = r + c * 1i;\n\n // elementwise square of n\n o(r,c) = std::pow(n(r,c), 2);\n }\n }\n\n // print to screen as demonstration\n cout << \"m:\" << endl;\n cout << m << endl;\n cout << endl << \"n:\" << endl;\n cout << n << endl;\n cout << endl << \"o:\" << endl;\n cout << n << endl;\n cout << endl << \"m + n:\" << endl;\n cout << m + n << endl;\n cout << endl << \"m * n:\" << endl;\n cout << prod(m, n) << endl;\n cout << endl << \"n * n - o:\" << endl;\n cout << prod(n, n) - o << endl;\n}\n", "meta": {"hexsha": "78469c1bd5dc0f62a0dccb918258cb30cc8819fc", "size": 1150, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/blas/boost_matrix.cc", "max_stars_repo_name": "chapman-cs510-2016f/cw-13-eric_lance", "max_stars_repo_head_hexsha": "98e61603efc7a04f6adde67b71a58c0a8f5d6b07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/blas/boost_matrix.cc", "max_issues_repo_name": "chapman-cs510-2016f/cw-13-eric_lance", "max_issues_repo_head_hexsha": "98e61603efc7a04f6adde67b71a58c0a8f5d6b07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/blas/boost_matrix.cc", "max_forks_repo_name": "chapman-cs510-2016f/cw-13-eric_lance", "max_forks_repo_head_hexsha": "98e61603efc7a04f6adde67b71a58c0a8f5d6b07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1363636364, "max_line_length": 64, "alphanum_fraction": 0.54, "num_tokens": 378, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197771, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6962967919633317}} {"text": "#pragma once\n#include \"coordinate_transform.hpp\"\n#include \"grad_shape.hpp\"\n#include \"integrate.hpp\"\n#include \n#include \n#include \n\n//----------------H1Begin----------------\n//! Computes the H^1 differences between\n//! u1 (considered as coefficients for Quadratic FEM) and u2grad.\ndouble computeH1Difference(const Eigen::MatrixXd &vertices,\n const Eigen::MatrixXi &dofs,\n const Eigen::VectorXd &u1,\n const std::function &u2grad) {\n\tconst int numberOfElements = dofs.rows();\n\n\tdouble error = 0;\n\tfor (int i = 0; i < numberOfElements; ++i) {\n\t\tauto &idSet = dofs.row(i);\n\n\t\tconst auto &a = vertices.row(idSet(0));\n\t\tconst auto &b = vertices.row(idSet(1));\n\t\tconst auto &c = vertices.row(idSet(2));\n\n\t\tauto coordinateTransform = makeCoordinateTransform(b - a, c - a);\n\t\tauto volumeFactor = std::abs(coordinateTransform.determinant());\n\t\tEigen::Matrix2d elementMap = coordinateTransform.inverse().transpose();\n\n\t\t// (write your solution here)\n\t\tauto f = [&](double x, double y) -> double {\n\t\t\tEigen::Vector2d transformedPoint = coordinateTransform * Eigen::Vector2d(x, y) + a.transpose();\n\n\t\t\tEigen::Vector2d approximate_grad = Eigen::Vector2d(0, 0);\n\t\t\tfor (int j = 0; j < 6; ++j) {\n\t\t\t\tapproximate_grad += u1(idSet(j)) * elementMap * gradientShapefun(j, x, y);\n\t\t\t}\n\t\t\tEigen::Vector2d diff = u2grad(transformedPoint.x(), transformedPoint.y()) - approximate_grad;\n\n\t\t\treturn diff.dot(diff) * volumeFactor;\n\t\t};\n\n\t\terror += integrate(f);\n\t}\n\n\treturn std::sqrt(error);\n}\n//----------------H1End----------------\n", "meta": {"hexsha": "2711c1e3cb796a17581cb8f8aa2b9ff9c6658c42", "size": 1691, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/H1_norm.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series3/2d-poissonqFEM/H1_norm.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series3/2d-poissonqFEM/H1_norm.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5102040816, "max_line_length": 98, "alphanum_fraction": 0.6221170905, "num_tokens": 430, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179068309441, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6962681211491213}} {"text": "// 2.62 Nov 10, 05 hyperparameter autosearch: observations weighted by inverse stddev\n// 3.02 Sep 01, 11 watch for denormal or infinite limits during autosearch\n// MAS Jan 02, 15 changed first step direction if hyperparameter is very small\n\n#define _USE_MATH_DEFINES\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n//#include \"tnt_array2d.h\"\n//#include \"tnt_array2d_utils.h\"\n//#include \"jama_lu.h\"\n//\n//#include \"logging.h\"\n\n#include \"HParSearch.h\"\n\n//observations weighted by inverse stddev\nQuadrCoefs QuadrLogFit( const map & y_by_x )\n{\n unsigned n = y_by_x.size();\n\n //prepare for case weights: inverse of stddev; beware of zero stddev\n double minstddev=numeric_limits::max();\n for (map::const_iterator itr=y_by_x.begin(); itr!=y_by_x.end(); itr++) {\n if (0 < itr->second.s && itr->second.s < minstddev) {\n \tminstddev = itr->second.s;\n }\n }\n const double zeroadjust = minstddev::max() ? 100.0/minstddev //non-zeroes present\n : 1.0; //all weights will be equal\n\n Eigen::MatrixXd X( n, 3 ); //nRows, nCols\n Eigen::MatrixXd XTW( 3, n ); //nRows, nCols\n Eigen::VectorXd Y( n );\n int i = 0;\n for (map::const_iterator itr=y_by_x.begin(); itr!=y_by_x.end();\n itr++, i++) {\n double weight = itr->second.s>0 ? 1/itr->second.s : zeroadjust;\n X(i,0) = XTW(0,i) = 1.0;\n X(i,1) = XTW(1,i) = log( itr->first );\n X(i,2) = XTW(2,i) = log( itr->first ) * log( itr->first );\n for (int j=0; j < 3; j++) { //for no weighting, just skip this\n XTW(j,i) *= weight;\n }\n Y(i) = itr->second.m;\n }\n\n Eigen::MatrixXd XTX = XTW * X;\n Eigen::VectorXd XTY = XTW * Y;\n Eigen::VectorXd b_hat = XTX.fullPivLu().solve(XTY);\n\n // TODO Check numerical accuracy and throw error\n\n QuadrCoefs ret;\n ret.c0 = b_hat(0);\n ret.c1 = b_hat(1);\n ret.c2 = b_hat(2);\n return ret;\n}\n\nStepValue UniModalSearch::step() //recommend: do/not next step, and the next x value\n{\n StepValue ret(true,0,0);\n switch( y_by_x.size() ) {\n case 0: ret.second = 1; break;\n case 1:\n if (y_by_x.begin()->first < m_first_cut)\n ret.second = y_by_x.begin()->first * m_stdstep;\n else\n ret.second = y_by_x.begin()->first / m_stdstep;\n //we divide here because step with more penalty is safer numerically\n break;\n case 2:\n if( y_by_x.begin()->second.m > y_by_x.rbegin()->second.m )\n ret.second = y_by_x.begin()->first / m_stdstep;\n else\n ret.second = y_by_x.rbegin()->first * m_stdstep;\n break;\n default: // 3 or more\n\t\tif( y_by_x.begin()->first==best->first ) { //max is at the left - move to the left\n ret.second = best->first / m_stdstep;\n\t\t\tif( !(best->first > numeric_limits::denorm_min()) ) { //inf or nan\n\t\t\t\tret.first = false;\n\t\t\t ret.expected = best->second.m;\n\t\t\t}\n\t\t}else if( y_by_x.rbegin()->first==best->first ) { //max is at the right - move to the right\n ret.second = best->first * m_stdstep;\n\t\t\tif( !(best->first < numeric_limits::infinity()) ) { //inf or nan\n\t\t\t\tret.first = false;\n\t\t\t ret.expected = best->second.m;\n\t\t\t}\n\t\t}else { //max is 'bracketed'\n QuadrCoefs coefs = QuadrLogFit( y_by_x );\n double log_argmax = - coefs.c1 / coefs.c2 / 2;\n double expected_max = - coefs.c1*coefs.c1 / coefs.c2 / 4 + coefs.c0;\n\n\t\t\tdouble maxval = best->second.m;\n if( 0==maxval ) ret.first=false;\n else if( (expected_max-maxval)/fabs(maxval) < m_stop_by_y ) ret.first=false;\n else if( fabs(log_argmax-log(best->first)) < m_stop_by_x ) ret.first=false;\n //double deriv = 2*coefs.c2*best->first + coefs.c1; cout<<\"\\nderiv \"< stop_by_y;\n\n ret.second = exp( log_argmax );\n ret.expected = expected_max;\n //map::const_iterator left = best; left--;\n //map::const_iterator right = best; right++;\n// std::cout\n// //Log(6)\n// <<\"\\nSearch step \"<first))) << endl;\n }\n }\n return ret;\n}\n\n//void UniModalSearch::dump(std::ostream& stream) const {\n// int i = 0;\n// for (map::const_iterator itr=y_by_x.begin(); itr!=y_by_x.end();\n// itr++, i++) {\n// \tstream << \"search[ \" << itr->first << \" ] = \" << itr->second << std::endl;\n// }\n//}\n\n\nstd::ostream& operator<< (std::ostream& stream, const UniModalSearch& search) {\n//\tsearch.dump(stream);\n\n for (map::const_iterator itr=search.y_by_x.begin(); itr!=search.y_by_x.end();\n itr++) {\n \tstream << \"search[ \" << itr->first << \" ] = \" << itr->second.m\n \t\t\t<< \"(\" << itr->second.s << \")\" << std::endl;\n }\n\n\treturn stream;\n}\n\n#ifdef UNITTEST_\n#include \nvoid main() {\n map y_by_x;\n //example llkl.d001145.b prepared in R\n y_by_x[ 2.000000e+04 ] = -408.199;\n y_by_x[ 2.002884e+03 ] = -328.581;\n y_by_x[ 2.000000e+02 ] = -281.788;\n y_by_x[ 2.002884e+01 ] = -229.966;\n y_by_x[ 2.000000e+00 ] = -184.908;\n y_by_x[ 2.002884e-01 ] = -150.792;\n y_by_x[ 2.000000e-02 ] = -132.081;\n y_by_x[ 2.002884e-03 ] = -127.708;\n y_by_x[ 2.000000e-04 ] = -146.397;\n y_by_x[ 2.002884e-05 ] = -183.208;\n QuadrCoefs c = QuadrLogFit( y_by_x );\n //R results:\n // (Intercept) logvar2 logvar\n // -171.030466 -1.186039 -12.662184\n cout<<\"c0=\"<::const_iterator itr=y_by_x.begin(); itr!=y_by_x.end(); itr++ )\n s.tried( itr->first, itr->second );\n //R result: 0.004805411\n cout<<\"step=\"<\n#include \n#define PRINT 1\n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n // User input\n arma::mat input;\n input << 1 << 3 << 2 << 4 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << endr\n << 5 << 7 << 6 << 8 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0 << endr;\n input = input.t();\n\n size_t size = 4; // input channels\n size_t upscale_factor = 2;\n size_t height = 2;\n size_t width = 2;\n\n // Forward()\n size_t batchSize = input.n_cols;\n size_t size_out = size / std::pow(upscale_factor, 2); // output channels\n size_t output_height = height * upscale_factor;\n size_t output_width = width * upscale_factor;\n\n arma::mat output;\n output.zeros(output_height * output_width * size_out, batchSize );\n\n for(size_t n = 0; n < batchSize; n++)\n {\n arma::mat inputImage = input.col(n);\n arma::mat outputImage = output.col(n);\n arma::cube inputTemp(const_cast(inputImage).memptr(), height, width, size, false, false);\n arma::cube outputTemp(const_cast(outputImage).memptr(), output_height, output_width, size_out, false, false);\n\n for (size_t c = 0; c < size_out ; c++)\n {\n for (size_t h = 0; h < output_height; h++)\n {\n for (size_t w = 0; w < output_width; w++)\n {\n size_t height_index = h / upscale_factor;\n size_t width_index = w / upscale_factor;\n size_t channel_index = (upscale_factor * (h % upscale_factor)) + (w % upscale_factor) + (c * std::pow(upscale_factor, 2));\n outputTemp(w, h, c) = inputTemp(width_index, height_index, channel_index);\n }\n }\n }\n\n output.col(n) = outputImage;\n\n if(PRINT)\n {\n cout << \"Image \" << n << \" calculations: \" << endl;\n cout << \"-----------------------------------\" << endl;\n cout << \"-----------------------------------\" << endl;\n cout << \"INPUT for Pixel Shuffle: \" << endl;\n cout << inputTemp << endl;\n cout << \"-----------------------------------\" << endl;\n cout << \"OUTPUT from Pixel Shuffle: \" << endl;\n cout << outputTemp << endl;\n cout << \"-----------------------------------\" << endl;\n }\n\n }\n\n // this is gy for Pixel Shuffle layer simulated as a tensor filled with an arbitrary sequence of values.\n arma::mat gy;\n gy << 1 << 5 << 9 << 13 << 2 << 6 << 10 << 14 << 3 << 7 << 11 << 15 << 4 << 8 << 12 << 16 << endr\n << 17 << 21 << 25 << 29 << 18 << 22 << 26 << 30 << 19 << 23 << 27 << 31 << 20 << 24 << 28 << 32 << endr;\n gy = gy.t();\n\n // Backward()\n arma::mat g;\n g.zeros(arma::size(input));\n\n for(size_t n = 0; n < batchSize; n++)\n {\n arma::mat gyImage = gy.col(n);\n arma::mat gImage = g.col(n);\n arma::cube gyTemp(const_cast(gyImage).memptr(), output_height, output_width, size_out, false, false);\n arma::cube gTemp(const_cast(gImage).memptr(), height, width, size, false, false);\n\n for (size_t c = 0; c < size_out ; c++)\n {\n for (size_t h = 0; h < output_height; h++)\n {\n for (size_t w = 0; w < output_width; w++)\n {\n size_t height_index = h / upscale_factor;\n size_t width_index = w / upscale_factor;\n size_t channel_index = (upscale_factor * (h % upscale_factor)) + (w % upscale_factor) + (c * std::pow(upscale_factor, 2));\n gTemp(width_index, height_index, channel_index) = gyTemp(w, h, c);\n }\n }\n }\n\n g.col(n) = gImage;\n\n if (PRINT)\n {\n cout << \"Image \" << n << \" calculations: \" << endl;\n cout << \"-----------------------------------\" << endl;\n cout << \"Hypothetical gy for Pixel Shuffle: \" << endl;\n cout << gyTemp << endl;\n cout << \"-----------------------------------\" << endl;\n cout << \"g for Pixel Shuffle: \" << endl;\n cout << gTemp << endl;\n cout << \"-----------------------------------\" << endl;\n }\n }\n\n return 0;\n}\n", "meta": {"hexsha": "db301d12803dde7b47a7c566e326d7667395a9e3", "size": 3920, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pixel_shuffle/test.cpp", "max_stars_repo_name": "iamshnoo/mlpack-testing", "max_stars_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pixel_shuffle/test.cpp", "max_issues_repo_name": "iamshnoo/mlpack-testing", "max_issues_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pixel_shuffle/test.cpp", "max_forks_repo_name": "iamshnoo/mlpack-testing", "max_forks_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7931034483, "max_line_length": 132, "alphanum_fraction": 0.5130102041, "num_tokens": 1160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8152324915965392, "lm_q1q2_score": 0.696137421194878}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate \nvoid print(T x)\n{\n std::ofstream output;\n output.open(\"output/output.txt\", std::ios_base::app); // std::ofstream::trunc);\n std::cout << x << std::endl;\n output.close();\n}\n\ndouble trapezRule(Eigen::VectorXd function(Eigen::VectorXd), double x_min, double x_max, double h)\n{\n double result = 100;\n double old_result = 0;\n int iterator = 0;\n\n do\n {\n h = h / 2;\n iterator++;\n Eigen::VectorXd deltaX = Eigen::VectorXd::LinSpaced((x_max - x_min) / h + 1, x_min, x_max);\n Eigen::VectorXd f = function(deltaX);\n Eigen::VectorXd result_vec = f * h;\n old_result = result;\n result = 0.5 * (result_vec(0) + result_vec(result_vec.size() - 1)) + result_vec(Eigen::seq(1, result_vec.size() - 2)).sum();\n\n } while ((abs(result - old_result) > 1e-6) & (iterator <= 30));\n print(\"Iterationen:\");\n print(iterator);\n return result;\n}\n\nEigen::VectorXd f1a(Eigen::VectorXd x)\n{\n return Eigen::exp(x.array()) / x.array();\n}\n\nEigen::VectorXd f1b(Eigen::VectorXd x)\n{\n return Eigen::exp(-x.array()) / Eigen::sqrt(x.array());\n}\n\nEigen::VectorXd f1c(Eigen::VectorXd x)\n{\n return Eigen::sin(x.array()) / x.array(); //sin(x) / x;\n}\n\ndouble f3a(double x)\n{\n return (x * x) - 2;\n}\n\ndouble bisection(double function(double), double a, double b, double c)\n{\n if ((a < b) & (b < c) & (function(b) < function(a)) & (function(b) < function(c)))\n {\n int iteration = 0;\n do\n {\n iteration++;\n\n if (abs(b - a) > abs(c - b))\n {\n double a_new = a;\n double b_new = (a + b) / 2;\n double c_new = b;\n if (function(b_new) < function(c_new))\n {\n a = a_new;\n b = b_new;\n c = c_new;\n }\n else\n {\n a = b_new;\n b = c_new;\n c = c;\n }\n }\n else\n {\n double a_new = b;\n double b_new = (b + c) / 2;\n double c_new = c;\n if (function(b_new) < function(a_new))\n {\n a = a_new;\n b = b_new;\n c = c_new;\n }\n else\n {\n a = a;\n b = a_new;\n c = b_new;\n }\n }\n } while ((abs(a - c) > 1e-9) & (iteration < 100));\n print(\"Iterationen: \");\n print(iteration);\n print(\"a - c = \");\n print(abs(a - c));\n }\n else\n {\n print(\"First requirement of bisection is not fullfiled.\");\n }\n return a;\n}\n\ndouble fDot(double function(double), double x0)\n{\n double deltaX = (x0 + 1) / 1000;\n // Eigen::VectorXd deltaX = Eigen::VectorXd::LinSpaced((x(x.size()-1) -x(0) ) / diff_x + 1, x(0), x(x.size()-1));\n return (function(x0 + deltaX) - function(x0 - deltaX)) / (2 * deltaX);\n}\n\ndouble fDDot(double function(double), double x0)\n{\n double deltaX = (x0 + 1) / 1000;\n // Eigen::VectorXd deltaX = Eigen::VectorXd::LinSpaced((x(x.size()-1) -x(0) ) / diff_x + 1, x(0), x(x.size()-1));\n return (function(x0 + deltaX) - 2 * function(x0) + function(x0 - deltaX)) / (deltaX * deltaX);\n}\n\ndouble newton(double function(double), double x0)\n{\n double x_new = x0;\n double x_old = 0;\n double iteration = 0;\n do\n {\n iteration++;\n x_old = x_new;\n x_new = x_old - fDot(function, x_old) / fDDot(function, x_old);\n } while ((abs(x_new - x_old) > 1e-9) & (iteration < 100));\n print(\"Iterationen: \");\n print(iteration);\n print(\"x_new - x_old = \");\n print(abs(x_new - x_old));\n return x_new;\n}\n\nint main()\n{\n for (int m = 3; m < 5; m++)\n {\n int j = pow(2, m);\n int N = 10;\n int l = N;\n std::complex complex_(0.0, 1.0);\n Eigen::VectorXcd F_j(j);\n Eigen::VectorXcd f_l(l);\n Eigen::MatrixXcd omega(j, l);\n\n for (int i = 0; i < l; i++)\n {\n f_l(i) = std::sqrt(1 + i);\n }\n\n for (int i = 0; i < l; i++)\n {\n for (int k = 0; k < j; k++)\n {\n omega(k, i) = std::exp(k * i / N * 2 * M_PI * complex_);\n }\n }\n\n F_j = omega * f_l;\n Eigen::VectorXd F_j_real = F_j.real();\n print(F_j_real);\n }\n\n // // Ex. 1\n // // a)\n\n // print(\"Exercise a): \");\n // double zero = 1e-6;\n // print(\"Zero is:\");\n // print(zero);\n // double i1 = trapezRule(f1a, -1, -zero, 0.5) + trapezRule(f1a, zero, 1, 0.5);\n // print(\"Result I1: \");\n // print(i1);\n\n // // b) see WolframAlpha for x_max\n // print(\"Exercise b): \");\n // double infty = 100.;\n // print(\"Infinity is:\");\n // print(infty);\n // double epsilon = 0.001;\n // print(\"Epsilon is:\");\n // print(epsilon);\n // zero = 1e-11;\n // print(\"Zero is:\");\n // print(zero);\n // double i2 = trapezRule(f1b, zero, epsilon, 0.0005) + trapezRule(f1b, epsilon, infty, 0.5);\n // print(\"Result I2: \");\n // print(i2);\n\n // // c)\n // print(\"Exercise c): \");\n // infty = 1000000.;\n // print(\"Infinity is:\");\n // print(infty);\n // zero = 1e-6;\n // print(\"Zero is:\");\n // print(zero);\n // double i3 = trapezRule(f1c, -infty, -zero, 0.5) + trapezRule(f1c, zero, infty, 0.5);\n // print(\"Result I3: \");\n // print(i3);\n\n // // Ex. 3\n // // a)\n // double a = -0.5;\n // double b = -0.1;\n // double c = 2.0;\n // double result_bisec = bisection(f3a, a, b, c);\n\n // // b)\n // double x0 = 1;\n // double result_newton = newton(f3a, x0);\n // print(\"Bisec - Newton:\");\n // print(abs(result_bisec - result_newton));\n\n return 0;\n}", "meta": {"hexsha": "ef98a1ab5d995b5dbaa6ca00fbcb648b8f11b9c3", "size": 6000, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Blatt5/src/main.cpp", "max_stars_repo_name": "lewis206/Computational_Physics", "max_stars_repo_head_hexsha": "06ad6126685eaf65f5834bfe70ebd91b33314395", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Blatt5/src/main.cpp", "max_issues_repo_name": "lewis206/Computational_Physics", "max_issues_repo_head_hexsha": "06ad6126685eaf65f5834bfe70ebd91b33314395", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Blatt5/src/main.cpp", "max_forks_repo_name": "lewis206/Computational_Physics", "max_forks_repo_head_hexsha": "06ad6126685eaf65f5834bfe70ebd91b33314395", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.974025974, "max_line_length": 132, "alphanum_fraction": 0.4735, "num_tokens": 1789, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802373309982, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6960191539764263}} {"text": "/*\n Solves the one-particle Schrodinger equation\n for a potential specified in function\n potential(). This example is for the harmonic oscillator in 3d\n*/\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace arma;\n\ndouble potential(double);\nvoid output(double, double, int, vec& );\n\n\n// Begin of main program \n\nint main(int argc, char* argv[])\n{\n int i, j, Dim, lOrbital;\n double RMin, RMax, Step, DiagConst, NondiagConst, OrbitalFactor; \n // With spherical coordinates RMin = 0 always\n RMin = 0.0;\n\n RMax = 8.0; lOrbital = 0; Dim =2000; \n mat Hamiltonian = zeros(Dim,Dim);\n // Integration step length\n Step = RMax/ Dim;\n DiagConst = 2.0 / (Step*Step);\n NondiagConst = -1.0 / (Step*Step);\n OrbitalFactor = lOrbital * (lOrbital + 1.0);\n \n // local memory for r and the potential w[r] \n vec r(Dim); vec w(Dim);\n for(i = 0; i < Dim; i++) {\n r(i) = RMin + (i+1) * Step;\n w(i) = potential(r(i)) + OrbitalFactor/(r(i) * r(i));\n }\n\n\n // Setting up tridiagonal matrix and brute diagonalization using Armadillo\n Hamiltonian(0,0) = DiagConst + w(0);\n Hamiltonian(0,1) = NondiagConst;\n for(i = 1; i < Dim-1; i++) {\n Hamiltonian(i,i-1) = NondiagConst;\n Hamiltonian(i,i) = DiagConst + w(i);\n Hamiltonian(i,i+1) = NondiagConst;\n }\n Hamiltonian(Dim-1,Dim-2) = NondiagConst;\n Hamiltonian(Dim-1,Dim-1) = DiagConst + w(Dim-1);\n // diagonalize and obtain eigenvalues\n \n\n\n\n\n vec Eigval(Dim);\n eig_sym(Eigval, Hamiltonian);\n output(RMin , RMax, Dim, Eigval);\n\n return 0;\n} // end of main function\n\n\n/*\n The function potential()\n calculates and return the value of the \n potential for a given argument x.\n The potential here is for the hydrogen atom\n*/ \n\ndouble potential(double x)\n{\n return x*x;\n\n} // End: function potential() \n\n\nvoid output(double RMin , double RMax, int Dim, vec& d)\n{\n int i;\n cout << \"RESULTS:\" << endl;\n cout << setiosflags(ios::showpoint | ios::uppercase);\n cout <<\"Rmin = \" << setw(15) << setprecision(8) << RMin << endl; \n cout <<\"Rmax = \" << setw(15) << setprecision(8) << RMax << endl; \n cout <<\"Number of steps = \" << setw(15) << Dim << endl; \n cout << \"Five lowest eigenvalues:\" << endl;\n for(i = 0; i < 5; i++) {\n cout << setw(15) << setprecision(8) << d[i] << endl;\n }\n} // end of function output \n\n// vec q1 = randu(100);\n", "meta": {"hexsha": "70278b9ce22a2a37eb0c23d5e5b6f73c5e52a523", "size": 2442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/Programs/CppQtCodesLectures/MatrixTest/lanczos.cpp", "max_stars_repo_name": "kimrojas/ComputationalPhysicsMSU", "max_stars_repo_head_hexsha": "a47cfc18b3ad6adb23045b3f49fab18c0333f556", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 220.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T09:18:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:09:16.000Z", "max_issues_repo_path": "doc/Programs/CppQtCodesLectures/MatrixTest/lanczos.cpp", "max_issues_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_issues_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-04T12:55:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-04T12:55:10.000Z", "max_forks_repo_path": "doc/Programs/CppQtCodesLectures/MatrixTest/lanczos.cpp", "max_forks_repo_name": "dnhdang94/ComputationalPhysicsMSU", "max_forks_repo_head_hexsha": "16990c74cf06eb5b933982137f0536d669567259", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 136.0, "max_forks_repo_forks_event_min_datetime": "2016-08-25T09:04:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:54:21.000Z", "avg_line_length": 25.175257732, "max_line_length": 76, "alphanum_fraction": 0.6216216216, "num_tokens": 798, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.921921841290738, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6959726147109772}} {"text": "#ifndef UTIL_H\n#define UTIL_H\n#include \n#include \n#include \n\ntemplate class Maybe {\n T value;\n bool has_value;\npublic:\n Maybe() : value(), has_value(false) {}\n Maybe(T val) : value(val), has_value(true) {}\n\n operator bool() {\n return has_value;\n }\n\n T val() {\n assert(has_value);\n return value;\n }\n};\n\nvoid log(const char* s) {\n printf(\"%s\\n\", s);\n fflush(stdout);\n}\n\ninline double sq(double val) {\n return val*val;\n}\n\nconst double EPS = 1e-6;\n\ninline bool almost_zero(double val) {\n return fabs(val) < EPS;\n}\n\nstruct Vector : boost::additive, boost::multiplicative2, boost::equality_comparable {\n double coord[3];\n Vector() : coord{0, 0, 0} {}\n Vector(double x, double y, double z) : coord{x, y, z} {}\n\n double length() const {\n return sqrt(sq(coord[0]) + sq(coord[1]) + sq(coord[2]));\n }\n\n bool operator==(const Vector& other) {\n for (int i = 0; i < 3; ++i) {\n if (fabs(coord[i] - other.coord[i]) > EPS) {\n return false;\n }\n }\n return true;\n }\n\n Vector& operator+=(const Vector& other) {\n for (int i = 0; i < 3; ++i) {\n coord[i] += other.coord[i];\n }\n return *this;\n }\n\n Vector& operator-=(const Vector& other) {\n for (int i = 0; i < 3; ++i) {\n coord[i] -= other.coord[i];\n }\n return *this;\n }\n\n Vector& operator*=(double factor) {\n for (int i = 0; i < 3; ++i) {\n coord[i] *= factor;\n }\n return *this;\n }\n\n Vector& operator/=(double factor) {\n for (int i = 0; i < 3; ++i) {\n coord[i] /= factor;\n }\n return *this;\n }\n\n Vector normalized() const {\n return *this / length();\n }\n\n friend Vector operator*(Vector a, Vector b) {\n return Vector(a.coord[0]*b.coord[0], a.coord[1]*b.coord[1], a.coord[2]*b.coord[2]);\n }\n\n friend double dot(Vector a, Vector b) {\n double ans = 0;\n for (int i = 0; i < 3; ++i) {\n ans += a.coord[i]*b.coord[i];\n }\n return ans;\n }\n\n friend Vector vec(Vector a, Vector b) {\n return Vector(a.coord[1]*b.coord[2]-a.coord[2]*b.coord[1], -(a.coord[0]*b.coord[2]-a.coord[2]*b.coord[0]), a.coord[0]*b.coord[1]-a.coord[1]*b.coord[0]);\n }\n\n friend double angle(Vector a, Vector b) {\n return dot(a, b) / a.length() / b.length();\n }\n};\n\ninline double sq(Vector v) {\n return dot(v, v);\n}\n\ntypedef Vector Point;\n\n#endif\n", "meta": {"hexsha": "7e73a91cd3acb7dac70c42bcde7270166d4c5e0c", "size": 2602, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "util.hpp", "max_stars_repo_name": "nzinov/ray-tracer", "max_stars_repo_head_hexsha": "f51919430a666ce0bc0d53b38449399cfc214c5e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util.hpp", "max_issues_repo_name": "nzinov/ray-tracer", "max_issues_repo_head_hexsha": "f51919430a666ce0bc0d53b38449399cfc214c5e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-04-21T11:53:07.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-21T11:53:55.000Z", "max_forks_repo_path": "util.hpp", "max_forks_repo_name": "nzinov/ray-tracer", "max_forks_repo_head_hexsha": "f51919430a666ce0bc0d53b38449399cfc214c5e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2393162393, "max_line_length": 160, "alphanum_fraction": 0.5196003075, "num_tokens": 736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774768002981829, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6959320723424813}} {"text": "/**\n * \\file SinusGeneratorFilter.cpp\n */\n\n#include \n\n#include \n\n#include \n\nnamespace ATK\n{\n template\n SinusGeneratorFilter::SinusGeneratorFilter()\n :Parent(0, 2)\n {\n }\n \n template\n void SinusGeneratorFilter::set_frequency(DataType_ frequency)\n {\n if(frequency <= 0)\n {\n throw std::out_of_range(\"Frequency must be strictly positive\");\n }\n this->frequency = frequency;\n this->frequ_cos = std::cos(2 * boost::math::constants::pi() * frequency / output_sampling_rate);\n this->frequ_sin = std::sin(2 * boost::math::constants::pi() * frequency / output_sampling_rate);\n }\n \n template\n DataType_ SinusGeneratorFilter::get_frequency() const\n {\n return frequency;\n }\n\n template\n void SinusGeneratorFilter::set_volume(DataType_ volume)\n {\n this->volume = volume;\n }\n \n template\n DataType_ SinusGeneratorFilter::get_volume() const\n {\n return volume;\n }\n \n template\n void SinusGeneratorFilter::set_offset(DataType_ offset)\n {\n this->offset = offset;\n }\n \n template\n DataType_ SinusGeneratorFilter::get_offset() const\n {\n return offset;\n }\n\n template\n void SinusGeneratorFilter::full_setup()\n {\n Parent::full_setup();\n cos = 1;\n sin = 0;\n }\n\n template\n void SinusGeneratorFilter::process_impl(gsl::index size) const\n {\n DataType* ATK_RESTRICT output_cos = outputs[0];\n DataType* ATK_RESTRICT output_sin = outputs[1];\n\n for(gsl::index i = 0; i < size; ++i)\n {\n auto new_cos = cos * frequ_cos - sin * frequ_sin;\n auto new_sin = cos * frequ_sin + sin * frequ_cos;\n auto norm = (new_cos * new_cos + new_sin * new_sin);\n\n cos = new_cos / norm;\n sin = new_sin / norm;\n\n output_cos[i] = volume * cos + offset;\n output_sin[i] = volume * sin + offset;\n }\n }\n \n#if ATK_ENABLE_INSTANTIATION\n template class SinusGeneratorFilter;\n#endif\n template class SinusGeneratorFilter;\n}\n", "meta": {"hexsha": "0810bc980d0d8917ec69ba998c585e614885aaf7", "size": 2288, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Tools/SinusGeneratorFilter.cpp", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/Tools/SinusGeneratorFilter.cpp", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/Tools/SinusGeneratorFilter.cpp", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 24.3404255319, "max_line_length": 111, "alphanum_fraction": 0.6896853147, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6957488344712136}} {"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Schüttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearloadvector.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace ElementMatrixComputation {\n\nnamespace {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector4d computeLoadVector(\n const Eigen::MatrixXd &vertices,\n std::function f) {\n // Number of nodes of the element: triangles = 3, rectangles = 4\n const int num_nodes = vertices.cols();\n // Vector for returning element vector\n Eigen::Vector4d elem_vec = Eigen::Vector4d::Zero();\n\n //====================\n // Your code goes here\n //====================\n \n Eigen::MatrixXd midpoints(2,num_nodes);\n \n double area;\n switch(num_nodes){\n case 3: {\n area = 0.5*(vertices(0,1)-vertices(0,0)*(vertices(1,2)-vertices(1,0))-\n vertices(0,2)-vertices(0,0)*(vertices(1,1)-vertices(1,0))\n );\n midpoints<<\n vertices(0,0)+vertices(0,1),\n vertices(0,1)+vertices(0,2),\n vertices(0,2)+vertices(0,0),\n vertices(1,0)+vertices(1,1),\n vertices(1,1)+vertices(1,2),\n vertices(1,2)+vertices(1,0);\n break;\n }\n case 4: {\n area = (vertices(0,1)-vertices(0,0))*(vertices(1,3)-vertices(1,0));\n midpoints<<\n vertices(0,0)+vertices(0,1),\n vertices(0,1)+vertices(0,2),\n vertices(0,2)+vertices(0,3),\n vertices(0,3)+vertices(0,0),\n vertices(1,0)+vertices(1,1),\n vertices(1,1)+vertices(1,2),\n vertices(1,2)+vertices(1,3),\n vertices(1,3)+vertices(1,0);\n break;\n }\n }\n midpoints *= 0.5;\n\n Eigen::VectorXd fvals = Eigen::VectorXd::Zero(num_nodes);\n for (int i=0;iGlobal(ref_el.NodeCoords());\n\n return computeLoadVector(vertices, f_);\n}\n\n} // namespace ElementMatrixComputation\n", "meta": {"hexsha": "a4264332c79f0a4b1fb937aa490e72c01aa40af9", "size": 2726, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_stars_repo_name": "hanyao8/NPDECODES", "max_stars_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_issues_repo_name": "hanyao8/NPDECODES", "max_issues_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_forks_repo_name": "hanyao8/NPDECODES", "max_forks_repo_head_hexsha": "b8e317665e80fd7a0025f71bb598e093b4b275ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.26, "max_line_length": 76, "alphanum_fraction": 0.6291269259, "num_tokens": 807, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267864276108, "lm_q2_score": 0.8006920044739461, "lm_q1q2_score": 0.6956626611653807}} {"text": "#include \n#include \n#include \n\n#include \"nntree/dataset.h\"\n\nnamespace nntree {\n namespace core {\n\n// TODO(equivalence1) memory leaks here, but we will rewrite it anyways\n void LeastSquares(Tensor& x, Tensor& y, Tensor& res) {\n namespace E = Eigen;\n\n assert(x.Ndim() == 2);\n assert(y.Ndim() == 2);\n\n E::Map>\n mxX_t(x.Data(),\n x.Ncols(),\n x.Nrows(),\n E::Stride(x.Strides()[0] / sizeof(double),\n x.Strides()[1] / sizeof(double)));\n auto mxX = mxX_t.transpose();\n E::Map>\n mxY_t(y.Data(),\n y.Ncols(),\n y.Nrows(),\n E::Stride(y.Strides()[0] / sizeof(double),\n y.Strides()[1] / sizeof(double)));\n auto mxY = mxY_t.transpose();\n\n auto solution = (mxX.transpose() * mxX).inverse() * mxX.transpose() * mxY;\n auto solution_t = solution.transpose();\n\n auto result = new double[solution_t.rows() * solution_t.cols()];\n assert(result != nullptr);\n E::Map resultMap(result, solution_t.rows(), solution_t.cols());\n resultMap = solution_t;\n\n std::vector shape({(uint64_t) solution.rows(),\n (uint64_t) solution.cols()});\n std::vector strides({(uint64_t) resultMap.outerStride() * sizeof(double),\n (uint64_t) resultMap.innerStride() * sizeof(double)});\n res.FromMem(resultMap.data(), shape, strides, true);\n }\n\n// TODO(equivalence1) reference is not const\n void LeastSquares(core::DataSet& ds, Tensor& res) {\n auto& x = ds.GetInput();\n auto& y = ds.GetOutput();\n assert(y.Nrows() == x.Nrows());\n LeastSquares(x, y, res);\n }\n\n }\n}\n", "meta": {"hexsha": "1d62aa12fbdeaa6838a63a59b99ad95a6b06d927", "size": 2279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/nn_trees/src/least_squares.cpp", "max_stars_repo_name": "equivalence1/ml_lib", "max_stars_repo_head_hexsha": "92d75ab73bc2d77ba8fa66022c803c06cad66f21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-15T09:40:43.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-15T09:40:43.000Z", "max_issues_repo_path": "cpp/nn_trees/src/least_squares.cpp", "max_issues_repo_name": "equivalence1/ml_lib", "max_issues_repo_head_hexsha": "92d75ab73bc2d77ba8fa66022c803c06cad66f21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/nn_trees/src/least_squares.cpp", "max_forks_repo_name": "equivalence1/ml_lib", "max_forks_repo_head_hexsha": "92d75ab73bc2d77ba8fa66022c803c06cad66f21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-29T10:17:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-03T20:33:31.000Z", "avg_line_length": 39.9824561404, "max_line_length": 97, "alphanum_fraction": 0.4927599824, "num_tokens": 502, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642806, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6956062905382703}} {"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef DLTV_PROBLEM_HPP_\n#define DLTV_PROBLEM_HPP_\n\n#include \n#include \n\ntemplate\nstruct DltvOcpDi\n{\n static_assert(_nPts > 1, \"Number of trajectory points must be > 1.\");\n\n // Must be defined\n constexpr static std::size_t nPts = _nPts;\n constexpr static std::size_t nx = 2;\n constexpr static std::size_t nu = 1;\n\n // Time step\n constexpr static double dt = 0.01;\n\n // Custom types\n using state_t = Eigen::Matrix;\n using input_t = Eigen::Matrix;\n using A_t = Eigen::Matrix;\n using B_t = Eigen::Matrix;\n using Q_t = Eigen::Matrix;\n using R_t = Eigen::Matrix;\n\n // Constants\n const A_t A = (A_t() << 1., 0.01, 0., 1.).finished();\n const B_t B = (B_t() << 5.0e-5, 0.01).finished();\n const state_t E = (state_t() << 0., 0.).finished();\n const Q_t Q = (Q_t() << 10., 0., 0., 0.1 ).finished();\n const R_t R = (R_t() << 0.01).finished();\n const Q_t QT = (Q_t() << 1., 0., 0., 1.).finished();\n\n void get_x0(Eigen::Ref x0) const\n {\n x0 << 1., 0.;\n }\n\n void get_T(std::size_t k, double & t) const\n {\n t = static_cast(k) * dt;\n }\n\n void get_state_lb(std::size_t, Eigen::Ref state_lb) const\n {\n state_lb <<\n -1000.,\n -0.5;\n }\n\n void get_state_ub(std::size_t, Eigen::Ref state_ub) const\n {\n state_ub <<\n 1000.,\n 0.5;\n }\n\n void get_input_lb(std::size_t, Eigen::Ref input_lb) const\n {\n input_lb << -1;\n }\n\n void get_input_ub(std::size_t, Eigen::Ref input_ub) const\n {\n input_ub << 1;\n }\n\n const A_t & get_A(std::size_t) const\n {\n return A;\n }\n\n const B_t & get_B(std::size_t) const\n {\n return B;\n }\n\n const state_t & get_E(std::size_t) const\n {\n return E;\n }\n\n const Q_t & get_Q(std::size_t) const\n {\n return Q;\n }\n\n const R_t & get_R(std::size_t) const\n {\n return R;\n }\n\n const Q_t & get_QT() const\n {\n return QT;\n }\n\n state_t get_xldot(double) const {return state_t::Zero();}\n};\n\n#endif // DLTV_PROBLEM_HPP_\n", "meta": {"hexsha": "4f3776b9965cf28d682e1966810c6d9ea7890fe1", "size": 2211, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "test/dltv_problem.hpp", "max_stars_repo_name": "yamaha-bps/cbr_control", "max_stars_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/dltv_problem.hpp", "max_issues_repo_name": "yamaha-bps/cbr_control", "max_issues_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/dltv_problem.hpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4722222222, "max_line_length": 71, "alphanum_fraction": 0.6110357304, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7799928900257127, "lm_q1q2_score": 0.6956062791736446}} {"text": "#include \"spectral_clustering.h\"\n#include \n#include \n#include \n\nusing namespace std;\n\n//these functions are defined later in this file\nvoid repair_clusters(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, Eigen::MatrixXi& sF, Eigen::VectorXi& sFC);\nstd::vector > spectral_clustering(const Eigen::MatrixXd& A, int K);\nstd::vector > kmeans_cluster(const Eigen::MatrixXd& data, int K);\n\n/*\nSpectral clustering of the faces\n- use similarity matrix and face connectivity to determine the clusters\n\nInput:\n\nK: number of clusters\nV, F: the mesh\nsimilarity: a |F|*|F| symmetric matrix\n\nOutput:\n\nsF: A face index matrix of size |F|*3. Faces in the same cluster are in consecutive rows of sF\nsFC: A K*1 vector. Each element indicates the size of each cluster stored in sF\n*/\n\nvoid spectral_clustering\n(int K, const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, const Eigen::MatrixXd& similarity,\n Eigen::MatrixXi& sF, Eigen::VectorXi& sFC)\n{\n\n\t//Requirements\n\t// - similar faces are clustered together based on the similarity matrix\n\t// - faces in a cluster must be contiguous and form a single connected component\n\n\n //dummy segmentation, replace the following code\n int cluster_size=F.rows()/K;\n sFC=Eigen::VectorXi::Constant(K,cluster_size);\n sFC[K-1]=F.rows()-cluster_size*(K-1);\n sF=F;\n\n //YOUR CODE HERE\n\n //make sure that faces in the same cluster are connected\n repair_clusters(V,F,sF,sFC);\n}\n\n\n/// repair clusters so that each cluster contains a compact connected component\nvoid repair_clusters\n(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, Eigen::MatrixXi& sF, Eigen::VectorXi& sFC)\n{\n //YOUR CODE HERE\n}\n\n/**\n* Spectral clustering into K clusters\n*\n* @param A \t\tthe affinity matrix\n* @param K the number of clusters\n*\n* @return\t\t ordered set of data row indices for each cluster\n*/\n\nstd::vector > spectral_clustering(const Eigen::MatrixXd& A, int K)\n{\n\t// compute normalized laplacian\n // using Ng, Jordan and Weiss, \"On Spectral Clustering: Analysis and an Algorithm\", NIPS 2002\n Eigen::VectorXd S=A.colwise().sum().array().pow(-0.5);\n Eigen::MatrixXd D=S.asDiagonal();\n Eigen::MatrixXd I=Eigen::MatrixXd::Identity(A.rows(),A.cols());\n Eigen::MatrixXd L = I - (D* A *D);\n\n //solve, eigenvalues are sorted in increasing order\n cout<<\"- Solving Eigen Decomposition\"< es(L);\n\tEigen::VectorXd E = es.eigenvalues();\n\tEigen::MatrixXd V = es.eigenvectors();\n\n // keep only the k-principal components (Eigen's eigenvectors are colwise)\n V = V.block(0,1,V.rows(),K);\n\n //normalize V\n Eigen::VectorXd norm = V.array().pow(2).matrix().rowwise().sum();\n for (unsigned int k = 0; k < K; ++k) V.col(k) = V.col(k).array() / norm.array();\n\n return kmeans_cluster(V, K);\n}\n\n/**\n * kmeans clustering\n * based on kmeans matlab script by Ian T Nabney (1996-2001)\n *\n * @param data \taffinity matrix\n * @oaram ncentres\tnumber of clusters\n * @return\t\tordered set of data row indices for each cluster\n * \t\t\t \t(order is based on distance to cluster centre)\n */\nstd::vector >\nkmeans_cluster(const Eigen::MatrixXd& data, int ncentres)\n{\n std::srand(std::time(nullptr));\n //std::srand(0); //use this to debug so you get the same results\n\n\tint ndims = data.cols();\n\tint ndata = data.rows();\n\n\tEigen::MatrixXd centres = Eigen::MatrixXd::Zero(ncentres, ndims);\n\tEigen::MatrixXd old_centres;\n\n\tstd::vector rands;\n\tfor (int i=0; i < ncentres; i++)\n {\n\t\t//randomly initialise centers\n\t\tbool flag;\n\t\tdo {\n\t\t\tflag = false;\n\t\t\tint randIndex = std::rand()%ndata;\n\t\t\t//make sure same row not chosen twice\n\t\t\tfor (unsigned int j=0; j < rands.size(); ++j) {\n\t\t\t\tif (randIndex == rands[j]) {\n\t\t\t\t\tflag = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!flag) {\n\t\t\t\tcentres.row(i) = data.row(randIndex);\n\t\t\t\trands.push_back(randIndex);\n\t\t\t}\n\t\t} while (flag);\n\t}\n\tEigen::MatrixXd id = Eigen::MatrixXd::Identity(ncentres, ncentres);\n\t//maps vectors to centres.\n\tEigen::MatrixXd post(ndata, ncentres);\n\n\tEigen::VectorXd minvals(ndata);\n\n\tdouble old_e = 0;\n\tint niters = 100;\n\tfor (int n=0; n < niters; n++) {\n\t\t//Save old centres to check for termination\n\t\told_centres = centres;\n\n\t\t// Calculate posteriors based on existing centres\n\t\tEigen::MatrixXd d2(ndata, ncentres);\n\t\tfor (int j = 0; j < ncentres; j++) {\n\t\t\tfor (int k=0; k < ndata; k++) {\n\t\t\t\td2(k,j) = (data.row(k)-centres.row(j)).squaredNorm();\n\t\t\t}\n\t\t}\n\n\t\tint r,c;\n\t\t// Assign each point to nearest centre\n\t\tfor (int k=0; k < ndata; k++) {\n\t\t\t//get centre index (c)\n\t\t\tminvals[k] = d2.row(k).minCoeff(&r, &c);\n\t\t\t//set centre\n\t\t\tpost.row(k) = id.row(c);\n\t\t}\n\n\t\tEigen::VectorXd num_points = post.colwise().sum();\n\t\t// Adjust the centres based on new posteriors\n\t\tfor (int j = 0; j < ncentres; j++) {\n\t\t\tif (num_points[j] > 0) {\n\t\t\t\tEigen::MatrixXd s = Eigen::MatrixXd::Zero(1,ndims);\n\t\t\t\tfor (int k=0; k 1) {\n\t\t\t//Test for termination\n\t\t\tif (cdiff < 0.0000000001 && ediff < 0.0000000001) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\told_e = e;\n\t}\n\n\t//------- finished kmeans ---------\n\n\t//find the item closest to the centre for each cluster\n\tstd::vector > clustered_items;\n\tfor (int j=0; j < ncentres; j++) {\n\t\t//put data into map (multimap because minvals[k] could be the same for multiple units)\n\t\tstd::multimap cluster;\n\t\tfor (int k=0; k < ndata; k++) {\n\t\t\tif (post(k,j) == 1) {\n\t\t\t\tcluster.insert(std::make_pair(minvals[k], k));\n\t\t\t}\n\t\t}\n\t\t//extract data from map\n\t\tstd::vector units;\n\t\t//the map will be sorted based on the key (the minval) so just loop through it\n\t\t//to get set of data indices sorted on the minval\n\t\tfor (std::multimap::iterator it = cluster.begin(); it != cluster.end(); it++) {\n\t\t\tunits.push_back(it->second);\n\t\t}\n\n\t\tclustered_items.push_back(units);\n\t}\n\t//return the ordered set of item indices for each cluster centre\n\treturn clustered_items;\n}\n", "meta": {"hexsha": "4098e4adef62f62c3e1381a6d4faec1de28b024f", "size": 6343, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spectral_clustering.cpp", "max_stars_repo_name": "jmlien/geometry-processing-mesh-segmentation", "max_stars_repo_head_hexsha": "c2ddf6e7ac0e9a531d64ee083993c8891cd1f690", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-03-25T22:47:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T06:07:50.000Z", "max_issues_repo_path": "src/spectral_clustering.cpp", "max_issues_repo_name": "jmlien/geometry-processing-mesh-segmentation", "max_issues_repo_head_hexsha": "c2ddf6e7ac0e9a531d64ee083993c8891cd1f690", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spectral_clustering.cpp", "max_forks_repo_name": "jmlien/geometry-processing-mesh-segmentation", "max_forks_repo_head_hexsha": "c2ddf6e7ac0e9a531d64ee083993c8891cd1f690", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-01T13:33:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-01T13:33:46.000Z", "avg_line_length": 29.0963302752, "max_line_length": 116, "alphanum_fraction": 0.6635661359, "num_tokens": 1878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887588023318196, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6955981584132603}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nint verbose;\nstd::vector Hleft;\n//#include \n\n/*\n\n Total Subgraph Centrality.\n\n For a graph G with adjacency matrix A, TSC(G) = exp(A)*b, where 1 is\n the ones vector.\n\n\n We're going to implement this with an Arnoldi solver, following Saad\n (1992).\n\n The algorithm works like this:\n Choose a maximum iteration m. Then make matrices V and H:\n b = ones(A.nodecount)\n V[0] = b/||b||\n for j in 0..m:\n w = A*V[j]\n for i in 0..j:\n H[i,j] = (w,V[i])\n\t w = w - H[i,j] * V[i]\n H[j+1,j] = ||w||\n V[j+1] =w/||w||\n\n Then TSC = exp(A)*b ~= (V * exp(H) / ||b||)[:,0]. Stop when\n successive approximations converge, or we run out of steps. \n\n We still have that matrix exponential, but it's small and dense, and\n there's an implementation in Eigen. \n \n\n \n*/\n\nclass node {\npublic: \nstd::vector V;\ndouble w;\n double TSC;\n double prev;\n node(): w(0.0),TSC(0.0),prev(0.0){};\n void load(graphlab::iarchive& infile) {\n infile>>V>>w>>TSC>>prev;\n }\n void save(graphlab::oarchive& outfile) const {\n outfile<>weight; \n }\n \n \n};\n\n\ntypedef node vertex_data_type;\ntypedef edge edge_data_type;\ntypedef graphlab::distributed_graph graph_type; \ntypedef graphlab::warp::warp_engine engine_type; \n\n\n// This is just a little class to be used to find the maximum change in TSC values. \nclass max_finder{\npublic:\n double data;\n max_finder& operator+=(const max_finder& other){\n if (this->data data = other.data;\n }\n return *this;\n }\n \n max_finder(): data(std::numeric_limits::max()) {};\n max_finder(double x): data(x) {};\n void load(graphlab::iarchive& infile) {\n infile>>data;\n }\n void save(graphlab::oarchive& outfile) const {\n outfile<graph.num_vertices()) {\n m = graph.num_vertices();\n }\n engine_type engine(dc,graph,clopts);\n\n engine.signal_all();\n Eigen::MatrixXd H = Eigen::MatrixXd::Zero(m+1,m+1);\n Hleft.resize(m);\n for(int i=0;i=0) {\n if (column>graph.num_vertices()){\n column = 0;\n }\n graph.transform_vertices(boost::bind(initialize_column,_1,column,m));\n beta = 1.0;\n } else {\n graph.transform_vertices(boost::bind(initialize_TSC,_1,m));\n beta = sqrt(m);\n }\n\n\n // The first column of V is just w\n graph.transform_vertices(w_to_v);\n\n\n for(int j=0;j(boost::bind(w_dot_V,_1,i));\n graph.transform_vertices(boost::bind(w_minus_hdot,_1,i,H(i,j)));\n }\n H(j+1,j)= sqrt(graph.map_reduce_vertices(sum_w));\n // If we're in this case, it means we have a spanning set and we shouldn't\n // prep for the next iteration. Otherwise, make the data we'll need next time.\n if ( ( !std::isnan(H(j+1,j))) && (H(j+1,j) > 0) ) {\n graph.transform_vertices(boost::bind(scale_w, _1, H(j+1,j)));\n graph.transform_vertices(w_to_v); \n }\n\n if (j>0) {\n // Have we converged? \n Eigen::MatrixXd EH(H);\n EH = EH.exp();\n Hleft.resize(j+1);\n \n for(int i=0;i<=j;i++) { Hleft[i] = EH(i,0) * beta;}\n graph.transform_vertices(accumulate_hleft);\n if (j>1) {\n \tmax_finder largest_error= graph.map_reduce_vertices(max_error);\n\tdouble all_error = graph.map_reduce_vertices(total_error);\n\tif (verbose){\n\t std::cerr<<\"ARNOLDI STEP FINISHED \"<\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions\n are met:\n 1. Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n 2. Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\n THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS \"AS IS\" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n SUCH DAMAGE.\n\n*******************************************************************************/\n\n#ifndef TOPOLOGY_HPP_79A57FE0_9EFD_11E2_9E96_0800200C9A66_\n#define TOPOLOGY_HPP_79A57FE0_9EFD_11E2_9E96_0800200C9A66_\n\n#include \n#include \n#include \n#include \n\n#include \"bo/core/vector.hpp\"\n\nnamespace bo {\nnamespace math {\n\n// Basic N-dimensional hyperrectangle (N-orthotope) geometry.\ntemplate \nclass OrthotopeTopology\n{\nprivate:\n BOOST_STATIC_ASSERT(N > 0);\n\npublic:\n typedef Vector Point;\n typedef std::pair Edge;\n typedef std::vector Edges;\n\n // Returns all the edges of a unit N-orthotope.\n static Edges edges()\n {\n // Initialize the source of the edge traverse.\n PointSet in_vertices;\n in_vertices.insert(Point(0));\n\n // Traverse the edges.\n Edges e;\n traverse_edges(in_vertices, e);\n\n return e;\n }\n\n // Returns the number of edges in a N-orthotope.\n static std::size_t edge_count()\n {\n return (1 << (N - 1)) * N;\n }\n\n // Returns the number of vertices in a N-orthotope.\n static std::size_t vertex_count()\n {\n return 1 << N;\n }\n\n // Returns the number of facets ((N-1)-dimensional faces) in a N-othotope.\n static std::size_t facet_count()\n {\n return 2 * N;\n }\n\nprivate:\n\n typedef std::set PointSet;\n\n // Recursively traverses the edges of a N-orthotope starting from the given set\n // of vertices in ascending order and pushes the edges into the given container.\n static void traverse_edges(const PointSet &in_vertices, Edges &edges)\n {\n if (in_vertices.size() == 1 && *in_vertices.begin() == Point(1))\n return;\n\n PointSet out_vertices;\n\n for (typename PointSet::const_iterator it = in_vertices.begin(); it != in_vertices.end(); ++it)\n {\n Point edge_begin = *it;\n\n // Find all adjacent vertices for the current one.\n for (std::size_t k = 0; k < N; ++k)\n {\n if (edge_begin[k] == 1)\n continue;\n\n // An adjacent vertex differs only in one dimension.\n Point edge_end = edge_begin;\n edge_end[k] = 1;\n\n // Insert the edge into the collection.\n edges.push_back(Edge(edge_begin, edge_end));\n\n // Save the end vertex.\n out_vertices.insert(edge_end);\n }\n }\n\n traverse_edges(out_vertices, edges);\n }\n\n};\n\n} // namespace math\n} // namespace bo\n\n#endif // TOPOLOGY_HPP_79A57FE0_9EFD_11E2_9E96_0800200C9A66_\n", "meta": {"hexsha": "ce773fb05db98f034b218933260d96811775d110", "size": 4166, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Bo/math/topology.hpp", "max_stars_repo_name": "rukletsov/bo", "max_stars_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-09-14T03:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-16T10:53:32.000Z", "max_issues_repo_path": "Bo/math/topology.hpp", "max_issues_repo_name": "rukletsov/bo", "max_issues_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bo/math/topology.hpp", "max_forks_repo_name": "rukletsov/bo", "max_forks_repo_head_hexsha": "bfece9e8f910b0c8f522733854405bf0a801b0e8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0895522388, "max_line_length": 103, "alphanum_fraction": 0.6437830053, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894604912848, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6955197234204524}} {"text": "// Copyright 2020, Madhur Chauhan\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// This is an example to calculate Reciprocal Fibonacci Constant (A079586 in the OEIS)\n// compile with flags: -std=c++11 -lmpfr\n\n//[fibonacci_eg\n\n#include \n#include \n#include \n#include \n\nint main() {\n using Real = boost::multiprecision::mpfr_float_1000;\n boost::math::fibonacci_generator gen;\n gen.set(1); // start producing values from 1st fibonacci number\n Real ans = 0;\n const int ITR = 1000;\n for (int i = 0; i < ITR; ++i) {\n ans += 1.0 / gen();\n }\n std::cout << std::setprecision(1000) << \"Reciprocal fibonacci constant after \"\n << ITR << \" iterations is: \" << ans << std::endl;\n}\n\n//]\n", "meta": {"hexsha": "7c6405c52b4ba052d8b675feaef14e8b8886ebfa", "size": 962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/reciprocal_fibonacci_constant.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "example/reciprocal_fibonacci_constant.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "example/reciprocal_fibonacci_constant.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 30.0625, "max_line_length": 86, "alphanum_fraction": 0.6715176715, "num_tokens": 272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6955197166234861}} {"text": "#include \"LogisticRegression.h\"\n#include \"TrainingType.h\"\n#include \n#include \n#include \n#include \n\nusing namespace arma;\n\nLogisticRegression::LogisticRegression(mat &x, vec &y, double regPara)\n : x{x}, y{y}, regPara{regPara}, trained{false} {\n assert(x.n_rows == y.n_rows);\n\n // Create bias column and append at the end of x\n mat bias = ones(this->ExampleNumber(), 1);\n this->x.insert_cols(0, bias);\n}\n\nLogisticRegression::~LogisticRegression() {}\n\nvoid LogisticRegression::AddData(mat &extraX, vec &extraY) {\n assert(extraX.n_rows == extraY.n_rows);\n // Add 1 because x has a bias column\n assert((extraX.n_cols + 1) == this->x.n_cols);\n\n this->trained = false;\n // Add Bias column to latest added input\n mat bias = ones(extraX.n_rows, 1);\n mat inputX = extraX;\n inputX.insert_cols(0, bias);\n this->x.insert_rows(this->x.n_rows, inputX);\n this->y.insert_rows(this->y.n_rows, extraY);\n}\n\nvoid LogisticRegression::Train(TrainingType Type, double alpha,\n unsigned int iters) {\n /*if (Type == normalEquation) {\n this->NormalEquation();\n } else*/\n if (Type == gradientDescent) {\n this->GradientDescent(alpha, iters);\n } else {\n std::cerr << \"Invalid training type\" << std::endl;\n }\n}\n\nuword LogisticRegression::ExampleNumber() { return this->x.n_rows; }\n\ndouble LogisticRegression::Probablity(vec &x) {\n if (!this->trained) {\n std::cerr << \"This model hasn't been trained\" << std::endl;\n return 0.0;\n }\n vec bias = vec(\"1\");\n vec input = x;\n input.insert_rows(0, bias);\n double prob = (input.t() * this->theta).eval()(0, 0);\n return prob;\n}\n\ndouble LogisticRegression::Predict(vec &x) {\n double prob = this->Probablity(x);\n if (prob >= probabilityThreshold) {\n return 1;\n } else {\n return 0;\n }\n}\n\narma::mat LogisticRegression::SigmoidFunction(arma::mat inputX) {\n //-- 1 --//\n //-- ---------- --//\n //-- 1 + e^(-inpuX) --//\n return 1 / (1 + exp(-inputX));\n}\n\ndouble LogisticRegression::SelfCost() { return this->Cost(this->x); }\n\ndouble LogisticRegression::Cost(mat &inputX) {\n this->InitializeTheta();\n //-- h = g(X Theta) --//\n //--J(Theta) = 1/m * (-y^T log(h) - (1-y)^T log(1-h)) +lambda/2m theta^2--//\n assert(inputX.n_cols == this->theta.n_rows);\n vec h = this->SigmoidFunction(inputX * this->theta);\n vec ve = (-this->y.t() * log(h)) - ((1 - y).t() * log(1 - h));\n vec thetaWithoutFirst = this->theta;\n thetaWithoutFirst[0] = 0;\n\n return (1 / (float)this->ExampleNumber() * ve +\n this->regPara / (double)this->ExampleNumber() * 2 *\n thetaWithoutFirst.t() * thetaWithoutFirst)\n .eval()(0, 0);\n}\n\nvec LogisticRegression::CostDerivative() {\n vec h = this->SigmoidFunction(this->x * this->theta);\n vec deriv = this->x.t() * (h - this->y);\n vec thetaWithoutFirst = this->theta;\n thetaWithoutFirst[0] = 0;\n return 1 / (double)this->ExampleNumber() * deriv +\n this->regPara / (double)this->ExampleNumber() * thetaWithoutFirst;\n}\n\nvoid LogisticRegression::GradientDescent(double alpha, unsigned int iters) {\n this->InitializeTheta();\n for (unsigned int i = 0; i < iters; i++) {\n this->theta = this->theta - (alpha * this->CostDerivative());\n }\n\n this->trained = true;\n}\n\nvoid LogisticRegression::InitializeTheta() {\n if (this->trained != true || this->theta.n_rows != this->x.n_cols) {\n // Initialize Theta\n this->theta = zeros(this->x.n_cols);\n }\n}\n", "meta": {"hexsha": "26feb79aa6e3ac1087073e3444ebfc5a0308b92f", "size": 3498, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/LinearModel/LogisticRegression.cc", "max_stars_repo_name": "Gh0u1L5/Cetus", "max_stars_repo_head_hexsha": "979a13db4f6837e845fd5f540f7a710d0256dd9a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LinearModel/LogisticRegression.cc", "max_issues_repo_name": "Gh0u1L5/Cetus", "max_issues_repo_head_hexsha": "979a13db4f6837e845fd5f540f7a710d0256dd9a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinearModel/LogisticRegression.cc", "max_forks_repo_name": "Gh0u1L5/Cetus", "max_forks_repo_head_hexsha": "979a13db4f6837e845fd5f540f7a710d0256dd9a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3949579832, "max_line_length": 78, "alphanum_fraction": 0.6255002859, "num_tokens": 1016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314858927011, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6954940098258949}} {"text": "#include \n#include \n#include \n\n#include \n\n#include \"FEM/FEM1DApp.hpp\"\n#include \"imgui/implot.h\"\n#include \"Visualization/Visualizer.h\"\n\n#include \n\nusing Linear = PolynomialFEMApp<1>;\nusing Quadratic = PolynomialFEMApp<2>;\n\nclass FEM1DVisualizer :public Visualizer\n{\nprotected:\n\n\tvoid evaluate()\n\t{\n\t\tint segement_ = segemnt;\n\n\t\tif (segement_ % 2 != 0)\n\t\t{\n\t\t\tsegement_ += 1;\n\t\t}\n\n\t\t//Homework 2\n\t\t//auto rhs = [](Float x) {return -4 - x + Power(x, 2) - Power(x, 3) + Power(x, 4) + Cos(x) - 2 * x * Cos(x) - 2 * Sin(x); };\n\t\t//auto a = [](Float x) {return sin(x) + 2; };\n\t\t//auto c = [](Float x) {return x * x + 1; };\n\t\tauto rhs = [](Float x) {return 2 * cos(1 - x) * cos(x) + 2 * sin(1 - x) * sin(x); };\n\t\tauto d = [this](Float x) {return 1; };\n\t\tauto b = [](Float x) {return 0;\t};\n\t\tauto c = [](Float x) {return 0; };\n\n\t\tInterval interval(0.0, 1.0);\n\n\t\tinterval.SetPartitionCount(segement_);\n\n\t\tStaticFEM1DMG mg_linear(rhs, d, b, c, interval);\n\t\tLinear cg_linear(rhs, d, b, c, interval);\n\t\tmg_linear.evaluate();\n\t\tcg_linear.evaluate();\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\tcg_val[i] = cg_linear.Value(1.0 / (Length - 1) * i);\n\t\t\tmg_val[i] = mg_linear.Value(1.0 / (Length - 1) * i);\n\n\t\t\tcg_diff[i] = cg_val[i] - precise_val[i];\n\t\t\tmg_diff[i] = mg_val[i] - precise_val[i];\n\t\t}\n\t}\n\n\tvoid Control_UI();\n\tvoid draw(bool* p_open) override;\n\n\tstd::vector points;\n\tbool updated = true;\n\tint segemnt = 16;\n\tfloat epsilon = 1E-7;\n\n\tvoid error(std::vector& ref, std::vector& eval, Float& L_1, Float& L_2, Float& L_inf)\n\t{\n\t\tassert(ref.size() == eval.size());\n\n\t\tstd::vector minus(ref.size());\n\n\t\tfor (int i = 0; i < ref.size(); ++i)\n\t\t{\n\t\t\tminus[i] = abs(ref[i] - eval[i]);\n\t\t}\n\n\t\tL_inf = *std::max_element(minus.begin(), minus.end(), [](Float a, Float b) {return a < b; });\n\t\tL_2 = sqrt(std::accumulate(minus.begin(), minus.end(), static_cast(0), [](Float r, Float a) {return r + a * a; }) / Float(ref.size()));\n\t\tL_1 = std::accumulate(minus.begin(), minus.end(), static_cast(0), [](Float r, Float a) {return r + a; }) / Float(ref.size());\n\t}\n\npublic:\n\tvoid CalcAccurateRst()\n\t{\n\t\tFloat h = 1.0 / (Length - 1);\n\t\tfor (int i = 0; i < Length; ++i)\n\t\t{\n\t\t\txs[i] = i * h;\n\n\t\t\tauto accurate_func = [this](Float x) {return sin(x) * sin(1 - x); };\n\n\t\t\tprecise_val[i] = accurate_func(xs[i]);\n\t\t}\n\t}\n\n\tFEM1DVisualizer() {\n\t\tCalcAccurateRst();\n\t\tsegemnt = 16;\n\t\tFloat L1, L2, L_inf;\n\t\tdo\n\t\t{\n\t\t\t//std::cout << \"Segmentations: \" << segemnt << std::endl;\n\t\t\tevaluate();\n\n\t\t\terror(precise_val, mg_val, L1, L2, L_inf);\n\n\t\t\tusing std::cout;\n\t\t\tusing std::endl;\n\n\t\t\t//if (segemnt == 16)\n\t\t\t//{\n\t\t\t//\tcout << segemnt << '&' << L1 << '&' << '-' << '&' << L2 << '&' << '-' << '&' << L_inf << '&' << '-' << \"\\\\\\\\\" << endl;\n\t\t\t//}\n\t\t\t//else\n\t\t\t//\tcout << segemnt << '&' << L1 << '&' <<- log2(L1 / linear_L1.back()) << '&' << L2 << '&' << -log2(L2 / mg_L2.back()) << '&' << L_inf << '&' << -log2(L_inf / mg_Linf.back()) << \"\\\\\\\\\" << endl;\n\n\t\t\tpointcount.push_back(segemnt);\n\t\t\tmg_L1.push_back(L1);\n\t\t\tmg_L2.push_back(L2);\n\t\t\tmg_Linf.push_back(L_inf);\n\t\t\terror(precise_val, cg_val, L1, L2, L_inf);\n\n\t\t\t//if (segemnt == 16)\n\t\t\t//{\n\t\t\t//\tcout << segemnt << '&' << L1 << '&' << '-' << '&' << L2 << '&' << '-' << '&' << L_inf << '&' << '-' << \"\\\\\\\\\" << endl;\n\t\t\t//}\n\t\t\t//else\n\t\t\t//\tcout << segemnt << '&' << L1 << '&' << -log2(L1 / cg_L1.back()) << '&' << L2 << '&' << -log2(L2 / cg_L2.back()) << '&' << L_inf << '&' << -log2(L_inf / cg_Linf.back()) << \"\\\\\\\\\" << endl;\n\n\t\t\tcg_L1.push_back(L1);\n\t\t\tcg_L2.push_back(L2);\n\t\t\tcg_Linf.push_back(L_inf);\n\n\t\t\tsegemnt *= 2;\n\t\t} while (segemnt != 8192);\n\t\tsegemnt = 16;\n\n\t\tevaluate();\n\t}\n\tconst size_t Length = 10001;\n\n\tstd::vector xs = std::vector(Length);\n\tstd::vector precise_val = std::vector(Length);\n\tstd::vector cg_val = std::vector(Length);\n\tstd::vector mg_val = std::vector(Length);\n\tstd::vector cg_diff = std::vector(Length);\n\tstd::vector mg_diff = std::vector(Length);\n\n\tstd::vector pointcount;\n\tstd::vector mg_L1;\n\tstd::vector mg_L2;\n\tstd::vector mg_Linf;\n\n\tstd::vector cg_L1;\n\tstd::vector cg_L2;\n\tstd::vector cg_Linf;\n};\n\nstatic inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x - rhs.x, lhs.y - rhs.y); }\n\nvoid FEM1DVisualizer::Control_UI()\n{\n\tif (ImGui::SliderInt(\"Number of segments\", &segemnt, 3, 200))\n\t{\n\t\tsegemnt = segemnt < 2 ? 2 : segemnt;\n\t\tevaluate();\n\t}\n\tif (ImGui::SliderFloat(\"Epsilon\", &epsilon, 1E-7, 1E-1, \"%.8f\", ImGuiSliderFlags_Logarithmic))\n\t{\n\t\tevaluate();\n\t\tCalcAccurateRst();\n\t}\n}\n\nvoid FEM1DVisualizer::draw(bool* p_open)\n{\n\tif (ImGui::BeginTabBar(\"FEM 1D App\")) {\n\t\tif (ImGui::BeginTabItem(\"FEM1D\"))\n\t\t{\n\t\t\tif (ImPlot::BeginPlot(\"Line Plot\", \"x\", \"f(x)\", ImGui::GetContentRegionAvail() - ImVec2(0, 100), ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMenus)) {\n\t\t\t\tImPlot::PlotLine(\"Precise solution\", &xs[0], &precise_val[0], Length);\n\t\t\t\tImPlot::PlotLine(\"FEM Conjugate Gradient\", &xs[0], &cg_val[0], Length);\n\t\t\t\tImPlot::PlotLine(\"FEM Multigrid\", &xs[0], &mg_val[0], Length);\n\n\t\t\t\tImPlot::EndPlot();\n\t\t\t}\n\t\t\tControl_UI();\n\t\t\tImGui::EndTabItem();\n\t\t}\n\t\tif (ImGui::BeginTabItem(\"FEM1D difference\"))\n\t\t{\n\t\t\tif (ImPlot::BeginPlot(\"Line Plot\", \"x\", \"f(x)\", ImGui::GetContentRegionAvail() - ImVec2(0, 100), ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMenus)) {\n\t\t\t\tImPlot::PlotLine(\"FEM diff Multigrid\", &xs[0], &mg_diff[0], Length);\n\t\t\t\tImPlot::PlotLine(\"FEM diff Conjugate Gradient\", &xs[0], &cg_diff[0], Length);\n\n\t\t\t\tImPlot::EndPlot();\n\t\t\t}\n\t\t\tControl_UI();\n\t\t\tImGui::EndTabItem();\n\t\t}\n\n\t\tif (ImGui::BeginTabItem(\"Error Plot\"))\n\t\t{\n\t\t\tif (ImPlot::BeginPlot(\"Line Plot\", \"x\", \"f(x)\", ImGui::GetContentRegionAvail() - ImVec2(0, 100), ImPlotFlags_NoBoxSelect | ImPlotFlags_NoMenus, ImPlotAxisFlags_LogScale, ImPlotAxisFlags_LogScale)) {\n\t\t\t\tImPlot::PlotLine(\"Multigrid L1 Error\", &pointcount[0], &mg_L1[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Multigrid L2 Error\", &pointcount[0], &mg_L2[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Multigrid L_inf Error\", &pointcount[0], &mg_Linf[0], pointcount.size());\n\n\t\t\t\tImPlot::PlotLine(\"Conjugate Gradient L1 Error\", &pointcount[0], &cg_L1[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Conjugate Gradient L2 Error\", &pointcount[0], &cg_L2[0], pointcount.size());\n\t\t\t\tImPlot::PlotLine(\"Conjugate Gradient L_inf Error\", &pointcount[0], &cg_Linf[0], pointcount.size());\n\n\t\t\t\tImPlot::EndPlot();\n\t\t\t}\n\n\t\t\tImGui::EndTabItem();\n\t\t}\n\t\tImGui::EndTabBar();\n\t}\n\n\tImGui::End();\n}\n\nint main()\n{\n\tFEM1DVisualizer visualizer;\n\tvisualizer.RenderLoop();\n}", "meta": {"hexsha": "69e7c95749bc0c86321b4a505ac134c02d225f4a", "size": 6696, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/FEM/FEM1DApp/test.cpp", "max_stars_repo_name": "Jerry-Shen0527/Numerical", "max_stars_repo_head_hexsha": "0bd6b630ac450caa0642029792ab348867d2390d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/FEM/FEM1DApp/test.cpp", "max_issues_repo_name": "Jerry-Shen0527/Numerical", "max_issues_repo_head_hexsha": "0bd6b630ac450caa0642029792ab348867d2390d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/FEM/FEM1DApp/test.cpp", "max_forks_repo_name": "Jerry-Shen0527/Numerical", "max_forks_repo_head_hexsha": "0bd6b630ac450caa0642029792ab348867d2390d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6283185841, "max_line_length": 201, "alphanum_fraction": 0.598864994, "num_tokens": 2339, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6954666280044367}} {"text": "#include \nextern \"C\"\n{\n#include \"induct.h\"\n}\n\n//#include \n\n\n/*Starts by applying QR decomposition using the householder transform and then applies \nSVD to obtain the recompressed U and V matrices.\nThe Eigen Library is used to assist in computing QR and SVD.*/\nint SVD_QR(double **U, double **V, int m, int n, int rank, double tol)\n{\n\tusing namespace Eigen;\n\n\tMatrixXd U2(m, rank);\n\tMatrixXd V2(n, rank);\n\tMatrixXd Q_u(m, rank);\n\tMatrixXd R_u(rank, rank);\n\tMatrixXd Q_v(n, rank);\n\tMatrixXd R_v(rank, rank);\n\n\tint new_rank = 0;\n\n\tfor (int i = 0; i < rank; i++)\n\t{\n\t\tfor (int j = 0; j < m; j++)\n\t\t{\n\t\t\tU2(j, i) = U[i][j];\n\t\t}\n\t\tfor (int j = 0; j < n; j++)\n\t\t{\n\t\t\tV2(j, i) = V[i][j];\n\t\t}\n\t}\n\n\tHouseholderQR qr(U2);\n\tQ_u = qr.householderQ()* MatrixXd::Identity(m, rank);\n\n\tR_u = Q_u.transpose()*U2;\n\n\tHouseholderQR qr2(V2);\n\t//Q_v = V2.colPivHouseholderQr().householderQ().setLength(V2.colPivHouseholderQr().nonzeroPivots());\n\tQ_v = qr2.householderQ()*MatrixXd::Identity(n, rank);\n\n\t//R_v = V2.colPivHouseholderQr().matrixR().topLeftCorner(rank, rank).template triangularView();\n\tR_v = Q_v.transpose()*V2;\n\n\tJacobiSVD svd(R_u*R_v.transpose(), ComputeFullU | ComputeFullV);\n\t//BDCSVD svd(R_u.block(0, 0, rank, rank)*R_v.transpose().block(0, 0, rank, rank), ComputeFullU | ComputeFullV);\n\n\n\tfor (int i = 0; i < rank; i++)\n\t{\n\t\tif (svd.singularValues()(i) >= tol*svd.singularValues()(0))\n\t\t{\n\t\t\t++new_rank;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor (int j = 0; j < m; j++)\n\t\t\t{\n\t\t\t\tU[i][j] = 0;\n\t\t\t}\n\t\t\tfor (int j = 0; j < n; j++)\n\t\t\t{\n\t\t\t\tV[i][j] = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\tdouble temp_U = 0;\n\tdouble temp_V = 0;\n\tMatrixXd U_temp(new_rank, new_rank);\n\n\n\tfor (int i = 0; i < new_rank; i++)\n\t{\n\t\tfor (int j = 0; j < new_rank; j++)\n\t\t{\n\t\t\tU_temp(i, j) = svd.matrixU()(j, i)*svd.singularValues()(i);//check\n\t\t}\n\t}\n\n\n\n\tfor (int i = 0; i < m; i++)\n\t{\n\t\tfor (int k = 0; k < new_rank; k++)\n\t\t{\n\n\t\t\tfor (int j = 0; j < new_rank; j++)\n\t\t\t{\n\t\t\t\ttemp_U += Q_u(i, j)*U_temp(k, j);\n\t\t\t}\n\t\t\tU[k][i] = temp_U;\n\t\t\ttemp_U = 0;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < n; i++)\n\t{\n\t\tfor (int k = 0; k < new_rank; k++)\n\t\t{\n\n\t\t\tfor (int j = 0; j < new_rank; j++)\n\t\t\t{\n\t\t\t\ttemp_V += Q_v(i, j)*svd.matrixV()(j, k);\n\t\t\t}\n\t\t\tV[k][i] = temp_V;\n\t\t\ttemp_V = 0;\n\t\t}\n\t}\n\treturn new_rank;\n}\n", "meta": {"hexsha": "3d5c332f83aa14a0c0b81598a965d2ba12187ddf", "size": 2279, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/SVD.cpp", "max_stars_repo_name": "Bnel13/FastHenry-ACA-", "max_stars_repo_head_hexsha": "dffeea9b4203c365e3f6f1e7a7715e39ee0202e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-03-03T10:48:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T14:20:00.000Z", "max_issues_repo_path": "src/SVD.cpp", "max_issues_repo_name": "Bnel13/FastHenry-ACA-", "max_issues_repo_head_hexsha": "dffeea9b4203c365e3f6f1e7a7715e39ee0202e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/SVD.cpp", "max_forks_repo_name": "Bnel13/FastHenry-ACA-", "max_forks_repo_head_hexsha": "dffeea9b4203c365e3f6f1e7a7715e39ee0202e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-02-01T15:51:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-30T13:06:28.000Z", "avg_line_length": 19.4786324786, "max_line_length": 122, "alphanum_fraction": 0.5778850373, "num_tokens": 863, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087946129328, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6954591461868188}} {"text": "//! [nbody-all]\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\ntypedef float T;\nnamespace bs = boost::simd;\nusing pack_t = bs::pack;\n\nstruct particles\n{\n std::vector> x, y, z, m, vx, vy, vz;\n std::size_t size_;\n\n particles(std::size_t size) : size_(size)\n , x(size + pack_t::static_size)\n , y(size + pack_t::static_size)\n , z(size + pack_t::static_size)\n , m(size + pack_t::static_size)\n , vx(size + pack_t::static_size)\n , vy(size + pack_t::static_size)\n , vz(size + pack_t::static_size)\n {}\n\n std::size_t size() const {return size_;}\n};\n\n//! [nbody-simd]\nvoid nbody_step(particles & ps)\n{\n pack_t grav_con {6.67408e-11};\n pack_t epsilon {0.00125f};\n for(std::size_t i = 0 ; i (&ps.x[ j ]);\n auto pjy = bs::load(&ps.y[ j ]);\n auto pjz = bs::load(&ps.z[ j ]);\n\n auto dx = pjx - pix;\n auto dy = pjy - piy;\n auto dz = pjz - piz;\n\n auto inorm = grav_con / bs::sqrt(dx * dx + dy * dy + dz * dz + epsilon);\n auto inorm3 = inorm * inorm *inorm;\n\n auto fi = bs::load(&ps.m[ j ]) * inorm3;\n auto fj = pim * inorm3;\n\n ax += dx * fi;\n ay += dy * fi;\n az += dz * fi;\n\n auto pjvx = bs::load(&ps.vx[ j ]);\n pjvx -= dx * fj;\n bs::store(pjvx, &ps.vx[ j ]);\n auto pjvy = bs::load(&ps.vy[ j ]);\n pjvy -= dy * fj;\n bs::store(pjvy, &ps.vy[ j ]);\n auto pjvz = bs::load(&ps.vz[ j ]);\n pjvz -= dz * fj;\n bs::store(pjvz, &ps.vz[ j ]);\n }\n\n pack_t pivx {&ps.vx[ i ]};\n pack_t pivy {&ps.vy[ i ]};\n pack_t pivz {&ps.vz[ i ]};\n\n pivx += ax;\n pivy += ay;\n pivz += az;\n\n pix += pivx;\n piy += pivy;\n piz += pivz;\n\n bs::aligned_store(pivx, &ps.vx[ i ]);\n bs::aligned_store(pivy, &ps.vy[ i ]);\n bs::aligned_store(pivz, &ps.vz[ i ]);\n\n bs::aligned_store(pix, &ps.x[ i ]);\n bs::aligned_store(piy, &ps.y[ i ]);\n bs::aligned_store(piz, &ps.z[ i ]);\n }\n}\n//! [nbody-simd]\n\n//! [nbody-scalar]\nvoid nbody_step_scalar(particles & ps)\n{\n T epsilon = 0.00125f;\n for(std::size_t i = 0 ; i (duration).count() <(duration).count() <\n#include \n\n#include \n// Eigen 几何模块\n#include \n#include \n\n#include \nusing namespace std::chrono;\nusing namespace std;\n\n\n\n/****************************\n* 本程序演示了 Eigen 几何模块的使用方法\n****************************/\n\n// TO-DO: 搞清楚四元数的顺序问题,明天去填下。\n\nint main ( int argc, char** argv )\n{\n // Eigen/Geometry 模块提供了各种旋转和平移的表示\n // 3D 旋转矩阵直接使用 Matrix3d 或 Matrix3f\n Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n // 旋转向量使用 AngleAxis, 它底层不直接是Matrix,但运算可以当作矩阵(因为重载了运算符)\n // 构造函数初始化\n Eigen::AngleAxisd rotation_vector ( M_PI/4, Eigen::Vector3d ( 0,0,1 ) ); //沿 Z 轴旋转 45 度\n // 保留三位小数!\n cout .precision(3);\n // 将旋转向量用矩阵的形式表征出来\n cout<<\"rotation matrix =\\n\"< (std::chrono::high_resolution_clock::now() - t0).count()<< '\\n';\n\n\n Eigen::Matrix4d T_m = Eigen::Matrix4d::Identity(); \n T_m.block<3, 3>(0, 0) = rotation_matrix;\n T_m.block<3, 1>(0, 3) = Eigen::Vector3d ( 1,3,4 );\n cout << \"Transform matrix = \\n\" << T_m <(0, 0) << endl;\n cout << \"Translation matrix= \\n\" << T_m.block<3, 1>(0, 3) << endl;\n\n // Test if Quaterniond only takes normalized rotation matrix\n cout << \"Rotation matrix= \\n\" << rotation_matrix << endl;\n rotation_matrix *= 2.0;\n cout << \"Rotation matrix= \\n\" << rotation_matrix << endl;\n double scale = std::sqrt((rotation_matrix.transpose() * rotation_matrix)(0, 0));\n Eigen::Matrix3d ret = (1. / scale) * rotation_matrix;\n Eigen::Matrix3d rotation_matrix_quat = Eigen::Quaterniond ( ret ).normalized().toRotationMatrix();;\n cout << \"Rotation matrix= \\n\" << rotation_matrix_quat << endl;\n \n\n return 0;\n}\n", "meta": {"hexsha": "54bbeae036f66a22b5e184ad6ac019f6d6d10525", "size": 4722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_stars_repo_name": "billamiable/slambook", "max_stars_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-29T05:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:27:43.000Z", "max_issues_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_issues_repo_name": "billamiable/slambook", "max_issues_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/useGeometry/eigenGeometry.cpp", "max_forks_repo_name": "billamiable/slambook", "max_forks_repo_head_hexsha": "c2c00b7338aaf071750f7a31d92facd0e0127c33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-28T11:53:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-04T02:59:20.000Z", "avg_line_length": 38.3902439024, "max_line_length": 147, "alphanum_fraction": 0.6249470563, "num_tokens": 1814, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896780646392, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6951179328012274}} {"text": "#pragma once\n\n#include \n#include \"../guia2/estructura_capas_red.cpp\"\n\nusing namespace std;\nusing namespace arma;\n\nnamespace ic {\n\nvec sigmoid(const vec& v)\n{\n\treturn 2 / (1 + exp(-v)) - 1;\n}\n\nvec winnerTakesAll(const vec& v)\n{\n\tif (v.n_elem == 1)\n\t\t// Si la red tiene una sola salida, aplicar la función signo\n\t\treturn v(0) >= 0 ? vec{1} : vec{-1};\n\telse {\n\t\tvec result = v;\n\t\t// Si la red tiene varias salidas, asignarle +1 a \"la que ganó\"\n\t\t// y -1 a las demás.\n\t\tconst double maximo = max(result);\n\n\t\tresult.transform([maximo](double val) {\n // Comparación de igualdad de números de coma flotante\n if (abs(val - maximo) < 1e-9)\n return 1;\n else\n return -1;\n\t\t});\n\n\t\treturn result;\n\t}\n}\n\nvector salidaMulticapa(const vector& pesos,\n const vec& patron)\n{\n\tvector ySalidas;\n\n\t// Calculo de la salida para la primer capa\n\t{\n\t\tconst vec v = pesos[0] * join_vert(vec{-1}, patron); // agrega entrada correspondiente al sesgo\n\t\tySalidas.push_back(sigmoid(v));\n\t}\n\n\t// Calculo de las salidas para las demas capas\n\tfor (unsigned int i = 1; i < pesos.size(); ++i) {\n\t\tconst vec v = pesos[i] * join_vert(vec{-1}, ySalidas[i - 1]); // agrega entrada correspondiente al sesgo\n\t\tySalidas.push_back(sigmoid(v)); // TODO: ver qué valor le pasamos como parámetro\n\t\t // a la sigmoidea\n\t}\n\n\treturn ySalidas;\n}\n\ndouble errorCuadraticoMulticapa(const vector& pesos,\n const mat& patrones,\n const mat& salidaDeseada)\n{\n\tdouble errorCuadraticoTotal = 0;\n\n\tfor (unsigned int n = 0; n < patrones.n_rows; ++n) {\n\t\tvector ySalidas = salidaMulticapa(pesos, patrones.row(n).t());\n\t\tconst vec salidaRed = ySalidas.back();\n\n\t\tconst double errorCuadraticoPatron = sum(pow(salidaDeseada.row(n).t() - salidaRed, 2));\n\t\terrorCuadraticoTotal += errorCuadraticoPatron;\n\t}\n\n\treturn errorCuadraticoTotal;\n}\n\ndouble errorClasificacionMulticapa(const vector& pesos,\n const mat& patrones,\n const mat& salidaDeseada)\n{\n\tint errores = 0;\n\n\tfor (unsigned int n = 0; n < patrones.n_rows; ++n) {\n\t\tvector ySalidas = salidaMulticapa(pesos, patrones.row(n).t());\n\n\t\tconst vec salidaRed = winnerTakesAll(ySalidas.back()); // fija los valores en -1 o 1.\n\n\t\tif (any(salidaRed.t() != salidaDeseada.row(n)))\n\t\t\t++errores;\n\t}\n\n\tdouble tasaError = static_cast(errores) / patrones.n_rows * 100;\n\n\treturn tasaError;\n}\n\ndouble errorClasificacionMulticapa(const vector& pesos,\n const mat& datos)\n{\n\tconst int nEntradas = pesos.front().n_cols - 1;\n\tconst int nSalidas = pesos.back().n_rows;\n\tif (nEntradas + nSalidas != int(datos.n_cols))\n\t\tthrow runtime_error(\"Están mal calculados el número de entradas y salidas\");\n\n\treturn errorClasificacionMulticapa(pesos,\n\t datos.head_cols(nEntradas),\n\t datos.tail_cols(nSalidas));\n}\n\npair, double> epocaMulticapa(const mat& patrones,\n const mat& salidaDeseada,\n double tasaAprendizaje,\n double inercia,\n vector pesos)\n{\n\t//Entrenamiento\n\tvector deltaWOld;\n\tfor (unsigned int i = 0; i < pesos.size(); ++i)\n\t\tdeltaWOld.push_back(zeros(size(pesos[i])));\n\n\tfor (unsigned int n = 0; n < patrones.n_rows; ++n) {\n\t\t// Calcular las salidas para cada capa\n\t\tconst vector ySalidas = salidaMulticapa(pesos, patrones.row(n).t());\n\n\t\t// Calculo del error\n\t\tconst vec error = salidaDeseada.row(n).t() - ySalidas.back();\n\n\t\t// Calculo retropropagacion\n\t\t// Calculo de gradiente error local instantaneo\n\t\tvector delta;\n\t\t// Tenemos tantos vectores de deltas como capas\n\t\tdelta.resize(ySalidas.size());\n\n\t\t// Delta de ultima capa\n\t\tdelta[delta.size() - 1] = error\n\t\t % (1 + ySalidas.back())\n\t\t % (1 - ySalidas.back());\n\t\t// Deltas de las capas anteriores\n\t\tfor (int i = ySalidas.size() - 2; i >= 0; --i) {\n\t\t\t// No participan los pesos correspondientes al sesgo en el cálculo de los deltas\n\t\t\tconst mat pesosAux = pesos[i + 1].tail_cols(pesos[i + 1].n_cols - 1);\n\t\t\tdelta[i] = (pesosAux.t() * delta[i + 1])\n\t\t\t % (1 + ySalidas[i])\n\t\t\t % (1 - ySalidas[i]);\n\t\t}\n\n // Actualizacion de pesos de todas las capas menos la primera.\n // Si la red tiene una sola capa, no se entra acá.\n\t\tfor (int i = pesos.size() - 1; i >= 1; --i) {\n\t\t\tconst mat deltaWnuevo = tasaAprendizaje\n\t\t\t * delta[i]\n\t\t\t * join_horiz(vec{-1}, ySalidas[i - 1].t())\n\t\t\t + inercia * deltaWOld[i];\n\t\t\tpesos[i] += deltaWnuevo;\n\t\t\tdeltaWOld[i] = deltaWnuevo;\n\t\t}\n\n\t\t// Actualización de pesos de la primer capa\n\t\tconst mat deltaW = tasaAprendizaje\n\t\t * delta[0]\n\t\t * join_horiz(vec{-1}, patrones.row(n))\n\t\t + inercia * deltaWOld[0];\n\t\tpesos[0] += deltaW;\n\t\tdeltaWOld[0] = deltaW;\n\t}\n\n\t// Calculo de Tasa de error\n\tdouble tasaError = errorClasificacionMulticapa(pesos, patrones, salidaDeseada);\n\n\treturn {pesos, tasaError};\n} // fin funcion Epoca\n\ntuple, vec, vec, int> entrenarMulticapa(const EstructuraCapasRed& estructura,\n const mat& datos,\n int nEpocas,\n double tasaAprendizaje,\n double inercia,\n double toleranciaErrorClasificacion,\n long long semilla = -1)\n{\n\tconst int nSalidas = estructura(estructura.n_elem - 1);\n\tconst int nEntradas = datos.n_cols - nSalidas;\n\tconst int nCapas = estructura.n_elem;\n\t// Vamos a tener tantas columnas en salidaDeseada\n\t// como neuronas en la capa de salida\n\tconst mat salidaDeseada = datos.tail_cols(nSalidas);\n\t// Extender la matriz de patrones con la entrada correspondiente al umbral\n\tconst mat patrones = datos.head_cols(nEntradas);\n\n\t// Inicializar pesos y tasa de error\n\tvector pesos;\n\n#pragma omp critical(inicializarPesos)\n\t{\n\t\tif (semilla != -1)\n\t\t\tarma_rng::set_seed(semilla);\n\n\t\t// La primer matriz matriz de pesos tiene tantas filas como neuronas en la primer capa\n\t\t// y tantas columnas como componentes tiene la entrada, más la entrada correspondiente\n\t\t// al sesgo.\n\t\tpesos.push_back(randu(estructura(0), nEntradas + 1) - 0.5);\n\n\t\tfor (int i = 1; i < nCapas; ++i) {\n\t\t\t// Las siguientes matrices de pesos tienen tantas filas como neuronas en dicha capa\n\t\t\t// y tantas columnas como entradas a esa capa, que van a ser las salidas de\n\t\t\t// la capa anterior mas la entrada correspondiente al sesgo.\n\t\t\t// Las salidas de la capa anterior es igual al nro de neuronas en la capa anterior.\n\t\t\tpesos.push_back(randu(estructura(i), estructura(i - 1) + 1) - 0.5);\n\t\t}\n\t}\n\n\tdouble tasaError = 100;\n\tvec erroresClasificacion;\n\tvec erroresCuadraticos;\n\n\t// Ciclo de las epocas\n\tint epoca = 1;\n\tfor (; epoca <= nEpocas; ++epoca) {\n\t\t// Ciclo para una época\n\t\ttie(pesos, tasaError) = epocaMulticapa(patrones,\n\t\t salidaDeseada,\n\t\t tasaAprendizaje,\n\t\t inercia,\n\t\t pesos);\n\n\t\terroresClasificacion.insert_rows(erroresClasificacion.n_elem, vec{tasaError});\n\t\tconst double errorCuadratico = errorCuadraticoMulticapa(pesos, patrones, salidaDeseada);\n\t\terroresCuadraticos.insert_rows(epoca - 1, vec{errorCuadratico});\n\n\t\tif (tasaError <= toleranciaErrorClasificacion)\n\t\t\tbreak;\n\t}\n\t// Fin ciclo (epocas)\n\n\t// Si el bucle anterior no cortó por tolerancia de error,\n\t// el for va a incrementar la variable una vez de más.\n\tif (epoca > nEpocas)\n\t\tepoca = nEpocas;\n\n\treturn make_tuple(pesos, erroresClasificacion, erroresCuadraticos, epoca);\n}\n\nstruct ParametrosMulticapa {\n\tEstructuraCapasRed estructuraRed;\n\tint nEpocas;\n\tdouble tasaAprendizaje;\n\tdouble inercia;\n\tdouble toleranciaError;\n};\n}\n\nistream& operator>>(istream& is, ic::ParametrosMulticapa& parametros)\n{\n\t// Formato:\n\t// estructura: [3 2 1]\n\t// n_epocas: 200\n\t// tasa_entrenamiento: 0.1\n\t// inercia: 0.5\n\t// parametro_sigmoidea: 1\n\t// tolerancia_error: 5\n\tstring str;\n\n\t// No chequeamos si la etiqueta de cada línea está bien o no. No nos importa\n\tis >> str >> parametros.estructuraRed\n\t >> str >> parametros.nEpocas\n\t >> str >> parametros.tasaAprendizaje\n\t >> str >> parametros.inercia\n\t >> str >> parametros.toleranciaError;\n\n\t// Control básico de valores de parámetros\n\tif (parametros.nEpocas <= 0\n\t || parametros.tasaAprendizaje <= 0\n\t || parametros.toleranciaError <= 0\n\t || parametros.toleranciaError >= 100)\n\t\tis.clear(ios::failbit);\n\n\treturn is;\n}\n", "meta": {"hexsha": "314593e87e52766fdf1c0cfd39ffd2f9de4faa6b", "size": 9156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia1/multicapa.cpp", "max_stars_repo_name": "junrrein/ic2017", "max_stars_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "guia1/multicapa.cpp", "max_issues_repo_name": "junrrein/ic2017", "max_issues_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "guia1/multicapa.cpp", "max_forks_repo_name": "junrrein/ic2017", "max_forks_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8172043011, "max_line_length": 112, "alphanum_fraction": 0.6032110092, "num_tokens": 2546, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909756, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6951179311602962}} {"text": "#include \n#include \n#include \n#include \n#include \n\n// Typedefs.\nusing Kernel = CGAL::Simple_cartesian;\nusing Point_2 = Kernel::Point_2;\nusing VectorXd = Eigen::VectorXd;\nusing MatrixXd = Eigen::MatrixXd;\n\nusing Output_iterator =\n std::back_insert_iterator< std::vector >;\n\nint main() {\n\n // Create a set of vertices.\n const std::vector vertices = {\n Point_2(0.0, 0.0), Point_2(0.75, 0.25), Point_2(0.5, 0.5), Point_2(0.4, -0.2) };\n\n // Create a set of query points.\n const std::vector queries = {\n Point_2(0.2, 0.2), Point_2(0.3, 0.3), Point_2(0.4, 0.4) };\n\n // Create a lambda function with affine coordinates.\n // This implementation is based on the following paper:\n // S. Waldron. Affine generalized barycentric coordinates.\n // Jaen Journal on Approximation, 3(2):209-226, 2011.\n // This function is a model of the `AnalyticWeights_2` concept.\n const auto affine = [&](\n const Point_2& query,\n Output_iterator coordinates) {\n\n const std::size_t n = vertices.size();\n const auto lambda = [](const Point_2& p){ return std::make_pair(p, 1.0); };\n const Point_2 b = CGAL::barycenter(\n boost::make_transform_iterator(vertices.begin(), lambda),\n boost::make_transform_iterator(vertices.end() , lambda), Kernel());\n\n MatrixXd V(2, n);\n for (std::size_t i = 0; i < n; ++i) {\n V(0, i) = vertices[i].x() - b.x();\n V(1, i) = vertices[i].y() - b.y();\n }\n\n const auto A = V.adjoint();\n const auto mat = V * A;\n const auto inv = mat.inverse();\n\n Point_2 diff; VectorXd vec(2);\n for (std::size_t i = 0; i < n; ++i) {\n const double x = query.x() - b.x();\n const double y = query.y() - b.y();\n diff = Point_2(x, y);\n\n vec(0) = V(0, i);\n vec(1) = V(1, i);\n const auto res = inv * vec;\n\n *(coordinates++) =\n diff.x() * res(0) + diff.y() * res(1) + 1.0 / double(n);\n }\n };\n\n // Compute affine coordinates for all query points.\n std::cout << std::endl << \"affine coordinates (all queries): \" << std::endl << std::endl;\n\n std::vector coordinates;\n coordinates.reserve(4);\n for (const auto& query : queries) {\n coordinates.clear();\n affine(query, std::back_inserter(coordinates));\n for (std::size_t i = 0; i < coordinates.size() - 1; ++i) {\n std::cout << coordinates[i] << \", \";\n }\n std::cout << coordinates[coordinates.size() - 1] << std::endl;\n }\n std::cout << std::endl;\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "abf8c9391853b705daebb3bb04a6334375035fa3", "size": 2587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Barycentric_coordinates_2/examples/Barycentric_coordinates_2/affine_coordinates.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Barycentric_coordinates_2/examples/Barycentric_coordinates_2/affine_coordinates.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Barycentric_coordinates_2/examples/Barycentric_coordinates_2/affine_coordinates.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 31.1686746988, "max_line_length": 91, "alphanum_fraction": 0.6134518748, "num_tokens": 796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6950680694778688}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace mp = boost::multiprecision;\nusing namespace std;\n\n\nint main(void) {\n int ab, bc, ca;\n cin >> ab;\n cin >> bc;\n cin >> ca;\n\n // ヘロンの公式 \n auto s = (ab + bc + ca) / 2;\n auto ans = sqrt(s * (s - ab) * (s - bc) * (s - ca));\n\n cout << ans << endl; \n\n return 0;\n}", "meta": {"hexsha": "696042fdfdbe732a4e0f1a738d89c3f139de1a6d", "size": 519, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc116/a/main.cpp", "max_stars_repo_name": "kamiyaowl/atcoder", "max_stars_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abc116/a/main.cpp", "max_issues_repo_name": "kamiyaowl/atcoder", "max_issues_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-20T11:51:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-20T11:51:59.000Z", "max_forks_repo_path": "abc116/a/main.cpp", "max_forks_repo_name": "kamiyaowl/atcoder", "max_forks_repo_head_hexsha": "30521be1684e72e75c7ba21312c5f96ae81bf25a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3, "max_line_length": 56, "alphanum_fraction": 0.5857418112, "num_tokens": 154, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248140158417, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6950420926529816}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\nint main()\n{\n // scaling 矩阵为一个对角阵\n //2 0\n //0 1\n Matrix t = Scaling(2.0f, 1.0f);\n std::cout << t.matrix() << std::endl;\n\n Affine3f aux(Affine3f::Identity());\n\n cout << aux.affine().matrix() << endl; // aux是一个齐次矩阵,采用.affine()忽略了最后一行\n\n cout << aux.matrix()< Affine_transform; // 仿射\n Affine_transform.setIdentity();\n Transform Isometry_transform; //等距\n Transform Projective_transform; // 射影变换\n Affine_transform.prerotate(AngleAxisd(3.14,Vector3d::UnitX()));\n\n\n}", "meta": {"hexsha": "d1341dc9678a698ce00ba38ced57fbdf14e69e88", "size": 742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ICP/EigenChineseDocument-master/Eigen/chapter4_test.cpp", "max_stars_repo_name": "Yihua-Ni/Tools", "max_stars_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ICP/EigenChineseDocument-master/Eigen/chapter4_test.cpp", "max_issues_repo_name": "Yihua-Ni/Tools", "max_issues_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICP/EigenChineseDocument-master/Eigen/chapter4_test.cpp", "max_forks_repo_name": "Yihua-Ni/Tools", "max_forks_repo_head_hexsha": "b40c24b0b2a7025f13182fc5ed5bfcf63b389585", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4814814815, "max_line_length": 80, "alphanum_fraction": 0.6051212938, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625126757597, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.6950005065119135}} {"text": "// #include \n#include \n\nvoid CalcElaStiffMat(\tEigen::Ref> C, \n\t\t\t\t\t\tconst double &G, \n\t\t\t\t\t\tconst double &LAMBDA)\n{\n C = Eigen::Matrix::Zero();\n // Kelvin Voigt\n for (int i = 0; i < 3; i++)\n {\n\t\tC(i,i) += 2*G;\n C(i+3,i+3) += G;\n for (int j = 0; j < 3; j++)\n {\n C(i,j) += LAMBDA;\n\n } \n } \n}\n\nextern \"C\" void umat(double *stress, double *statev, double *ddsdde, double *sse, double *spd,\n\t\tdouble *scd, double *rpl, double *ddsddt, double *drplde, double *drpldt,\n\t\tdouble *stran, double *dstran, double *time, double *dtime, double *temp,\n\t\tdouble *dtemp, double *predef, double *dpred, char *cmname, int *ndi,\n\t\tint *nshr, int *ntens, int *nstatv, double *props, int *nprops, \n\t\tdouble *coords, double *drot, double *pnewdt, double *celent, double *dfgrd0, \n\t\tdouble *dfgrd1, int *noel, int *npt, int *layer, int *kspt, \n\t\tint *kstep, int *kinc, short cmname_len)\n{\n\tdouble E = props[0]; //210000\n\tdouble NU = props[1]; //0.3\n\tdouble G = E/2.0/(1.0 + NU); //80769,23\n\tdouble LAMBDA = 2.0*G*NU/(1.0 - 2.0*NU);//121153,85\n\tdouble eps [6];\n\tdouble eps_trace;\n\n// Update strain\n\tfor (int i = 0; i < 6; i++)\n\t{\n\t\teps[i] = stran[i] + dstran[i];\t\n\t}\n\t\n\teps_trace = eps[0] + eps[1] + eps[2];\n\n//Calculation of the stress\n\tfor(int i = 0; i < 3; i++)\n\t{\n\t\tstress[i] = LAMBDA*eps_trace + 2.0*G*eps[i];\n\t\tstress[i+3] = G*eps[i+3];\n\t}\n\n// Calc Isotropic elastic stiffness matrix through Eigen \n// (unnessary but informative)\n\tEigen::Matrix C;\n\tCalcElaStiffMat(C, G, LAMBDA);\n\n//\tIsotropic elastic stiffness matrix ddsdde as a 36x1-Vector\n// But first it`s Initialization\n\tfor (int i = 0; i < 6; i++)\n\t{\n\t\tfor(int j = 0; j< 6; j++)\n\t\t{\n\t\t\tddsdde[6*i+j] = 0.0; \n\t\t}\n\t}\n\tfor(int i = 0; i < 3; i++)\n\t{\n\t\tddsdde[6*i+0] \t\t\t= C(0,i);\n\t\tddsdde[6*i+1] \t\t\t= C(1,i);\n\t\tddsdde[6*i+2] \t\t\t= C(2,i);\n\t\tddsdde[6*(i+3)+(i+3)] \t= C(i+3, i+3);\n\t}\n}\n", "meta": {"hexsha": "306e27380b8a0ddfce82d86359eb2aeac36b1dff", "size": 1953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "umat.cpp", "max_stars_repo_name": "michael-schw/Abaqus-UMAT-subroutine", "max_stars_repo_head_hexsha": "cd14fb7e2287369c86a82f4e71e13fc229faad8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-30T01:10:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:52:16.000Z", "max_issues_repo_path": "umat.cpp", "max_issues_repo_name": "michael-schw/Abaqus-UMAT-subroutine", "max_issues_repo_head_hexsha": "cd14fb7e2287369c86a82f4e71e13fc229faad8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "umat.cpp", "max_forks_repo_name": "michael-schw/Abaqus-UMAT-subroutine", "max_forks_repo_head_hexsha": "cd14fb7e2287369c86a82f4e71e13fc229faad8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-18T07:05:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T05:00:04.000Z", "avg_line_length": 26.04, "max_line_length": 94, "alphanum_fraction": 0.5729646697, "num_tokens": 799, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625069680098, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6950004969950099}} {"text": "/**\n * @file gradientflow.h\n * @brief NPDE homework GradientFlow code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"gradientflow.h\"\n\n#include \n#include \n#include \n\nnamespace GradientFlow {\n\n/* SAM_LISTING_BEGIN_0 */\nEigen::MatrixXd ButcherMatrix() {\n Eigen::MatrixXd A(6, 5);\n // clang-format off\n A << 0.25, 0., 0., 0., 0.,\n 0.5, 0.25, 0., 0., 0.,\n 17./50., -1./25., 0.25, 0., 0.,\n 371./1360., -137./2720., 15./544., 0.25, 0.,\n 25./24., -49./48., 125./16., -85./12., 0.25,\n 25./24., -49./48., 125./16., -85./12., 0.25;\n // clang-format on\n return A;\n}\n/* SAM_LISTING_END_0 */\n\n/* SAM_LISTING_BEGIN_1 */\nstd::vector SolveGradientFlow(const Eigen::VectorXd &d,\n double lambda,\n const Eigen::VectorXd &y0,\n double T, unsigned int M) {\n // initialize solution vector\n std::vector sol(M + 1, Eigen::VectorXd::Zero(y0.size()));\n\n#if SOLUTION\n // Define the right hand side of the ODE y' = f(y), and the Jacobian of f.\n auto f = [d, lambda](const Eigen::VectorXd &y) {\n Eigen::VectorXd val =\n -2. * std::cos(y.squaredNorm()) * y - 2. * lambda * d.dot(y) * d;\n return val;\n };\n auto df = [d, lambda](const Eigen::VectorXd &y) {\n int dim = y.size();\n Eigen::MatrixXd term1 = 4. * std::sin(y.squaredNorm()) * y * y.transpose();\n Eigen::MatrixXd term2 =\n -2. * std::cos(y.squaredNorm()) * Eigen::MatrixXd::Identity(dim, dim);\n Eigen::MatrixXd term3 = -2. * lambda * d * d.transpose();\n Eigen::MatrixXd dfval = term1 + term2 + term3;\n return dfval;\n };\n\n // Split the interval [0,T] into M intervals of size h.\n double h = T / M;\n Eigen::VectorXd y = y0;\n sol[0] = y;\n // Evolve up to time T:\n for (int i = 1; i <= M; i++) {\n y = DiscEvolSDIRK(f, df, y, h);\n sol[i] = y;\n }\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return sol;\n}\n/* SAM_LISTING_END_1 */\n\n} // namespace GradientFlow\n", "meta": {"hexsha": "adaa63fe475d515dfcd7b25d770ea2a08b3e4143", "size": 2239, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/GradientFlow/mastersolution/gradientflow.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/GradientFlow/mastersolution/gradientflow.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/GradientFlow/mastersolution/gradientflow.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 29.4605263158, "max_line_length": 79, "alphanum_fraction": 0.5270209915, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.84997116805678, "lm_q1q2_score": 0.6949147325037214}} {"text": "/*******************************************************************************\n *\n * File Name: H01indexedCSVdatabaseAlgorithms.hpp\n * Author: Richard Bruce Baxter - Copyright (c) 2021 Baxter AI (baxterai.com)\n * License: MIT License\n * Project: H01LocalConnectome\n * Requirements: see H01indexedCSVdatabase.hpp\n * Compilation: see H01indexedCSVdatabase.hpp\n * Usage: see H01indexedCSVdatabase.hpp\n * Description: H01 indexed CSV database algorithms\n * Comments:\n * /\n *******************************************************************************/\n\n#ifndef HEADER_H01indexedCSVdatabaseAlgorithms\n#define HEADER_H01indexedCSVdatabaseAlgorithms\n\n#include \"H01indexedCSVdatabase.hpp\"\n\n#include \n#include \n\n#ifdef INDEXED_CSV_DATABASE_ALGORITHMS\n\n//https://gist.github.com/chrisengelsma/108f7ab0a746323beaaf7d6634cf4add\n/**\n * PURPOSE:\n *\n *\tPolynomial Regression aims to fit a non-linear relationship to a set of\n *\tpoints. It approximates this by solving a series of linear equations using \n *\ta least-squares approach.\n *\n *\tWe can model the expected value y as an nth degree polynomial, yielding\n *\tthe general polynomial regression model:\n *\n *\ty = a0 + a1 * x + a2 * x^2 + ... + an * x^n\n *\n * LICENSE:\n *\n * MIT License\n * \n * Copyright (c) 2020 Chris Engelsma\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * @author Chris Engelsma\n */\n#include \n#include \n#include \n#include \n#include \"SHAREDvars.hpp\"\n\nclass H01indexedCSVdatabaseAlgorithmsFit\n{\npublic:\n\n\tH01indexedCSVdatabaseAlgorithmsFit(void);\n\t~H01indexedCSVdatabaseAlgorithmsFit(void);\n\n\t#ifdef INDEXED_CSV_DATABASE_QUERY_PERFORM_INCOMING_AXON_MAPPING_2D_POLY_REGRESSION\n\tdouble calculatePoly(int xx);\n\t#endif\n\n\tlong connectionNeuronID;\n\tint estSynapseType;\n\t#ifdef INDEXED_CSV_DATABASE_QUERY_PERFORM_INCOMING_AXON_MAPPING_2D_POLY_REGRESSION\n\tdouble a;\n\tdouble b;\n\tdouble c;\n\t#endif\n\t#ifdef INDEXED_CSV_DATABASE_QUERY_PERFORM_INCOMING_AXON_MAPPING_3D_LINEAR_REGRESSION\n\tvec origin;\n\tvec axis;\n\t#endif\n};\n\t\t\ntemplate \nclass PolynomialRegression {\n\tpublic:\n\n\t\tPolynomialRegression();\n\t\tvirtual ~PolynomialRegression(){};\n\n\t\tbool fitIt(\n\t\t\tconst std::vector & x,\n\t\t\tconst std::vector & y,\n\t\t\tconst int & order,\n\t\t\tstd::vector &\tcoeffs);\n};\n\ntemplate \nPolynomialRegression::PolynomialRegression() {};\n\ntemplate \nbool PolynomialRegression::fitIt( \n\tconst std::vector & x,\n\tconst std::vector & y,\n\tconst int & order,\n\tstd::vector & coeffs)\n{\n\t// The size of xValues and yValues should be same\n\tif (x.size() != y.size()) {\n\t\tthrow std::runtime_error( \"The size of x & y arrays are different\" );\n\t\treturn false;\n\t}\n\t// The size of xValues and yValues cannot be 0, should not happen\n\tif (x.size() == 0 || y.size() == 0) {\n\t\tthrow std::runtime_error( \"The size of x or y arrays is 0\" );\n\t\treturn false;\n\t}\n\t\n\tsize_t N = x.size();\n\tint n = order;\n\tint np1 = n + 1;\n\tint np2 = n + 2;\n\tint tnp1 = 2 * n + 1;\n\tTYPE tmp;\n\n\t// X = vector that stores values of sigma(xi^2n)\n\tstd::vector X(tnp1);\n\tfor (int i = 0; i < tnp1; ++i) {\n\t\tX[i] = 0;\n\t\tfor (int j = 0; j < N; ++j)\n\t\t\tX[i] += (TYPE)pow(x[j], i);\n\t}\n\n\t// a = vector to store final coefficients.\n\tstd::vector a(np1);\n\n\t// B = normal augmented matrix that stores the equations.\n\tstd::vector > B(np1, std::vector (np2, 0));\n\n\tfor (int i = 0; i <= n; ++i) \n\t\tfor (int j = 0; j <= n; ++j) \n\t\t\tB[i][j] = X[i + j];\n\n\t// Y = vector to store values of sigma(xi^n * yi)\n\tstd::vector Y(np1);\n\tfor (int i = 0; i < np1; ++i) {\n\t\tY[i] = (TYPE)0;\n\t\tfor (int j = 0; j < N; ++j) {\n\t\t\tY[i] += (TYPE)pow(x[j], i)*y[j];\n\t\t}\n\t}\n\n\t// Load values of Y as last column of B\n\tfor (int i = 0; i <= n; ++i) \n\t\tB[i][np1] = Y[i];\n\n\tn += 1;\n\tint nm1 = n-1;\n\n\t// Pivotisation of the B matrix.\n\tfor (int i = 0; i < n; ++i) \n\t\tfor (int k = i+1; k < n; ++k) \n\t\t\tif (B[i][i] < B[k][i]) \n\t\t\t\tfor (int j = 0; j <= n; ++j) {\n\t\t\t\t\ttmp = B[i][j];\n\t\t\t\t\tB[i][j] = B[k][j];\n\t\t\t\t\tB[k][j] = tmp;\n\t\t\t\t}\n\n\t// Performs the Gaussian elimination.\n\t// (1) Make all elements below the pivot equals to zero\n\t//\t\t or eliminate the variable.\n\tfor (int i=0; i= 0; --i) {\n\t\ta[i] = B[i][n];\t\t\t\t\t\t\t\t\t // (1)\n\t\tfor (int j = 0; j\nstd::pair < Vector3, Vector3 > best_line_from_points(const std::vector & c)\n{\n\t//copy coordinates to matrix in Eigen format\n\tsize_t num_atoms = c.size();\n\tEigen::Matrix< double, Eigen::Dynamic, Eigen::Dynamic > centers(num_atoms, 3);\n\tfor (size_t i = 0; i < num_atoms; ++i) centers.row(i) = c[i];\n\n\tVector3 origin = centers.colwise().mean();\n\tEigen::MatrixXd centered = centers.rowwise() - origin.transpose();\n\tEigen::MatrixXd cov = centered.adjoint() * centered;\n\tEigen::SelfAdjointEigenSolver eig(cov);\n\tVector3 axis = eig.eigenvectors().col(2).normalized();\n\n\treturn std::make_pair(origin, axis);\n}\n\n\n\n#endif\n\n#endif\n", "meta": {"hexsha": "9f215b43c4701b5f24f9348a96c303c920e44c4d", "size": 6617, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "H01indexedCSVdatabase/H01indexedCSVdatabaseAlgorithms.hpp", "max_stars_repo_name": "baxterai/H01localConnectome", "max_stars_repo_head_hexsha": "52118d10edc4d6d5534ee39c43a4db3b588481de", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "H01indexedCSVdatabase/H01indexedCSVdatabaseAlgorithms.hpp", "max_issues_repo_name": "baxterai/H01localConnectome", "max_issues_repo_head_hexsha": "52118d10edc4d6d5534ee39c43a4db3b588481de", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "H01indexedCSVdatabase/H01indexedCSVdatabaseAlgorithms.hpp", "max_forks_repo_name": "baxterai/H01localConnectome", "max_forks_repo_head_hexsha": "52118d10edc4d6d5534ee39c43a4db3b588481de", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2777777778, "max_line_length": 85, "alphanum_fraction": 0.6527127097, "num_tokens": 1942, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972583359805, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.6948992182504082}} {"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Example of tikhonov class with blurred sine test problem.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"num_collect/regularization/explicit_l_curve.h\"\n#include \"num_collect/regularization/tikhonov.h\"\n#include \"num_prob_collect/regularization/blur_sine.h\"\n\nauto main() -> int {\n constexpr int prec = 15;\n std::cout << std::setprecision(prec);\n\n using coeff_type = Eigen::MatrixXd;\n using data_type = Eigen::VectorXd;\n static constexpr num_collect::index_type solution_size = 60;\n static constexpr num_collect::index_type data_size = 60;\n constexpr double error_rate = 0.01;\n\n // create test problem\n const auto prob =\n num_prob_collect::regularization::blur_sine(data_size, solution_size);\n std::mt19937 engine; // NOLINT\n std::normal_distribution dist{0.0,\n std::sqrt(prob.data().squaredNorm() /\n static_cast(prob.data().size()) * error_rate)};\n auto data_with_error = prob.data();\n for (num_collect::index_type i = 0; i < data_with_error.size(); ++i) {\n data_with_error(i) += dist(engine);\n }\n\n // solve\n using solver_type =\n num_collect::regularization::tikhonov;\n solver_type tikhonov;\n tikhonov.compute(prob.coeff(), data_with_error);\n\n using searcher_type =\n num_collect::regularization::explicit_l_curve;\n searcher_type searcher{tikhonov};\n searcher.search();\n Eigen::VectorXd solution;\n searcher.solve(solution);\n std::cout << \"Optimal parameter: \" << searcher.opt_param() << std::endl;\n std::cout << \"Error rate: \"\n << (solution - prob.solution()).squaredNorm() /\n prob.solution().squaredNorm()\n << std::endl;\n\n // plot graphs\n std::vector param_list;\n std::vector type_list;\n std::vector value_list;\n const auto [min_param, max_param] = tikhonov.param_search_region();\n constexpr std::size_t num_samples = 101;\n for (std::size_t i = 0; i < num_samples; ++i) {\n const double rate =\n static_cast(i) / static_cast(num_samples - 1);\n const double param = min_param * std::pow(max_param / min_param, rate);\n\n const double residual_norm = tikhonov.residual_norm(param);\n param_list.push_back(param);\n type_list.emplace_back(\"residual norm\");\n value_list.push_back(residual_norm);\n\n const double regularization_term = tikhonov.regularization_term(param);\n param_list.push_back(param);\n type_list.emplace_back(\"regularization term\");\n value_list.push_back(regularization_term);\n\n const double curvature_value = tikhonov.l_curve_curvature(param);\n param_list.push_back(param);\n type_list.emplace_back(\"curvature\");\n value_list.push_back(curvature_value);\n\n tikhonov.solve(param, solution);\n const double error = (solution - prob.solution()).squaredNorm() /\n prob.solution().squaredNorm();\n param_list.push_back(param);\n type_list.emplace_back(\"error rate\");\n value_list.push_back(error);\n }\n\n pybind11::scoped_interpreter interpreter;\n auto pd = pybind11::module::import(\"pandas\");\n auto px = pybind11::module::import(\"plotly.express\");\n\n std::unordered_map data;\n data.try_emplace(\"param\", pybind11::cast(param_list));\n data.try_emplace(\"type\", pybind11::cast(type_list));\n data.try_emplace(\"value\", pybind11::cast(value_list));\n\n auto fig = px.attr(\"line\")(pybind11::arg(\"data_frame\") = data,\n pybind11::arg(\"x\") = \"param\", pybind11::arg(\"y\") = \"value\",\n pybind11::arg(\"color\") = \"type\", pybind11::arg(\"log_x\") = true,\n pybind11::arg(\"log_y\") = true);\n\n fig.attr(\"write_html\")(\"blur_sine_tikhonov_norms.html\");\n fig.attr(\"write_image\")(\"blur_sine_tikhonov_norms.png\");\n}\n", "meta": {"hexsha": "ea91162da2c0052594819793abcde819b183ae58", "size": 4675, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/regularization/blur_sine_tikhonov.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/regularization/blur_sine_tikhonov.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/regularization/blur_sine_tikhonov.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4, "max_line_length": 79, "alphanum_fraction": 0.6793582888, "num_tokens": 1143, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.694705728642979}} {"text": "// faces_angles.cpp\n/*\n * Calculates all angles between crystal grids\n * (C) 2006 olegabr. All rights reserved.\n*/\n\n#include \nusing std::cout; using std::endl;\n\n#include \nusing std::sqrt;\n\n#include \nusing std::vector;\n\n#include \nusing std::multimap;\n\n#include \nusing std::pair; using std::make_pair;\n\n#include \n#include \n\n#include \ntypedef point3d face_t;\n\ntypedef boost::array hkl_array;\n\nstruct face_pair\n{\n\tface_t face1;\n\tface_t face2;\n\tfriend bool operator == (face_pair const& lh, face_pair const& rh) {\n\t\treturn\n\t\t\tlh.face1 == rh.face1 &&\n\t\t\tlh.face2 == rh.face2;\n\t}\n\tfriend bool operator != (face_pair const& lh, face_pair const& rh) {\n\t\treturn !(lh == rh);\n\t}\n};\n\nstruct face_triple\n{\n\tface_t face1;\n\tface_t face2;\n\tface_t face3;\n};\n\nnamespace {\n\tdouble calc_angle(face_t const& face1, face_t const& face2)\n\t{\n\t\tdouble dCosAngle = face1 * face2 / (norm(face1) * norm(face2));\n\t\tdouble dAngleRadians = std::acos(dCosAngle);\n\t\tdouble dAngleDegrees = 180.0 - 180.0 * dAngleRadians / 3.14159265358979323F;\n\t\treturn dAngleDegrees;\n\t}\n\n\tvoid print_faces(hkl_array const& arrHKL)\n\t{\n\t\thkl_array::const_iterator iHKL = arrHKL.begin();\n\t\thkl_array::const_iterator hklEnd = arrHKL.end();\n\t\tfor (; iHKL != hklEnd; ++iHKL) {\n\t\t\thkl_array::const_iterator jHKL = iHKL;\n\t\t\tfor (++jHKL; jHKL != hklEnd; ++jHKL) {\n\t\t\t\tcout\n\t\t\t\t\t<< iHKL->x << iHKL->y << iHKL->z\n\t\t\t\t\t<< '\\t'\n\t\t\t\t\t<< jHKL->x << jHKL->y << jHKL->z\n\t\t\t\t\t<< '\\t'\n\t\t\t\t\t<< calc_angle(*iHKL, *jHKL) << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n\n\tvector< face_pair >\n\tcalc_faces(hkl_array const& arrHKL, double dAngle12, double dAngleErrorMin, double dAngleErrorMax)\n\t{\n\t\tmultimap< double/*angle error*/, face_pair > mapFaces;\n\n\t\thkl_array::const_iterator iHKL = arrHKL.begin();\n\t\thkl_array::const_iterator hklEnd = arrHKL.end();\n\t\tfor (; iHKL != hklEnd; ++iHKL) {\n\t\t\thkl_array::const_iterator jHKL = iHKL;\n\t\t\tfor (++jHKL; jHKL != hklEnd; ++jHKL) {\n\t\t\t\tdouble dAngle = calc_angle(*iHKL, *jHKL);\n\t\t\t\tdouble dAngleDelta = fabs(dAngle - dAngle12);\n\t\t\t\tif (dAngleDelta >= dAngleErrorMin && dAngleDelta <= dAngleErrorMax) {\n\t\t\t\t\tface_pair pr;\n\t\t\t\t\tpr.face1 = *iHKL;\n\t\t\t\t\tpr.face2 = *jHKL;\n\t\t\t\t\tmapFaces.insert(make_pair(dAngleDelta, pr));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvector< face_pair > vecFaces;\n\t\tvecFaces.reserve(mapFaces.size());\n\n\t\tmultimap< double, face_pair >::const_iterator iterMap = mapFaces.begin();\n\t\tmultimap< double, face_pair >::const_iterator iterMapEnd = mapFaces.end();\n\t\tfor(; iterMap != iterMapEnd; ++iterMap) {\n\t\t\tvecFaces.push_back(iterMap->second);\n\t\t}\n\n\t\treturn vecFaces;\n\t}\n\n\tvoid print_faces_pairs(vector< face_pair > const& vecFaces, double dAngle12)\n\t{\n\t\tvector< face_pair >::const_iterator iHKL = vecFaces.begin();\n\t\tvector< face_pair >::const_iterator hklEnd = vecFaces.end();\n\t\tfor (; iHKL != hklEnd; ++iHKL) {\n\t\t\tface_t f1 = iHKL->face1;\n\t\t\tface_t f2 = iHKL->face2;\n\t\t\tdouble dAngle = calc_angle(f1, f2);\n\t\t\tdouble dErr = fabs(dAngle - dAngle12);\n\t\t\tdErr = dErr >= 0.01 ? dErr : 0.0;\n\t\t\tcout\n\t\t\t\t<< f1.x << f1.y << f1.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< f2.x << f2.y << f2.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dErr\n\t\t\t\t<< \"\\n\";\n\t\t}\n\t}\n\n\tvoid print_faces_within_error_bounds(hkl_array const& arrHKL, double dAngle12, double dAngleErrorMin, double dAngleErrorMax)\n\t{\n\t\tvector< face_pair > vecFaces;\n\t\tvecFaces = calc_faces(arrHKL, dAngle12, dAngleErrorMin, dAngleErrorMax);\n\t\tif (!vecFaces.empty()) {\n\t\t\tcout << \"Angle error is in range [\" << dAngleErrorMin << \", \" << dAngleErrorMax << \"]\\n\";\n\t\t\tprint_faces_pairs(vecFaces, dAngle12);\n\t\t\tcout << \"\\n\";\n\t\t}\n\t}\n\n\tvoid print_faces_triples(vector< face_triple > const& vecFaces, double dAngle12, double dAngle23)\n\t{\n\t\tvector< face_triple >::const_iterator iHKL = vecFaces.begin();\n\t\tvector< face_triple >::const_iterator hklEnd = vecFaces.end();\n\t\tfor (; iHKL != hklEnd; ++iHKL) {\n\t\t\tface_t f1 = iHKL->face1;\n\t\t\tface_t f2 = iHKL->face2;\n\t\t\tface_t f3 = iHKL->face3;\n\t\t\tdouble dAngle1 = calc_angle(f1, f2);\n\t\t\tdouble dAngle2 = calc_angle(f2, f3);\n\t\t\tdouble dAngle3 = calc_angle(f3, f1);\n\n\t\t\tdouble dErr1 = fabs(dAngle1 - dAngle12);\n\t\t\tdErr1 = dErr1 >= 0.01 ? dErr1 : 0.0;\n\n\t\t\tdouble dErr2 = fabs(dAngle2 - dAngle23);\n\t\t\tdErr2 = dErr2 >= 0.01 ? dErr2 : 0.0;\n\n\t\t\tcout\n\t\t\t\t<< f1.x << f1.y << f1.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< f2.x << f2.y << f2.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< f3.x << f3.y << f3.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle1\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dErr1\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle2\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dErr2\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle3\n\t\t\t\t<< \"\\n\";\n\t\t}\n\t}\n\n\tvoid print_faces_within_error_bounds(\n\t\thkl_array const& arrHKL,\n\t\tdouble dAngle12,\n\t\tdouble dAngle23,\n\t\tdouble dAngleErrorMin, double dAngleErrorMax\n\t)\n\t{\n\t\tvector< face_pair > vecFaces12;\n\t\tvecFaces12 = calc_faces(arrHKL, dAngle12, dAngleErrorMin, dAngleErrorMax);\n\n\t\tvector< face_pair > vecFaces23;\n\t\tvecFaces23 = calc_faces(arrHKL, dAngle23, dAngleErrorMin, dAngleErrorMax);\n\n\t\tif (!vecFaces12.empty() && !vecFaces23.empty()) {\n\t\t\tvector vecFaceTriples;\n\n\t\t\tvector< face_pair >::const_iterator iterFacePair12 = vecFaces12.begin();\n\t\t\tvector< face_pair >::const_iterator iterFacePair12End = vecFaces12.end();\n\t\t\tfor (; iterFacePair12 != iterFacePair12End; ++iterFacePair12) {\n\t\t\t\tvector< face_pair >::const_iterator iterFacePair23 = vecFaces23.begin();\n\t\t\t\tvector< face_pair >::const_iterator iterFacePair23End = vecFaces23.end();\n\t\t\t\tfor (; iterFacePair23 != iterFacePair23End; ++iterFacePair23) {\n\t\t\t\t\tif (*iterFacePair12 != *iterFacePair23) {\n\t\t\t\t\t\tif (iterFacePair12->face1 == iterFacePair23->face1) {\n\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face2;\n\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face1;\n\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face2;\n\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t} else if (iterFacePair12->face1 == iterFacePair23->face2) {\n\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face2;\n\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face1;\n\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face1;\n\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t} else if (iterFacePair12->face2 == iterFacePair23->face1) {\n\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face1;\n\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face2;\n\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face2;\n\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t} else if (iterFacePair12->face2 == iterFacePair23->face2) {\n\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face1;\n\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face2;\n\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face1;\n\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\tcout << \"Angle error is in range [\" << dAngleErrorMin << \", \" << dAngleErrorMax << \"]\\n\";\n\t\t\tprint_faces_triples(vecFaceTriples, dAngle12, dAngle23);\n\t\t\tcout << \"\\n\";\n\t\t}\n\t}\n\n\tvoid print_faces_triples(vector< face_triple > const& vecFaces, double dAngle12, double dAngle23, double dAngle31)\n\t{\n\t\tvector< face_triple >::const_iterator iHKL = vecFaces.begin();\n\t\tvector< face_triple >::const_iterator hklEnd = vecFaces.end();\n\t\tfor (; iHKL != hklEnd; ++iHKL) {\n\t\t\tface_t f1 = iHKL->face1;\n\t\t\tface_t f2 = iHKL->face2;\n\t\t\tface_t f3 = iHKL->face3;\n\t\t\tdouble dAngle1 = calc_angle(f1, f2);\n\t\t\tdouble dAngle2 = calc_angle(f2, f3);\n\t\t\tdouble dAngle3 = calc_angle(f3, f1);\n\n\t\t\tdouble dErr1 = fabs(dAngle1 - dAngle12);\n\t\t\tdErr1 = dErr1 >= 0.01 ? dErr1 : 0.0;\n\n\t\t\tdouble dErr2 = fabs(dAngle2 - dAngle23);\n\t\t\tdErr2 = dErr2 >= 0.01 ? dErr2 : 0.0;\n\n\t\t\tdouble dErr3 = fabs(dAngle3 - dAngle31);\n\t\t\tdErr3 = dErr3 >= 0.01 ? dErr3 : 0.0;\n\n\t\t\tcout\n\t\t\t\t<< f1.x << f1.y << f1.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< f2.x << f2.y << f2.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< f3.x << f3.y << f3.z\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle1\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dErr1\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle2\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dErr2\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dAngle3\n\t\t\t\t<< '\\t'\n\t\t\t\t<< dErr3\n\t\t\t\t<< \"\\n\";\n\t\t}\n\t}\n\n\tvoid print_faces_within_error_bounds(\n\t\thkl_array const& arrHKL,\n\t\tdouble dAngle12,\n\t\tdouble dAngle23,\n\t\tdouble dAngle31,\n\t\tdouble dAngleErrorMin, double dAngleErrorMax\n\t)\n\t{\n\t\tvector< face_pair > vecFaces12;\n\t\tvecFaces12 = calc_faces(arrHKL, dAngle12, dAngleErrorMin, dAngleErrorMax);\n\n\t\tvector< face_pair > vecFaces23;\n\t\tvecFaces23 = calc_faces(arrHKL, dAngle23, dAngleErrorMin, dAngleErrorMax);\n\n\t\tif (!vecFaces12.empty() && !vecFaces23.empty()) {\n\t\t\tvector vecFaceTriples;\n\n\t\t\tvector< face_pair >::const_iterator iterFacePair12 = vecFaces12.begin();\n\t\t\tvector< face_pair >::const_iterator iterFacePair12End = vecFaces12.end();\n\t\t\tfor (; iterFacePair12 != iterFacePair12End; ++iterFacePair12) {\n\t\t\t\tvector< face_pair >::const_iterator iterFacePair23 = vecFaces23.begin();\n\t\t\t\tvector< face_pair >::const_iterator iterFacePair23End = vecFaces23.end();\n\t\t\t\tfor (; iterFacePair23 != iterFacePair23End; ++iterFacePair23) {\n\t\t\t\t\tif (*iterFacePair12 != *iterFacePair23) {\n\t\t\t\t\t\tif (iterFacePair12->face1 == iterFacePair23->face1) {\n\t\t\t\t\t\t\tdouble dAngle = calc_angle(iterFacePair12->face2, iterFacePair23->face2);\n\t\t\t\t\t\t\tdouble dErr = fabs(dAngle - dAngle31);\n\t\t\t\t\t\t\tdErr = dErr >= 0.01 ? dErr : 0;\n\t\t\t\t\t\t\tif (dErr >= dAngleErrorMin && dErr <= dAngleErrorMax) {\n\t\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face2;\n\t\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face1;\n\t\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face2;\n\t\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (iterFacePair12->face1 == iterFacePair23->face2) {\n\t\t\t\t\t\t\tdouble dAngle = calc_angle(iterFacePair12->face2, iterFacePair23->face1);\n\t\t\t\t\t\t\tdouble dErr = fabs(dAngle - dAngle31);\n\t\t\t\t\t\t\tdErr = dErr >= 0.01 ? dErr : 0;\n\t\t\t\t\t\t\tif (dErr >= dAngleErrorMin && dErr <= dAngleErrorMax) {\n\t\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face2;\n\t\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face1;\n\t\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face1;\n\t\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (iterFacePair12->face2 == iterFacePair23->face1) {\n\t\t\t\t\t\t\tdouble dAngle = calc_angle(iterFacePair12->face1, iterFacePair23->face2);\n\t\t\t\t\t\t\tdouble dErr = fabs(dAngle - dAngle31);\n\t\t\t\t\t\t\tdErr = dErr >= 0.01 ? dErr : 0;\n\t\t\t\t\t\t\tif (dErr >= dAngleErrorMin && dErr <= dAngleErrorMax) {\n\t\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face1;\n\t\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face2;\n\t\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face2;\n\t\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else if (iterFacePair12->face2 == iterFacePair23->face2) {\n\t\t\t\t\t\t\tdouble dAngle = calc_angle(iterFacePair12->face1, iterFacePair23->face1);\n\t\t\t\t\t\t\tdouble dErr = fabs(dAngle - dAngle31);\n\t\t\t\t\t\t\tdErr = dErr >= 0.01 ? dErr : 0;\n\t\t\t\t\t\t\tif (dErr >= dAngleErrorMin && dErr <= dAngleErrorMax) {\n\t\t\t\t\t\t\t\tface_triple triple;\n\t\t\t\t\t\t\t\ttriple.face1 = iterFacePair12->face1;\n\t\t\t\t\t\t\t\ttriple.face2 = iterFacePair12->face2;\n\t\t\t\t\t\t\t\ttriple.face3 = iterFacePair23->face1;\n\t\t\t\t\t\t\t\tvecFaceTriples.push_back(triple);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!vecFaceTriples.empty()) {\n\t\t\t\tcout << \"Angle error is in range [\" << dAngleErrorMin << \", \" << dAngleErrorMax << \"]\\n\";\n\t\t\t\tprint_faces_triples(vecFaceTriples, dAngle12, dAngle23, dAngle31);\n\t\t\t\tcout << \"\\n\";\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid usage()\n\t{\n\t\tcout\n\t\t\t<< \"up to 3 angles between 3 faces (in degrees):\\n\"\n\t\t\t \"f1 f2 f3 => angle12 [angle23 [angle31]]\"\n\t\t\t<< endl;\n\t}\n}\n\nusing std::fixed;\n\nint main(int argc, char* argv[])\ntry {\n\thkl_array arrHKL =\n\t{\n\t\tface_t(1.0, 1.0, 1.0),\n\n\t\tface_t(1.0, 1.0, 0.0),\n\t\tface_t(1.0, 0.0, 1.0),\n\t\tface_t(0.0, 1.0, 1.0),\n\n\t\tface_t(1.0, 0.0, 0.0),\n\t\tface_t(0.0, 0.0, 1.0),\n\t\tface_t(0.0, 1.0, 0.0),\n\n\t\tface_t(1.0, 1.0, 2.0),\n\t\tface_t(2.0, 1.0, 1.0),\n\t\tface_t(1.0, 2.0, 1.0),\n\n\t\tface_t(2.0, 1.0, 0.0),\n\t\tface_t(1.0, 2.0, 0.0),\n\t\tface_t(1.0, 0.0, 2.0),\n\t\tface_t(2.0, 0.0, 1.0),\n\t\tface_t(0.0, 2.0, 1.0),\n\t\tface_t(0.0, 1.0, 2.0),\n\n\t\tface_t(1.0, 2.0, 2.0),\n\t\tface_t(2.0, 1.0, 2.0),\n\t\tface_t(2.0, 2.0, 1.0)\n\t};\n\n\t//cout.precision(2);\n\t//cout << fixed;\n\n\tswitch(argc) {\n\t\tcase 1 :\n\t\t\tprint_faces(arrHKL);\n\t\t\tbreak;\n\t\tcase 2 : // angle12 in degrees\n\t\t\t{\n\t\t\t\tdouble dAngle12 = boost::lexical_cast(argv[1]);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, 0.0, 1.0);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, 1.0, 2.0);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, 2.0, 3.0);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, 3.0, 4.0);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, 4.0, 5.0);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, 5.0, 6.0);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 3 : // angle12 angle23\n\t\t\t{\n\t\t\t\tdouble dAngle12 = boost::lexical_cast(argv[1]);\n\t\t\t\tdouble dAngle23 = boost::lexical_cast(argv[2]);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 0.0, 5.0);\n\t\t\t\t////print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 0.0, 1.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 1.0, 2.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 2.0, 3.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 3.0, 4.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 4.0, 5.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, 5.0, 6.0);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase 4 : // angle12 angle23 angle31\n\t\t\t{\n\t\t\t\tdouble dAngle12 = boost::lexical_cast(argv[1]);\n\t\t\t\tdouble dAngle23 = boost::lexical_cast(argv[2]);\n\t\t\t\tdouble dAngle31 = boost::lexical_cast(argv[3]);\n\t\t\t\tprint_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 0.0, 5.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 0.0, 1.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 1.0, 2.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 2.0, 3.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 3.0, 4.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 4.0, 5.0);\n\t\t\t\t//print_faces_within_error_bounds(arrHKL, dAngle12, dAngle23, dAngle31, 5.0, 6.0);\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault :\n\t\t\tusage();\n\t\t\tbreak;\n\t}\n\n\treturn 0;\n}\ncatch (std::exception &e) {\n\tcout << e.what() << endl;\n\treturn 1;\n}\ncatch (...) {\n\tcout << \"Unknown exception occured.\" << endl;\n\treturn 1;\n}\n", "meta": {"hexsha": "52bebdbfa2be0842d6caa0912bea49a6ec013c5a", "size": 14134, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "faces_angles/faces_angles.cpp", "max_stars_repo_name": "olegabr/tomo3d", "max_stars_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-01-07T12:27:58.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T06:58:42.000Z", "max_issues_repo_path": "faces_angles/faces_angles.cpp", "max_issues_repo_name": "olegabr/tomo3d", "max_issues_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "faces_angles/faces_angles.cpp", "max_forks_repo_name": "olegabr/tomo3d", "max_forks_repo_head_hexsha": "36ffca69aba8556170ec7330271eb58ebaf7459b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-10T10:22:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-10T10:22:13.000Z", "avg_line_length": 30.3956989247, "max_line_length": 125, "alphanum_fraction": 0.6448988255, "num_tokens": 4943, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6947057110723989}} {"text": "// The MIT License \n// (c) 2019 Daniel Williams\n\n#include \n#include \n#include \n\n#include \n\n#include \"geometry/cell_value.hpp\"\n#include \"geometry/sample.hpp\"\n\nusing std::cerr;\nusing std::endl;\nusing std::make_unique;\nusing std::string;\nusing std::unique_ptr;\n\nusing Eigen::Vector2d;\n\n\nnamespace terrain::geometry {\n\ncell_value_t interpolate_linear(const Eigen::Vector2d& to, const Sample& s1, const Sample& s2){\n if(s1.at.isApprox(s2.at)){\n return s1.is;\n }\n\n // distances from query point to each interpolation point\n const double dist1 = (s1.at - to).norm();\n const double dist2 = (s2.at - to).norm();\n\n // If the point is farther than from a point than the distance between the two interpolation points, \n // return the value at one of the end-points.\n // This is not perfect, but it's a reasonable heuristic.\n // ... in particular, it will return odd values at large distances\n // ... arguably, this should return a NAN value instead -- for not-applicable\n const double dist12 = (s1.at - s2.at).norm();\n if(dist12 < dist1){\n return s2.is;\n }else if( dist12 < dist2){\n return s1.is;\n }\n\n const double combined_distance = dist1 + dist2;\n const double normdist1 = 1 - dist1 / combined_distance;\n const double normdist2 = 1 - dist2 / combined_distance;\n const double interp_value = (normdist1*s1.is + normdist2*s2.is);\n\n return round(interp_value);\n}\n\ncell_value_t interpolate_bilinear( const Eigen::Vector2d& to, \n const Sample& ne,\n const Sample& nw,\n const Sample& sw,\n const Sample& se)\n{\n // cerr << \" ==>> to: @\" << to[0] << \", \" << to[1] << endl;\n // cerr << \" - NE: \" << ne.at[0] << \", \" << ne.at[1] << \" = \" << (int)ne.is << endl;\n // cerr << \" - NW: \" << nw.at[0] << \", \" << nw.at[1] << \" = \" << (int)nw.is << endl;\n // cerr << \" - SW: \" << sw.at[0] << \", \" << sw.at[1] << \" = \" << (int)sw.is << endl;\n // cerr << \" - SE: \" << se.at[0] << \", \" << se.at[1] << \" = \" << (int)se.is << endl;\n\n // not necessary ?\n // // test for degenerate cases:\n // if( &sx == &sd ){\n // // top or bottom border\n // return interpolate_linear(to, {to[0], xn.at[1]}, xn);\n // }else if( &sy == &sd ){\n // // left or right border\n // return interpolate_linear({yn[0], to[1]}, yn);\n // }\n\n // calculate full bilinear interpolation:\n const Eigen::Vector2d upper_point = {to[0], (nw.at[1] + ne.at[1])/2};\n const Sample upper_sample = { upper_point,\n interpolate_linear(upper_point, nw, ne)};\n\n\n const Eigen::Vector2d lower_point = {to[0], (sw.at[1] + se.at[1])/2};\n const Sample lower_sample = { lower_point,\n interpolate_linear(lower_point, sw, se) };\n\n // cerr << \" ::Upper: \" << upper_point[0] << \", \" << upper_point[1] << \" = \" << (int)upper_sample.is << endl;\n // cerr << \" ::Lower: \" << lower_point[0] << \", \" << lower_point[1] << \" = \" << (int)lower_sample.is << endl;\n\n return interpolate_linear(to, upper_sample, lower_sample);\n}\n\n} // namespace terrain::geometry\n", "meta": {"hexsha": "4539e45359d8969e143a2f07c8addf3d936c7df6", "size": 3339, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/geometry/interpolate.cpp", "max_stars_repo_name": "teyrana/quadtree", "max_stars_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geometry/interpolate.cpp", "max_issues_repo_name": "teyrana/quadtree", "max_issues_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-24T17:31:50.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-24T17:31:50.000Z", "max_forks_repo_path": "src/geometry/interpolate.cpp", "max_forks_repo_name": "teyrana/quadtree", "max_forks_repo_head_hexsha": "4172ad2f2e36414caebf80013a3d32e6df200945", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2934782609, "max_line_length": 123, "alphanum_fraction": 0.5438754118, "num_tokens": 907, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.7931059414036511, "lm_q1q2_score": 0.6945918767650768}} {"text": "#include \n#include \n#include \n#include \"../src/utils.h\"\n\n// Use either Eigen or Diospyros RQ routine.\n#ifdef DIOS\n#include \"dios_rq_decomposition.h\"\nstatic const char *BACKEND = \"Dios\";\n#else\n#include \"rq_decomposition.h\"\nstatic const char *BACKEND = \"Eigen\";\n#endif\n\nusing namespace theia;\nusing Eigen::Matrix3f;\nusing Eigen::Vector3f;\n\n// Copied from `util.cc` in Theia! --AS\n// Projects a 3x3 matrix to the rotation matrix in SO3 space with the closest\n// Frobenius norm. For a matrix with an SVD decomposition M = USV, the nearest\n// rotation matrix is R = UV'.\nMatrix3f ProjectToRotationMatrix(const Matrix3f& matrix) {\n Eigen::JacobiSVD svd(matrix,\n Eigen::ComputeFullU | Eigen::ComputeFullV);\n Matrix3f rotation_mat = svd.matrixU() * (svd.matrixV().transpose());\n\n // The above projection will give a matrix with a determinant +1 or -1. Valid\n // rotation matrices have a determinant of +1.\n if (rotation_mat.determinant() < 0) {\n rotation_mat *= -1.0;\n }\n\n return rotation_mat;\n}\n\n// Used as the projection matrix type.\ntypedef Eigen::Matrix Matrix3x4f;\n\n// Generate a calibration matrix from some parameters.\nvoid IntrinsicsToCalibrationMatrix(const float focal_length,\n const float skew,\n const float aspect_ratio,\n const float principal_point_x,\n const float principal_point_y,\n Matrix3f* calibration_matrix) {\n *calibration_matrix <<\n focal_length, skew, principal_point_x,\n 0, focal_length * aspect_ratio, principal_point_y,\n 0, 0, 1.0;\n}\n\n// Generate a projection matrix from a rotation and position.\nbool ComposeProjectionMatrix(const Matrix3f& calibration_matrix,\n const Vector3f& rotation,\n const Vector3f& position,\n Matrix3x4f* pmatrix) {\n const double rotation_angle = rotation.norm();\n if (rotation_angle == 0) {\n pmatrix->block<3, 3>(0, 0) = Matrix3f::Identity();\n } else {\n pmatrix->block<3, 3>(0, 0) = Eigen::AngleAxisf(\n rotation_angle, rotation / rotation_angle).toRotationMatrix();\n }\n\n pmatrix->col(3) = - (pmatrix->block<3, 3>(0, 0) * position);\n *pmatrix = calibration_matrix * (*pmatrix);\n return true;\n}\n\nbool DecomposeProjectionMatrix(const Matrix3x4f pmatrix,\n Eigen::Matrix3f* calibration_matrix,\n Eigen::Vector3f* rotation,\n Eigen::Vector3f* position) {\n\n#ifdef DIOS\n RQDecomposition rq(pmatrix.block<3, 3>(0, 0));\n#else\n RQDecomposition rq(pmatrix.block<3, 3>(0, 0));\n#endif\n\n Eigen::Matrix3f rotation_matrix = ProjectToRotationMatrix(rq.matrixQ());\n\n const float k_det = rq.matrixR().determinant();\n if (k_det == 0) {\n return false;\n }\n\n Eigen::Matrix3f& kmatrix = *calibration_matrix;\n if (k_det > 0) {\n kmatrix = rq.matrixR();\n } else {\n kmatrix = -rq.matrixR();\n }\n\n // Fix the matrix such that all internal parameters are greater than 0.\n for (int i = 0; i < 3; ++i) {\n if (kmatrix(i, i) < 0) {\n kmatrix.col(i) *= -1.0;\n rotation_matrix.row(i) *= -1.0;\n }\n }\n\n // Solve for t.\n const Eigen::Vector3f t =\n kmatrix.triangularView().solve(pmatrix.col(3));\n\n // c = - R' * t, and flip the sign according to k_det;\n if (k_det > 0) {\n *position = - rotation_matrix.transpose() * t;\n } else {\n *position = rotation_matrix.transpose() * t;\n }\n\n const Eigen::AngleAxisf rotation_aa(rotation_matrix);\n *rotation = rotation_aa.angle() * rotation_aa.axis();\n\n return true;\n}\n\nint main() {\n int time = 0;\n\n // Create a projection matrix from \"raw materials.\"\n Matrix3f in_calibration;\n IntrinsicsToCalibrationMatrix(0.3, 0.2, 0.4, 0.5, 0.6, &in_calibration);\n Vector3f in_rotation;\n in_rotation << 0.3, 0.7, 0.2;\n Vector3f in_position;\n in_position << 0.9, 0.1, 0.6;\n Matrix3x4f random_pmatrix;\n ComposeProjectionMatrix(in_calibration, in_rotation, in_position, &random_pmatrix);\n\n Matrix3f calibration_matrix;\n Vector3f rotation, position;\n\n start_cycle_timing;\n bool success = DecomposeProjectionMatrix(random_pmatrix,\n &calibration_matrix,\n &rotation,\n &position);\n stop_cycle_timing;\n time = get_time();\n printf(\"DecomposeProjectionMatrix - %s: %d cycles\\n\", BACKEND, time);\n\n std::cout << \"Input:\" << std::endl << random_pmatrix << std::endl;\n std::cout << \"Rotation:\" << std::endl << rotation << std::endl;\n std::cout << \"Position:\" << std::endl << position << std::endl;\n return 0;\n}\n", "meta": {"hexsha": "3da8043300d87268af8baa5ea6dff79601260989", "size": 4837, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "evaluation/theia/decompose-projection-matrix.cpp", "max_stars_repo_name": "sgpthomas/diospyros", "max_stars_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-02-16T22:26:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T04:17:19.000Z", "max_issues_repo_path": "evaluation/theia/decompose-projection-matrix.cpp", "max_issues_repo_name": "sgpthomas/diospyros", "max_issues_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T15:37:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T19:48:43.000Z", "max_forks_repo_path": "evaluation/theia/decompose-projection-matrix.cpp", "max_forks_repo_name": "sgpthomas/diospyros", "max_forks_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T20:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T20:35:15.000Z", "avg_line_length": 32.0331125828, "max_line_length": 85, "alphanum_fraction": 0.6222865412, "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869819218865, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6945918651904204}} {"text": "#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\ndouble compute_probability_from_distance(const double distance, const bool left_tail) {\n\tdouble prob;\n\tif (left_tail) {\n\t\tprob = (double) 1.0 - distance;\n\t} else {\n\t\tprob = distance;\n\t}\n\tif (isnan(prob)) {\n\t\tthrow runtime_error(\"compute_probability_from_distance: NaN values encountered\");\n\t}\n\treturn prob;\n}\n\nxt::xarray compute_probabilities_from_distance(const vector& distances, const bool left_tail) {\n\txt::xarray probabilities = xt::zeros({distances.size()});\n\tfor (int i = 0; i < distances.size(); ++i) {\n\t\tprobabilities[i] = compute_probability_from_distance(distances[i], left_tail);\n\t}\n\treturn probabilities;\n}\n\nxt::xarray compute_baseline_probabilities(const xt::xarray& probabilities) {\n\txt::xarray baseline = xt::zeros({probabilities.size()});\n\tdouble mean = xt::mean(probabilities)();\n\tfor (int j = 0; j < probabilities.size(); ++j) {\n\t\tbaseline[j] = mean;\n\t}\n\treturn baseline;\n}\n\nclass GeneProbabilies {\n\tvector keys;\n\tunordered_map lookup;\n\txt::xarray probabilities;\n\txt::xarray random_probabilities;\n\n\tpublic:\n\t\tGeneProbabilies(istream& is, const string& tail) :keys{}, lookup{} {\n\t\t\tif (tail != \"left\" && tail != \"right\") {\n\t\t\t\tthrow runtime_error(\n\t\t\t\t\t\"GeneProbabilies: tail argument must be one of left, right \"\n\t\t\t\t\t\"but got: \" + tail\n\t\t\t\t);\n\t\t\t}\n\t\t\tstring line;\n\t\t\tint i = 0;\n\t\t\tvector distances;\n\t\t\twhile (getline(is, line)) {\n\t\t\t\tif (i == 0 || line.empty()) {\n\t\t\t\t\t++i;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tvector elements;\n\t\t\t\tboost::split(elements, line, boost::is_any_of(\",\"));\n\t\t\t\tif (elements.size() != 2) {\n\t\t\t\t\tthrow runtime_error(\n\t\t\t\t\t\t\"GeneProbabilies: 2 columns expected \"\n\t\t\t\t\t\t\"but got: \" + to_string(elements.size())\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tstring key = elements[0];\n\t\t\t\tkeys.push_back(key);\n\t\t\t\tlookup[key] = i-1;\n\n\t\t\t\tdouble distance = stod(elements[1]);\n\t\t\t\tdistances.push_back(distance);\n\t\t\t\t++i;\n\t\t\t}\n\n\t\t\tif (distances.empty()) {\n\t\t\t\tthrow runtime_error(\"GeneProbabilies: no data\");\n\t\t\t}\n\n\t\t\tprobabilities = compute_probabilities_from_distance(distances, tail == \"left\");\t\n\t\t\trandom_probabilities = compute_baseline_probabilities(probabilities);\n\t\t}\n\n\t\tdouble operator[](const string& id) {\n\t\t\treturn probabilities[lookup[id]];\n\t\t}\n\n\t\tdouble Get(const string& id, const bool random = false) {\n\t\t\tif (!random) {\n\t\t\t\treturn probabilities[lookup[id]];\n\t\t\t} else {\n\t\t\t\treturn random_probabilities[lookup[id]];\n\t\t\t}\n\t\t}\n\n\t\tsize_t IndexOf(const string& id) {\n\t\t\treturn lookup[id];\n\t\t}\n\n\t\tvector& Keys() {\n\t\t\treturn keys;\n\t\t}\n\n\t\txt::xarray& Values() {\n\t\t\treturn probabilities;\n\t\t}\n\n\t\txt::xarray& RandomValues() {\n\t\t\treturn random_probabilities;\n\t\t}\n\n\t\tsize_t size() {\n\t\t\treturn lookup.size();\n\t\t}\n};\n\nxt::xarray make_uniform_prior(const size_t n_elements) {\n\treturn xt::ones({n_elements}) / n_elements;\n}\n\nxt::xarray make_uniform_prior(const size_t n_rows, const size_t n_cols) {\n\treturn xt::ones({n_rows, n_cols}) / n_cols;\n}\n\ndouble normalize_probability(const double& probability, const size_t& n_elements) {\n\treturn exp(log(probability) / n_elements);\n}\n", "meta": {"hexsha": "e301d51bf7d1c011b5a2826f322e82c6a6fe04d3", "size": 3383, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/probability/probability_util.cpp", "max_stars_repo_name": "srom/nbias", "max_stars_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/probability/probability_util.cpp", "max_issues_repo_name": "srom/nbias", "max_issues_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/probability/probability_util.cpp", "max_forks_repo_name": "srom/nbias", "max_forks_repo_head_hexsha": "be8cf8dd623038dcf08d38ed3d19f635ee2dbeae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2462686567, "max_line_length": 111, "alphanum_fraction": 0.6783919598, "num_tokens": 883, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004186, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.6944231755247322}} {"text": "#include \"utils.hpp\"\n\n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nusing Bint = boost::multiprecision::cpp_int;\n\n//return f s.t. q^f generate_primes(unsigned long MAX);\n\nstring PminusOneFactorizer_step1_cppfunc(string s, unsigned long M){\n Bint n(s);\n Bint A(\"2\");\n if(n%A==0){\n return A.str();\n }\n for(unsigned long p : generate_primes(M)){\n unsigned long f = get_f(p, M);\n Bint Mp = pow(Bint(p), f);\n A = powm(A, Mp, n);\n }\n Bint retval = gcd(A-1, n);\n return retval.str();\n}\n\nstring PminusOneFactorizer_step2_cppfunc(string s, unsigned long M, unsigned long L){\n Bint n(s);\n Bint A(\"2\");\n if(n%A==0){\n return A.str();\n }\n for(unsigned long p : generate_primes(L)){\n if(p generate_primes(unsigned long MAX){ // we have to make this more smart...\n vector v(MAX+1, true);\n v.at(0) = false;\n v.at(1) = false;\n vector retval;\n retval.clear();\n unsigned long sqrt_MAX = (unsigned long)sqrt(MAX);\n for(unsigned long i=2;i<=MAX;i++){\n if(!v.at(i)){\n continue;\n } \n retval.push_back(i);\n if(i>sqrt_MAX+1){continue;}\n for(unsigned long k=2;k*i<=MAX;k++){\n v.at(k*i) = false;\n }\n }\n return retval;\n}", "meta": {"hexsha": "85d7b2e993096a504a983882d8d836e125d69e3a", "size": 2094, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PminusOneFactorizer_cpp.cpp", "max_stars_repo_name": "FullteaR/factorizer", "max_stars_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PminusOneFactorizer_cpp.cpp", "max_issues_repo_name": "FullteaR/factorizer", "max_issues_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PminusOneFactorizer_cpp.cpp", "max_forks_repo_name": "FullteaR/factorizer", "max_forks_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2289156627, "max_line_length": 95, "alphanum_fraction": 0.553008596, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.890294223211224, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6944231732419998}} {"text": "//==============================================================================\r\n// Copyright 2011-2014 Karsten Ahnert\r\n// Copyright 2011-2014 Mario Mulansky\r\n// Copyright 2014 LRI UMR 8623 CNRS/Univ Paris Sud XI\r\n// Copyright 2014 NumScale SAS\r\n//\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// See accompanying file LICENSE.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt\r\n//==============================================================================\r\n\r\n#include \r\n#include \r\n\r\n#include \r\n\r\n#ifndef M_PI //not there on windows\r\n#define M_PI 3.141592653589793 //...\r\n#endif\r\n\r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\n\r\ntemplate \r\npair< T, T > calc_mean_field( const container_type &x )\r\n\r\n{\r\n T cos_sum = 0.0 , sin_sum = 0.0;\r\n\r\n nt2::tie(cos_sum,sin_sum) = nt2::tie(nt2::mean( nt2::cos(x) ), nt2::mean( nt2::sin(x) ));\r\n\r\n T K = nt2::hypot(sin_sum,cos_sum);\r\n T Theta = nt2::atan2( sin_sum , cos_sum );\r\n\r\n return make_pair( K , Theta );\r\n}\r\n\r\ntemplate \r\nstruct phase_ensemble\r\n{\r\n typedef typename boost::dispatch::meta::as_integer::type int_type;\r\n container_type m_omega;\r\n T m_epsilon;\r\n\r\n phase_ensemble( const int_type n , T g = 1.0 , T epsilon = 1.0 )\r\n : m_epsilon( epsilon )\r\n {\r\n m_omega = nt2::zeros(nt2::of_size(n), nt2::meta::as_());\r\n create_frequencies( g );\r\n }\r\n\r\n void create_frequencies( T g )\r\n {\r\n boost::mt19937 rng;\r\n boost::cauchy_distribution<> cauchy( 0.0 , g );\r\n boost::variate_generator< boost::mt19937&, boost::cauchy_distribution<> > gen( rng , cauchy );\r\n generate( m_omega.begin() , m_omega.end() , gen );\r\n}\r\n\r\n void set_epsilon( T epsilon ) { m_epsilon = epsilon; }\r\n\r\n T get_epsilon( void ) const { return m_epsilon; }\r\n\r\n void operator()( const container_type &x , container_type &dxdt , T ) const\r\n {\r\n pair< T, T > mean = calc_mean_field( x );\r\n dxdt = m_omega + m_epsilon * mean.first * nt2::sin( mean.second - x );\r\n }\r\n};\r\n\r\ntemplate\r\nstruct statistics_observer\r\n{\r\n typedef typename boost::dispatch::meta::as_integer::type int_type;\r\n T m_K_mean;\r\n int_type m_count;\r\n\r\n statistics_observer( void )\r\n : m_K_mean( 0.0 ) , m_count( 0 ) { }\r\n\r\n template< class State >\r\n void operator()( const State &x , T t )\r\n {\r\n pair< T, T > mean = calc_mean_field( x );\r\n m_K_mean += mean.first;\r\n ++m_count;\r\n }\r\n\r\n T get_K_mean( void ) const { return ( m_count != 0 ) ? m_K_mean / T( m_count ) : 0.0 ; }\r\n\r\n void reset( void ) { m_K_mean = 0.0; m_count = 0; }\r\n};\r\n\r\ntemplate\r\nstruct test_ode_table\r\n{\r\n typedef nt2::table array_type;\r\n typedef void experiment_is_immutable;\r\n\r\n typedef typename boost::dispatch::meta::as_integer::type int_type;\r\n\r\n test_ode_table ( )\r\n : size_(16384), ensemble( size_ , 1.0 ), unif( 0.0 , 2.0 * M_PI ), gen( rng , unif ), obs()\r\n {\r\n x.resize(nt2::of_size(size_));\r\n }\r\n\r\n void operator()()\r\n {\r\n for( T epsilon = 0.0 ; epsilon < 5.0 ; epsilon += 0.1 )\r\n {\r\n ensemble.set_epsilon( epsilon );\r\n obs.reset();\r\n\r\n // start with random initial conditions\r\n generate( x.begin() , x.end() , gen );\r\n // calculate some transients steps\r\n integrate_const( runge_kutta4< array_type, T >() , boost::ref( ensemble ) , x , T(0.0) , T(10.0) , dt );\r\n\r\n // integrate and compute the statistics\r\n integrate_const( runge_kutta4< array_type, T >() , boost::ref( ensemble ) , x , T(0.0) , T(100.0) , dt , boost::ref( obs ) );\r\n cout << epsilon << \"\\t\" << obs.get_K_mean() << endl;\r\n }\r\n }\r\n\r\n friend std::ostream& operator<<(std::ostream& os, test_ode_table const& p)\r\n {\r\n return os << \"(\" << p.size() << \")\";\r\n }\r\n\r\n std::size_t size() const { return size_; }\r\n\r\n private:\r\n std::size_t size_;\r\n phase_ensemble ensemble;\r\n boost::uniform_real<> unif;\r\n array_type x;\r\n boost::mt19937 rng;\r\n boost::variate_generator< boost::mt19937&, boost::uniform_real<> > gen;\r\n statistics_observer obs;\r\n\r\n static const T dt = 0.1;\r\n};\r\n\r\nint main()\r\n{\r\n std::cout<< \" With T = [double] \\n\";\r\n test_ode_table test_double;\r\n test_double();\r\n\r\n std::cout<< \" With T = [float] \\n\";\r\n test_ode_table test_float;\r\n test_float();\r\n}\r\n", "meta": {"hexsha": "99d307e74f74495014390d34970b0dbdc2c64566", "size": 5130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/nt2/phase_oscillator_ensemble.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/nt2/phase_oscillator_ensemble.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-03-04T11:21:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-24T01:36:31.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/nt2/phase_oscillator_ensemble.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 30.0, "max_line_length": 132, "alphanum_fraction": 0.5992202729, "num_tokens": 1401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898203834278, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6942542400604111}} {"text": "// Boost.Geometry\r\n\r\n// Copyright (c) 2016, Oracle and/or its affiliates.\r\n// Contributed and/or modified by Vissarion Fysikopoulos, on behalf of Oracle\r\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_FORMULAS_SPHERICAL_HPP\r\n#define BOOST_GEOMETRY_FORMULAS_SPHERICAL_HPP\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n//#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\nnamespace boost { namespace geometry {\r\n \r\nnamespace formula {\r\n\r\ntemplate \r\nstruct result_spherical\r\n{\r\n result_spherical()\r\n : azimuth(0)\r\n , reverse_azimuth(0)\r\n {}\r\n\r\n T azimuth;\r\n T reverse_azimuth;\r\n};\r\n\r\ntemplate \r\nstatic inline void sph_to_cart3d(T const& lon, T const& lat, T & x, T & y, T & z)\r\n{\r\n T const cos_lat = cos(lat);\r\n x = cos_lat * cos(lon);\r\n y = cos_lat * sin(lon);\r\n z = sin(lat);\r\n}\r\n\r\ntemplate \r\nstatic inline Point3d sph_to_cart3d(PointSph const& point_sph)\r\n{\r\n typedef typename coordinate_type::type calc_t;\r\n\r\n calc_t const lon = get_as_radian<0>(point_sph);\r\n calc_t const lat = get_as_radian<1>(point_sph);\r\n calc_t x, y, z;\r\n sph_to_cart3d(lon, lat, x, y, z);\r\n\r\n Point3d res;\r\n set<0>(res, x);\r\n set<1>(res, y);\r\n set<2>(res, z);\r\n\r\n return res;\r\n}\r\n\r\ntemplate \r\nstatic inline void cart3d_to_sph(T const& x, T const& y, T const& z, T & lon, T & lat)\r\n{\r\n lon = atan2(y, x);\r\n lat = asin(z);\r\n}\r\n\r\ntemplate \r\nstatic inline PointSph cart3d_to_sph(Point3d const& point_3d)\r\n{\r\n typedef typename coordinate_type::type coord_t;\r\n typedef typename coordinate_type::type calc_t;\r\n\r\n calc_t const x = get<0>(point_3d);\r\n calc_t const y = get<1>(point_3d);\r\n calc_t const z = get<2>(point_3d);\r\n calc_t lonr, latr;\r\n cart3d_to_sph(x, y, z, lonr, latr);\r\n\r\n PointSph res;\r\n set_from_radian<0>(res, lonr);\r\n set_from_radian<1>(res, latr);\r\n\r\n coord_t lon = get<0>(res);\r\n coord_t lat = get<1>(res);\r\n\r\n math::normalize_spheroidal_coordinates\r\n <\r\n typename coordinate_system::type::units,\r\n coord_t\r\n >(lon, lat);\r\n\r\n set<0>(res, lon);\r\n set<1>(res, lat);\r\n\r\n return res;\r\n}\r\n\r\n// -1 right\r\n// 1 left\r\n// 0 on\r\ntemplate \r\nstatic inline int sph_side_value(Point3d1 const& norm, Point3d2 const& pt)\r\n{\r\n typedef typename select_coordinate_type::type calc_t;\r\n calc_t c0 = 0;\r\n calc_t d = dot_product(norm, pt);\r\n return math::equals(d, c0) ? 0\r\n : d > c0 ? 1\r\n : -1; // d < 0\r\n}\r\n\r\ntemplate \r\nstatic inline result_spherical spherical_azimuth(T1 const& lon1,\r\n T1 const& lat1,\r\n T2 const& lon2,\r\n T2 const& lat2)\r\n{\r\n typedef result_spherical result_type;\r\n result_type result;\r\n\r\n // http://williams.best.vwh.net/avform.htm#Crs\r\n // https://en.wikipedia.org/wiki/Great-circle_navigation\r\n CT dlon = lon2 - lon1;\r\n\r\n // An optimization which should kick in often for Boxes\r\n //if ( math::equals(dlon, ReturnType(0)) )\r\n //if ( get<0>(p1) == get<0>(p2) )\r\n //{\r\n // return - sin(get_as_radian<1>(p1)) * cos_p2lat);\r\n //}\r\n\r\n CT const cos_dlon = cos(dlon);\r\n CT const sin_dlon = sin(dlon);\r\n CT const cos_lat1 = cos(lat1);\r\n CT const cos_lat2 = cos(lat2);\r\n CT const sin_lat1 = sin(lat1);\r\n CT const sin_lat2 = sin(lat2);\r\n\r\n {\r\n // \"An alternative formula, not requiring the pre-computation of d\"\r\n // In the formula below dlon is used as \"d\"\r\n CT const y = sin_dlon * cos_lat2;\r\n CT const x = cos_lat1 * sin_lat2 - sin_lat1 * cos_lat2 * cos_dlon;\r\n result.azimuth = atan2(y, x);\r\n }\r\n\r\n if (ReverseAzimuth)\r\n {\r\n CT const y = sin_dlon * cos_lat1;\r\n CT const x = sin_lat2 * cos_lat1 * cos_dlon - cos_lat2 * sin_lat1;\r\n result.reverse_azimuth = atan2(y, x);\r\n }\r\n\r\n return result;\r\n}\r\n\r\ntemplate \r\ninline ReturnType spherical_azimuth(T1 const& lon1, T1 const& lat1,\r\n T2 const& lon2, T2 const& lat2)\r\n{\r\n return spherical_azimuth(lon1, lat1, lon2, lat2).azimuth;\r\n}\r\n\r\ntemplate \r\ninline T spherical_azimuth(T const& lon1, T const& lat1, T const& lon2, T const& lat2)\r\n{\r\n return spherical_azimuth(lon1, lat1, lon2, lat2).azimuth;\r\n}\r\n\r\ntemplate \r\ninline int azimuth_side_value(T const& azi_a1_p, T const& azi_a1_a2)\r\n{\r\n T const pi = math::pi();\r\n T const two_pi = math::two_pi();\r\n\r\n // instead of the formula from XTD\r\n //calc_t a_diff = asin(sin(azi_a1_p - azi_a1_a2));\r\n\r\n T a_diff = azi_a1_p - azi_a1_a2;\r\n // normalize, angle in [-pi, pi]\r\n while (a_diff > pi)\r\n a_diff -= two_pi;\r\n while (a_diff < -pi)\r\n a_diff += two_pi;\r\n\r\n // NOTE: in general it shouldn't be required to support the pi/-pi case\r\n // because in non-cartesian systems it makes sense to check the side\r\n // only \"between\" the endpoints.\r\n // However currently the winding strategy calls the side strategy\r\n // for vertical segments to check if the point is \"between the endpoints.\r\n // This could be avoided since the side strategy is not required for that\r\n // because meridian is the shortest path. So a difference of\r\n // longitudes would be sufficient (of course normalized to [-pi, pi]).\r\n\r\n // NOTE: with the above said, the pi/-pi check is temporary\r\n // however in case if this was required\r\n // the geodesics on ellipsoid aren't \"symmetrical\"\r\n // therefore instead of comparing a_diff to pi and -pi\r\n // one should probably use inverse azimuths and compare\r\n // the difference to 0 as well\r\n\r\n // positive azimuth is on the right side\r\n return math::equals(a_diff, 0)\r\n || math::equals(a_diff, pi)\r\n || math::equals(a_diff, -pi) ? 0\r\n : a_diff > 0 ? -1 // right\r\n : 1; // left\r\n}\r\n\r\n} // namespace formula\r\n\r\n}} // namespace boost::geometry\r\n\r\n#endif // BOOST_GEOMETRY_FORMULAS_SPHERICAL_HPP\r\n", "meta": {"hexsha": "0f3e75e9e0a1c64f96368387413df51b8d35dc71", "size": 7057, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/formulas/spherical.hpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T00:12:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-05T01:52:56.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/formulas/spherical.hpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-11T00:36:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T15:39:01.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/boost/geometry/formulas/spherical.hpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2015-02-28T01:38:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-13T13:36:36.000Z", "avg_line_length": 31.3644444444, "max_line_length": 87, "alphanum_fraction": 0.6332719286, "num_tokens": 1909, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.800691997339971, "lm_q1q2_score": 0.6942285997831397}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n\ntypedef boost::multiprecision::checked_cpp_int bigint;\n\nnamespace std {\n template<> struct hash {\n size_t operator()(const bigint& x) const {\n auto mask = bigint(numeric_limits::max());\n return size_t(bigint(x & mask));\n }\n };\n} // namespace std\n\n// Solve h = g^x [mod p], using a meet-in-the-middle attack\nint main(int argc, char** argv) {\n if (argc <= 4) {\n cerr << \"Not enough arguments, usage: ./middle p g h xmax\\n\"\n << \"computes (x) s.t. h = g^x [mod p] | 0 < x < xmax\" << endl;\n }\n\n // read in the parameters of the problem\n auto p = bigint(), g = bigint(), h = bigint();\n auto xmax = uint64_t();\n istringstream(argv[1]) >> p;\n istringstream(argv[2]) >> g;\n istringstream(argv[3]) >> h;\n istringstream(argv[4]) >> xmax;\n cerr << \"# p=\" << p << \"\\n# g=\" << g << \"\\n# h=\" << h << \"\\n# xmax=\" << xmax << endl;\n\n // solve it\n const auto b = uint64_t(sqrt(xmax));\n const auto gb = powm(g, b, p);\n cerr << \"# b=\" << b << \"\\n# gb=\" << gb << endl;\n\n // // build a table of the lefts\n auto lefts = unordered_map();\n for (uint64_t x1 = 0; x1 <= b; ++x1) {\n auto gx1 = bigint(powm(g, x1, p));\n auto lhs = (h * bigint(powm(gx1, p-2, p))) % p;\n // cerr << lhs << endl;\n lefts.insert(make_pair(lhs, x1));\n }\n // // search for a matching right\n for (uint64_t x0 = 0; x0 <= b; ++x0) {\n auto rhs = powm(gb, x0, p);\n auto it = lefts.find(rhs);\n if (it != lefts.end()) {\n auto x1 = it->second;\n auto x = x0 * b + x1;\n cout << x << endl;\n cerr << \"# Check: \" << (powm(g, x, p) == h ? \"OK\" : \"Not OK\") << endl;\n return 0;\n }\n }\n cerr << \"# No solution found\" << endl;\n return 1;\n}\n", "meta": {"hexsha": "e96b717ef71bfe24f30cafe0fdc01d431dbd0d29", "size": 1865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "crypto-013/pa5/middle.cpp", "max_stars_repo_name": "DouglasOrr/Snippets", "max_stars_repo_head_hexsha": "026e15a422b518ee7d9ce4849f971c4403ad9fe8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "crypto-013/pa5/middle.cpp", "max_issues_repo_name": "DouglasOrr/Snippets", "max_issues_repo_head_hexsha": "026e15a422b518ee7d9ce4849f971c4403ad9fe8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-04-11T18:07:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-11T18:07:19.000Z", "max_forks_repo_path": "crypto-013/pa5/middle.cpp", "max_forks_repo_name": "DouglasOrr/Snippets", "max_forks_repo_head_hexsha": "026e15a422b518ee7d9ce4849f971c4403ad9fe8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.140625, "max_line_length": 87, "alphanum_fraction": 0.5544235925, "num_tokens": 602, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6942227019019015}} {"text": "//\tObjective: To implement the option class that is defined in the header file: CashOrNothingOption.hpp\r\n//\r\n// (c) Sudhansh Dua\r\n\r\n#include \"CashOrNothingOption.hpp\"\r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n\r\ndouble CashOrNothingOption::CallPrice() const\r\n{\r\n\treturn ::CashOrNothingCallPrice(S, K, cr, T, r, sig, b, type);\r\n}\r\n\r\ndouble CashOrNothingOption::PutPrice() const\r\n{\r\n\treturn ::CashOrNothingPutPrice(S, K, cr, T, r, sig, b, type);\r\n}\r\n\r\n\r\nvoid CashOrNothingOption::init()\t\t\t\t\t// Initialising all the default values\r\n{\r\n\t//\tDefault values\r\n\tT = 1;\r\n\tcr = 10;\r\n\tr = 0.08;\r\n\tsig = 0.25;\r\n\tK = 100;\r\n\tS = 100;\t\t\t//\tDefault stock price \r\n\tb = r;\t\t\t\t//\tBlack - Scholes(1973) stock option model : b = r\r\n\r\n\ttype = \"C\";\t\t\t//\tCall option as the default\r\n\r\n}\r\n\r\nvoid CashOrNothingOption::copy(const CashOrNothingOption& option)\r\n{\r\n\tcr = option.cr;\r\n\tT = option.T;\r\n\tr = option.r;\r\n\tsig = option.sig;\r\n\tK = option.K;\r\n\tb = option.b;\r\n\ttype = option.type;\r\n\tS = option.S;\r\n}\r\n\r\n//\tConstructors and destructor\r\n//\tDefault Constructor\r\nCashOrNothingOption::CashOrNothingOption() : Option()\r\n{\r\n\tinit();\r\n}\r\n\r\n//\tCopy constructor\r\nCashOrNothingOption::CashOrNothingOption(const CashOrNothingOption& option) : Option(option)\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nCashOrNothingOption::CashOrNothingOption(const double& S1, const double& K1, const double& cr1, const double& T1, const double& r1, const double& sig1,\r\n\tconst double& b1, const string type1) : Option(), S(S1), K(K1), cr(cr1), T(T1), r(r1), sig(sig1), b(b1), type(type1) {}\r\n\r\n//\tDestructor\r\nCashOrNothingOption::~CashOrNothingOption() {}\r\n\r\n\r\n//\tAssignment Operator\r\nCashOrNothingOption& CashOrNothingOption::operator = (const CashOrNothingOption& option)\r\n{\r\n\tif (this == &option)\r\n\t{\r\n\t\treturn *this;\t\t//\tSelf-assignment check!\r\n\t}\r\n\tOption::operator = (option);\r\n\tcopy(option);\r\n\treturn *this;\r\n}\r\n\r\n\r\n// Functions that calculate the option price\r\ndouble CashOrNothingOption::Price() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallPrice();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutPrice();\r\n\t}\r\n}\r\n\r\n\r\n// Modifier functions\r\nvoid CashOrNothingOption::toggle()\t\t\t\t\t\t\t\t//\tChange the option type\r\n{\r\n\ttype = ((type == \"C\") ? \"P\" : \"C\");\r\n}\r\n\r\n// Global Functions\r\ndouble CashOrNothingCallPrice(const double S, const double K, const double cr, const double T, const double r, const double sig, const double b, const string type)\r\n{\r\n\tdouble d = (log(S / K) + (b - (sig * sig * 0.5)) * T) / (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn (cr * exp(-r * T) * cdf(standard_normal, d));\r\n}\r\n\r\ndouble CashOrNothingPutPrice(const double S, const double K, const double cr, const double T, const double r, const double sig, const double b, const string type)\r\n{\r\n\tdouble d = (log(S / K) + (b - (sig * sig * 0.5)) * T) / (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn (cr * exp(-r * T) * cdf(standard_normal, -d));\r\n}\r\n\r\n", "meta": {"hexsha": "c154b3dec47eee0cad55f072bbc17256d8add8c2", "size": 3035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CashOrNothingOption.cpp", "max_stars_repo_name": "sudhanshdua/Option_Classes", "max_stars_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CashOrNothingOption.cpp", "max_issues_repo_name": "sudhanshdua/Option_Classes", "max_issues_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CashOrNothingOption.cpp", "max_forks_repo_name": "sudhanshdua/Option_Classes", "max_forks_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0826446281, "max_line_length": 164, "alphanum_fraction": 0.6550247117, "num_tokens": 852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6942214306210317}} {"text": "#include \n#include \n#include \n\n#include \"LinearCodeGenerator.h\"\n#include \"Math.h\"\n#include \n\ntemplate\nT hamming_distance(uint32_t size, I1 b1, I2 b2)\n{\n\treturn std::inner_product(b1, b1 + size, b2, T{},\n\t\tstd::plus(), std::not_equal_to());\n}\n\nint getMinHammingDistance(const int q, const int k, const arma::s32_mat &G)\n{\n\tauto language = Math::generateLanguage(q, k);\n\tlanguage.erase(language.begin());\n\n\tstd::vector codes;\n\tcodes.reserve(language.size());\n\tfor (const auto& word : language)\n\t{\n\t\tcodes.push_back(Math::encode(word, G, q));\n\t}\n\n\tauto minDistance = std::numeric_limits::max();\n\tfor (auto& codeword : codes)\n\t{\n\t\tfor (auto& codeword2 : codes)\n\t\t{\n\t\t\tconst auto distance = hamming_distance(codeword.size(), codeword.begin(), codeword2.begin());\n\t\t\tif (distance > 0 && distance < minDistance)\n\t\t\t{\n\t\t\t\tminDistance = distance;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn minDistance;\n}\n\nint main()\n{\n\t/* Parameters */\n\tconstexpr int q = 7;\n\tconstexpr int k = 3;\n\tconstexpr int b = 3;\n\n\tstd::cout << \"###### Linear Code Creator ######\" << std::endl << std::endl;\n\tstd::cout << \"q = \" << q << std::endl << \"k = \" << k << std::endl << \"b = \" << b << std::endl;\n\n\tconst LinearCodeGenerator linCodeGenerator(q, k, b);\n\n\ttry\n\t{\n\t\tconst auto linCode = linCodeGenerator.generateCode();\n\n\t\tstd::cout << \"We have now following code\" << std::endl;\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\t\tstd::cout << \"[n,k,d]_q\" << std::endl;\n\t\tstd::cout << \"[\" << linCode.n << \",\" << linCode.k << \",\" << linCode.d << \"]_\" << linCode.q << \"\" << std::endl;\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\t\tstd::cout << \"Generatormatrix G\" << std::endl;\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\t\tlinCode.G.raw_print();\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\n\n\t\tstd::cout << \"Proof Hamming Distance\" << std::endl;\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl;\n\t\tconst int minDistance = getMinHammingDistance(q, k, linCode.G);\n\t\tstd::cout << minDistance << \" = calculated distance\" << std::endl;\n\t\tstd::cout << linCode.d << \" = should be the distance\" << std::endl;\n\t\tstd::cout << \"----------------------------------------------------\" << std::endl << std::endl;\n\t}\n\tcatch (const GRBException& e) {\n\t\tstd::cout << \"Error code = \" << e.getErrorCode() << std::endl;\n\t\tstd::cout << e.getMessage() << std::endl;\n\t}\n\tcatch (...) {\n\t\tstd::cout << \"Exception during optimization\" << std::endl;\n\t}\n\n\tstd::cout << \"Press any key to exit...\";\n\tstd::cin.get();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "206d695cf026d8d3c4debaa33ed031716c9a710e", "size": 2762, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lin-code-gen/main.cpp", "max_stars_repo_name": "ZeraPain/Coding-Theory", "max_stars_repo_head_hexsha": "34e6e43e6ed65405e3c388add912e6e775e54af5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lin-code-gen/main.cpp", "max_issues_repo_name": "ZeraPain/Coding-Theory", "max_issues_repo_head_hexsha": "34e6e43e6ed65405e3c388add912e6e775e54af5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lin-code-gen/main.cpp", "max_forks_repo_name": "ZeraPain/Coding-Theory", "max_forks_repo_head_hexsha": "34e6e43e6ed65405e3c388add912e6e775e54af5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-08-01T06:02:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-01T06:02:28.000Z", "avg_line_length": 30.3516483516, "max_line_length": 112, "alphanum_fraction": 0.5347574222, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.941654159388319, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6941480445288825}} {"text": "//\r\n// Copyright (c) 2016 - 2017 Mesh Consultants Inc.\r\n// Permission is hereby granted, free of charge, to any person obtaining a copy\r\n// of this software and associated documentation files (the \"Software\"), to deal\r\n// in the Software without restriction, including without limitation the rights\r\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\n// copies of the Software, and to permit persons to whom the Software is\r\n// furnished to do so, subject to the following conditions:\r\n//\r\n// The above copyright notice and this permission notice shall be included in\r\n// all copies or substantial portions of the Software.\r\n//\r\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n// THE SOFTWARE.\r\n//\r\n\r\n\r\n#include \"Geomlib_BestFitPlane.h\"\r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\nnamespace {\r\n\r\nEigen::Vector3f ComputeCentroid(const Eigen::MatrixXf& V)\r\n{\r\n\tassert(V.rows() == 3);\r\n\r\n\tEigen::Vector3f c(0.0f, 0.0f, 0.0f);\r\n\r\n\tfor (int i = 0; i < V.cols(); ++i) {\r\n\t\tc += V.col(i);\r\n\t}\r\n\r\n\tif (V.cols() != 0) {\r\n\t\tfloat sc = (1.0f / V.cols());\r\n\t\tc *= sc;\r\n\t}\r\n\r\n\treturn c;\r\n}\r\n\r\n\r\n} // namespace\r\n\r\nvoid Geomlib::BestFitPlane(\r\n\tconst Urho3D::Vector& point_cloud,\r\n\tUrho3D::Vector3& point,\r\n\tUrho3D::Vector3& normal\r\n)\r\n{\r\n\tusing Urho3D::Vector3;\r\n\r\n\tint num_vertices = (int)point_cloud.Size();\r\n\tif (num_vertices <= 0) {\r\n\t\treturn;\r\n\t}\r\n\r\n\tEigen::MatrixXf V(3, num_vertices);\r\n\tfor (int i = 0; i < num_vertices; ++i) {\r\n\t\tVector3 vec = point_cloud[i];\r\n\t\tV.col(i) = Eigen::Vector3f(vec.x_, vec.y_, vec.z_);\r\n\t}\r\n\r\n\tEigen::Vector3f c = ComputeCentroid(V);\r\n\r\n\tEigen::MatrixXf NV = V;\r\n\tfor (int i = 0; i < NV.cols(); ++i) {\r\n\t\tNV.col(i) -= c;\r\n\t}\r\n\r\n\tEigen::JacobiSVD svd(NV, Eigen::DecompositionOptions::ComputeThinU);\r\n\r\n\tEigen::MatrixXf U = svd.matrixU();\r\n\tassert(U.rows() == 3 && U.cols() == 3);\r\n\r\n\tnormal = Vector3(U(0, 2), U(1, 2), U(2, 2));\r\n\tpoint = Vector3(c(0), c(1), c(2));\r\n}\r\n\r\nvoid Geomlib::BestFitPlane(\r\n\tconst Urho3D::VariantVector& vertex_list,\r\n\tUrho3D::Vector3& point,\r\n\tUrho3D::Vector3& normal\r\n)\r\n{\r\n\tusing Urho3D::Vector;\r\n\tusing Urho3D::Vector3;\r\n\r\n\tVector point_cloud;\r\n\tfor (int i = 0; i < vertex_list.Size(); ++i) {\r\n\t\tpoint_cloud.Push(vertex_list[i].GetVector3());\r\n\t}\r\n\r\n\tBestFitPlane(point_cloud, point, normal);\r\n}\r\n", "meta": {"hexsha": "b1e5b66aa7f5066795f25e01dfdfe551f8c306d9", "size": 2796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Geometry/Geomlib_BestFitPlane.cpp", "max_stars_repo_name": "elix22/IogramSource", "max_stars_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2017-03-01T04:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-01T13:33:50.000Z", "max_issues_repo_path": "Geometry/Geomlib_BestFitPlane.cpp", "max_issues_repo_name": "elix22/IogramSource", "max_issues_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-03-09T05:22:49.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-02T18:38:05.000Z", "max_forks_repo_path": "Geometry/Geomlib_BestFitPlane.cpp", "max_forks_repo_name": "elix22/IogramSource", "max_forks_repo_head_hexsha": "3a4ce55d94920e060776b4aa4db710f57a4280bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2017-03-01T14:00:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T06:36:54.000Z", "avg_line_length": 26.6285714286, "max_line_length": 87, "alphanum_fraction": 0.662732475, "num_tokens": 794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6940902642395762}} {"text": "/*\n * generate_data.cpp\n * Date: 2016-02-26\n * Author: Karsten Ahnert (karsten.ahnert@gmx.de)\n * Copyright: Karsten Ahnert\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \"generate_data.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace dynsys {\n \nusing stepper_type = boost::numeric::odeint::runge_kutta4< state_type > ;\n \n \ndata_type generate_data( void )\n{\n data_type data;\n state_type x {{ 10.0 , 10.0 , 10.0 }};\n state_type dxdt;\n double dt = 0.1;\n stepper_type stepper;\n for( double t = 0.0 ; t<100.0 ; t+= dt )\n {\n lorenz( x , dxdt , t );\n data.first.push_back( x );\n data.second.push_back( dxdt );\n stepper.do_step( lorenz , x , dxdt , t , dt );\n }\n return data;\n}\n\nvoid plot_data( data_type const& data , std::ostream& out )\n{\n for( size_t i=0 ; i\n#include \n#include \n#include \n#include \n\nusing namespace boost::numeric::ublas;\n\ntemplate\nbool InvertMatrix (const matrix& input, matrix& inverse) {\n typedef permutation_matrix pmatrix;\n matrix 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(A.size1()));\n lu_substitute(A, pm, inverse);\n return true;\n}\n\ntemplatevoid newton_raphson(U & F,V & J,vector& x0,double tol){\n double res = norm_1(F(x0));\n //std::cout << \"F(x0):\" << F(x0) << std::endl;\n int size = x0.size();\n matrix A;\n matrix inverse(size,size);\n inverse = set_zero(inverse);\n std::cout << \"Residu:\" << res << std::endl;\n while(res > tol){\n A = J(x0);\n std::cout<< \"A: \" << A << std::endl;\n InvertMatrix(A, inverse);\n // //std::cout << \"Inverse size \" << inverse.size1() << \" \" << inverse.size2() << std::endl;\n // x0 = x0 - prod(inverse,F(x0));\n // res = norm_1(F(x0));\n // std::cout << \"Residu: \"<< res << std::endl;\n // std::cout << \"Solution: \"<< x0 << std::endl;\n }\n\n}\n\n#endif\n", "meta": {"hexsha": "2d9417157efbba77697409e7d743bec0cb38070d", "size": 1377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/deprecated/newton_raphson.hpp", "max_stars_repo_name": "PieterAppeltans/ProjectWIT", "max_stars_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/deprecated/newton_raphson.hpp", "max_issues_repo_name": "PieterAppeltans/ProjectWIT", "max_issues_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/deprecated/newton_raphson.hpp", "max_forks_repo_name": "PieterAppeltans/ProjectWIT", "max_forks_repo_head_hexsha": "081e2537e2e9d9b92e50fdca2cb44039db5ffa59", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6875, "max_line_length": 96, "alphanum_fraction": 0.6332607117, "num_tokens": 419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939515, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.693882285012374}} {"text": "#pragma once\n\n#include \n#include \n\n#include \n#include \n\n#include \"km_utils/types.hpp\"\n\nnamespace km\n{\nnamespace math\n{\ntemplate \nconstexpr Scalar_t multivariateNormalProb(\n types::Vec const &x,\n types::Vec const &mean,\n types::SquareMat const &cov_inverse,\n Scalar_t const normal_pdf_constant)\n{\n types::Vec const dx = x - mean;\n Scalar_t const normal_pdf_exponent =\n Scalar_t{-0.5} * (dx.transpose() * cov_inverse * dx).value();\n return normal_pdf_constant * std::exp(normal_pdf_exponent);\n}\n\ntemplate \nconstexpr Scalar_t multivariateNormalProb(\n types::Vec const &dx,\n types::SquareMat const &cov_inverse,\n Scalar_t const normal_pdf_constant)\n{\n Scalar_t const normal_pdf_exponent =\n Scalar_t{-0.5} * (dx.transpose() * cov_inverse * dx).value();\n return normal_pdf_constant * std::exp(normal_pdf_exponent);\n}\n\ntemplate \nconstexpr Scalar_t multivariateNormalProb(\n types::Vec const &x,\n types::Vec const &mean,\n types::SquareMat const &cov_inverse)\n{\n Scalar_t const normal_pdf_constant =\n std::sqrt((cov_inverse / Scalar_t{2 * M_PI}).determinant());\n return multivariateNormalProb(x, mean, cov_inverse, normal_pdf_constant);\n}\n\ntemplate \nconstexpr auto getNormalPDFConstant(\n Eigen::MatrixBase const &cov_inverse)\n{\n using Scalar = typename Eigen::internal::traits::Scalar;\n return std::sqrt((cov_inverse / Scalar{2 * M_PI}).determinant());\n}\n\ntemplate \nconstexpr std::vector getNormalPDFConstant(\n types::vector_aligned> const\n &vec_cov_inverse)\n{\n std::vector ret;\n ret.reserve(vec_cov_inverse.size());\n for(auto const &M : vec_cov_inverse)\n ret.push_back(getNormalPDFConstant(M));\n return ret;\n}\n\n/**\n * Calculate the matrix square root of a positive (semi-)definite matrix.\n *\n * @param mat The input matrix.\n * @param semidefinite_mat Indicates whether the input is a semidefinite matrix.\n *\n * @return The matrix square root of the input mat.\n */\ntemplate \nconstexpr typename Derived::PlainObject matrixSquareRoot(\n Eigen::MatrixBase const &mat, bool semidefinite_mat = false)\n{\n constexpr auto M = Derived::RowsAtCompileTime;\n constexpr auto N = Derived::ColsAtCompileTime;\n static_assert(M == N, \"Only valid for a square matrix\");\n if constexpr(M == 0 || N == 0)\n return Derived::PlainObject::Zero(mat.rows(), mat.cols());\n else\n {\n if(!semidefinite_mat)\n {\n Eigen::LLT cov_chol{mat};\n if(cov_chol.info() == Eigen::Success)\n return cov_chol.matrixL();\n }\n Eigen::LDLT cov_chol{mat};\n if(cov_chol.info() == Eigen::Success)\n {\n typename Derived::PlainObject const L = cov_chol.matrixL();\n auto const P = cov_chol.transpositionsP();\n auto const D_sqrt =\n cov_chol.vectorD().array().sqrt().matrix().asDiagonal();\n return P.transpose() * L * D_sqrt;\n }\n return Derived::PlainObject::Zero(mat.rows(), mat.cols());\n }\n}\n\ntemplate \ntypes::vector_aligned randomSamplesGaussian(Vec const &mean,\n Cov const &covariance_sqrt,\n unsigned int n,\n std::random_device &rd)\n{\n std::mt19937 rng{rd()};\n std::normal_distribution<> dist;\n\n types::vector_aligned ret;\n ret.reserve(n);\n for(unsigned int i = 0; i < n; ++i)\n {\n Vec z = Vec::Zero(mean.size());\n for(unsigned int j = 0; j < mean.size(); ++j)\n z(j) = dist(rng);\n ret.push_back(mean + covariance_sqrt * z);\n }\n return ret;\n}\n\ntemplate \nconstexpr typename Derived::PlainObject pseudoInverse(\n Eigen::MatrixBase const &m)\n{\n // JacobiSVD: thin U and V are only available when your matrix has a dynamic\n // number of columns.\n constexpr auto flags = (Derived::ColsAtCompileTime == Eigen::Dynamic) ?\n (Eigen::ComputeThinU | Eigen::ComputeThinV) :\n (Eigen::ComputeFullU | Eigen::ComputeFullV);\n Eigen::JacobiSVD m_svd(m, flags);\n // std::cout << \"singular values: \" << m_svd.singularValues().transpose()\n // << \"\\n\";\n return m_svd.solve(Derived::PlainObject::Identity(m.rows(), m.rows()));\n}\n\ntemplate \nconstexpr auto blockDiagonalMatrix(Eigen::EigenBase const &X)\n{\n using Scalar = typename Eigen::internal::traits::Scalar;\n constexpr auto M = Eigen::internal::traits::RowsAtCompileTime;\n constexpr auto N = Eigen::internal::traits::ColsAtCompileTime;\n\n auto const in_rows = (M == Eigen::Dynamic) ? X.rows() : M;\n auto const in_cols = (N == Eigen::Dynamic) ? X.cols() : N;\n auto const out_rows = num_repeat * in_rows;\n auto const out_cols = num_repeat * in_cols;\n constexpr auto out_template_rows =\n (M == Eigen::Dynamic) ? Eigen::Dynamic : out_rows;\n constexpr auto out_template_cols =\n (N == Eigen::Dynamic) ? Eigen::Dynamic : out_cols;\n\n auto ret = Eigen::Matrix::Zero(\n out_rows, out_cols)\n .eval();\n\n if constexpr(M != Eigen::Dynamic && N != Eigen::Dynamic)\n {\n for(unsigned int i = 0; i < num_repeat; ++i)\n ret.template block(i * M, i * N) = X;\n }\n else\n {\n for(unsigned int i = 0; i < num_repeat; ++i)\n ret.block(i * in_rows, i * in_cols, in_rows, in_cols) = X;\n }\n return ret;\n}\n\ntemplate \nconstexpr auto blockDiagonalMatrix(Eigen::EigenBase const &X,\n unsigned int const num_repeat)\n{\n using Scalar = typename Eigen::internal::traits::Scalar;\n constexpr auto M = Eigen::internal::traits::RowsAtCompileTime;\n constexpr auto N = Eigen::internal::traits::ColsAtCompileTime;\n\n auto const in_rows = X.rows();\n auto const in_cols = X.cols();\n\n auto ret = Eigen::Matrix::Zero(\n num_repeat * in_rows, num_repeat * in_cols)\n .eval();\n\n if constexpr(M != Eigen::Dynamic && N != Eigen::Dynamic)\n {\n for(unsigned int i = 0; i < num_repeat; ++i)\n ret.template block(i * M, i * N) = X;\n }\n else\n {\n for(unsigned int i = 0; i < num_repeat; ++i)\n ret.block(i * in_rows, i * in_cols, in_rows, in_cols) = X;\n }\n return ret;\n}\n\ntemplate \nconstexpr T square(T p)\n{\n return p * p;\n}\n\n// From https://stackoverflow.com/a/33454406\ntemplate \nconstexpr T powInt(T x, unsigned int n)\n{\n if(n == 0)\n return T{1};\n else if(n == 1)\n return x;\n else if(n == 2)\n return x * x;\n\n auto y = x * x;\n n -= 2;\n while(n > 1)\n {\n if(n % 2 == 1)\n y *= x;\n x *= x;\n n /= 2;\n }\n return x * y;\n}\n\n/**\n * @brief Normalize the given angle in radians to (-PI, PI]\n *\n * @param[in] x angle in radians\n *\n * @return normalized angle in the range (-PI, PI]\n */\ntemplate \nconstexpr Scalar_t normalize_angle(Scalar_t x)\n{\n constexpr Scalar_t pi = M_PI, two_pi = 2 * M_PI;\n return x - (std::ceil((x + pi) / two_pi) - Scalar_t{1}) * two_pi;\n}\n} // namespace math\n} // namespace km\n", "meta": {"hexsha": "335664970ee6d622f7835c0c0aaea40152794b5b", "size": 7731, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/km_utils/math.hpp", "max_stars_repo_name": "kartikmohta/km_utils", "max_stars_repo_head_hexsha": "41fa812f3cfddcf214653081c8e4183f2b3fa543", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-03-26T23:21:22.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-26T23:21:22.000Z", "max_issues_repo_path": "include/km_utils/math.hpp", "max_issues_repo_name": "kartikmohta/km_utils", "max_issues_repo_head_hexsha": "41fa812f3cfddcf214653081c8e4183f2b3fa543", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/km_utils/math.hpp", "max_forks_repo_name": "kartikmohta/km_utils", "max_forks_repo_head_hexsha": "41fa812f3cfddcf214653081c8e4183f2b3fa543", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0481927711, "max_line_length": 80, "alphanum_fraction": 0.656706765, "num_tokens": 2009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308073258007, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.693695914257856}} {"text": "//\n// STL includes\n#include \n#include \n\n// BGL includes\n#include \n#include \n#include \n\ntypedef boost::adjacency_list > weighted_graph;\ntypedef boost::property_map::type weight_map;\ntypedef boost::graph_traits::edge_descriptor edge_desc;\ntypedef boost::graph_traits::vertex_descriptor vertex_desc;\n\nusing namespace std;\n\nint dijkstra(const weighted_graph &G, int s, int k) {\n int n = boost::num_vertices(G);\n std::vector dist_map(n);\n\n boost::dijkstra_shortest_paths(G, s,\n boost::distance_map(boost::make_iterator_property_map(\n dist_map.begin(), boost::get(boost::vertex_index, G))));\n int min_dist = dist_map[0];\n for(int i = 1; i < k; i++) {\n min_dist = min(min_dist, dist_map[i]);\n }\n return min_dist;\n}\n\n\nvoid testcase() {\n int n; cin >> n;\n int m; cin >> m;\n int k; cin >> k;\n int T; cin >> T;\n vector tele_nodes(T);\n for(int i = 0; i < T; i++) {\n cin >> tele_nodes[i];\n }\n weighted_graph G(n);\n \n weight_map weights = boost::get(boost::edge_weight, G);\n edge_desc e;\n for(int i = 0; i < m; i++) {\n int u,v; cin >> u; cin >> v;\n int c; cin >> c;\n e = boost::add_edge(v, u, G).first; weights[e] = c; // flipped edges!\n }\n // scc_map[i]: index of SCC containing i-th vertex\n vector scc_map(n); // exterior property map\n // nscc: total number of SCCs\n int nscc = boost::strong_components(G,\n boost::make_iterator_property_map(scc_map.begin(),\n boost::get(boost::vertex_index, G)));\n \n vector size_scc(nscc);\n for(int i = 0; i < T; i++) {\n size_scc[scc_map[tele_nodes[i]]]++;\n }\n \n \n for(int i = 0; i < T; i++) {\n int u = tele_nodes[i];\n int scc = scc_map[u];\n int size_this_scc = size_scc[scc] - 1;\n e = boost::add_edge(u, n + scc, G).first;\n weights[e] = size_this_scc;\n e = boost::add_edge(n + scc, u, G).first;\n weights[e] = 0;\n }\n \n int min_dist_to_warehouse = dijkstra(G, n - 1, k);\n if(min_dist_to_warehouse <= 1e6) {\n cout << min_dist_to_warehouse << endl;\n } else {\n cout << \"no\" << endl;\n }\n \n}\nint main()\n{\n std::ios_base::sync_with_stdio(false); // Always!\n int t; cin >> t;\n for(int i = 0; i < t; i++)\n testcase();\n return 0;\n}\n", "meta": {"hexsha": "d07555915527d7c8a55487e3e53b8e7af775043a", "size": 2515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week06-potw-planet_express/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/week06-potw-planet_express/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/week06-potw-planet_express/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6373626374, "max_line_length": 87, "alphanum_fraction": 0.6310139165, "num_tokens": 758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6936493724979871}} {"text": "// The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n/*\n\n This is an example illustrating the use the general purpose non-linear \n least squares optimization routines from the dlib C++ Library.\n\n This example program will demonstrate how these routines can be used for data fitting.\n In particular, we will generate a set of data and then use the least squares \n routines to infer the parameters of the model which generated the data.\n*/\n\n\n#include \n#include \n#include \n\n\nusing namespace std;\nusing namespace dlib;\n\n// ----------------------------------------------------------------------------------------\n\ntypedef matrix input_vector;\ntypedef matrix parameter_vector;\ntypedef std::vector > data_samples;\n\nconst double sqrt2pi = std::sqrt(2*pi);\nconst double sqrtpi = std::sqrt(pi);\n// ----------------------------------------------------------------------------------------\n\n// We will use this function to generate data. It represents a function of 2 variables\n// and 3 parameters. The least squares procedure will be used to infer the values of \n// the 3 parameters based on a set of input/output pairs.\ndouble model (\n const input_vector& input,\n const parameter_vector& params\n)\n{\n const double a = params(0);\n const double b = params(1);\n\n const double x = input(0);\n\n /*\n / 2 \\\n | (a - log(x)) |\n sqrt(2) exp| - ------------- |\n | 2 |\n \\ 2 b /\n ------------------------------\n b x sqrt(pi) 2\n */\n\n const double logx = log(x);\n const double nominator = sqrt_2 * exp(- ((a - logx)*(a - logx))/(2*b*b));\n const double denominator = b * x * sqrtpi * 2;\n double out = nominator/denominator;\n return out;\n\n}\n\n// ----------------------------------------------------------------------------------------\n\n// This function is the \"residual\" for a least squares problem. It takes an input/output\n// pair and compares it to the output of our model and returns the amount of error. The idea\n// is to find the set of parameters which makes the residual small on all the data pairs.\ndouble residual (\n const std::pair& data,\n const parameter_vector& params\n)\n{\n return model(data.first, params) - data.second;\n}\n\n// ----------------------------------------------------------------------------------------\n\n// This function is the derivative of the residual() function with respect to the parameters.\nparameter_vector residual_derivative (\n const std::pair& data,\n const parameter_vector& params\n)\n{\n /*\n wrt a (mean)\n / 2 \\\n | (a - log(x)) |\n sqrt(2) exp| - ------------- | (2 a - 2 log(x))\n | 2 |\n \\ 2 b /\n- -----------------------------------------------\n 3\n b x sqrt(pi) 4\n\n\n / 2 \\ / 2 \\\n | (a - log(x)) | 2 | (a - log(x)) |\nsqrt(2) exp| - ------------- | (a - log(x)) sqrt(2) exp| - ------------- |\n | 2 | | 2 |\n \\ 2 b / \\ 2 b /\n-------------------------------------------- - ------------------------------\n 4 2\n b x sqrt(pi) 2 b x sqrt(pi) 2\n */\n parameter_vector der;\n\n const double a = params(0);\n const double b = params(1);\n\n const double x = data.first(0);\n const double logx = log(x);\n const double a_logxsq = (a - logx)*(a - logx);\n const double sqb = b*b;\n const double exp_fraction = sqrt_2 * exp(- a_logxsq/(2*sqb));\n\n const double numeratorA = exp_fraction * (2 * a - 2 * logx);\n const double denominatorA = b*sqb * x * sqrtpi * 4;\n\n const double numeratorB = exp_fraction * a_logxsq;\n const double denominatorB = sqb*sqb * x * sqrtpi * 2;\n\n der(0) = -numeratorA/denominatorA;\n der(1) = numeratorB/denominatorB - exp_fraction/(sqb * x * sqrtpi * 2);\n\n return der;\n}\n\n// ----------------------------------------------------------------------------------------\n\nbool read_inputfile(std::string filename, data_samples& DS, double& maxYPos, std::string& errmsg){\n bool out = false;\n std::ifstream datafile(filename.c_str());\n if (!datafile.good()) {\n errmsg = \"Can't open the file\" + filename;\n }\n else{\n std::string line;\n double y;\n double max_y = 0;\n double x = 1;\n input_vector input;\n while (getline(datafile, line)){\n if (line.size() > 0){\n std::istringstream inp(line.c_str());\n inp >> y;\n input(0) = x;\n DS.push_back(make_pair(input, y));\n if (y > max_y){\n max_y = y;\n maxYPos = x;\n }\n x = x + 1.0;\n }\n }\n out = true;\n }\n return out;\n}\n\nint main(int argc, char* argv[])\n{\n if (argc == 1){\n std::cout << \"No input file!\" << std::endl;\n return 0;\n }\n\n std::string infile = argv[1];\n data_samples DS;\n double maxYpos = 1;\n std::string msg;\n bool tf = read_inputfile(infile, DS ,maxYpos,msg);\n\n parameter_vector params;\n params(0) = log(maxYpos);\n params(1) = 0.3;\n try\n {\n // randomly pick a set of parameters to use in this example\n// const parameter_vector params = 10*randm(3,1);\n// cout << \"params: \" << trans(params) << endl;\n\n\n // Now let's generate a bunch of input/output pairs according to our model.\n// std::vector > data_samples;\n// input_vector input;\n// for (int i = 0; i < 1000; ++i)\n// {\n// input = 10*randm(2,1);\n// const double output = model(input, params);\n//\n// // save the pair\n// data_samples.push_back(make_pair(input, output));\n// }\n\n // Before we do anything, let's make sure that our derivative function defined above matches\n // the approximate derivative computed using central differences (via derivative()). \n // If this value is big then it means we probably typed the derivative function incorrectly.\n //cout << \"derivative error: \" << length(residual_derivative(DS[18], params) -\n // derivative(residual)(DS[18], params) ) << endl;\n\n\n\n\n\n // Now let's use the solve_least_squares_lm() routine to figure out what the\n // parameters are based on just the data_samples.\n parameter_vector x;\n x = params;\n\n //cout << \"Use Levenberg-Marquardt\" << endl;\n // Use the Levenberg-Marquardt method to determine the parameters which\n // minimize the sum of all squared residuals.\n solve_least_squares_lm(objective_delta_stop_strategy(1e-7),\n residual,\n residual_derivative,\n DS,\n x);\n\n // Now x contains the solution. If everything worked it will be equal to params.\n //cout << \"inferred parameters: \"<< trans(x) << endl;\n //cout << \"solution error: \"<< length(x - params) << endl;\n //cout << endl;\n cout << trans(x) << endl;\n\n\n /*\n\n x = params;\n cout << \"Use Levenberg-Marquardt, approximate derivatives\" << endl;\n // If we didn't create the residual_derivative function then we could\n // have used this method which numerically approximates the derivatives for you.\n solve_least_squares_lm(objective_delta_stop_strategy(1e-7).be_verbose(), \n residual,\n derivative(residual),\n DS,\n x);\n\n // Now x contains the solution. If everything worked it will be equal to params.\n cout << \"inferred parameters: \"<< trans(x) << endl;\n cout << \"solution error: \"<< length(x - params) << endl;\n cout << endl;\n\n\n\n\n x = params;\n cout << \"Use Levenberg-Marquardt/quasi-newton hybrid\" << endl;\n // This version of the solver uses a method which is appropriate for problems\n // where the residuals don't go to zero at the solution. So in these cases\n // it may provide a better answer.\n solve_least_squares(objective_delta_stop_strategy(1e-7).be_verbose(), \n residual,\n residual_derivative,\n DS,\n x);\n\n // Now x contains the solution. If everything worked it will be equal to params.\n cout << \"inferred parameters: \"<< trans(x) << endl;\n cout << \"solution error: \"<< length(x - params) << endl;\n */\n\n }\n catch (std::exception& e)\n {\n cout << e.what() << endl;\n }\n}\n", "meta": {"hexsha": "a48de070d614b93c8fe4f45e1bd53554fcc3d36e", "size": 9285, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lgnrmfit.cpp", "max_stars_repo_name": "giorgk/lgnrmfit", "max_stars_repo_head_hexsha": "3e63eb66fd3a2fb4c7356365f5efaa8cb2984a07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lgnrmfit.cpp", "max_issues_repo_name": "giorgk/lgnrmfit", "max_issues_repo_head_hexsha": "3e63eb66fd3a2fb4c7356365f5efaa8cb2984a07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lgnrmfit.cpp", "max_forks_repo_name": "giorgk/lgnrmfit", "max_forks_repo_head_hexsha": "3e63eb66fd3a2fb4c7356365f5efaa8cb2984a07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7752808989, "max_line_length": 100, "alphanum_fraction": 0.5018847604, "num_tokens": 2062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6934917322296218}} {"text": "#include \"average_case_relative_error.hpp\"\n#include \"average_case_error.hpp\"\n#include \"cudd_helpers.hpp\"\n#include \n\nnamespace abo::error_metrics {\n std::pair\n average_relative_value(const Cudd &mgr, const std::vector &f, const std::vector &g) {\n\n BDD zero_so_far = mgr.bddOne();\n\n boost::multiprecision::cpp_dec_float_100 min_average_result = 0;\n boost::multiprecision::cpp_dec_float_100 max_average_result = 0;\n std::vector max_one = abo::util::bdd_max_one(mgr, g);\n for (int i = int(g.size())-1;i>=0;i--) {\n std::vector partial_result;\n partial_result.reserve(max_one.size());\n BDD modifier = zero_so_far & max_one[i];\n for (const BDD &b : f) {\n partial_result.push_back(b & modifier);\n }\n auto average = average_value(partial_result);\n min_average_result += average / (std::pow(2.0, i + 1) - 1);\n max_average_result += average / std::pow(2.0, i);\n\n zero_so_far &= !max_one[i];\n }\n\n return {min_average_result, max_average_result};\n }\n\n std::pair\n average_relative_error_bounds(const Cudd &mgr, const std::vector &f, const std::vector &f_hat,\n const util::NumberRepresentation num_rep) {\n\n std::vector absolute_difference = abo::util::bdd_absolute_difference(mgr, f, f_hat, num_rep);\n return average_relative_value(mgr, absolute_difference, abo::util::abs(mgr, f));\n }\n\n boost::multiprecision::cpp_dec_float_100 average_relative_error_add(const Cudd &mgr, const std::vector &f, const std::vector &f_hat,\n const NumberRepresentation num_rep) {\n\n ADD diff = abo::util::absolute_difference_add(mgr, f, f_hat, num_rep);\n ADD respective_diff = diff.Divide(abo::util::bdd_forest_to_add(mgr, abo::util::abs(mgr, f)).Maximum(mgr.addOne()));\n std::vector> terminal_values = abo::util::add_terminal_values(respective_diff);\n\n boost::multiprecision::cpp_dec_float_100 sum = 0;\n boost::multiprecision::uint256_t path_sum = 0;\n for (auto p : terminal_values) {\n boost::multiprecision::cpp_dec_float_100 value(p.first);\n sum += value * p.second;\n path_sum += p.second;\n }\n return boost::multiprecision::cpp_dec_float_100(sum) /\n boost::multiprecision::cpp_dec_float_100(path_sum);\n }\n\n boost::multiprecision::cpp_dec_float_100 average_relative_error_symbolic_division(const Cudd &mgr, const std::vector &f, const std::vector &f_hat,\n unsigned int num_extra_bits, const NumberRepresentation num_rep) {\n\n std::vector absolute_difference = abo::util::bdd_absolute_difference(mgr, f, f_hat, num_rep);\n\n std::vector no_zero = abo::util::bdd_max_one(mgr, abo::util::abs(mgr, f));\n std::vector divided = abo::util::bdd_divide(mgr, absolute_difference, no_zero, num_extra_bits);\n\n return average_value(divided) / std::pow(2.0, num_extra_bits);\n }\n\n}\n", "meta": {"hexsha": "8b344f78eb762ceb7ec3c508f29fd7f7cb7378ea", "size": 3489, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/error_metrics/average_case_relative_error.cpp", "max_stars_repo_name": "andreaswendler/abo", "max_stars_repo_head_hexsha": "d5d31e0714365960fb9c02a6a5b240c07ac3a738", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/error_metrics/average_case_relative_error.cpp", "max_issues_repo_name": "andreaswendler/abo", "max_issues_repo_head_hexsha": "d5d31e0714365960fb9c02a6a5b240c07ac3a738", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/error_metrics/average_case_relative_error.cpp", "max_forks_repo_name": "andreaswendler/abo", "max_forks_repo_head_hexsha": "d5d31e0714365960fb9c02a6a5b240c07ac3a738", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.8428571429, "max_line_length": 160, "alphanum_fraction": 0.633992548, "num_tokens": 855, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9294404018582427, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6934917255246059}} {"text": "/*\n * libcluster -- A collection of hierarchical Bayesian clustering algorithms.\n * Copyright (C) 2013 Daniel M. Steinberg (daniel.m.steinberg@gmail.com)\n *\n * This file is part of libcluster.\n *\n * libcluster is free software: you can redistribute it and/or modify it under\n * the terms of the GNU Lesser General Public License as published by the Free\n * Software Foundation, either version 3 of the License, or (at your option)\n * any later version.\n *\n * libcluster is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License\n * for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with libcluster. If not, see .\n */\n\n#include \"probutils.h\"\n#include \n\n\n//\n// Namespaces\n//\n\n\nusing namespace std;\nusing namespace Eigen;\n\n\n//\n// Local Constants\n//\n\n\nconst double EIGCONTHRESH = 1.0e-8f;\nconst int MAXITER = 100;\n\n\n//\n// Public Functions\n//\n\n\nRowVectorXd probutils::mean (const MatrixXd& X)\n{\n return X.colwise().sum()/X.rows();\n}\n\n\nRowVectorXd probutils::mean (const vector& X)\n{\n const int J = X.size(),\n D = X[0].cols();\n int N = 0;\n RowVectorXd mean = RowVectorXd::Zero(D);\n\n for (int j = 0; j < J; ++j)\n {\n if (X[j].cols() != D)\n throw invalid_argument(\"X dimensions are inconsistent between groups!\");\n\n mean += X[j].colwise().sum();\n N += X[j].rows();\n }\n return mean / N;\n}\n\n\nRowVectorXd probutils::stdev (const MatrixXd& X)\n{\n RowVectorXd meanX = mean(X);\n return ((X.rowwise() - meanX).array().square().colwise().sum()\n / (X.rows()-1)).sqrt();\n}\n\n\nMatrixXd probutils::cov (const MatrixXd& X)\n{\n if (X.rows() <= 1)\n throw invalid_argument(\"Insufficient no. of observations.\");\n\n MatrixXd X_mu = X.rowwise() - probutils::mean(X); // X - mu\n return (X_mu.transpose()*X_mu)/(X.rows()-1); // (X-mu)'*(X-mu)/(N-1)\n}\n\n\nMatrixXd probutils::cov (const vector& X)\n{\n const int J = X.size(),\n D = X[0].cols();\n int N = 0;\n const RowVectorXd mean = probutils::mean(X);\n MatrixXd cov = MatrixXd::Zero(D, D),\n X_mu;\n\n for (int j = 0; j < J; ++j)\n {\n if (X[j].rows() <= 1)\n throw invalid_argument(\"Insufficient no. of observations.\");\n X_mu = X[j].rowwise() - mean;\n N += X[j].rows();\n cov.noalias() += (X_mu.transpose() * X_mu); // (X_j-mu)'*(X_j-mu)\n }\n\n return cov / (N-1);\n}\n\n\nVectorXd probutils::mahaldist (\n const MatrixXd& X,\n const RowVectorXd& mu,\n const MatrixXd& A\n )\n{\n // Check for same number of dimensions, D\n if((X.cols() != mu.cols()) || (X.cols() != A.cols()))\n throw invalid_argument(\"Arguments do not have the same dimensionality\");\n\n // Check if A is square\n if (A.rows() != A.cols())\n throw invalid_argument(\"Matrix A must be square!\");\n\n // Decompose A\n LDLT Aldl(A);\n\n // Check if A is PD\n if ((Aldl.vectorD().array() <= 0).any() == true)\n throw invalid_argument(\"Matrix A is not positive definite\");\n\n // Do the Mahalanobis distance for each sample (N times)\n MatrixXd X_mu = (X.rowwise() - mu).transpose();\n return ((X_mu.array() * (Aldl.solve(X_mu)).array())\n .colwise().sum()).transpose();\n}\n\n\nVectorXd probutils::logsumexp (const MatrixXd& X)\n{\n const VectorXd mx = X.rowwise().maxCoeff(); // Get max of each row\n\n // Perform the sum(exp(x - mx)) part\n ArrayXd se = ((X.colwise() - mx).array().exp()).rowwise().sum();\n\n // return total log(sum(exp(x))) - hoping for return value optimisation\n return (se.log()).matrix() + mx;\n}\n\n\ndouble probutils::eigpower (const MatrixXd& A, VectorXd& eigvec)\n{\n // Check if A is square\n if (A.rows() != A.cols())\n throw invalid_argument(\"Matrix A must be square!\");\n\n // Check if A is a scalar\n if (A.rows() == 1)\n {\n eigvec.setOnes(1);\n return A(0,0);\n }\n\n // Initialise working vectors\n VectorXd v = VectorXd::LinSpaced(A.rows(), -1, 1);\n VectorXd oeigvec(A.rows());\n\n // Initialise eigenvalue and eigenvectors etc\n double eigval = v.norm();\n double vdist = numeric_limits::infinity();\n eigvec = v/eigval;\n\n // Loop until eigenvector converges or we reach max iterations\n for (int i=0; (vdist>EIGCONTHRESH) && (i\n#include \n#include \n\n#include \"../classes/structs.hh\"\n\ntypedef dlib::matrix input_vector;\ntypedef dlib::matrix parameter_vector;\n\n// ----------------------------------------------------------------------------------------\n\n// We will use this function to generate data. It represents a function of 2 variables\n// and 3 parameters. The least squares procedure will be used to infer the values of\n// the 3 parameters based on a set of input/output pairs.\ndouble model (\n const input_vector& input,\n const parameter_vector& params\n)\n{\n const double p0 = params(0);\n const double p1 = params(1);\n const double p2 = params(2);\n\n const double i0 = input(0);\n const double i1 = input(1);\n\n const double temp = p0*i0 + p1*i1 + p2;\n\n return temp*temp;\n}\n\n// ----------------------------------------------------------------------------------------\n\n// This function is the \"residual\" for a least squares problem. It takes an input/output\n// pair and compares it to the output of our model and returns the amount of error. The idea\n// is to find the set of parameters which makes the residual small on all the data pairs.\ndouble residual (\n const std::pair& data,\n const parameter_vector& params\n)\n{\n return model(data.first, params) - data.second;\n}\n\n// ----------------------------------------------------------------------------------------\n\n// This function is the derivative of the residual() function with respect to the parameters.\nparameter_vector residual_derivative (\n const std::pair& data,\n const parameter_vector& params\n)\n{\n parameter_vector der;\n\n const double p0 = params(0);\n const double p1 = params(1);\n const double p2 = params(2);\n\n const double i0 = data.first(0);\n const double i1 = data.first(1);\n\n const double temp = p0*i0 + p1*i1 + p2;\n\n der(0) = i0*2*temp;\n der(1) = i1*2*temp;\n der(2) = 2*temp;\n\n return der;\n}\n\nPDC::gaussParameter fitGauss(std::vector& xVals, std::vector& yValsData, PDC::gaussParameter initialParams) {\n try {\n // randomly pick a set of parameters to use in this example\n const parameter_vector params = 10*dlib::randm(3,1);\n std::cout << \"params: \" << trans(params) << std::endl;\n\n\n // Now let's generate a bunch of input/output pairs according to our model.\n std::vector > data_samples;\n input_vector input;\n for (int i = 0; i < 1000; ++i)\n {\n input = 10*dlib::randm(2,1);\n const double output = model(input, params);\n\n // save the pair\n data_samples.push_back(std::make_pair(input, output));\n }\n\n // Before we do anything, let's make sure that our derivative function defined above matches\n // the approximate derivative computed using central differences (via derivative()).\n // If this value is big then it means we probably typed the derivative function incorrectly.\n std::cout << \"derivative error: \" << length(residual_derivative(data_samples[0], params) -\n derivative(residual)(data_samples[0], params) ) << std::endl;\n\n\n\n\n\n // Now let's use the solve_least_squares_lm() routine to figure out what the\n // parameters are based on just the data_samples.\n parameter_vector x;\n x = 1;\n\n std::cout << \"Use Levenberg-Marquardt\" << std::endl;\n // Use the Levenberg-Marquardt method to determine the parameters which\n // minimize the sum of all squared residuals.\n dlib::solve_least_squares_lm(dlib::objective_delta_stop_strategy(1e-7).be_verbose(),\n residual,\n residual_derivative,\n data_samples,\n x);\n\n // Now x contains the solution. If everything worked it will be equal to params.\n std::cout << \"inferred parameters: \"<< trans(x) << std::endl;\n std::cout << \"solution error: \"<< length(x - params) << std::endl;\n std::cout << std::endl;\n\n\n\n\n x = 1;\n std::cout << \"Use Levenberg-Marquardt, approximate derivatives\" << std::endl;\n // If we didn't create the residual_derivative function then we could\n // have used this method which numerically approximates the derivatives for you.\n dlib::solve_least_squares_lm(dlib::objective_delta_stop_strategy(1e-7).be_verbose(),\n residual,\n derivative(residual),\n data_samples,\n x);\n\n // Now x contains the solution. If everything worked it will be equal to params.\n std::cout << \"inferred parameters: \"<< trans(x) << std::endl;\n std::cout << \"solution error: \"<< length(x - params) << std::endl;\n std::cout << std::endl;\n\n\n\n\n x = 1;\n std::cout << \"Use Levenberg-Marquardt/quasi-newton hybrid\" << std::endl;\n // This version of the solver uses a method which is appropriate for problems\n // where the residuals don't go to zero at the solution. So in these cases\n // it may provide a better answer.\n dlib::solve_least_squares(dlib::objective_delta_stop_strategy(1e-7).be_verbose(),\n residual,\n residual_derivative,\n data_samples,\n x);\n\n // Now x contains the solution. If everything worked it will be equal to params.\n std::cout << \"inferred parameters: \"<< trans(x) << std::endl;\n std::cout << \"solution error: \"<< length(x - params) << std::endl;\n\n }\n catch (std::exception& e) {\n std::cout << \"Error while fitting: \" << e.what() << std::endl;\n }\n}\n\n#endif /* PDC_gauss_hh_included */\n", "meta": {"hexsha": "aa0ea180167d804b0e2f9c2c84bc92e078af79c0", "size": 6053, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/util/fit_gauss.hh", "max_stars_repo_name": "ClundXIII/timepix-data-crunching", "max_stars_repo_head_hexsha": "442a31e61a462cf8665f14f7de8ffec25262dadd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/util/fit_gauss.hh", "max_issues_repo_name": "ClundXIII/timepix-data-crunching", "max_issues_repo_head_hexsha": "442a31e61a462cf8665f14f7de8ffec25262dadd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/util/fit_gauss.hh", "max_forks_repo_name": "ClundXIII/timepix-data-crunching", "max_forks_repo_head_hexsha": "442a31e61a462cf8665f14f7de8ffec25262dadd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6848484848, "max_line_length": 125, "alphanum_fraction": 0.5833471006, "num_tokens": 1361, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6934535086556761}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"block_iterative_solvers.hpp\"\n#include \"linear_algebra_addon.hpp\"\nusing namespace std;\nusing namespace Eigen;\nusing namespace std::chrono;\n\nint main(int argc, char *argv[]){\n\n double tol= 1e-8;\n int itermax= 1000;\n\n std::srand((unsigned int) time(0));\n int L=atoi(argv[1]); // dimension of matrix A\n\n MatrixXcd A;\n\n\n switch (argc)\n {\n case 2:\n {\n // load A from a file in matrix market format .mtx\n cout << \"please enter filename for A (.mtx): \" ;\n string matfname;\n cin >> matfname;\n SparseMatrix> mat;\n //Matrix collections is available in http://www.cise.ufl.edu/research/sparse/matrices/\n if(!loadMarket(mat,matfname)){\n cerr << \"can't open file\" << matfname << endl;\n exit(EXIT_FAILURE);\n }\n cout << \"A was loaded from \" << matfname << endl;\n A= MatrixXcd(mat);\n\n break;\n }\n case 3:\n {\n // Set A as a random matrix\n int n=atoi(argv[2]); // number of RHS vector\n A= MatrixXcd::Random(n,n);\n A= A.transpose()*A; // complex-symmetric\n cout << \"A is a \" << n << \" x \" << n << \" square random matrix\" << endl;\n break;\n }\n default:\n {\n\n break;\n }\n }\n\n MatrixXcd B= MatrixXcd::Random(A.rows(),L);\n\n\n {\n time_point start= steady_clock::now();\n cout << \"solving AX=B using bl_cocg_rq ...\" << endl;\n MatrixXcd X= bl_cocg_rq(A, B, tol, itermax); // only applicable to complex-symmetric matrix A\n cout << \" bl_cocg_rq relative error: \" << (A*X-B).norm()/B.norm() << endl << endl;\n auto end= steady_clock::now();\n cout << \"bl_cocg_rq computation time= \" << duration_cast((end - start)).count() << \" sec\" << endl << endl<< endl;\n }\n\n\n {\n time_point start= steady_clock::now();\n cout << \"solving AX=B using bl_bicg_rq ...\" << endl;\n MatrixXcd X= bl_bicg_rq(A, B, tol, itermax); // applicable to general matrix A but needs A.adjoint()\n cout << \" bl_bicg_rq relative error: \" << (A*X-B).norm()/B.norm() << endl << endl;\n auto end= steady_clock::now();\n cout << \"bl_bicg_rq computation time= \" << duration_cast((end - start)).count() << \" sec\" << endl << endl<< endl;\n }\n\n {\n time_point start= steady_clock::now();\n cout << \"solving AX=B using bl_bicr_rq ...\" << endl;\n MatrixXcd X= bl_bicr_rq(A, B, tol, itermax); // applicable to general matrix A but needs A.adjoint()\n cout << \" bl_bicr_rq relative error: \" << (A*X-B).norm()/B.norm() << endl << endl;\n auto end= steady_clock::now();\n cout << \"bl_bicr_rq computation time= \" << duration_cast((end - start)).count() << \" sec\" << endl << endl<< endl;\n }\n\n {\n time_point start= steady_clock::now();\n cout << \"solving AX=B using bl_bicgstab_rq ...\" << endl;\n MatrixXcd X= bl_bicgstab_rq(A, B, tol, itermax); // only applicable to complex-symmetric matrix A\n cout << \" bl_bicgstab_rq relative error: \" << (A*X-B).norm()/B.norm() << endl << endl;\n auto end= steady_clock::now();\n cout << \"bl_bicgstab_rq computation time= \" << duration_cast((end - start)).count() << \" sec\" << endl << endl<< endl;\n }\n\n {\n time_point start= steady_clock::now();\n cout << \"solving AX=B using bl_bicgstab ...\" << endl;\n MatrixXcd X= bl_bicgstab(A, B, tol, itermax); // only applicable to complex-symmetric matrix A\n cout << \" bl_bicgstab relative error: \" << (A*X-B).norm()/B.norm() << endl << endl;\n auto end= steady_clock::now();\n cout << \"bl_bicgstab computation time= \" << duration_cast((end - start)).count() << \" sec\" << endl << endl<< endl;\n }\n\n {\n time_point start= steady_clock::now();\n cout << \"solving AX=B using bl_bicggr ...\" << endl;\n MatrixXcd X= bl_bicggr(A, B, tol, itermax); // only applicable to complex-symmetric matrix A\n cout << \" bl_bicggr relative error: \" << (A*X-B).norm()/B.norm() << endl << endl;\n auto end= steady_clock::now();\n cout << \"bl_bicggr computation time= \" << duration_cast((end - start)).count() << \" sec\" << endl << endl<< endl;\n }\n\n\n\n\n\n\n\n\n}\n", "meta": {"hexsha": "1085584672ccf39873a2aec322f0a09c7b136832", "size": 4619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "block_iterative_solvers_test.cpp", "max_stars_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_stars_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-27T08:44:06.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-27T08:44:06.000Z", "max_issues_repo_path": "block_iterative_solvers_test.cpp", "max_issues_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_issues_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "block_iterative_solvers_test.cpp", "max_forks_repo_name": "nmoteki/block-Krylov-linear-solvers", "max_forks_repo_head_hexsha": "0c123f474296219c1b944ad83f8e3c7abbf0c2b0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8062015504, "max_line_length": 134, "alphanum_fraction": 0.5780471964, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.914900957313305, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.693306805734782}} {"text": "#include \n#include \nusing namespace std;\n\n#include \n#include \n\n#define MATRIX_SIZE 50\n\nint main(int argc, char** argv) {\n Eigen::Matrix matrix_23;\n Eigen::Vector3d v_3d;//Matrix\n Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero();//Matrix\n Eigen::Matrix matrix_dynamic;\n Eigen::MatrixXd matric_x;\n\n matrix_23<<1,2,3,4,5,6;\n cout< result=matrix_23.cast()*v_3d; //cast 转换类型\n cout< eigen_solver (matrix_33);\n cout<< \"Eigen values = \"<matrix_NN;\n matrix_NN = Eigen::MatrixXd::Random(MATRIX_SIZE,MATRIX_SIZE);\n Eigen::Matrix v_Nd;\n v_Nd =Eigen::MatrixXd::Random(MATRIX_SIZE,1);\n\n //计时\n clock_t time_stt=clock();\n Eigen::Matrix x=matrix_NN.inverse()*v_Nd;\n cout<<\"time use in normal inverse is \"<<1000*(clock()-time_stt)/(double)CLOCKS_PER_SEC<<\"ms\"<\r\n#include \r\n#include // Linear Algebra library. Don't forget to add path to Makefile.\r\n\r\n#include \"HousingData.h\" // For reading data files.\r\n\r\n#ifndef ITR\r\n#define ITR 2000\r\n#endif\r\n\r\n#ifndef ALPHA\r\n#define ALPHA 0.01\r\n#endif\r\n\r\n// Made for convinance of managing \r\n// the max and min values of the data.\r\nstruct Tuple{\r\n float x;\r\n float y;\r\n};\r\n\r\nvoid loadData(Eigen::MatrixXf &X, Eigen::VectorXf &Y, std::ifstream &fp){\r\n int r = 0;\r\n HousingData data;\r\n // Read data line by line and sotre it into X matrix.\r\n while (fp >> data){\r\n // Again this could be put into an array.\r\n // See HousingData.h for why it is currently structered this way.\r\n //X(r,0) = 1; // Dummy value.\r\n X(r,0) = std::stof(data.crim, NULL);\r\n X(r,1) = std::stof(data.zn, NULL);\r\n X(r,2) = std::stof(data.indus, NULL);\r\n X(r,3) = std::stof(data.chas, NULL);\r\n X(r,4) = std::stof(data.nox, NULL);\r\n X(r,5) = std::stof(data.rm, NULL);\r\n X(r,6) = std::stof(data.age, NULL);\r\n X(r,7) = std::stof(data.dis, NULL);\r\n X(r,8) = std::stof(data.rad, NULL);\r\n X(r,9) = std::stof(data.tax, NULL);\r\n X(r,10) = std::stof(data.ptratio, NULL);\r\n X(r,11) = std::stof(data.B, NULL);\r\n X(r,12) = std::stof(data.lstat, NULL);\r\n\r\n Y(r) = std::stof(data.medv, NULL); // Values of interest.\r\n r++;\r\n }\r\n\r\n fp.clear();\r\n fp.seekg(0, fp.beg);// Reset to head of file. \r\n}\r\n/**\r\n * @param fp is a file pointer.\r\n * Function gets the number of rows in a file.\r\n */\r\nint getFileRowCount(std::ifstream &fp){\r\n int num_of_rows = 0;\r\n std::string rows;\r\n while (std::getline( fp, rows ))\r\n num_of_rows++;\r\n \r\n fp.clear();\r\n fp.seekg(0, fp.beg); // Reset to head of file.\r\n return num_of_rows;\r\n}\r\n\r\n/**\r\n * @param X Matrix of Quantitative Variables.\r\n * @param W Learned vector of weight coefficients\r\n * @param Y Vector of Response Variables.\r\n * Measures the Sum Squared Error of the learned weights.\r\n */\r\nfloat leastSquares(Eigen::MatrixXf &X, Eigen::VectorXf &W, Eigen::VectorXf &Y){\r\n Eigen::VectorXf e( Y.size() );\r\n e = (Y - X*W);\r\n for (int i = 0; i < e.size(); i++)\r\n e[i] = e[i]*e[i]/Y.size();\r\n\r\n return (float)e.sum();\r\n}\r\n/**\r\n * @param X Matrix of Quantitative Variables.\r\n * @param W Learned vector of weight coefficients, hypothosis.\r\n * @param Y Vector of Response Variables.\r\n * @param alpha The learning rate to apply.\r\n * @param iter The number of iterations to complete.\r\n * Use batch gradient descent to minimize the cost/error of the system.\r\n * Returns the cost history of the system over iterations.\r\n */\r\nfloat* BGD(Eigen::MatrixXf &X, Eigen::VectorXf &W, Eigen::VectorXf &Y, float alpha, int itr, const Tuple &maxmin){\r\n Eigen::VectorXf Hypo ( Y.size() );\r\n Eigen::VectorXf Loss ( Y.size() );\r\n Eigen::VectorXf Gradient ( Y.size() );\r\n float* costHistory = new float[itr];\r\n\r\n float cost = 0.0;\r\n for (int i = 0; i < itr; i++){\r\n Hypo = X*W;\r\n Loss = Hypo - Y;\r\n Gradient = (X.transpose() * Loss) / Y.size();\r\n W = W - alpha * Gradient;\r\n cost = leastSquares(X, W, Y);\r\n costHistory[i] = cost*(maxmin.x - maxmin.y) + maxmin.y;\r\n }\r\n return costHistory;\r\n}\r\n/**\r\n * @param X Matrix of Quantitative Variables.\r\n * @param Y Vector of Response Variables.\r\n * Nomralize the data between 0 and 1.\r\n * Returns a tuple of the max and min value.\r\n * Max is the x component and min is the y.\r\n */\r\nTuple normalize(Eigen::MatrixXf &X, Eigen::VectorXf &Y){\r\n float max_x, max_y, max;\r\n float min_x, min_y, min;\r\n Tuple maxmin;\r\n\r\n Eigen::MatrixXf::Index maxRow,maxCol;\r\n Eigen::MatrixXf::Index minRow,minCol;\r\n\r\n max_x = X.maxCoeff(&maxRow, &maxCol);\r\n max_y = Y.maxCoeff(&maxRow, &maxCol);\r\n\r\n min_x = X.minCoeff(&minRow, &minCol);\r\n min_y = Y.minCoeff(&minRow, &minCol);\r\n \r\n if (max_x < max_y)\r\n max = max_y;\r\n else\r\n max = max_x;\r\n\r\n if (min_x < min_y)\r\n min = min_x;\r\n else\r\n min = min_y;\r\n\r\n for (int i = 0; i < X.rows(); i++){\r\n for (int j = 0; j < X.cols(); j++){\r\n X(i,j) = (X(i,j) - min) / (max - min);\r\n }\r\n }\r\n \r\n for (int i = 0; i < Y.rows(); i++)\r\n Y(i) = (Y(i) - min) / (max - min);\r\n \r\n maxmin.x = max;\r\n maxmin.y = min;\r\n\r\n return maxmin;\r\n}\r\n/**\r\n * @param cost Dynamic array of cost history.\r\n * @param W Learned vector of weight coefficients, hypothesis.\r\n * @param Y Vector of Response Variables.\r\n * Saves data produced such as the cost history, weights/hypotheses, and normalization min max.\r\n */\r\nvoid saveData(float *cost, const Tuple &maxmin, Eigen::VectorXf &W){\r\n std::ofstream weights(\"weights.csv\");\r\n std::ofstream norm(\"normalize.csv\");\r\n std::ofstream costHistory(\"cost_history.csv\");\r\n\r\n if (weights.is_open()){\r\n for (int i = 0; i < W.size()-1; i++)\r\n weights << W(i) << \",\";\r\n weights << W(W.size()-1);\r\n }\r\n weights.close();\r\n\r\n if (norm.is_open()){\r\n norm << \"max\" << \",\" << maxmin.x << \"\\n\";\r\n norm << \"min\" << \",\" << maxmin.y << \"\\n\"; \r\n }\r\n norm.close();\r\n\r\n if(costHistory.is_open()){\r\n for (int i = 0; i < ITR; i++)\r\n if ( i % 2 ) // No need to see cost at every step.\r\n costHistory << i << \",\" << cost[i] << \"\\n\";\r\n }\r\n costHistory.close();\r\n}\r\n\r\nint main()\r\n{\r\n // Files in training and testing data.\r\n std::ifstream fp_train(\"./data/data/housing_train.csv\");\r\n std::ifstream fp_test(\"./data/data/housing_test.csv\");\r\n\r\n // Build maxtix for traning and testing data.\r\n Eigen::MatrixXf X(getFileRowCount(fp_train), COL_SIZE);\r\n Eigen::MatrixXf X_test(getFileRowCount(fp_test), COL_SIZE);\r\n \r\n // Build Vectors for target variables and weight/hypotheses.\r\n Eigen::VectorXf Y( X.rows() );\r\n Eigen::VectorXf Y_test( X_test.rows() );\r\n Eigen::VectorXf W ( X.cols() );// Size is the number of features/dimensions.\r\n\r\n Tuple maxmin; // Used to keep track of max and min value during normalization.\r\n float *costHistory; // Pointer for array to cost history.\r\n\r\n // Load data into matrices and vectors.\r\n loadData(X, Y, fp_train);\r\n loadData(X_test, Y_test, fp_test);\r\n fp_train.close(); // Don't need this anymore, data is now in the matrix.\r\n fp_test.close();\r\n\r\n // Set all initial weight/hypothesis values to 0.\r\n W = Eigen::VectorXf::Ones( X.cols() ) * 0;\r\n \r\n normalize(X, Y); // Normalize data.\r\n maxmin = normalize(X_test, Y_test); // Keep max and min values for future data sets.\r\n std::cout << \"Max: \" << maxmin.x << \" Min: \" << maxmin.y << std::endl;\r\n\r\n // Run batch gradient descent.\r\n costHistory = BGD(X, W, Y, ALPHA, ITR, maxmin);\r\n std::cout << \"SSE for training set: \" << leastSquares(X, W, Y) *\r\n (maxmin.x - maxmin.y) + maxmin.y << std::endl;\r\n std::cout << \"SSE for testing set: \" << leastSquares(X_test, W, Y_test) *\r\n (maxmin.x - maxmin.y) + maxmin.y << std::endl;\r\n\r\n saveData(costHistory, maxmin, W);\r\n delete costHistory;\r\n\r\n return 0;\r\n}", "meta": {"hexsha": "cbd755591ea7c73227a84b1c7e478d49b8e72c90", "size": 7545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "regression.cpp", "max_stars_repo_name": "boxman888/LinearRegression", "max_stars_repo_head_hexsha": "32826e44de32545a81ba52d0d6cc134e333765e1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T06:15:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T06:15:08.000Z", "max_issues_repo_path": "regression.cpp", "max_issues_repo_name": "boxman888/LinearRegression", "max_issues_repo_head_hexsha": "32826e44de32545a81ba52d0d6cc134e333765e1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "regression.cpp", "max_forks_repo_name": "boxman888/LinearRegression", "max_forks_repo_head_hexsha": "32826e44de32545a81ba52d0d6cc134e333765e1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5215517241, "max_line_length": 115, "alphanum_fraction": 0.5676607025, "num_tokens": 2084, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218434359676, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6932968234115391}} {"text": "#include \"case.hpp\"\n\n#include \n#include \n\nusing namespace Eigen;\n\nCase1::Case1(const Ref &matM, const Ref &matD,\n const Ref &matK)\n\n : ndim_(matM.cols()), matM_(matM), matD_(matD), matK_(matK),\n matC_(ndim_ * 2, ndim_ * 2), matG_(ndim_ * 2, ndim_ * 2),\n alphas(ndim_ * 2), betas(ndim_ * 2) {\n MatrixXd mzero = MatrixXd::Zero(ndim_, ndim_);\n MatrixXd mone = MatrixXd::Identity(ndim_, ndim_);\n matC_ << -matD_, -matK_, mone, mzero;\n matG_ << matM_, mzero, mzero, mone;\n\n GeneralizedEigenSolver ges(matC_, matG_, false);\n alphas = ges.alphas();\n betas = ges.betas();\n}\n", "meta": {"hexsha": "e3d62d6c5fb8b4e286afbc8e070af9724584d87e", "size": 688, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/case.cc", "max_stars_repo_name": "pan3rock/QuadEigsSOAR", "max_stars_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/case.cc", "max_issues_repo_name": "pan3rock/QuadEigsSOAR", "max_issues_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/case.cc", "max_forks_repo_name": "pan3rock/QuadEigsSOAR", "max_forks_repo_head_hexsha": "6b4a2e939c8987773cd7990f665e9ebf57ecdbde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.9130434783, "max_line_length": 78, "alphanum_fraction": 0.6569767442, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.69315649777489}} {"text": "#include \"matrix.h\"\n#include \"mex.h\"\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \"estimator.h\"\n#include \"prosac.h\"\n#include \"mlesac.h\"\n#include \"ransac.h\"\n\nusing namespace std;\nusing namespace theia;\nusing namespace Eigen;\n\n// Structure for a 2-D point\nstruct Point\n{\n\tdouble x;\n\tdouble y;\n\tPoint() {}\n\tPoint(double _x, double _y) : x(_x), y(_y) {}\n\tPoint(const Point& p)\n\t{\n\t\tx = p.x;\n\t\ty = p.y;\n\t}\n};\n\n// A pair of points that correspond to each other. These two points are two keypoints in to separate images that have been matched to each other\nstruct Correspondence\n{\n\tPoint p1;\n\tPoint p2;\n\tCorrespondence() {}\n\tCorrespondence(double x1, double y1, double x2, double y2)\n\t{\n\t\tp1.x = x1;\n\t\tp1.y = y1;\n\t\tp2.x = x2;\n\t\tp2.y = y2;\n\t}\n\tCorrespondence(Point& _p1, Point& _p2) : p1(_p1), p2(_p2) {}\n\tCorrespondence(const Correspondence& other) : p1(other.p1), p2(other.p2) { }\n};\n\n// Homography matrix is a 3-by-3 matrix which is the model we are trying to estimate\nstruct Homography\n{\n\tdouble Matrix[9];\n\tHomography() {}\n\tHomography(const Homography& other)\n\t{\n\t\tfor (size_t i = 0; i < 9; i++)\n\t\t{\n\t\t\tMatrix[i] = other.Matrix[i];\n\t\t}\n\t}\n};\n\n// This is the estimator class for estimating a homography matrix between two images. A model estimation method and error calculation method are implemented\nclass HomographyEstimator : public Estimator < Correspondence, Homography >\n{\npublic:\n\tHomographyEstimator() {}\n\t~HomographyEstimator() {}\n\n\n\n\tint SampleSize() const { return 4; }\n\tbool EstimateModel(const vector& data, vector* models) const\n\t{\n\t\tHomography model;\n\n\t\t//calculate homography -- see gc_lecture_notes pp. 17-19\n\t\tMatrixXd Q = MatrixXd::Zero(2 * data.size(), 9);\n\t\tfor (size_t i = 0; i < data.size(); i++)\n\t\t{\n\t\t\tQ(i, 0) = data[i].p2.x;\n\t\t\tQ(i, 1) = data[i].p2.y;\n\t\t\tQ(i, 2) = 1.0;\n\t\t\tQ(i, 6) = -1 * data[i].p2.x * data[i].p1.x;\n\t\t\tQ(i, 7) = -1 * data[i].p2.y * data[i].p1.x;\n\t\t\tQ(i, 8) = -1 * data[i].p1.x;\n\n\t\t\tQ(i + data.size(), 3) = data[i].p2.x;\n\t\t\tQ(i + data.size(), 4) = data[i].p2.y;\n\t\t\tQ(i + data.size(), 5) = 1.0;\n\t\t\tQ(i + data.size(), 6) = -1.0 * data[i].p2.x * data[i].p1.y;\n\t\t\tQ(i + data.size(), 7) = -1.0 * data[i].p2.y * data[i].p1.y;\n\t\t\tQ(i + data.size(), 8) = -1.0 * data[i].p1.y;\n\t\t}\n\n\t\tMatrixXd qtq = Q.transpose() * Q;\n\t\tJacobiSVD svd(qtq, ComputeThinV);\n\t\tsvd.computeV();\n\t\tMatrixXd minEigenVector = svd.matrixV().col(8);\n\t\tfor (size_t i = 0; i < 9; i++)\n\t\t{\n\t\t\tmodel.Matrix[i] = minEigenVector(i);\n\t\t}\n\t\tmodels->push_back(model);\n\t\treturn true;\n\t}\n\n\tdouble Error(const Correspondence& correspondence, const Homography& model) const\n\t{\n\t\t// calculate reporojection error\n\t\tdouble projectionPointZ = model.Matrix[6] * correspondence.p1.x + model.Matrix[7] * correspondence.p1.y + model.Matrix[8];\n\t\tdouble projectionPointX = (model.Matrix[0] * correspondence.p1.x + model.Matrix[1] * correspondence.p1.y + model.Matrix[2]) / projectionPointZ;\n\t\tdouble projectionPointY = (model.Matrix[3] * correspondence.p1.x + model.Matrix[4] * correspondence.p1.y + model.Matrix[5]) / projectionPointZ;\n\n\t\treturn (double) (fabs(projectionPointX - correspondence.p2.x) + fabs(projectionPointY - correspondence.p2.y));\n\t}\n};\n\n// This is the entry point from MATLAB to this routine\n// plhs and prhs represent a pointer to the left hand side (output) and a pointer to the right hand side (input) respectively\n// matlab function signature: H = homography_estimator(points1, points2, 'mode')\n// H -> 9-by-9 homography matrix as output\n// points1 -> n-by-2 matrix, coordinates of the keypoints of the first image\n// points2 -> n-by-2 matrix, coordinates of the keypoints of the second image\n// 'mode' -> {'ransac', 'prosac', 'mlesac'}\nvoid mexFunction(int nlhs, mxArray *plhs [], int nrhs, const mxArray*prhs [])\n{\n\tif (nlhs != 1)\n\t{\n\t\tmexPrintf(\"Only one output expected\\n\");\n\t\treturn;\n\t}\n\tif (nrhs != 3)\n\t{\n\t\tmexPrintf(\"Only three inputs expected\\n\");\n\t\treturn;\n\t}\n\n\tconst mwSize *dims1, *dims2;\n\tchar* modeStr;\n\tdouble *points1, *points2;\n\n\n\tdims1 = mxGetDimensions(prhs[0]);\n\tdims2 = mxGetDimensions(prhs[1]);\n\n\tint dim1y = (int) dims1[0]; int dim1x = (int) dims1[1];\n\tint dim2y = (int) dims2[0]; int dim2x = (int) dims2[1];\n\n\tif (dim1x != dim2x || dim1y != dim2y)\n\t{\n\t\tmexPrintf(\"Error! two input points arrays must be of the same size\\n\");\n\t\treturn;\n\t}\n\n\tif (dim1x != 2 || dim2x != 2)\n\t{\n\t\tmexPrintf(\"Error! Points must be 2-D!\\n\");\n\t\treturn;\n\t}\n\n\tmodeStr = mxArrayToString(prhs[2]);\n\n\tif (!modeStr || mxGetDimensions(prhs[2])[0] != 1)\n\t{\n\t\tmexPrintf(\"Error! Last argument must be an string!\\n\");\n\t\treturn;\n\t}\n\n\tmexPrintf(\"string:\\n%s\\n\", modeStr);\n\tvector correspondences(dim1y);\n\tpoints1 = mxGetPr(prhs[0]);\n\tpoints2 = mxGetPr(prhs[1]);\n\tfor (size_t j = 0; j < dim1y; j++)\n\t{\n\t\t/*Correspondence corr;\n\t\tcorr.p1.x = points1[j];\n\t\tcorr.p2.x = points2[j];\n\t\tcorr.p1.y = points1[dim1y + j];\n\t\tcorr.p2.y = points2[dim1y + j];*/\n\t\tcorrespondences[j] = Correspondence(points1[j], points1[dim1y + j], points2[j], points2[dim1y + j]);\n\t}\n\tHomography homographyModel;\n\tRansacParameters params;\n\tparams.error_thresh = 0.5;\n\tHomographyEstimator homographyEstimator;\n\tSampleConsensusEstimator *sacEstimator;\n\t// RANSAC mode\n\tif (!strcmp(\"ransac\", modeStr))\n\t{\n\t\tsacEstimator = new Ransac(params, homographyEstimator);\n\t}\n\t// MLESAC mode\n\telse if (!strcmp(\"mlesac\", modeStr))\n\t{\n\t\tsacEstimator = new Mlesac(params, homographyEstimator);\n\t}\n\t// PROSAC mode\n\telse if (!strcmp(\"prosac\", modeStr))\n\t{\n\t\tsacEstimator = new Prosac(params, homographyEstimator);\n\t}\n\t// Unknown mode\n\telse\n\t{\n\t\tmexPrintf(\"Error! unknown estimation mode selected!\\n\");\n\t\treturn;\n\t}\n\n\n\tsacEstimator->Initialize();\n\tRansacSummary summary;\n\tsacEstimator->Estimate(correspondences, &homographyModel, &summary);\n\n\tauto outArray = mxCreateDoubleMatrix(3, 3, mxREAL);\n\tdouble *outp = mxGetPr(outArray);\n\t// Copy the estimated homography matrix to the output matrix, note the difference between matrix's column-wise arrays vs. C's row-wise arrays convention\n\tauto lastElement = homographyModel.Matrix[8];\n\tfor (size_t i = 0; i < 3; i++)\n\t{\n\t\tfor (size_t j = 0; j < 3; j++)\n\t\t{\n\t\t\toutp[i * 3 + j] = homographyModel.Matrix[j * 3 + i] / lastElement;\n\t\t}\n\t}\n\n\tplhs[0] = outArray;\n}\n", "meta": {"hexsha": "c98077c0766c237bb8ffac5179cf2d0d11867eb7", "size": 6388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "homography_estimator.cpp", "max_stars_repo_name": "erfannoury/sac", "max_stars_repo_head_hexsha": "7e4c183a91bf16803bc78536476bba594bfba109", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-10-19T12:35:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T08:19:24.000Z", "max_issues_repo_path": "homography_estimator.cpp", "max_issues_repo_name": "erfannoury/sac", "max_issues_repo_head_hexsha": "7e4c183a91bf16803bc78536476bba594bfba109", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homography_estimator.cpp", "max_forks_repo_name": "erfannoury/sac", "max_forks_repo_head_hexsha": "7e4c183a91bf16803bc78536476bba594bfba109", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.2991452991, "max_line_length": 156, "alphanum_fraction": 0.6693800877, "num_tokens": 2069, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6930894270096563}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n//namespace plt = matplotlibcpp;\ntemplate \nusing Matrix = vector>;\nusing sec_type = std::chrono::microseconds;\nusing _type = float;\nconstexpr double _c = 0.9;\n\nstruct matrix_with_det\n{\n int det;\n Matrix mat;\n};\n\ntemplate \nvoid getCofactor(Matrix &A, Matrix &temp, int p, int q, int n)\n{\n int i = 0, j = 0;\n\n // Looping for each element of the matrix\n for (int row = 0; row < n; row++)\n {\n for (int col = 0; col < n; col++)\n {\n // Copying into temporary matrix only those element\n // which are not in given row and column\n if (row != p && col != q)\n {\n temp[i][j++] = A[row][col];\n\n // Row is filled, so increase row index and\n // reset col index\n if (j == n - 1)\n {\n j = 0;\n i++;\n }\n }\n }\n }\n}\n/* Recursive function for finding determinant of matrix.\n n is current dimension of A[][]. */\ntemplate \nT determinant(Matrix &A, int n)\n{\n\n // Base case : if matrix contains single element\n if (n == 1)\n return A[0][0];\n T D = 0; // Initialize result\n Matrix temp(n, vector(n, 0)); // To store cofactors\n\n float sign = 1; // To store sign multiplier\n\n // Iterate for each element of first row\n for (int f = 0; f < n; f++)\n {\n // Getting Cofactor of A[0][f]\n getCofactor(A, temp, 0, f, n);\n D += sign * A[0][f] * determinant(temp, n - 1);\n\n // terms are to be added with alternate sign\n sign = -sign;\n }\n\n return D;\n}\n\n// Function to get adjoint of A[N][N] in adj[N][N].\nvoid adjoint(Matrix<_type> &A, Matrix<_type> &adj)\n{\n int n = A.size();\n if (n == 1)\n {\n adj[0][0] = 1;\n return;\n }\n\n // temp is used to store cofactors of A[][]\n _type sign = 1;\n Matrix<_type> temp(n, vector<_type>(n, 0));\n\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < n; j++)\n {\n // Get cofactor of A[i][j]\n getCofactor(A, temp, i, j, n);\n\n // sign of adj[j][i] positive if sum of row\n // and column indexes is even.\n sign = ((i + j) % 2 == 0) ? 1 : -1;\n\n // Interchanging rows and columns to get the\n // transpose of the cofactor matrix\n adj[j][i] = (sign) * (determinant(temp, n - 1));\n }\n }\n}\n\n// Function to calculate and store inverse, returns false if\n// matrix is singular\nbool inverse(Matrix<_type> &A, Matrix<_type> &inverse)\n{\n // Find determinant of A[][]\n int det = determinant(A, A.size());\n //_type det = 6;\n if (det == 0)\n {\n cout << \"Singular matrix, can't find its inverse\";\n return false;\n }\n\n // Find adjoint\n Matrix<_type> adj;\n for (int i = 0; i < A.size(); i++)\n {\n adj.push_back(vector<_type>());\n for (int j = 0; j < A.size(); j++)\n adj[i].push_back(0);\n }\n adjoint(A, adj);\n\n // Find Inverse using formula \"inverse(A) = adj(A)/det(A)\"\n for (int i = 0; i < A.size(); i++)\n for (int j = 0; j < A.size(); j++)\n inverse[i][j] = adj[i][j] / float(det);\n\n return true;\n}\n\ntemplate \ndouble dotProduct(const vector &v1, const vector &v2)\n{\n double ret = 0;\n for (int i = 0; i < v1.size(); ++i)\n ret += (v1.at(i) * v2.at(i));\n return ret;\n}\n\ntemplate \nvector operator*(const double &c, const vector &v)\n{\n vector ret = v;\n for (auto &d : ret)\n d *= c;\n return ret;\n}\n\nvector<_type> operator*(Matrix<_type> &M, const vector<_type> &v)\n{\n int n = v.size();\n vector<_type> res(n, 0);\n for (size_t i = 0; i < n; i++)\n {\n for (size_t j = 0; j < n; j++)\n {\n res[i] += M[j][i] * v[j];\n }\n }\n return res;\n}\ntemplate \nvector subtract(const vector &v1, const vector &v2)\n{\n vector ret(v1.size());\n for (int i = 0; i < v1.size(); ++i)\n ret[i] = (v1[i] - v2[i]);\n return ret;\n}\ntemplate \nvector operator-(const vector &v1, const vector &v2)\n{\n vector ret(v1.size());\n for (int i = 0; i < v1.size(); ++i)\n ret[i] = v1[i] - v2[i];\n return ret;\n}\ntemplate \nvector inverse(const vector &v1)\n{\n vector ret(v1.size());\n for (int i = 0; i < v1.size(); ++i)\n ret[i] = -v1[i];\n return ret;\n}\ntemplate \nbool operator==(const vector &v1, const vector &v2)\n{\n if (v1.size() == v2.size())\n {\n if (v1.size())\n {\n if (v1[0] == v2[0])\n {\n if (v1[0] == 0)\n {\n int sign = 0;\n for (int i = 1; i < v1.size(); i++)\n {\n if (v1[i] == 0 && v2[i] == 0)\n continue;\n if (sign == 0)\n {\n if (v1[i] == v2[i])\n sign = 1;\n else if (v1[i] == -v2[i])\n sign = -1;\n else\n return false;\n }\n else if (v1[i] != sign * v2[i])\n {\n return false;\n }\n }\n }\n else\n {\n for (int i = 1; i < v1.size(); i++)\n {\n if (v1[i] != v2[i])\n {\n return false;\n }\n }\n }\n return true;\n }\n if (v1[0] == -v2[0])\n {\n for (int i = 1; i < v1.size(); i++)\n {\n if (v1[i] != -v2[i])\n {\n return false;\n }\n }\n return true;\n }\n return false;\n }\n else\n return true;\n }\n else\n return false;\n}\ntemplate \nvector operator+(const vector &v1, const vector &v2)\n{\n vector ret(v1.size());\n for (int i = 0; i < v1.size(); ++i)\n ret[i] = (v1.at(i) + v2.at(i));\n return ret;\n}\nvector<_type> roundV(vector<_type> a)\n{\n for (size_t i = 0; i < a.size(); i++)\n {\n a[i] = round(a[i]);\n }\n return a;\n}\n\nvector<_type> proj(const vector<_type> &v1, const vector<_type> &v2)\n{\n vector<_type> proj = (dotProduct(v1, v2) / dotProduct(v1, v1)) * v1;\n return proj;\n}\n\nvector<_type> proj(const vector<_type> &v1, const vector &v2)\n{\n vector<_type> proj = (dotProduct(v1, v2) / dotProduct(v1, v1)) * v1;\n return proj;\n}\n\nMatrix<_type> gSchmidt(const Matrix &vspace)\n{\n Matrix<_type> uspace(vspace.size(), vector<_type>(vspace[0].size()));\n for (int i = 0; i < vspace[0].size(); i++)\n {\n uspace[0][i] = vspace[0][i];\n }\n for (int i = 1; i < vspace.size(); ++i)\n {\n for (int j = 0; j < i; ++j)\n {\n uspace.at(i) = subtract(vspace.at(i), proj(uspace.at(j), vspace.at(i)));\n }\n }\n return uspace;\n}\nMatrix<_type> gSchmidt(const Matrix<_type> &vspace, int limit)\n{\n Matrix<_type> uspace;\n for (int i = 0; i <= limit; ++i)\n {\n uspace.push_back(vspace.at(i));\n for (int j = 0; j < i; ++j)\n {\n uspace.at(i) = uspace.at(i) - proj(uspace.at(j), vspace.at(i));\n }\n }\n return uspace;\n}\ntemplate \nvoid printVS(const Matrix &vspace)\n{\n for (auto &v : vspace)\n {\n cout << '|';\n for (auto &d : v)\n cout << d << ' ';\n cout << \"|\\n\";\n }\n}\ntemplate \nvoid printVS(const Matrix &vspace, ostream &file)\n{\n file << '[';\n for (auto &v : vspace)\n {\n file << '[';\n for (auto &d : v)\n file << d << ' ';\n file << \"]\\n\";\n }\n file << \"]\\n\";\n}\ntemplate \nvoid printVec(const vector &v)\n{\n cout << endl;\n cout << \"$$$$$$$$$$$$$$$$$$$$$$$$\" << endl;\n for (auto &d : v)\n cout << d << ' ';\n cout << \"$$$$$$$$$$$$$$$$$$$$$$$$\" << endl;\n}\ntemplate \nvoid printVec(const vector &v, ostream &file)\n{\n file << endl;\n file << \"$$$$$$$$$$$$$$$$$$$$$$$$\" << endl;\n for (auto &d : v)\n file << d << ' ';\n file << endl\n << \"$$$$$$$$$$$$$$$$$$$$$$$$\" << endl;\n}\ntemplate \nfloat mu(int k1, int k2, Matrix *m, Matrix<_type> *gsm)\n{\n T init = 0;\n vector *a = &m->at(k1);\n vector<_type> *b = &gsm->at(k2);\n return std::inner_product(a->begin(), a->end(), b->begin(), init) /\n std::inner_product(b->begin(), b->end(), b->begin(), init);\n}\ntemplate \nfloat mu(vector &a, vector &b)\n{\n float init = 0.0;\n double d = std::inner_product(a.begin(), a.end(), b.begin(), init);\n double dd = std::inner_product(b.begin(), b.end(), b.begin(), init);\n return d / dd;\n}\ntemplate \ndouble squaredLengthOfVector(vector *v)\n{\n return std::inner_product(v->begin(), v->end(), v->begin(), 0.0);\n}\ntemplate \ndouble squaredLengthOfVector(vector &v)\n{\n return std::inner_product(v.begin(), v.end(), v.begin(), 0.0);\n}\n\nint KabatianskyLevenshteinC(Matrix &M)\n{\n float angle = 1;\n for (int i = 0; i < M.size(); i++)\n {\n auto v1 = M[i];\n for (int j = i + 1; j < M.size(); j++)\n {\n auto v2 = M[j];\n float t = dotProduct(v1, v2) / (sqrt(squaredLengthOfVector(&v1)) *\n sqrt(squaredLengthOfVector(&v2)));\n angle = fmin(angle, t);\n }\n }\n return fmax((int)(-1.0 / 2.0 * log(1 - cos(angle)) - 0.099), 1);\n}\n\nvector lll_reduce(vector<_type> &gsreducing, vector &target,\n vector &reducing)\n{\n vector t = target - round(mu(target, gsreducing)) * reducing;\n return t;\n}\n\nvoid LLL(Matrix &B, ostream &o)\n{\n bool cont;\n Matrix<_type> gramSmidt;\n int iter = 0;\n do\n {\n iter++;\n gramSmidt = gSchmidt(B);\n cont = false;\n for (int i = 1; i < B.size(); i++)\n {\n for (int j = 0; j < i; j++)\n {\n B.at(i) = lll_reduce(gramSmidt.at(j), B.at(i), B.at(j));\n }\n }\n for (int i = 1; i < B.size() && !cont; i++)\n {\n float a1 = squaredLengthOfVector(&gramSmidt.at(i - 1));\n float a2 = squaredLengthOfVector(&gramSmidt.at(i));\n float mu1 = mu(i, i - 1, &B, &gramSmidt);\n if (a2 < (_c - mu1 * mu1) * a1)\n {\n B.at(i - 1).swap(B.at(i));\n cont = true;\n }\n }\n } while (cont);\n o << \"lll iter : \" << iter << \"|\\n\";\n}\n\nvoid LLL(Matrix &B)\n{\n bool cont;\n Matrix<_type> gramSmidt;\n int iter = 0;\n do\n {\n iter++;\n gramSmidt = gSchmidt(B);\n cont = false;\n for (int i = 1; i < B.size(); i++)\n {\n for (int j = 0; j < i; j++)\n {\n B.at(i) = lll_reduce(gramSmidt.at(j), B.at(i), B.at(j));\n }\n float a1 = squaredLengthOfVector(&gramSmidt.at(i - 1));\n float a2 = squaredLengthOfVector(&gramSmidt.at(i));\n float mu1 = mu(i, i - 1, &B, &gramSmidt);\n if (a2 < (_c - mu1 * mu1) * a1)\n {\n B.at(i - 1).swap(B.at(i));\n i--;\n cont = true;\n }\n }\n } while (cont);\n}\n// opera 918\nvoid LLL2(Matrix &B)\n{\n bool cont;\n Matrix<_type> gramSmidt;\n int iter = 0;\n do\n {\n iter++;\n gramSmidt = gSchmidt(B);\n cont = false;\n for (int i = 1; i < B.size(); i++)\n {\n for (int j = i - 1; j > 0; j--)\n {\n B.at(i) = lll_reduce(gramSmidt.at(j), B.at(i), B.at(j));\n }\n float a1 = squaredLengthOfVector(&gramSmidt.at(i - 1));\n float a2 = squaredLengthOfVector(&gramSmidt.at(i));\n float mu1 = mu(i, i - 1, &B, &gramSmidt);\n if (a2 < (_c - mu1 * mu1) * a1)\n {\n B.at(i - 1).swap(B.at(i));\n i--;\n cont = true;\n }\n }\n } while (cont);\n}\nvoid preparePlot(Matrix<_type> res, Matrix<_type> og)\n{\n map<_type, _type> m;\n vector<_type> x, y, z;\n int maxSize = 20;\n if (res.size() == 2)\n {\n vector<_type> bounds = 2 * og[0] + 2 * og[1];\n int boundX = bounds[0];\n int boundY = bounds[1];\n for (int i = -maxSize; i < maxSize; i++)\n {\n for (int j = -maxSize; j < maxSize; j++)\n {\n vector<_type> t = i * res.at(0) + j * res.at(1);\n if (-boundX < t[0] < boundX && -boundY < t[1] < boundY)\n {\n x.push_back(t.at(0));\n y.push_back(t.at(1));\n }\n }\n }\n //plt::plot(x, y, \".\");\n }\n if (res.size() == 3)\n {\n vector<_type> bounds = 2 * og[0] + 2 * og[1];\n int boundX = bounds[0];\n int boundY = bounds[1];\n int boundZ = bounds[2];\n for (int i = -maxSize; i < maxSize; i++)\n {\n for (int j = -maxSize; j < maxSize; j++)\n for (int k = -maxSize; k < maxSize; j++)\n {\n vector<_type> t = i * res.at(0) + j * res.at(1) + k * res.at(2);\n if (-boundX < t[0] < boundX && -boundY < t[1] < boundY)\n {\n x.push_back(t.at(0));\n y.push_back(t.at(1));\n z.push_back(t.at(2));\n }\n }\n }\n }\n /*plt::plot({ 0 }, { 0 }, \"bo\");\n plt::plot({ res.at(0).at(0) }, { res.at(0).at(1) }, \"r+\");\n plt::plot({ res.at(1).at(0) }, { res.at(1).at(1) }, \"r+\");\n plt::plot({ og.at(0).at(0) }, { og.at(0).at(1) }, \"g*\");\n plt::plot({ og.at(1).at(0) }, { og.at(1).at(1) }, \"g*\");*/\n}\n//https://tel.archives-ouvertes.fr/tel-01245066v2/document\nvector kleinSample(Matrix &B, Matrix<_type> &GSO, float deviation, vector &c)\n{\n vector v(c.size(), 0);\n std::random_device mch;\n std::default_random_engine generator(mch());\n\n double d, z;\n for (int i = B.size() - 1; i >= 0; i--)\n {\n double length = squaredLengthOfVector(GSO.at(i));\n d = dotProduct(c, GSO.at(i)) / length;\n double sigma = deviation / sqrt(length);\n std::normal_distribution distribution(d, 1);\n z = round(distribution(generator));\n //std::cout << z << \" \" ;\n c = c - z * B[i];\n v = v + z * B[i];\n }\n //std::cout << std::endl;\n return v;\n}\n\n// todo discover\nvector<_type> sample_gaussian(Matrix<_type> &B)\n{\n vector<_type> a;\n a = (5 - rand() % 10) * B.back();\n for (auto b : B)\n a = a + (5 - rand() % 10) * b;\n return a;\n}\n\nbool reduce(vector &p, Matrix &L, vector &lengths)\n{\n double s = squaredLengthOfVector(p);\n for (size_t i = 0; i < L.size(); i++)\n {\n if (s >= lengths[i])\n {\n auto diff = p - L[i];\n double s2 = squaredLengthOfVector(diff);\n if (s2 < s)\n {\n p = diff;\n return true;\n }\n }\n }\n return false;\n}\n\nvector gauss_reduce(vector &v_new, Matrix &L, Matrix &S, vector &lengths)\n{\n bool cont = true;\n while (cont)\n {\n auto same = std::find_if(L.begin(), L.end(), [&v_new](vector &v) { return v_new == v; });\n if (same != L.end())\n {\n return vector(v_new.size());\n }\n // 2 раза считается разница, можно сохранить и сравнить с минимумом\n cont = reduce(v_new, L, lengths);\n }\n auto it = L.begin();\n auto it2 = lengths.begin();\n int i = 0;\n vector a(v_new.size());\n while (it != L.end())\n {\n double v_new_length = squaredLengthOfVector(&v_new);\n vector v = *it;\n if (lengths[i] > v_new_length)\n {\n a = v - v_new;\n if (squaredLengthOfVector(a) <= lengths[i])\n {\n S.push_back(a);\n it = L.erase(it);\n it2 = lengths.erase(it2);\n }\n else\n {\n ++it;\n ++it2, ++i;\n }\n }\n else\n {\n ++it;\n ++it2, ++i;\n }\n }\n return v_new;\n}\n// https://cseweb.ucsd.edu/~daniele/papers/Sieve.pdf\n// c= 1000\nvector gaussSieve(Matrix &B, float bound, ostream &o)\n{\n Matrix L, S;\n vector v_new;\n Matrix<_type> gramSmidt = gSchmidt(B);\n vector squarelengthsVector;\n int K = 0, iter = 0;\n //int c = KabatianskyLevenshteinC(B);\n map _map;\n\n size_t max_number_of_collistions = 200;\n do\n {\n _map.insert(make_pair(iter, K));\n\n iter++;\n if (S.size() > 0)\n {\n v_new = S.back();\n S.pop_back();\n }\n else\n {\n vector a(B[0].size(), 0);\n v_new = kleinSample(B, gramSmidt, 1, a);\n }\n v_new = gauss_reduce(v_new, L, S, squarelengthsVector);\n if (!v_new.size() ||\n std::count(v_new.begin(), v_new.end(), 0) == v_new.size())\n {\n K++;\n }\n else if (sqrt(squaredLengthOfVector(v_new)) < bound)\n {\n o << \"early exit gauss iter : \" << iter << \"|\\n\";\n return v_new;\n }\n else\n {\n L.push_back(v_new);\n squarelengthsVector.push_back(squaredLengthOfVector(v_new));\n }\n max_number_of_collistions = std::max(max_number_of_collistions, L.size());\n } while (10 * K < max_number_of_collistions + 2000 || L.size() == 0);\n vector shortestVector = L[0];\n int _a = 0, count = 0;\n for (int i = 1; i < L.size(); i++)\n {\n if (sqrt(squaredLengthOfVector(L[i])) <= bound)\n {\n count++;\n }\n if (squaredLengthOfVector(shortestVector) > squaredLengthOfVector(L[i]))\n {\n shortestVector = L[i];\n _a = i;\n }\n }\n cout << \"count \" << count << endl;\n cout << \"gauss at : \" << _map.at(_a) << endl;\n o << \"gauss iter : \" << iter << \"|\\n\";\n return shortestVector;\n}\n\nvector<_type> randomInBall(const int dimm, float r)\n{\n vector<_type> randVector(dimm);\n for (int i = 0; i < dimm; i++)\n {\n randVector[i] = (rand() % (int)(r + 1));\n }\n return (r * (rand() / double(RAND_MAX)) / sqrt(squaredLengthOfVector(randVector))) * randVector;\n}\n//https://crypto.stackexchange.com/questions/29661/how-to-find-the-value-of-a-vector-modulo-a-basis-in-lattice-based-cryptography/29701#29701\nvector<_type> mod(vector<_type> vec, Matrix<_type> m)\n{\n Matrix<_type> r(m.size(), vector<_type>(m.size(), 0));\n inverse(m, r);\n return m * roundV(r * vec);\n}\n\nvoid ListReduce(vector &p, Matrix &L, vector &lengths)\n{\n bool cont = true;\n while (cont)\n {\n auto same = std::find(L.begin(), L.end(), p);\n if (same != L.end())\n {\n p = vector(p.size());\n return;\n }\n if (!reduce(p, L, lengths))\n return;\n /*auto f = std::find_if(L.begin(), L.end(), [&p](vector& v) {\n return squaredLengthOfVector(&p) >= squaredLengthOfVector(&v) && squaredLengthOfVector(&(p - v)) < squaredLengthOfVector(&p);\n });\n if (f == L.end()) return;\n p = p - *f;*/\n }\n}\n//https://math.stackexchange.com/questions/396382/what-does-this-dollar-sign-over-arrow-in-function-mapping-mean\n//https://eprint.iacr.org/2014/714.pdf\nvector ListSieve(Matrix &B, float bound, ostream &o)\n{\n Matrix L;\n Matrix<_type> gramSmidt = gSchmidt(B);\n vector a(B[0].size(), 0);\n vector lengths;\n map _map;\n size_t max_number_of_collistions = 200;\n int iter = 0;\n for (int i = 0, k = 0; 10*i < max_number_of_collistions + 2000 || L.size() == 0; k++)\n {\n iter++;\n vector v = kleinSample(B, gramSmidt, 1, a);\n ListReduce(v, L, lengths);\n bool isZero = true;\n for (auto in : v)\n {\n if (in != 0)\n {\n isZero = false;\n break;\n }\n }\n _map.insert(make_pair(k, i));\n if (isZero)\n {\n i++;\n }\n else if (sqrt(squaredLengthOfVector(v)) < bound)\n {\n o << \"early list iter : \" << iter << \"|\\n\";\n return v;\n }\n else\n {\n L.push_back(v);\n lengths.push_back(squaredLengthOfVector(v));\n }\n max_number_of_collistions = std::max(max_number_of_collistions, L.size());\n\n }\n vector shortestVector = L[0];\n int _a = 0, count = 0;\n for (int i = 1; i < L.size(); i++)\n {\n if (sqrt(squaredLengthOfVector(L[i])) <= bound)\n {\n count++;\n }\n if (squaredLengthOfVector(shortestVector) > squaredLengthOfVector(L[i]))\n {\n shortestVector = L[i];\n _a = i;\n }\n }\n cout << \"count \" << count << endl;\n cout << \"list at : \" << _map.at(_a) << endl;\n o << \"list iter : \" << iter << \"|\\n\";\n return shortestVector;\n}\n\nvector sumVectorsWithCoeff(Matrix &matrix, vector &c)\n{\n vector a(c.size(), 0);\n for (size_t i = 0; i < c.size(); i++)\n {\n a = a + c[i] * matrix[i];\n }\n return a;\n}\n\nbool checkifBiggerByEachCoordinate(vector &a, vector &b)\n{\n for (size_t i = 0; i < a.size(); i++)\n {\n if (abs(a[i]) > abs(b[i]))\n return false;\n }\n return true;\n}\n\nvector LLLenumerate(Matrix &matrix, ofstream &myfile)\n{\n Matrix enumeration;\n int n = matrix.size();\n int lim = pow(2, n * (n - 1) / 4.0);\n vector c(n, 0);\n c[0] = 1;\n vector shortest = sumVectorsWithCoeff(matrix, c);\n auto shortestL = squaredLengthOfVector(shortest);\n long long tmpL;\n vector tmp;\n tmp = sumVectorsWithCoeff(matrix, c);\n if (!checkifBiggerByEachCoordinate(shortest, tmp))\n {\n tmpL = squaredLengthOfVector(tmp);\n if (tmpL > 0 && shortestL > tmpL)\n {\n shortestL = tmpL;\n shortest = tmp;\n }\n }\n for (int i = 0; i < n;)\n {\n int &a = c[i];\n if (a == -lim)\n {\n for (int j = 0; j < i; j++)\n c[j] = -lim;\n a++;\n i = 0;\n tmp = sumVectorsWithCoeff(matrix, c);\n if (!checkifBiggerByEachCoordinate(shortest, tmp))\n {\n tmpL = squaredLengthOfVector(tmp);\n if (tmpL > 0 && shortestL > tmpL)\n {\n shortestL = tmpL;\n shortest = tmp;\n }\n }\n // for (auto &bb : c)\n // cout << bb;\n // cout << endl;\n // // enumeration.push_back(sumVectorsWithCoeff(matrix, c));\n }\n else if (a < lim)\n {\n a++;\n if (a == lim)\n i++;\n else\n i = 0;\n tmp = sumVectorsWithCoeff(matrix, c);\n if (!checkifBiggerByEachCoordinate(shortest, tmp))\n {\n tmpL = squaredLengthOfVector(tmp);\n if (tmpL > 0 && shortestL > tmpL)\n {\n shortestL = tmpL;\n shortest = tmp;\n }\n }\n // for (auto &bb : c)\n // cout << bb;\n // cout << endl;\n // // enumeration.push_back(sumVectorsWithCoeff(matrix, c));\n }\n else if (a == lim)\n {\n i++;\n }\n }\n return shortest;\n}\n\n//https://web.eecs.umich.edu/~cpeikert/pubs/lattice-survey.pdf\nMatrix generateLattice(int dimm, int diff, int iter, bool print, ofstream &file)\n{\n Matrix m(dimm, vector(dimm, 0));\n\n file << \"---------------------------------------------\\n\\n\"\n << \"dimm: \" << dimm << \" iter: \" << iter << \" diff: \" << diff << \"|\\n\";\n int summ = 0;\n srand(time(0));\n file << '[';\n for (auto &v : m)\n {\n file << '[';\n for (auto &el : v)\n {\n float f = rand();\n el = f / RAND_MAX * (float)diff * 3;\n summ += el;\n file << el << ' ';\n }\n file << \"]\\n\";\n }\n file << \"]\\n\";\n file << \" summ: \" << summ << \"\\n\\n\";\n return m;\n}\n//void preprocessVoronoi(Matrix& B)\n//{\n// LLL(B);\n//}\n//\n//vector findRelevantHelper(Matrix& B, int p, int n)\n//{\n// vector res(B.size(), 0);\n// for (size_t i = 0; i < n; i++)\n// {\n// if (p & 1)\n// {\n// res = res - B[i];\n// }\n// p = p >> 1;\n// }\n// for (auto& b : res)\n// b = b / 2;\n// return res;\n//}\n//\n//vector CVPP2V(vector& t, Matrix>& Voronoi) {\n// int i = 0;\n// vector t0(t.size()), ti(t.size());\n// while (find_if(Voronoi.begin(), Voronoi.end(), [&ti](auto& v) {\n// return v[0] == ti\n// }) == Voronoi.end()) {\n// float tmp = mu(ti, Voronoi[0][0]);\n// int maxi = 0;\n// for (size_t j = 1; j < Voronoi.size(); j++)\n// {\n// if (tmp < mu(ti,Voronoi[j][0])) {\n// maxi = j;\n// }\n// }\n// ti = ti - ti;\n// i++;\n// }\n//\n// return t0 - ti;\n//}\n//vector CVPP(vector& t, Matrix& B, Matrix>& Voronoi) {\n// vector res(t.size(), 0), tp;\n// for (auto& v : B) {\n// res = res + mu(t, v) * v;\n// }\n// // not sure about this\n// int p = 0;\n// while(true) {\n// p++;\n// if (squaredLengthOfVector(t) < (squaredLengthOfVector(pow(2, p) * Voronoi[0][0]))) {\n// break;\n// }\n// }\n//\n// for (int i = p - 1; i > 0; i--) {\n// tp = tp - CVPP2V(tp, pow(2, i - 1) * Voronoi);\n// }\n// return res - tp;\n//}\n//\n//vector rankReduceCVP(const vector& t, Matrix& B, Matrix>& Voronoi, int H) {\n// vector res(t.size(), 0), v, closest, tmp;\n// int h = mu(t, B.at(Voronoi.size()));\n// float length, tmplength;\n// int i = h - H + 1;\n// res = CVPP(t - h * B.at(Voronoi.size()), Voronoi.back());\n// length = squaredLengthOfVector(res);\n// i++;\n// // todo is it correct?\n// for (; abs(i - h) < H; i++) {\n// v = CVPP(t - i * B.at(Voronoi.size()), Voronoi.back());\n// tmp = v - t;\n// tmplength = squaredLengthOfVector(tmp);\n// if (tmplength < length) {\n// length = tmplength;\n// res = tmp;\n// }\n// }\n// return res;\n//}\n//\n//Matrix> findRelevant(Matrix& B, Matrix>& Voronoi, int H)\n//{\n// Matrix> res;\n// vector t, c;\n// int l = pow(2, B.size());\n// // p - вектор из нелей и 1\n// for (int p = 1; p < l; p++)\n// {\n// t = findRelevantHelper(B, p, B.size());\n// c = rankReduceCVP(t, B, Voronoi, H);\n// t = 2 * (t - c);\n// c = inverse(t);\n// res.push_back({ t, c });\n// }\n// return res;\n//}\n//void removeNonRelevant(Matrix>& res)\n//{\n// for (size_t i = 0; i < res.size(); i++)\n// {\n// for (size_t j = 0; j < res.size(); j++)\n// {\n// if (i != j && squaredLengthOfVector(res[j][0] - 0.5 * res[i][0]) <= squaredLengthOfVector(0.5 * res[i][0])) {\n// // debug whats in it\n// res.erase(res.begin() + i);\n// }\n// }\n//\n// }\n//\n//}\n//\n//Matrix> computeVcell(Matrix& B, Matrix>& Voronoi, int H)\n//{\n// Matrix> res = findRelevant(B, Voronoi, H);\n// removeNonRelevant(res);\n// return res;\n//}\n//// https://cseweb.ucsd.edu/~pvoulgar/files/voronoi_full.pdf\n//void basicVoronoiCell(Matrix& B)\n//{\n// preprocessVoronoi(B);\n// Matrix> Voronoi(1);\n// Matrix newB;\n// Voronoi[0] = { B[0], inverse(B[0]) };\n// for (int i = 1; i < B.size(); i++)\n// {\n// for (size_t j = 0; j < i; j++)\n// {\n// newB.push_back(B[j]);\n// }\n// // nedd to remake to vec of vec of vec\n// Voronoi = computeVcell(newB, Voronoi, pow(2, 0.5 * i));\n// }\n//}\n// void printShortestVector(const plll::linalg::math_matrix & A,\n// unsigned index, const plll::arithmetic::Integer & sqnorm)\n// {\n// std::cout << \"The currently shortest vector is \" << A.row(index)\n// << \" with squared norm \" << sqnorm << \" (Integer)\\n\";\n// }\n// void printShortestVector_LI(const plll::linalg::math_matrix > & A,\n// unsigned index, const plll::arithmetic::NInt & sqnorm)\n// {\n// std::cout << \"The currently shortest vector is \" << A.row(index)\n// << \" with squared norm \" << sqnorm << \" (NInt)\\n\";\n// }\n\nplll::LatticeReduction::MinCallbackFunction_LI f_LI(ostream &file, vector &r)\n{\n return [&r, &file](const plll::linalg::math_matrix> &A,\n unsigned index, const plll::arithmetic::NInt &sqnorm) {\n auto i = A.row(index).enumerate();\n int iter = 0;\n while (i.has_current())\n {\n r[iter++] = plll::arithmetic::convert(i.current());\n i.next();\n }\n file << \"The currently shortest vector is \" << A.row(index)\n << \" with squared norm \" << sqnorm << \" (Integer)\\n\";\n };\n}\n\nplll::LatticeReduction::MinCallbackFunction f(ostream &file, vector &r)\n{\n return [&r, &file](const plll::linalg::math_matrix &A,\n unsigned index, const plll::arithmetic::Integer &sqnorm) {\n auto i = A.row(index).enumerate();\n int iter = 0;\n while (i.has_current())\n {\n r[iter++] = plll::arithmetic::convert(i.current());\n i.next();\n }\n file << \"The currently shortest vector is \" << A.row(index)\n << \" with squared norm \" << sqnorm << \" (Integer)\\n\";\n };\n}\nvector shortestVectorByVoronoi(Matrix &B, int dimm, ostream &file)\n{\n cout << \"mat\";\n vector res(dimm);\n cout << \"mat\";\n plll::linalg::base_matrix mat(dimm, dimm);\n cout << \"mat\";\n\n plll::linalg::base_matrix::Enumerator iterr = mat.enumerate();\n cout << \"mat\";\n\n int i = 0, x, y;\n while (iterr.has_current())\n {\n x = i / dimm;\n y = i % dimm;\n iterr.current() = plll::arithmetic::Integer(B[x][y]);\n iterr.next();\n i++;\n }\n cout << mat << endl;\n plll::LatticeReduction lr;\n //cin >> mat;\n plll::linalg::math_matrix A(mat);\n lr.setLattice(A);\n lr.setSVPMode(plll::LatticeReduction::SVP_VoronoiCellSVP);\n cout << \"mat\";\n\n lr.setMinCallbackFunction(f(file, res), f_LI(file, res));\n lr.svp();\n file << \"voronoi res \" << lr.getLattice() << endl\n << endl;\n mat = lr.getLattice();\n iterr = mat.enumerate();\n for (int i = 0; i < dimm; i++)\n {\n res[i] = plll::arithmetic::convert(iterr.current());\n iterr.next();\n }\n return res;\n}\n\nmatrix_with_det readFromFile(ifstream &myfile)\n{\n matrix_with_det res;\n string line;\n std::regex e(\"det.*\");\n getline(myfile, line);\n // cout << line << endl;\n // while (!regex_match(line, e))\n // {\n if (myfile.eof())\n {\n res.det = 0;\n return res;\n }\n // getline(myfile, line);\n // cout << line << \"k\" << endl;\n // }\n std::regex e2(\"\\\\d+\");\n std::smatch sm;\n\n // std::regex_search(line, sm, e2);\n int det = 3;\n // line = sm.suffix().str();\n // cout << \"\\ndet \" << det;\n // std::regex_search(line, sm, e2);\n int dimm = 3;\n \n // std::regex_search(line, sm, e2);\n // int det = stoi(sm.str());\n // line = sm.suffix().str();\n // cout << \"\\ndet \" << det;\n // std::regex_search(line, sm, e2);\n // int dimm = stoi(sm.str());\n \n Matrix matr(dimm, vector(dimm));\n cout << \"\\ndimm \" << dimm;\n\n for (int i = 0; i < dimm; i++)\n {\n getline(myfile, line);\n int j = 0;\n while (std::regex_search(line, sm, e2))\n {\n matr[i][j++] = stoi(sm.str());\n line = sm.suffix().str();\n }\n cout << endl;\n }\n printVS(matr);\n res.det = det;\n res.mat = matr;\n return res;\n}\n\nvoid printResVector(vector &v, string method, ostream &o)\n{\n o << endl\n << method << \" size: \" << sqrt(squaredLengthOfVector(v)) << endl\n << \"[ \";\n for (auto &a : v)\n {\n o << a << \" \";\n }\n o << \"] \" << endl;\n}\n\nint main()\n{\n\n ofstream myfile;\n\n ifstream datafile;\n myfile.open(\"example.txt\");\n\n datafile.open(\"det3.txt\");\n matrix_with_det md = readFromFile(datafile);\n cout << md.det;\n\n while (md.det != 0)\n {\n cout << \"det\" << md.det;\n\n Matrix matrix = md.mat;\n Matrix matrix2 = matrix;\n Matrix matrix3 = matrix;\n Matrix original(matrix2);\n Matrix gramSmidt = gSchmidt(matrix);\n\n cout << \"starting voronoi\" << endl;\n auto t1 = std::chrono::high_resolution_clock::now();\n int dimm = matrix.size();\n cout << \"t\";\n auto vector_voronoi = shortestVectorByVoronoi(matrix, matrix.size(), myfile);\n auto t2 = std::chrono::high_resolution_clock::now();\n auto duration = std::chrono::duration_cast(t2 - t1).count();\n myfile << \"voronoi duration \" << duration << endl;\n myfile << \"\\n\\n\";\n\n float bound = 1;\n // bound = 1;\n cout << \"starting gauss\" << endl;\n t1 = std::chrono::high_resolution_clock::now();\n vector sv = gaussSieve(matrix2, bound, myfile);\n t2 = std::chrono::high_resolution_clock::now();\n duration = std::chrono::duration_cast(t2 - t1).count();\n myfile << \"gauss duration: \" << duration << endl;\n myfile << \"\\n\\n\";\n cout << \"f\\n\\n\";\n\n cout << \"starting list\" << endl;\n t1 = std::chrono::high_resolution_clock::now();\n vector v3 = ListSieve(matrix3, bound, myfile);\n // auto vector_voronoi = v3;\n t2 = std::chrono::high_resolution_clock::now();\n duration = std::chrono::duration_cast(t2 - t1).count();\n myfile << \"list duration: \" << duration << endl;\n\n bound = 1.01 * (sqrt(dimm)) * pow(abs(md.det), 1.0 / dimm);\n myfile << \"bound \" << bound << endl;\n t1 = std::chrono::high_resolution_clock::now();\n vector gauss_with_bound = gaussSieve(matrix2, bound, myfile);\n t2 = std::chrono::high_resolution_clock::now();\n duration = std::chrono::duration_cast(t2 - t1).count();\n myfile << \"gauss with bound duration: \" << duration << endl;\n myfile << \"\\n\\n\";\n cout << \"f\\n\\n\";\n\n cout << \"starting bound list\" << endl;\n t1 = std::chrono::high_resolution_clock::now();\n vector list_with_bound = ListSieve(matrix3, bound, myfile);\n // auto vector_voronoi = v3;\n t2 = std::chrono::high_resolution_clock::now();\n duration = std::chrono::duration_cast(t2 - t1).count();\n myfile << \"list with bound duration: \" << duration;\n\n if (squaredLengthOfVector(list_with_bound) != squaredLengthOfVector(gauss_with_bound))\n {\n myfile << \"found different norms of vectors\";\n printResVector(list_with_bound, \"list with bound\", myfile);\n printResVector(gauss_with_bound, \"gauss with bound\", myfile);\n }\n else\n {\n myfile << endl\n << \"shortest with bound norm\" << (long)squaredLengthOfVector(gauss_with_bound) << endl;\n printVec(gauss_with_bound, myfile);\n }\n\n if (squaredLengthOfVector(vector_voronoi) != squaredLengthOfVector(sv) || squaredLengthOfVector(sv) != squaredLengthOfVector(vector_voronoi))\n {\n myfile << \"found different norms of vectors\";\n\n printResVector(vector_voronoi, \"voronoi\", myfile);\n printResVector(sv, \"gauss\", myfile);\n printResVector(v3, \"list\", myfile);\n }\n else\n {\n myfile << endl\n << \"shortest with norm\" << (long)squaredLengthOfVector(sv) << endl;\n printVec(sv, myfile);\n }\n myfile << \"---------------------------------------------------------------------\\n\\n\";\n md = readFromFile(datafile);\n }\n\n // myfile << dimm << \" \" << diff << \" \" << iter << endl;\n\n // }\n // }\n // }\n // }\n // catch (exception e)\n // {\n // cout << e.what();\n // }\n myfile.close();\n return 0;\n}", "meta": {"hexsha": "d4d47317a6708c87d55d4c67b28fa6b7b9932f12", "size": 37968, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "svp/src/svp2.cpp", "max_stars_repo_name": "KudrinMatvey/myfplll", "max_stars_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "svp/src/svp2.cpp", "max_issues_repo_name": "KudrinMatvey/myfplll", "max_issues_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "svp/src/svp2.cpp", "max_forks_repo_name": "KudrinMatvey/myfplll", "max_forks_repo_head_hexsha": "99fa018201097b6c078c00721cdc409cdcd4092c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.2921013413, "max_line_length": 149, "alphanum_fraction": 0.473820059, "num_tokens": 10938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6930894270096561}} {"text": "#include \n#include \n#include \nusing namespace std; \n#include \n\n// for sophus \n#include \nusing Sophus::SE3;\n\n// for eigen \n#include \n#include \nusing namespace Eigen;\n\n#include \n#include \n#include \n\nusing namespace cv;\n\n/**********************************************\n* 本程序演示了单目相机在已知轨迹下的稠密深度估计\n* 使用极线搜索 + NCC 匹配的方式,与书本的 13.2 节对应\n* 请注意本程序并不完美,你完全可以改进它——我其实在故意暴露一些问题。\n***********************************************/\n\n\n\n// ------------------------------------------------------------------\n// parameters \nconst int boarder = 20; \t// 边缘宽度\nconst int width = 640; \t// 宽度 \nconst int height = 480; \t// 高度\nconst double fx = 481.2f;\t// 相机内参\nconst double fy = -480.0f;\nconst double cx = 319.5f;\nconst double cy = 239.5f;\nconst int ncc_window_size = 2;\t// NCC 取的窗口半宽度\nconst int ncc_area = (2*ncc_window_size+1)*(2*ncc_window_size+1); // NCC窗口面积\nconst double min_cov = 0.1;\t// 收敛判定:最小方差\nconst double max_cov = 10;\t// 发散判定:最大方差\n\n// ------------------------------------------------------------------\n// 重要的函数 \n// 从 REMODE 数据集读取数据 \nbool readDatasetFiles( \n const string& path, \n vector& color_image_files, \n vector& poses \n);\n\n// 根据新的图像更新深度估计\nbool update( \n const Mat& ref, \n const Mat& curr, \n const SE3& T_C_R, \n Mat& depth, \n Mat& depth_cov \n);\n\n// 极线搜索 \nbool epipolarSearch( \n const Mat& ref, \n const Mat& curr, \n const SE3& T_C_R, \n const Vector2d& pt_ref, \n const double& depth_mu, \n const double& depth_cov,\n Vector2d& pt_curr\n);\n\n// 更新深度滤波器 \nbool updateDepthFilter( \n const Vector2d& pt_ref, \n const Vector2d& pt_curr, \n const SE3& T_C_R, \n Mat& depth, \n Mat& depth_cov\n);\n\n// 计算 NCC 评分 \ndouble NCC( const Mat& ref, const Mat& curr, const Vector2d& pt_ref, const Vector2d& pt_curr );\n\n// 双线性灰度插值 \ninline double getBilinearInterpolatedValue( const Mat& img, const Vector2d& pt ) {\n uchar* d = & img.data[ int(pt(1,0))*img.step+int(pt(0,0)) ];\n double xx = pt(0,0) - floor(pt(0,0)); \n double yy = pt(1,0) - floor(pt(1,0));\n return (( 1-xx ) * ( 1-yy ) * double(d[0]) +\n xx* ( 1-yy ) * double(d[1]) +\n ( 1-xx ) *yy* double(d[img.step]) +\n xx*yy*double(d[img.step+1]))/255.0;\n}\n\n// ------------------------------------------------------------------\n// 一些小工具 \n// 显示估计的深度图 \nbool plotDepth( const Mat& depth );\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\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\n// 检测一个点是否在图像边框内\ninline bool inside( const Vector2d& pt ) {\n return pt(0,0) >= boarder && pt(1,0)>=boarder \n && pt(0,0)+boarder color_image_files; \n vector poses_TWC;\n bool ret = readDatasetFiles( argv[1], color_image_files, poses_TWC );\n if ( ret==false )\n {\n cout<<\"Reading image files failed!\"<& color_image_files, \n std::vector& poses\n)\n{\n ifstream fin( path+\"/first_200_frames_traj_over_table_input_sequence.txt\");\n if ( !fin ) return false;\n \n while ( !fin.eof() )\n {\n\t\t// 数据格式:图像文件名 tx, ty, tz, qx, qy, qz, qw ,注意是 TWC 而非 TCW\n string image; \n fin>>image; \n double data[7];\n for ( double& d:data ) fin>>d;\n \n color_image_files.push_back( path+string(\"/images/\")+image );\n poses.push_back(\n SE3( Quaterniond(data[6], data[3], data[4], data[5]), \n Vector3d(data[0], data[1], data[2]))\n );\n if ( !fin.good() ) break;\n }\n return true;\n}\n\n// 对整个深度图进行更新\nbool update(const Mat& ref, const Mat& curr, const SE3& T_C_R, Mat& depth, Mat& depth_cov )\n{\n#pragma omp parallel for\n for ( int x=boarder; x(y)[x] < min_cov || depth_cov.ptr(y)[x] > max_cov ) // 深度已收敛或发散\n continue;\n // 在极线上搜索 (x,y) 的匹配 \n Vector2d pt_curr; \n bool ret = epipolarSearch ( \n ref, \n curr, \n T_C_R, \n Vector2d(x,y), \n depth.ptr(y)[x], \n sqrt(depth_cov.ptr(y)[x]),\n pt_curr\n );\n \n if ( ret == false ) // 匹配失败\n continue; \n \n\t\t\t// 取消该注释以显示匹配\n // showEpipolarMatch( ref, curr, Vector2d(x,y), pt_curr );\n \n // 匹配成功,更新深度图 \n updateDepthFilter( Vector2d(x,y), pt_curr, T_C_R, depth, depth_cov );\n }\n}\n\n// 极线搜索\n// 方法见书 13.2 13.3 两节\nbool epipolarSearch(\n const Mat& ref, const Mat& curr, \n const SE3& T_C_R, const Vector2d& pt_ref, \n const double& depth_mu, const double& depth_cov, \n Vector2d& pt_curr )\n{\n Vector3d f_ref = px2cam( pt_ref );\n f_ref.normalize();\n Vector3d P_ref = f_ref*depth_mu;\t// 参考帧的 P 向量\n \n Vector2d px_mean_curr = cam2px( T_C_R*P_ref ); // 按深度均值投影的像素\n double d_min = depth_mu-3*depth_cov, d_max = depth_mu+3*depth_cov;\n if ( d_min<0.1 ) d_min = 0.1;\n Vector2d px_min_curr = cam2px( T_C_R*(f_ref*d_min) );\t// 按最小深度投影的像素\n Vector2d px_max_curr = cam2px( T_C_R*(f_ref*d_max) );\t// 按最大深度投影的像素\n \n Vector2d epipolar_line = px_max_curr - px_min_curr;\t// 极线(线段形式)\n Vector2d epipolar_direction = epipolar_line;\t\t// 极线方向 \n epipolar_direction.normalize();\n double half_length = 0.5*epipolar_line.norm();\t// 极线线段的半长度\n if ( half_length>100 ) half_length = 100; // 我们不希望搜索太多东西 \n \n\t// 取消此句注释以显示极线(线段)\n // showEpipolarLine( ref, curr, pt_ref, px_min_curr, px_max_curr );\n \n // 在极线上搜索,以深度均值点为中心,左右各取半长度\n double best_ncc = -1.0;\n Vector2d best_px_curr; \n for ( double l=-half_length; l<=half_length; l+=0.7 ) // l+=sqrt(2) \n {\n Vector2d px_curr = px_mean_curr + l*epipolar_direction; // 待匹配点\n if ( !inside(px_curr) )\n continue; \n // 计算待匹配点与参考帧的 NCC\n double ncc = NCC( ref, curr, pt_ref, px_curr );\n if ( ncc>best_ncc )\n {\n best_ncc = ncc; \n best_px_curr = px_curr;\n }\n }\n if ( best_ncc < 0.85f ) // 只相信 NCC 很高的匹配\n return false; \n pt_curr = best_px_curr;\n return true;\n}\n\ndouble NCC (\n const Mat& ref, const Mat& curr, \n const Vector2d& pt_ref, const Vector2d& pt_curr\n)\n{\n // 零均值-归一化互相关\n // 先算均值\n double mean_ref = 0, mean_curr = 0;\n vector values_ref, values_curr; // 参考帧和当前帧的均值\n for ( int x=-ncc_window_size; x<=ncc_window_size; x++ )\n for ( int y=-ncc_window_size; y<=ncc_window_size; y++ )\n {\n double value_ref = double(ref.ptr( int(y+pt_ref(1,0)) )[ int(x+pt_ref(0,0)) ])/255.0;\n mean_ref += value_ref;\n \n double value_curr = getBilinearInterpolatedValue( curr, pt_curr+Vector2d(x,y) );\n mean_curr += value_curr;\n \n values_ref.push_back(value_ref);\n values_curr.push_back(value_curr);\n }\n \n mean_ref /= ncc_area;\n mean_curr /= ncc_area;\n \n\t// 计算 Zero mean NCC\n double numerator = 0, demoniator1 = 0, demoniator2 = 0;\n for ( int i=0; i [ f_ref^T f_ref, -f_ref^T f_cur ] [d_ref] = [f_ref^T t]\n // [ f_cur^T f_ref, -f_cur^T f_cur ] [d_cur] = [f_cur^T t]\n // 二阶方程用克莱默法则求解并解之\n Vector3d t = T_R_C.translation();\n Vector3d f2 = T_R_C.rotation_matrix() * f_curr; \n Vector2d b = Vector2d ( t.dot ( f_ref ), t.dot ( f2 ) );\n double A[4];\n A[0] = f_ref.dot ( f_ref );\n A[2] = f_ref.dot ( f2 );\n A[1] = -A[2];\n A[3] = - f2.dot ( f2 );\n double d = A[0]*A[3]-A[1]*A[2];\n Vector2d lambdavec = \n Vector2d ( A[3] * b ( 0,0 ) - A[1] * b ( 1,0 ),\n -A[2] * b ( 0,0 ) + A[0] * b ( 1,0 )) /d;\n Vector3d xm = lambdavec ( 0,0 ) * f_ref;\n Vector3d xn = t + lambdavec ( 1,0 ) * f2;\n Vector3d d_esti = ( xm+xn ) / 2.0; // 三角化算得的深度向量\n double depth_estimation = d_esti.norm(); // 深度值\n \n // 计算不确定性(以一个像素为误差)\n Vector3d p = f_ref*depth_estimation;\n Vector3d a = p - t; \n double t_norm = t.norm();\n double a_norm = a.norm();\n double alpha = acos( f_ref.dot(t)/t_norm );\n double beta = acos( -a.dot(t)/(a_norm*t_norm));\n double beta_prime = beta + atan(1/fx);\n double gamma = M_PI - alpha - beta_prime;\n double p_prime = t_norm * sin(beta_prime) / sin(gamma);\n double d_cov = p_prime - depth_estimation; \n double d_cov2 = d_cov*d_cov;\n \n // 高斯融合\n double mu = depth.ptr( int(pt_ref(1,0)) )[ int(pt_ref(0,0)) ];\n double sigma2 = depth_cov.ptr( int(pt_ref(1,0)) )[ int(pt_ref(0,0)) ];\n \n double mu_fuse = (d_cov2*mu+sigma2*depth_estimation) / ( sigma2+d_cov2);\n double sigma_fuse2 = ( sigma2 * d_cov2 ) / ( sigma2 + d_cov2 );\n \n depth.ptr( int(pt_ref(1,0)) )[ int(pt_ref(0,0)) ] = mu_fuse; \n depth_cov.ptr( int(pt_ref(1,0)) )[ int(pt_ref(0,0)) ] = sigma_fuse2;\n \n return true;\n}\n\n// 后面这些太简单我就不注释了(其实是因为懒)\nbool plotDepth(const Mat& depth)\n{\n imshow( \"depth\", depth*0.4 );\n waitKey(1);\n}\n\nvoid showEpipolarMatch(const Mat& ref, const Mat& curr, const Vector2d& px_ref, const Vector2d& px_curr)\n{\n Mat ref_show, curr_show;\n cv::cvtColor( ref, ref_show, CV_GRAY2BGR );\n cv::cvtColor( curr, curr_show, CV_GRAY2BGR );\n \n cv::circle( ref_show, cv::Point2f(px_ref(0,0), px_ref(1,0)), 5, cv::Scalar(0,0,250), 2);\n cv::circle( curr_show, cv::Point2f(px_curr(0,0), px_curr(1,0)), 5, cv::Scalar(0,0,250), 2);\n \n imshow(\"ref\", ref_show );\n imshow(\"curr\", curr_show );\n waitKey(1);\n}\n\nvoid showEpipolarLine(const Mat& ref, const Mat& curr, const Vector2d& px_ref, const Vector2d& px_min_curr, const Vector2d& px_max_curr)\n{\n\n Mat ref_show, curr_show;\n cv::cvtColor( ref, ref_show, CV_GRAY2BGR );\n cv::cvtColor( curr, curr_show, CV_GRAY2BGR );\n \n cv::circle( ref_show, cv::Point2f(px_ref(0,0), px_ref(1,0)), 5, cv::Scalar(0,255,0), 2);\n cv::circle( curr_show, cv::Point2f(px_min_curr(0,0), px_min_curr(1,0)), 5, cv::Scalar(0,255,0), 2);\n cv::circle( curr_show, cv::Point2f(px_max_curr(0,0), px_max_curr(1,0)), 5, cv::Scalar(0,255,0), 2);\n cv::line( curr_show, Point2f(px_min_curr(0,0), px_min_curr(1,0)), Point2f(px_max_curr(0,0), px_max_curr(1,0)), Scalar(0,255,0), 1);\n \n imshow(\"ref\", ref_show );\n imshow(\"curr\", curr_show );\n waitKey(1);\n}\n\n", "meta": {"hexsha": "9cdc2e3387a96236e31c1659effb0e5141e6174b", "size": 13276, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch13/dense_monocular/dense_mapping.cpp", "max_stars_repo_name": "renzhuli/SLAM", "max_stars_repo_head_hexsha": "4020737ae5b14322696f7af6ecd2e952335d924b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-29T06:45:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-10T14:00:36.000Z", "max_issues_repo_path": "ch13/dense_monocular/dense_mapping.cpp", "max_issues_repo_name": "renzhuli/SLAM", "max_issues_repo_head_hexsha": "4020737ae5b14322696f7af6ecd2e952335d924b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch13/dense_monocular/dense_mapping.cpp", "max_forks_repo_name": "renzhuli/SLAM", "max_forks_repo_head_hexsha": "4020737ae5b14322696f7af6ecd2e952335d924b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-09-01T16:24:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-01T04:02:23.000Z", "avg_line_length": 30.9463869464, "max_line_length": 139, "alphanum_fraction": 0.5720849654, "num_tokens": 4723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6930890639445418}} {"text": "// C++ includes\n#include \nusing namespace std;\n\n// Eigen includes\n#include \nusing namespace Eigen;\n\n// autodiff include\n#include \n#include \nusing namespace autodiff;\n\n// The scalar function for which the gradient is needed\nvar f(const VectorXvar& x)\n{\n return sqrt(x.cwiseProduct(x).sum()); // sqrt(sum([x(i) * x(i) for i = 1:5]))\n}\n\nint main()\n{\n VectorXvar x(5); // the input vector x with 5 variables\n x << 1, 2, 3, 4, 5; // x = [1, 2, 3, 4, 5]\n\n var u = f(x); // the output variable u\n\n VectorXd g; // the gradient vector to be computed in method `hessian`\n MatrixXd H = hessian(u, x, g); // evaluate the Hessian matrix H and the gradient vector g of u\n\n cout << \"u = \" << u << endl; // print the evaluated output variable u\n cout << \"g = \\n\" << g << endl; // print the evaluated gradient vector of u\n cout << \"H = \\n\" << H << endl; // print the evaluated Hessian matrix of u\n}\n", "meta": {"hexsha": "1f066a20b54d38ebfe32a4df93dac97d3608e87b", "size": 994, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common/autodiff/examples/reverse/example-reverse-hessian-derivatives-using-eigen.cpp", "max_stars_repo_name": "Speech-VINO/Speech-Analysis", "max_stars_repo_head_hexsha": "e95083c4709f3ba7bcc89006ff4623d73475dacd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-22T16:38:48.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-22T16:38:48.000Z", "max_issues_repo_path": "examples/reverse/example-reverse-hessian-derivatives-using-eigen.cpp", "max_issues_repo_name": "gayatri-a-b/autodiff", "max_issues_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/reverse/example-reverse-hessian-derivatives-using-eigen.cpp", "max_forks_repo_name": "gayatri-a-b/autodiff", "max_forks_repo_head_hexsha": "98bdfea087cb67dd6e2a1a399e90bbd7ac4eb326", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-02-26T13:14:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-25T03:52:45.000Z", "avg_line_length": 29.2352941176, "max_line_length": 99, "alphanum_fraction": 0.6287726358, "num_tokens": 303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6930779346815342}} {"text": "#include \"forward_kinematics.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n//perform the forward kinematics of the robot to figure out where you are\nwsState* fk (configState* c)\n{\n double theta0 = tick_to_radians(c->theta[0]);\n double theta1 = tick_to_radians(c->theta[1]);\n double theta2 = tick_to_radians(c->theta[2]);\n double theta3 = tick_to_radians(c->theta[3]);\n double theta4 = tick_to_radians(c->theta[4]);\n /* Eigen::Matrix4d T_01 = DH(M_PI/2 , 0, 26.5, theta0);\n Eigen::Matrix4d T_12 = DH(0, 150, 0 , M_PI/2+theta1);\n Eigen::Matrix4d T_23 = DH(0, 150, 0, theta2);\n Eigen::Matrix4d T_34 = DH(-M_PI/2, 0, 0, M_PI/2+theta3);\n Eigen::Matrix4d T_45 = DH(0,0,116.525, theta4);\n\n Eigen::Matrix4d T_05 = T_01*T_12*T_23*T_34*T_45;\n\n wsState* outstate = new wsState;\n outstate->x = T_05(0,3);\n outstate->y = T_05(1,3);\n outstate->z = T_05(2,3);\n outstate->alpha = tick_to_radians(c->theta[0]+c->theta[1]+\n c->theta[2]+c->theta[3]+c->theta[4]);\n //TODO calculate angles based on rotation matrix\n */\n double c0 = cos(theta0);\n double s0 = sin(theta0);\n double c1 = cos(theta1);\n double s1 = sin(theta1);\n double c12 = cos(theta1+theta2);\n double s12 = sin(theta1+theta2);\n double c123 = cos(theta1+theta2+theta3);\n double s123 = sin(theta1+theta2+theta3);\n\n wsState* outstate = new wsState;\n outstate->x = c0*(150*(c1+c12) + 116.525*s123);\n outstate->y = s0*(150*(c1+c12) + 116.525*s123);\n outstate->z = 150*(s12+s1) - 116.525*c123 + 26.5;\n outstate->alpha = theta1+ theta2+ theta3;\n\n return outstate;\n\n}//end forward_kinematics\n\nEigen::Matrix4d DH(double alpha,double a,double d,double theta)\n{\n Eigen::Matrix4d T;\n T << cos(theta),sin(theta)*cos(alpha),-sin(theta)*sin(alpha),a*cos(theta),\n sin(theta), cos(theta)*cos(alpha), -cos(theta)*sin(alpha),a*sin(theta),\n 0,sin(alpha),cos(alpha),d,\n 0,0,0,1;\n return T;\n}\n\n\n//calculate Euclidean ndistance between two states\ndouble distance(wsState* s1,wsState* s2)\n{\n return (pow(s1->x - s2->x,2)+pow(s1->y-s2->y,2)+pow(s1->z-s2->z,2)+pow(s1->alpha-s2->alpha,2));\n}\n\nconfigState* clone_configstate(configState* c){\n\n configState* clone = new configState;\n clone->theta[0] = c->theta[0];\n clone->theta[1] = c->theta[1];\n clone->theta[2] = c->theta[2];\n clone->theta[3] = c->theta[3];\n clone->theta[4] = c->theta[4];\n return clone;\n}\n\ndouble tick_to_radians(int i){\n return (M_PI/100)*i;\n}\n\nwsState* create_wsstate(){\n return (wsState*)malloc(sizeof(struct wsState));\n}\n\nconfigState* create_configstate(){\n return (configState*)malloc(sizeof(struct configState));\n}\n\nvisData* create_visdata(){\n return (visData*)malloc(sizeof(struct visData));\n}\n\nvoid deallocate_wsstate(wsState* w){\n if(w != 0)\n free(w);\n}\n\nvoid deallocate_configstate(configState* c){\n if(c != 0)\n free(c);\n}\n\nvoid deallocate_visdata(visData* v){\n if(v != 0)\n free(v);\n}\n\nvoid wsstate_tostring(wsState* w){\n printf(\"Work Space State: x:%f, y:%f, z:%f\\n\",\n w->x, w->y, w->z);\n}\n\nvoid configstate_tostring(configState* c){\n printf(\"Theta1: %i, Theta2: %i, Theta3: %i, Theta4: %i, Theta5: %i\\n\"\n , c->theta[0], c->theta[1],c->theta[2], c->theta[3], c->theta[4]);\n}\n", "meta": {"hexsha": "5df27efc23f3ecd124a83beb07e5e36d31d514f2", "size": 3260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "armplanning_test/forward_kinematics.cpp", "max_stars_repo_name": "Boberito25/ButlerBot", "max_stars_repo_head_hexsha": "959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "armplanning_test/forward_kinematics.cpp", "max_issues_repo_name": "Boberito25/ButlerBot", "max_issues_repo_head_hexsha": "959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-06-08T19:55:40.000Z", "max_issues_repo_issues_event_max_datetime": "2015-06-08T19:55:40.000Z", "max_forks_repo_path": "armplanning_test/forward_kinematics.cpp", "max_forks_repo_name": "Boberito25/ButlerBot", "max_forks_repo_head_hexsha": "959f961bbc8c43be0ccb533dd2e2af5c55b0cc2a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1666666667, "max_line_length": 97, "alphanum_fraction": 0.6567484663, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299632771662, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6930779346815342}} {"text": "//Neural network in C++\n// Author: Sethu Iyer \n//Sigmoid is used because the sigmoid function assumes \n//minimal structure and reflects our general state of ignorance about the underlying model.\n\n//This code implements simple 3 layer feed forward neural network with no regularization.\n// we use fast sigmoid approximation to speed up the calculation.\n\n#include \n#include \n\nusing namespace std;\nusing namespace arma;\n\nclass Neural_Network\n{\n private:\n //define the architecture of the network\n int inputLayerSize = 2;\n int outputLayerSize = 1;\n int hiddenLayerSize = 3;\n\n // activation function and the weights\n arma::mat W1,W2;\n arma::mat z2,a2;\n arma::mat z3,a3;\n arma::mat delta3,delta2;\n arma::mat dJdW1, djdW2;\n\n public:\n Neural_Network()\n {\n //fills in random weights\n W1.randu(2,3);\n W2.randu(3,1);\n }\n\n //helper functions\n static double sigmoid(double x)\n {\n return x / (1 + abs(x));\n }\n static double sigmoidPrime(double x)\n {\n double f = sigmoid(x);\n return f * (1-f);\n }\n\n\n //forwarding function.\n arma::mat forward(arma::mat X)\n {\n z2 = X * W1;\n a2 = z2;\n a2.transform(*sigmoid);\n z3 = a2 * W2;\n a3 = z3;\n a3.transform(*sigmoid);\n return a3;\n }\n\n //cost function\n double costFunction(mat X,mat y)\n {\n mat yHat = forward(X);\n\n double cost = 0;\n for(int i = 0; i < outputLayerSize; i++)\n {\n cost = cost + (yHat[i] - y[i])*(yHat[i] - y[i]);\n }\n cost = cost / 2;\n return cost;\n\n }\n\n //derivative of cost function \n //backpropogation of errors can be understood in this code\n void computeGradients(mat X, mat y)\n {\n\n mat yHat = forward(X);\n mat z = z3;\n z.transform(*sigmoidPrime);\n delta3 = (yHat - y.t()) % z;\n djdW2 = a2.t() * delta3;\n\n z = z2;\n z.transform(*sigmoidPrime);\n delta2 = delta3 * W2.t()*z;\n dJdW1 = X.t() * delta2;\n\n }\n\n //alpha is our learning rate\n void gradientDescent(mat X,mat y,double alpha,int numIter)\n {\n int i;\n mat transdj1,transdj2;\n for(i=0;i\n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nint main(int argc, char **argv) {\n double ar = 1.0, br = 2.0, cr = 1.0; // 真实参数值\n double ae = 2.0, be = -1.0, ce = 5.0; // 估计参数值\n int N = 100; // 数据点\n double w_sigma = 1.0; // 噪声Sigma值\n cv::RNG rng; // OpenCV随机数产生器\n\n vector x_data, y_data; // 数据\n for (int i = 0; i < N; i++) {\n double x = i / 100.0;\n x_data.push_back(x);\n y_data.push_back(exp(ar * x * x + br * x + cr) + rng.gaussian(w_sigma));\n }\n\n // 开始Gauss-Newton迭代\n int iterations = 100; // 迭代次数\n double cost = 0, lastCost = 0; // 本次迭代的cost和上一次迭代的cost\n\n for (int iter = 0; iter < iterations; iter++) {\n\n Matrix3d H = Matrix3d::Zero(); // Hessian = J^T J in Gauss-Newton\n Vector3d b = Vector3d::Zero(); // bias\n cost = 0;\n\n for (int i = 0; i < N; i++) {\n double xi = x_data[i], yi = y_data[i]; // 第i个数据点\n // start your code here\n double error = 0 ; // 第i个数据点的计算误差\n // 填写计算error的表达式\n error = yi- exp(ae * xi * xi + be * xi + ce);\n Vector3d J; // 雅可比矩阵\n J[0] = -exp(ae * xi * xi + be * xi + ce)*xi*xi; // de/da\n J[1] = -exp(ae * xi * xi + be * xi + ce)*xi; // de/db\n J[2] = -exp(ae * xi * xi + be * xi + ce); // de/dc\n\n H += J * J.transpose(); // GN近似的H\n b += -error * J;\n // end your code here\n\n cost += error * error;\n }\n\n // 求解线性方程 Hx=b,建议用ldlt\n \t// start your code here\n Vector3d dx;\n dx = H.ldlt().solve(b);\n\t// end your code here\n\n if (isnan(dx[0])) {\n cout << \"result is nan!\" << endl;\n break;\n }\n\n if (iter > 0 && cost > lastCost) {\n // 误差增长了,说明近似的不够好\n cout << \"cost: \" << cost << \", last cost: \" << lastCost << endl;\n break;\n }\n\n // 更新abc估计值\n ae += dx[0];\n be += dx[1];\n ce += dx[2];\n\n lastCost = cost;\n\n cout << \"total cost: \" << cost << endl;\n }\n\n cout << \"estimated abc = \" << ae << \", \" << be << \", \" << ce << endl;\n return 0;\n}", "meta": {"hexsha": "9cdd996cd290050c53181c5c32653bf87b3385bb", "size": 2410, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "4/gaussnewton.cpp", "max_stars_repo_name": "Yvon-Shong/SLAM", "max_stars_repo_head_hexsha": "4f633e71e13e1b3482255bc5abc38446a56beebf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2018-03-16T16:30:30.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T12:25:08.000Z", "max_issues_repo_path": "SLAM14Lectures-master/4/gaussnewton.cpp", "max_issues_repo_name": "HCH2CHO/Visual_SLAM", "max_issues_repo_head_hexsha": "a5e977eb000b39e78d7b44e78e7856f6aabc4a02", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-08T11:52:08.000Z", "max_issues_repo_issues_event_max_datetime": "2019-11-01T18:40:41.000Z", "max_forks_repo_path": "SLAM14Lectures-master/4/gaussnewton.cpp", "max_forks_repo_name": "HCH2CHO/Visual_SLAM", "max_forks_repo_head_hexsha": "a5e977eb000b39e78d7b44e78e7856f6aabc4a02", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-03-16T16:30:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-28T11:37:37.000Z", "avg_line_length": 29.0361445783, "max_line_length": 85, "alphanum_fraction": 0.4369294606, "num_tokens": 830, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850057480347, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6930141568162483}} {"text": "#include \n#include \n#include \n\nusing namespace std;\nusing namespace arma;\n\n/* ----------------- useful help functions -------------- */\n\nstruct MyVec\n{\n double *data;\n size_t n;\n};\n\nstruct MyMat\n{\n double *data;\n size_t num_rows, num_cols;\n};\n\nextern \"C\" void freeMyVec(MyVec &vec)\n{\n delete[] vec.data;\n memset((void *)&vec, 0, sizeof(vec));\n}\n\nextern \"C\" void freeMyMat(MyMat &mat)\n{\n delete[] mat.data;\n memset((void *)&mat, 0, sizeof(mat));\n}\n\nstruct HuberCovResult\n{\n MyVec means;\n MyMat cov;\n};\n\nextern \"C\" void freeHuberCovResult(const HuberCovResult &result)\n{\n delete[] result.means.data;\n delete[] result.cov.data;\n memset((void *)&result, 0, sizeof(result));\n}\n\n /* --------------------------------- */ \n/*------------ Tuning-Free Huber Regression Funtions ---------------*/\n /* --------------------------------- */ \n\nint sgn(const double x)\n{\n return (x > 0) - (x < 0);\n}\n\ndouble f1(const double x, const arma::vec &resSq, const int n, const double rhs)\n{\n return arma::mean(arma::min(resSq / x, arma::ones(n))) - rhs;\n}\n\ndouble rootf1(const arma::vec &resSq, const int n, const double rhs, double low, double up, const double tol = 0.001, const int maxIte = 500)\n{\n int ite = 1;\n while (ite <= maxIte && up - low > tol)\n {\n double mid = 0.5 * (up + low);\n double val = f1(mid, resSq, n, rhs);\n if (val < 0)\n {\n up = mid;\n }\n else\n {\n low = mid;\n }\n ite++;\n }\n return 0.5 * (low + up);\n}\n\ndouble f2(const double x, const arma::vec &resSq, const int N, const double rhs)\n{\n return arma::mean(arma::min(resSq / x, arma::ones(N))) - rhs;\n}\n\ndouble rootf2(const arma::vec &resSq, const int n, const int d, const int N, const double rhs, double low, double up, const double tol = 0.001,\n const int maxIte = 500)\n{\n int ite = 0;\n while (ite <= maxIte && up - low > tol)\n {\n double mid = 0.5 * (up + low);\n double val = f2(mid, resSq, N, rhs);\n if (val < 0)\n {\n up = mid;\n }\n else\n {\n low = mid;\n }\n ite++;\n }\n return 0.5 * (low + up);\n}\n\ndouble g1(const double x, const arma::vec &resSq, const int n, const double rhs)\n{\n return arma::mean(arma::min(resSq / x, arma::ones(n))) - rhs;\n}\n\ndouble rootg1(const arma::vec &resSq, const int n, const double rhs, double low, double up, const double tol = 0.001, const int maxIte = 500)\n{\n int ite = 0;\n while (ite <= maxIte && up - low > tol)\n {\n double mid = 0.5 * (up + low);\n double val = g1(mid, resSq, n, rhs);\n if (val < 0)\n {\n up = mid;\n }\n else\n {\n low = mid;\n }\n ite++;\n }\n return 0.5 * (low + up);\n}\n\ndouble huberDer(const arma::vec &res, const double tau, const int n)\n{\n double rst = 0.0;\n for (int i = 0; i < n; i++)\n {\n double cur = res(i);\n rst -= std::abs(cur) <= tau ? cur : tau * sgn(cur);\n }\n return rst / n;\n}\n\nextern \"C\" double huberMean(MyVec _X, const double tol = 0.001, const int iteMax = 500)\n{\n arma::vec X(_X.data, _X.n);\n int n = X.n_rows;\n double rhs = std::log(n) / n;\n double mx = arma::mean(X);\n X -= mx;\n double tau = arma::stddev(X) * std::sqrt((long double)n / std::log(n));\n double derOld = huberDer(X, tau, n);\n double mu = -derOld, muDiff = -derOld;\n arma::vec res = X - mu;\n arma::vec resSq = arma::square(res);\n tau = std::sqrt((long double)rootf1(resSq, n, rhs, arma::min(resSq), arma::accu(resSq)));\n double derNew = huberDer(res, tau, n);\n double derDiff = derNew - derOld;\n int ite = 1;\n while (std::abs(derNew) > tol && ite <= iteMax)\n {\n double alpha = 1.0;\n double cross = muDiff * derDiff;\n if (cross > 0)\n {\n double a1 = cross / derDiff * derDiff;\n double a2 = muDiff * muDiff / cross;\n alpha = std::min(std::min(a1, a2), 100.0);\n }\n derOld = derNew;\n muDiff = -alpha * derNew;\n mu += muDiff;\n res = X - mu;\n resSq = arma::square(res);\n tau = std::sqrt((long double)rootf1(resSq, n, rhs, arma::min(resSq), arma::accu(resSq)));\n derNew = huberDer(res, tau, n);\n derDiff = derNew - derOld;\n ite++;\n }\n return mu + mx;\n}\n\ndouble _huberMean(arma::vec X, const double tol = 0.001, const int iteMax = 500)\n{\n int n = X.n_rows;\n double rhs = std::log(n) / n;\n double mx = arma::mean(X);\n X -= mx;\n double tau = arma::stddev(X) * std::sqrt((long double)n / std::log(n));\n double derOld = huberDer(X, tau, n);\n double mu = -derOld, muDiff = -derOld;\n arma::vec res = X - mu;\n arma::vec resSq = arma::square(res);\n tau = std::sqrt((long double)rootf1(resSq, n, rhs, arma::min(resSq), arma::accu(resSq)));\n double derNew = huberDer(res, tau, n);\n double derDiff = derNew - derOld;\n int ite = 1;\n while (std::abs(derNew) > tol && ite <= iteMax)\n {\n double alpha = 1.0;\n double cross = muDiff * derDiff;\n if (cross > 0)\n {\n double a1 = cross / derDiff * derDiff;\n double a2 = muDiff * muDiff / cross;\n alpha = std::min(std::min(a1, a2), 100.0);\n }\n derOld = derNew;\n muDiff = -alpha * derNew;\n mu += muDiff;\n res = X - mu;\n resSq = arma::square(res);\n tau = std::sqrt((long double)rootf1(resSq, n, rhs, arma::min(resSq), arma::accu(resSq)));\n derNew = huberDer(res, tau, n);\n derDiff = derNew - derOld;\n ite++;\n }\n return mu + mx;\n}\n\ndouble hMeanCov(const arma::vec &Z, const int n, const int d, const int N, double rhs, const double epsilon = 0.0001, const int iteMax = 500)\n{\n double muOld = 0;\n double muNew = arma::mean(Z);\n double tau = arma::stddev(Z) * std::sqrt((long double)n / (2 * std::log(d) + std::log(n)));\n int iteNum = 0;\n arma::vec res(n), resSq(n), w(n);\n while ((std::abs(muNew - muOld) > epsilon) && iteNum < iteMax)\n {\n muOld = muNew;\n res = Z - muOld;\n resSq = arma::square(res);\n tau = std::sqrt((long double)rootf2(resSq, n, d, N, rhs, arma::min(resSq), arma::accu(resSq)));\n w = arma::min(tau / arma::abs(res), arma::ones(N));\n muNew = arma::as_scalar(Z.t() * w) / arma::accu(w);\n iteNum++;\n }\n return muNew;\n}\n\nextern \"C\" HuberCovResult huberCov(const MyMat &_X)\n{\n const arma::mat X(_X.data, _X.num_rows, _X.num_cols);\n const int n = X.n_rows;\n const int p = X.n_cols;\n\n double rhs2 = (2 * std::log(p) + std::log(n)) / n;\n arma::vec mu(p);\n arma::mat sigmaHat(p, p);\n for (int j = 0; j < p; j++)\n {\n mu(j) = _huberMean(X.col(j), n);\n double theta = _huberMean(arma::square(X.col(j)), n);\n double temp = mu(j) * mu(j);\n if (theta > temp)\n {\n theta -= temp;\n }\n sigmaHat(j, j) = theta;\n }\n int N = n * (n - 1) >> 1;\n arma::mat Y(N, p);\n for (int i = 0, k = 0; i < n - 1; i++)\n {\n for (int j = i + 1; j < n; j++)\n {\n Y.row(k++) = X.row(i) - X.row(j);\n }\n }\n for (int i = 0; i < p - 1; i++)\n {\n for (int j = i + 1; j < p; j++)\n {\n sigmaHat(i, j) = sigmaHat(j, i) = hMeanCov(0.5 * Y.col(i) % Y.col(j), n, p, N, rhs2);\n }\n }\n\n HuberCovResult result;\n\n result.means.data = new double[mu.size()];\n result.means.n = mu.size();\n memcpy(result.means.data, mu.memptr(), mu.size() * sizeof(double));\n\n result.cov.data = new double[sigmaHat.n_rows * sigmaHat.n_cols];\n result.cov.num_rows = sigmaHat.n_rows;\n result.cov.num_cols = sigmaHat.n_cols;\n memcpy(result.cov.data, sigmaHat.memptr(), sigmaHat.n_rows * sigmaHat.n_cols * sizeof(double));\n\n return result;\n}\n\ndouble mad(const arma::vec &x)\n{\n return 1.482602 * arma::median(arma::abs(x - arma::median(x)));\n}\n\narma::mat standardize(arma::mat X, const arma::rowvec &mx, const arma::vec &sx, const int p)\n{\n for (int i = 0; i < p; i++)\n {\n X.col(i) = (X.col(i) - mx(i)) / sx(i);\n }\n return X;\n}\n\nvoid updateHuber(const arma::mat &Z, const arma::vec &res, arma::vec &der, arma::vec &grad, const int n, const double tau, const double n1)\n{\n for (int i = 0; i < n; i++)\n {\n double cur = res(i);\n if (std::abs(cur) <= tau)\n {\n der(i) = -cur;\n }\n else\n {\n der(i) = -tau * sgn(cur);\n }\n }\n grad = n1 * Z.t() * der;\n}\n\nextern \"C\" MyVec adaHuberReg(MyMat _X, MyVec _Y, const double tol = 0.0001, const int iteMax = 5000)\n{\n arma::mat X(_X.data, _X.num_rows, _X.num_cols);\n arma::vec Y(_Y.data, _Y.n);\n int n = X.n_rows;\n int p = X.n_cols;\n const double n1 = 1.0 / n;\n double rhs = n1 * (p + std::log(n * p));\n arma::rowvec mx = arma::mean(X, 0);\n arma::vec sx = arma::stddev(X, 0, 0).t();\n double my = arma::mean(Y);\n arma::mat Z = arma::join_rows(arma::ones(n), standardize(X, mx, sx, p));\n Y -= my;\n double tau = 1.345 * mad(Y);\n arma::vec der(n);\n arma::vec gradOld(p + 1), gradNew(p + 1);\n updateHuber(Z, Y, der, gradOld, n, tau, n1);\n arma::vec beta = -gradOld, betaDiff = -gradOld;\n arma::vec res = Y - Z * beta;\n arma::vec resSq = arma::square(res);\n tau = std::sqrt((long double)rootg1(resSq, n, rhs, arma::min(resSq), arma::accu(resSq)));\n updateHuber(Z, res, der, gradNew, n, tau, n1);\n arma::vec gradDiff = gradNew - gradOld;\n int ite = 1;\n while (arma::norm(gradNew, \"inf\") > tol && ite <= iteMax)\n {\n double alpha = 1.0;\n double cross = arma::as_scalar(betaDiff.t() * gradDiff);\n if (cross > 0)\n {\n double a1 = cross / arma::as_scalar(gradDiff.t() * gradDiff);\n double a2 = arma::as_scalar(betaDiff.t() * betaDiff) / cross;\n alpha = std::min(std::min(a1, a2), 100.0);\n }\n gradOld = gradNew;\n betaDiff = -alpha * gradNew;\n beta += betaDiff;\n res -= Z * betaDiff;\n resSq = arma::square(res);\n tau = std::sqrt((long double)rootg1(resSq, n, rhs, arma::min(resSq), arma::accu(resSq)));\n updateHuber(Z, res, der, gradNew, n, tau, n1);\n gradDiff = gradNew - gradOld;\n ite++;\n }\n beta.rows(1, p) /= sx;\n beta(0) = _huberMean(Y + my - X * beta.rows(1, p));\n\n MyVec result;\n result.data = new double[n];\n result.n = n;\n memcpy(result.data, beta.memptr(), n * sizeof(double));\n return result;\n}\n\nextern \"C\" MyVec huberReg(MyMat _X, MyVec _Y, const double tol = 0.0001, const double constTau = 1.345, const int iteMax = 5000)\n{\n arma::mat X(_X.data, _X.num_rows, _X.num_cols);\n arma::vec Y(_Y.data, _Y.n);\n int n = X.n_rows;\n int p = X.n_cols;\n const double n1 = 1.0 / n;\n arma::rowvec mx = arma::mean(X, 0);\n arma::vec sx = arma::stddev(X, 0, 0).t();\n double my = arma::mean(Y);\n arma::mat Z = arma::join_rows(arma::ones(n), standardize(X, mx, sx, p));\n Y -= my;\n double tau = constTau * mad(Y);\n arma::vec der(n);\n arma::vec gradOld(p + 1), gradNew(p + 1);\n updateHuber(Z, Y, der, gradOld, n, tau, n1);\n arma::vec beta = -gradOld, betaDiff = -gradOld;\n arma::vec res = Y - Z * beta;\n tau = constTau * mad(res);\n updateHuber(Z, res, der, gradNew, n, tau, n1);\n arma::vec gradDiff = gradNew - gradOld;\n int ite = 1;\n while (arma::norm(gradNew, \"inf\") > tol && ite <= iteMax)\n {\n double alpha = 1.0;\n double cross = arma::as_scalar(betaDiff.t() * gradDiff);\n if (cross > 0)\n {\n double a1 = cross / arma::as_scalar(gradDiff.t() * gradDiff);\n double a2 = arma::as_scalar(betaDiff.t() * betaDiff) / cross;\n alpha = std::min(std::min(a1, a2), 100.0);\n }\n gradOld = gradNew;\n betaDiff = -alpha * gradNew;\n beta += betaDiff;\n res -= Z * betaDiff;\n tau = constTau * mad(res);\n updateHuber(Z, res, der, gradNew, n, tau, n1);\n gradDiff = gradNew - gradOld;\n ite++;\n }\n beta.rows(1, p) /= sx;\n beta(0) = _huberMean(Y + my - X * beta.rows(1, p), n);\n\n MyVec result;\n result.data = new double[n];\n result.n = n;\n memcpy(result.data, beta.memptr(), n * sizeof(double));\n return result;\n}\n\n /* - */ \n/*------------ LASSO ------------*/\n /* - */ \n\narma::vec softThresh(const arma::vec& x, const arma::vec& lambda)\n{\n return arma::sign(x) % arma::max(arma::abs(x) - lambda, arma::zeros(x.size()));\n}\n\narma::vec cmptLambda(const arma::vec& beta, const double lambda)\n{\n arma::vec rst = lambda * arma::ones(beta.size());\n rst(0) = 0;\n return rst;\n}\n\ndouble loss(const arma::vec& Y, const arma::vec& Ynew, const std::string lossType, const double tau)\n{\n double rst = 0;\n if (lossType == \"l2\") {\n rst = arma::mean(arma::square(Y - Ynew)) / 2;\n } else if (lossType == \"Huber\") {\n arma::vec res = Y - Ynew;\n for (int i = 0; i < Y.size(); i++) {\n if (std::abs(res(i)) <= tau) {\n rst += res(i) * res(i) / 2;\n } else {\n rst += tau * std::abs(res(i)) - tau * tau / 2;\n }\n }\n rst /= Y.size();\n }\n return rst;\n}\n\narma::vec gradLoss(const arma::mat& X, const arma::vec& Y, const arma::vec& beta,\n const std::string lossType, const double tau)\n{\n arma::vec res = Y - X * beta;\n arma::vec rst = arma::zeros(beta.size());\n if (lossType == \"l2\") {\n rst = -1 * (res.t() * X).t();\n } else if (lossType == \"Huber\") {\n for (int i = 0; i < Y.size(); i++) {\n if (std::abs(res(i)) <= tau) {\n rst -= res(i) * X.row(i).t();\n } else {\n rst -= tau * sgn(res(i)) * X.row(i).t();\n }\n }\n }\n return rst / Y.size();\n}\n\narma::vec updateBeta(const arma::mat& X, const arma::vec& Y, arma::vec beta, const double phi,\n const arma::vec& Lambda, const std::string lossType, const double tau)\n{\n arma::vec first = beta - gradLoss(X, Y, beta, lossType, tau) / phi;\n arma::vec second = Lambda / phi;\n return softThresh(first, second);\n}\n\ndouble cmptPsi(const arma::mat& X, const arma::vec& Y, const arma::vec& betaNew,\n const arma::vec& beta, const double phi, const std::string lossType,\n const double tau) \n{\n arma::vec diff = betaNew - beta;\n double rst = loss(Y, X * beta, lossType, tau)\n + arma::as_scalar((gradLoss(X, Y, beta, lossType, tau)).t() * diff)\n + phi * arma::as_scalar(diff.t() * diff) / 2;\n return rst;\n}\n\nRcpp::List LAMM(const arma::mat& X, const arma::vec& Y, const arma::vec& Lambda, arma::vec beta,\n const double phi, const std::string lossType, const double tau, \n const double gamma) \n{\n double phiNew = phi;\n arma::vec betaNew = arma::vec();\n double FVal, PsiVal;\n while (true) {\n betaNew = updateBeta(X, Y, beta, phiNew, Lambda, lossType, tau);\n FVal = loss(Y, X * betaNew, lossType, tau);\n PsiVal = cmptPsi(X, Y, betaNew, beta, phiNew, lossType, tau);\n if (FVal <= PsiVal) {\n break;\n }\n phiNew *= gamma;\n }\n return Rcpp::List::create(Rcpp::Named(\"beta\") = betaNew, Rcpp::Named(\"phi\") = phiNew);\n}\n\narma::vec lasso(const arma::mat& X, const arma::vec& Y, const double lambda,\n const double phi0 = 0.001, const double gamma = 1.5, \n const double epsilon_c = 0.001, const int iteMax = 500) \n{\n int d = X.n_cols - 1;\n arma::vec beta = arma::zeros(d + 1);\n arma::vec betaNew = arma::zeros(d + 1);\n arma::vec Lambda = cmptLambda(beta, lambda);\n double phi = phi0;\n int ite = 0;\n Rcpp::List listLAMM;\n while (ite < iteMax) {\n ite++;\n listLAMM = LAMM(X, Y, Lambda, beta, phi, \"l2\", 1, gamma);\n betaNew = Rcpp::as(listLAMM[\"beta\"]);\n phi = listLAMM[\"phi\"];\n phi = std::max(phi0, phi / gamma);\n if (arma::norm(betaNew - beta, \"inf\") <= epsilon_c) {\n break;\n }\n beta = betaNew;\n }\n return betaNew;\n}\n\nRcpp::List huberLasso(const arma::mat& X, const arma::vec& Y, const double lambda,\n double tau = -1, const double constTau = 1.345, const double phi0 = 0.001, \n const double gamma = 1.5, const double epsilon_c = 0.001, \n const int iteMax = 500) \n{\n int n = X.n_rows;\n int d = X.n_cols - 1;\n arma::vec beta = arma::zeros(d + 1);\n arma::vec betaNew = arma::zeros(d + 1);\n arma::vec Lambda = cmptLambda(beta, lambda);\n double mad;\n if (tau <= 0) {\n arma::vec betaLasso = lasso(X, Y, lambda, phi0, gamma, epsilon_c, iteMax);\n arma::vec res = Y - X * betaLasso;\n mad = arma::median(arma::abs(res - arma::median(res))) / 0.6744898;\n tau = constTau * mad;\n }\n double phi = phi0;\n int ite = 0;\n Rcpp::List listLAMM;\n arma::vec res(n);\n while (ite < iteMax) {\n ite++;\n listLAMM = LAMM(X, Y, Lambda, beta, phi, \"Huber\", tau, gamma);\n betaNew = Rcpp::as(listLAMM[\"beta\"]);\n phi = listLAMM[\"phi\"];\n phi = std::max(phi0, phi / gamma);\n if (arma::norm(betaNew - beta, \"inf\") <= epsilon_c) {\n break;\n }\n beta = betaNew;\n res = Y - X * beta;\n mad = arma::median(arma::abs(res - arma::median(res))) / 0.6744898;\n tau = constTau * mad;\n }\n return Rcpp::List::create(Rcpp::Named(\"beta\") = betaNew, Rcpp::Named(\"tau\") = tau,\n Rcpp::Named(\"iteration\") = ite);\n}\n\narma::uvec getIndex(const int n, const int low, const int up) \n{\n arma::vec seq = arma::regspace(0, n - 1);\n return arma::find(seq >= low && seq <= up);\n}\n\narma::uvec getIndexComp(const int n, const int low, const int up)\n{\n arma::vec seq = arma::regspace(0, n - 1);\n return arma::find(seq < low || seq > up);\n}\n\ndouble pairPred(const arma::mat& X, const arma::vec& Y, const arma::vec& beta)\n{\n int n = X.n_rows;\n int d = X.n_cols - 1;\n int m = n * (n - 1) >> 1;\n arma::mat pairX(m, d + 1);\n arma::vec pairY(m);\n int k = 0;\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n pairX.row(k) = X.row(i) - X.row(j);\n pairY(k++) = Y(i) - Y(j);\n }\n }\n arma::vec predY = pairX * beta;\n return arma::accu(arma::square(pairY - predY));\n}\n\nRcpp::List cvHuberLasso(const arma::mat& X, const arma::vec& Y,\n Rcpp::Nullable lSeq = R_NilValue, int nlambda = 30,\n const double constTau = 2.5, const double phi0 = 0.001, \n const double gamma = 1.5, const double epsilon_c = 0.001, \n const int iteMax = 500, int nfolds = 3) \n{\n int n = X.n_rows;\n int d = X.n_cols;\n arma::mat Z(n, d + 1);\n Z.cols(1, d) = X;\n Z.col(0) = arma::ones(n);\n arma::vec lambdaSeq = arma::vec();\n if (lSeq.isNotNull()) {\n lambdaSeq = Rcpp::as(lSeq);\n nlambda = lambdaSeq.size();\n } else {\n double lambdaMax = arma::max(arma::abs(Y.t() * Z)) / n;\n double lambdaMin = 0.01 * lambdaMax;\n lambdaSeq = arma::exp(arma::linspace(std::log((long double)lambdaMin),\n std::log((long double)lambdaMax), nlambda));\n }\n if (nfolds > 10 || nfolds > n) {\n nfolds = n < 10 ? n : 10;\n }\n int size = n / nfolds;\n arma::vec mse = arma::zeros(nlambda);\n int low, up;\n arma::uvec idx, idxComp;\n Rcpp::List hLassoList;\n arma::vec thetaHat(d + 1);\n for (int i = 0; i < nlambda; i++) {\n for (int j = 0; j < nfolds; j++) {\n low = j * size;\n up = (j == (nfolds - 1)) ? (n - 1) : ((j + 1) * size - 1);\n idx = getIndex(n, low, up);\n idxComp = getIndexComp(n, low, up);\n hLassoList = huberLasso(Z.rows(idxComp), Y.rows(idxComp), lambdaSeq(i), -1, constTau, phi0, \n gamma, epsilon_c, iteMax);\n thetaHat = Rcpp::as(hLassoList[\"beta\"]);\n mse(i) += pairPred(Z.rows(idx), Y.rows(idx), thetaHat);\n }\n }\n arma::uword cvIdx = mse.index_min();\n hLassoList = huberLasso(Z, Y, lambdaSeq(cvIdx), -1, constTau, phi0, gamma, epsilon_c, iteMax);\n arma::vec theta = Rcpp::as(hLassoList[\"beta\"]);\n Rcpp::List listMean = huberMean(Y - Z.cols(1, d) * theta.rows(1, d));\n theta(0) = listMean[\"mu\"];\n return Rcpp::List::create(Rcpp::Named(\"theta\") = theta, Rcpp::Named(\"lambdaSeq\") = lambdaSeq,\n Rcpp::Named(\"lambdaMin\") = lambdaSeq(cvIdx), \n Rcpp::Named(\"tauCoef\") = hLassoList[\"tau\"], \n Rcpp::Named(\"tauItcp\") = listMean[\"tau\"], \n Rcpp::Named(\"iteCoef\") = hLassoList[\"iteration\"],\n Rcpp::Named(\"iteItcp\") = listMean[\"iteration\"]);\n}\n\n /* ------------------------------------ */ \n/*------------ Alternating Gradient Descent Functions ------------*/\n /* ------------------------------------ */ \n\ndouble LnVal(const arma::vec &Y, double mu, double tau, const int n, double z)\n{\n return (arma::accu(arma::sqrt(tau * tau + arma::square(Y - mu)) - tau) / (z * std::sqrt(n)) + z * tau / std::sqrt(n)) / n;\n}\n\ndouble gradientMuVal(const arma::vec &Y, double mu, double tau, const int n, double z)\n{\n return -(1 / std::sqrt(n)) * arma::accu((Y - mu) / (z * arma::sqrt(tau * tau + arma::square(Y - mu)))) / n;\n}\n\ndouble gradientTauVal(const arma::vec &Y, double mu, double tau, const int n, double z)\n{\n return (1 / std::sqrt(n)) * arma::accu(tau / (z * arma::sqrt(tau * tau + arma::square(Y - mu)))) / n - (std::sqrt(n) / z - z / std::sqrt(n)) / n;\n}\n\nextern \"C\" double agd(MyVec _Y, double epsilon = 1e-5, int iteMax = 5000)\n{\n arma::vec Y(_Y.data, _Y.n);\n int n = Y.n_elem;\n double eta1 = 1.0;\n double eta2 = std::sqrt(n);\n double muOld = std::numeric_limits::infinity();\n double muNew = arma::mean(Y);\n double tauOld = std::numeric_limits::infinity();\n double delta = 0.05;\n double z = std::min(std::sqrt(std::log(n)), std::sqrt(std::log(1 / delta)));\n double tauNew = arma::stddev(Y) * std::sqrt(n) / (std::sqrt(2) * z);\n int iteNum = 0;\n double LMuOld = std::numeric_limits::infinity();\n double LMuNew = LnVal(Y, muNew, tauNew, n, z);\n\n while (((LMuOld - LMuNew > 1e-10) && std::abs(muOld - muNew) > epsilon) && std::abs(tauOld - tauNew) > epsilon && iteNum < iteMax)\n {\n muOld = muNew;\n tauOld = tauNew;\n LMuOld = LMuNew;\n\n double gradientLnTauVal = gradientTauVal(Y, muOld, tauOld, n, z);\n tauNew = tauOld - eta2 * gradientLnTauVal;\n\n double gradientLnMuVal = gradientMuVal(Y, muOld, tauNew, n, z);\n muNew = muOld - eta1 * gradientLnMuVal;\n LMuNew = LnVal(Y, muNew, tauNew, n, z);\n iteNum += 1;\n }\n return muNew;\n}\n\nextern \"C\" double agdBB(MyVec _Y, double epsilon = 1e-5, int iteMax = 5000)\n{\n arma::vec Y(_Y.data, _Y.n);\n int n = Y.n_elem;\n double eta1 = 1.0;\n double eta2 = std::sqrt(n);\n double muOld = std::numeric_limits::infinity();\n double muNew = arma::mean(Y);\n double tauOld = std::numeric_limits::infinity();\n double delta = 0.05;\n double z = std::min(std::sqrt(std::log(n)), std::sqrt(std::log(1 / delta)));\n double tauNew = arma::stddev(Y) * std::sqrt(n) / (std::sqrt(2) * z);\n int iteNum = 0;\n\n double stepSizeTau = eta2;\n double stepSizeMu = eta1;\n\n double LMuOld = std::numeric_limits::infinity();\n double LMuNew = LnVal(Y, muNew, tauNew, n, z);\n\n double lastTauTilde;\n double lastGradTau;\n double lastMuTilde;\n double lastGradMu;\n\n while (((LMuOld - LMuNew) > epsilon * epsilon && std::abs(muOld - muNew) > epsilon) && std::abs(tauOld - tauNew) > epsilon && iteNum < iteMax)\n {\n LMuOld = LMuNew;\n muOld = muNew;\n tauOld = tauNew;\n\n double gradTau = gradientTauVal(Y, muOld, tauOld, n, z);\n if (iteNum > 0)\n {\n double sTau = tauOld - lastTauTilde;\n double yTau = gradTau - lastGradTau;\n stepSizeTau = std::max(eta2, std::min(std::min((sTau * yTau) / (yTau * yTau), (sTau * sTau) / std::max(0.000001, sTau * yTau)), 1e3));\n }\n lastGradTau = gradTau;\n lastTauTilde = tauOld;\n\n tauNew = std::max(1.35, tauOld - stepSizeTau * (gradientTauVal(Y, muOld, tauOld, n, z)));\n\n double gradMu = gradientMuVal(Y, muOld, tauNew, n, z);\n if (iteNum > 0)\n {\n double sMu = muOld - lastMuTilde;\n double yMu = gradMu - lastGradMu;\n stepSizeMu = std::max(eta1, std::min(std::min((sMu * yMu) / (yMu * yMu), (sMu * sMu) / std::max(0.000001, sMu * yMu)), 1e3));\n }\n lastGradMu = gradMu;\n lastMuTilde = muOld;\n\n muNew = muOld - stepSizeMu * (gradientMuVal(Y, muOld, tauNew, n, z));\n LMuNew = LnVal(Y, muNew, tauNew, n, z);\n iteNum += 1;\n }\n return muNew;\n}\n\n\nextern \"C\" double agdBacktracking(MyVec _Y, double s1 = 1.0, double gamma1 = 0.5, double beta1 = 0.8, double s2 = 1.0, \n double gamma2 = 0.5, double beta2 = 0.8, double epsilon = 1e-5, int iteMax = 5000)\n{ \n arma::vec Y(_Y.data, _Y.n);\n int n = Y.n_elem;\n double muOld = std::numeric_limits::infinity();\n double muNew = arma::mean(Y);\n double tauOld = std::numeric_limits::infinity();\n double delta = 0.05;\n double z = std::min(std::sqrt(std::log(n)), std::sqrt(std::log(1 / delta)));\n double tauNew = arma::stddev(Y) * std::sqrt(n) / (std::sqrt(2) * z);\n int iteNum = 0;\n\n while (std::abs(muOld - muNew) > epsilon && std::abs(tauOld - tauNew) > epsilon && iteNum < iteMax)\n {\n muOld = muNew;\n tauOld = tauNew;\n double LTauOld = LnVal(Y, muOld, tauOld, n, z);\n double gradientLnTauVal = gradientTauVal(Y, muOld, tauOld, n, z);\n\n /*backtracking for eta2*/\n double eta2 = s2;\n tauNew = tauOld - eta2*gradientLnTauVal;\n double LTauNew = LnVal(Y, muOld, tauNew, n ,z);\n \n while (LTauNew > LTauOld + gamma2*eta2*gradientLnTauVal)\n {\n eta2 = beta2*eta2;\n tauNew = tauOld - eta2*gradientLnTauVal;\n LTauNew = LnVal(Y, muOld, tauNew, n ,z);\n gradientLnTauVal = gradientTauVal(Y, muOld, tauNew, n, z);\n }\n \n double LMuOld = LTauNew;\n double gradientLnMuVal = gradientMuVal(Y, muOld, tauNew, n, z);\n \n /*backtracking for eta1*/\n double eta1 = s1;\n muNew = muOld - eta1*gradientLnMuVal;\n double LMuNew = LnVal(Y, muNew, tauNew, n ,z);\n \n while (LMuNew > LMuOld + gamma1*eta1*gradientLnMuVal)\n {\n eta1 = beta1*eta1;\n muNew = muOld - eta1*gradientLnMuVal;\n LMuNew = LnVal(Y, muNew, tauNew, n ,z);\n gradientLnMuVal = gradientMuVal(Y, muNew, tauNew, n, z);\n }\n iteNum += 1;\n }\n return muNew;\n}\n", "meta": {"hexsha": "e70822e3864013050b9a44a19eb34e43a6ee59bc", "size": 26934, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/pyAutoAdaptiveRobustRegression.cpp", "max_stars_repo_name": "YichiZhang-Oxford/auto-adaptive-robust-regression", "max_stars_repo_head_hexsha": "cf48c5fd4e04dc6a2766ff46cc9739be9fc68fd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-28T14:15:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-28T14:15:32.000Z", "max_issues_repo_path": "cpp/pyAutoAdaptiveRobustRegression.cpp", "max_issues_repo_name": "YichiZhang-Oxford/pyAutoAdaptiveRobustRegression", "max_issues_repo_head_hexsha": "cf48c5fd4e04dc6a2766ff46cc9739be9fc68fd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/pyAutoAdaptiveRobustRegression.cpp", "max_forks_repo_name": "YichiZhang-Oxford/pyAutoAdaptiveRobustRegression", "max_forks_repo_head_hexsha": "cf48c5fd4e04dc6a2766ff46cc9739be9fc68fd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3337334934, "max_line_length": 149, "alphanum_fraction": 0.5406920621, "num_tokens": 8693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6928802874152487}} {"text": "/**\n * @file pose_estimation_3d3d.cpp\n * @version v1.0.0\n * @date Nov,6 2017\n * @author jacob.lin\n */\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\nusing namespace cv;\n\n/* find the two photo feature matches points */\nvoid find_feature_matches(const cv::Mat&, const cv::Mat&, std::vector&, std::vector&, std::vector&);\n\n/* Converts the pixel coordinate system to the normalized imaging plane coordinate system */\ncv::Point2d pixel2cam(const cv::Point2d&, const cv::Mat&);\n\n/* */\nvoid pose_estimation_3d3d(const std::vector&, const std::vector&, cv::Mat&, cv::Mat&);\n\n/* */\nvoid bundleAdjustment(const std::vector&, const std::vector&, cv::Mat&, cv::Mat&);\n\n/* g2o edge */\nclass EdgeProjectXYZRGBDPoseOnly : public g2o::BaseUnaryEdge<3, Eigen::Vector3d, g2o::VertexSE3Expmap>\n{\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n EdgeProjectXYZRGBDPoseOnly(const Eigen::Vector3d& point) : _point(point) {}\n \n virtual void computeError()\n {\n const g2o::VertexSE3Expmap* pose = static_cast(_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(_vertices[0]);\n g2o::SE3Quat T(pose->estimate());\n Eigen::Vector3d xyz_trans = T.map(_point);\n \n double x = xyz_trans[0];\n double y = xyz_trans[1];\n double z = xyz_trans[2];\n \n _jacobianOplusXi(0, 0) = 0;\n _jacobianOplusXi(0, 1) = -z;\n _jacobianOplusXi(0, 2) = y;\n _jacobianOplusXi(0, 3) = -1;\n _jacobianOplusXi(0, 4) = 0;\n _jacobianOplusXi(0, 5) = 0;\n \n _jacobianOplusXi(1, 0) = z;\n _jacobianOplusXi(1, 1) = 0;\n _jacobianOplusXi(1, 2) = -x;\n _jacobianOplusXi(1, 3) = 0;\n _jacobianOplusXi(1, 4) = -1;\n _jacobianOplusXi(1, 5) = 0;\n \n _jacobianOplusXi(2, 0) = -y;\n _jacobianOplusXi(2, 1) = x;\n _jacobianOplusXi(2, 2) = 0;\n _jacobianOplusXi(2, 3) = 0;\n _jacobianOplusXi(2, 4) = 0;\n _jacobianOplusXi(2, 5) = -1;\n }\n \n bool read(std::istream& in) {}\n bool write(std::ostream & out) const {}\n \nprotected:\n Eigen::Vector3d _point;\n};\n\nint main(int argc, char** argv)\n{\n if (argc != 5) {\n cout << \"usage: pose_estimation_3d3d img1 img2 depth1 depth2.\" << endl;\n return 1;\n }\n \n //-- 1st, read photo\n cv::Mat img_1 = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);\n cv::Mat img_2 = cv::imread(argv[2], CV_LOAD_IMAGE_COLOR);\n if (img_1.empty() || img_2.empty()) {\n cerr << \"img1 or img2 is empty.\" << endl;\n return 1;\n }\n \n //-- 2nd, find the two photo feature matches points\n std::vector keypoints_1, keypoints_2;\n std::vector matches;\n find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n cout << \"feature matches points total is \" << matches.size() << endl;\n \n //-- 3rd, create 3 dimensions point correspondences\n cv::Mat depth1 = cv::imread(argv[3], CV_LOAD_IMAGE_UNCHANGED); // 深度图为16位无符号数,单通道图像\n cv::Mat depth2 = cv::imread(argv[4], CV_LOAD_IMAGE_UNCHANGED);\n if (depth1.empty() || depth2.empty()) {\n cerr << \"depth1 or depth2 is empty.\" << endl;\n return 1;\n }\n \n cv::Mat K = (cv::Mat_(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n std::vector pts1, pts2;\n \n for (cv::DMatch m : matches) {\n ushort d1 = depth1.ptr((int)keypoints_1[m.queryIdx].pt.y)[(int)keypoints_1[m.queryIdx].pt.x];\n ushort d2 = depth2.ptr((int)keypoints_2[m.trainIdx].pt.y)[(int)keypoints_2[m.trainIdx].pt.x];\n if (d1 == 0 || d2 == 0) {\n continue;\n }\n cv::Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n cv::Point2d p2 = pixel2cam(keypoints_2[m.trainIdx].pt, K);\n float dd1 = float(d1) / 5000.0;\n float dd2 = float(d2) / 5000.0;\n pts1.push_back(cv::Point3f(p1.x * dd1, p1.y * dd1, dd1));\n pts2.push_back(cv::Point3f(p2.x * dd2, p2.y * dd2, dd2));\n }\n cout << \"3d-3d pairs: \" << pts1.size() << endl;\n \n cv::Mat R, t;\n pose_estimation_3d3d(pts1, pts2, R, t);\n cout << \"ICP vid SVD results: \" << endl;\n cout << \"R = \" << R << endl;\n cout << \"t = \" << t << endl;\n cout << \"R_inv = \" << R.t() << endl;\n cout << \"t_inv = \" << -R.t() * t << endl;\n \n cout << \"calling bundle adjustment. \\r\\n\";\n \n bundleAdjustment(pts1, pts2, R, t);\n \n // verify p1 = R*p2 + t\n for (int i = 0; i < 5; i ++) {\n cout << \"p1 = \" << pts1[i] << endl;\n cout << \"p2 = \" << pts2[i] << endl;\n cout << \"R*p2 + t = \" << R * (Mat_(3, 1) << pts2[i].x, pts2[i].y, pts2[i].z) + t << endl;\n cout << endl;\n }\n \n return 0;\n}\n\n\n/**\n * find the two photo feature matches points\n */\nvoid find_feature_matches(const cv::Mat& img_1, const cv::Mat& img_2, std::vector& keypoints_1, std::vector& keypoints_2, std::vector& matches)\n{\n //-- Initialize\n cv::Mat descriptors_1, descriptors_2;\n cv::Ptr detector = cv::ORB::create();\n cv::Ptr descriptor = cv::ORB::create();\n cv::Ptr matcher = cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n \n //-- 1st: detect Oriented FAST KeyPoint \n detector->detect(img_1, keypoints_1);\n detector->detect(img_2, keypoints_2);\n \n //-- 2nd: Calculates BRIEF descriptors with KeyPoint's coordinate\n descriptor->compute(img_1, keypoints_1, descriptors_1);\n descriptor->compute(img_2, keypoints_2, descriptors_2);\n \n //-- 3rd: 对两幅图像中的BRIEF描述子进行匹配,使用 Hamming 距离\n std::vector match;\n matcher->match(descriptors_1, descriptors_2, match);\n \n //-- 4th: 匹配点对筛选\n double min_dist = 10000, max_dist = 0;\n \n /* 找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离 */\n for (int i = 0; i < descriptors_1.rows; i++) {\n double dist = match[i].distance;\n if (dist < min_dist) {\n min_dist = dist;\n }\n if (dist > max_dist) {\n max_dist = dist;\n }\n }\n \n printf(\"-- Max distance : %f \\r\\n\", max_dist);\n printf(\"-- Min distance : %f \\r\\n\", min_dist);\n \n // 当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.但有时候最小距离会非常小,设置一个经验值30作为下限.\n for (int i = 0; i < descriptors_2.rows; i ++) {\n if (match[i].distance <= max(2*min_dist, 30.0)) {\n matches.push_back(match[i]);\n }\n }\n}\n\n/**\n * Converts the pixel coordinate system to the normalized imaging plane coordinate system\n */\ncv::Point2d pixel2cam(const cv::Point2d& p, const cv::Mat& K)\n{\n return cv::Point2d\n (\n (p.x - K.at(0, 2)) / K.at(0, 0),\n (p.y - K.at(1, 2)) / K.at(1, 1)\n );\n}\n\nvoid pose_estimation_3d3d(const std::vector& pts1, const std::vector& pts2, cv::Mat& R, cv::Mat& t)\n{\n // center of mass\n cv::Point3f p1, p2;\n int N = pts1.size();\n for (int i = 0; i < N; i ++) {\n p1 += pts1[i];\n p2 += pts2[i];\n }\n p1 = cv::Point3f(Vec3f(p1) / N);\n p2 = cv::Point3f(Vec3f(p2) / N);\n \n // remove the center\n std::vector q1(N), q2(N);\n for (int i = 0; i < N; i ++) {\n q1[i] = pts1[i] - p1;\n q2[i] = pts2[i] - p2;\n }\n \n // compute q1*q2^T\n Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n for (int i = 0; i < N; i ++) {\n W += Eigen::Vector3d(q1[i].x, q1[i].y, q1[i].z) * Eigen::Vector3d(q2[i].x, q2[i].y, q2[i].z).transpose();\n }\n cout << \"W = \" << W << endl;\n \n // SVD on W\n Eigen::JacobiSVD svd(W, Eigen::ComputeFullU | Eigen::ComputeFullV);\n Eigen::Matrix3d U = svd.matrixU();\n Eigen::Matrix3d V = svd.matrixV();\n\n // 利用SVD求解3D-3D变换,需要U和V的行列式同号。换言之,旋转矩阵的行列式只能为1,不能为-1\n if (U.determinant() * V.determinant() < 0) {\n for (int x = 0; x < 3; ++x) {\n U(x, 2) *= -1;\n }\n }\n cout << \"U = \" << U << endl;\n cout << \"V = \" << V << endl;\n \n \n Eigen::Matrix3d R_ = U * (V.transpose());\n Eigen::Vector3d t_ = Eigen::Vector3d(p1.x, p1.y, p1.z) - R_ * Eigen::Vector3d(p2.x, p2.y, p2.z);\n \n // convert to cv::mat\n R = (cv::Mat_(3, 3) <<\n R_(0, 0), R_(0, 1), R_(0, 2),\n R_(1, 0), R_(1, 1), R_(1, 2),\n R_(2, 0), R_(2, 1), R_(2, 2)\n );\n t = (cv::Mat_(3, 1) << t_(0, 0), t_(1, 0), t_(2, 0));\n}\n\nvoid bundleAdjustment(const std::vector& pts1, const std::vector& pts2, cv::Mat& R, cv::Mat& t)\n{\n // Initialize g2o\n typedef g2o::BlockSolver> Block; // pose维度为 6, landmark 维度为 3\n Block::LinearSolverType* linear_solver = new g2o::LinearSolverEigen(); // 线性方程求解器\n Block* solver_ptr = new Block((std::unique_ptr) linear_solver);\n g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton((std::unique_ptr) solver_ptr);\n g2o::SparseOptimizer optimizer;\n optimizer.setAlgorithm(solver);\n \n // vertex \n g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap(); // camera pose\n pose->setId(0);\n pose->setEstimate(g2o::SE3Quat(Eigen::Matrix3d::Identity(), Eigen::Vector3d(0, 0, 0)));\n optimizer.addVertex(pose);\n \n // edges\n int index = 1;\n std::vector edges;\n for (size_t i = 0; i < pts1.size(); i ++) {\n EdgeProjectXYZRGBDPoseOnly* edge = new EdgeProjectXYZRGBDPoseOnly(Eigen::Vector3d(pts2[i].x, pts2[i].y, pts2[i].z));\n edge->setId(index);\n edge->setVertex(0, dynamic_cast(pose));\n edge->setMeasurement(Eigen::Vector3d(pts1[i].x, pts1[i].y, pts1[i].z));\n edge->setInformation(Eigen::Matrix3d::Identity() * 1e4);\n optimizer.addEdge(edge);\n index ++;\n edges.push_back(edge);\n }\n \n chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n optimizer.setVerbose(true);\n optimizer.initializeOptimization();\n optimizer.optimize(10);\n chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n chrono::duration time_used = chrono::duration_cast> (t2 - t1);\n cout << \"optimization costs time: \" << time_used.count() << \" seconds.\" << \"\\r\\n\";\n \n cout << endl << \"after optimization: \" << endl;\n cout << \"T = \" << endl << Eigen::Isometry3d(pose->estimate()).matrix() << endl;\n}\n\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "74056cf2e28a9b4ea296265d3f5278da79a20f38", "size": 11313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_estimation_3d3d/src/pose_estimation_3d3d.cpp", "max_stars_repo_name": "LSXiang/slam_learning_journey", "max_stars_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-03-22T00:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T05:23:27.000Z", "max_issues_repo_path": "pose_estimation_3d3d/src/pose_estimation_3d3d.cpp", "max_issues_repo_name": "LSXiang/slam_learning_journey", "max_issues_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pose_estimation_3d3d/src/pose_estimation_3d3d.cpp", "max_forks_repo_name": "LSXiang/slam_learning_journey", "max_forks_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1782477341, "max_line_length": 183, "alphanum_fraction": 0.5927693804, "num_tokens": 3891, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6928802831901788}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \"expsum/exponential_sum.hpp\"\n#include \"expsum/kernel_functions/sph_bessel_kernel.hpp\"\n// #include \"expsum/fitting/fast_esprit.hpp\"\n#include \n\nusing size_type = arma::uword;\nusing expsum_type = expsum::exponential_sum>;\n\ntemplate \nvoid make_sample(F f, double xmin, double xmax, Vec& result)\n{\n auto np = result.n_elem;\n auto h = (xmax - xmin) / (np - 1);\n for (size_type n = 0; n < np; ++n)\n {\n result(n) = f(xmin + n * h);\n }\n\n return;\n}\n\n// expsum_type sph_bessel_kernel(int l, double xmax, size_type N, size_type L,\n// size_type M, double eps)\n// {\n// using esprit_type = expsum::fast_esprit;\n// using vector_type = arma::Col;\n\n// vector_type exact(N);\n// make_sample([=](double x) { return boost::math::sph_bessel(l, x); }, 0.0,\n// xmax, exact);\n// auto delta = xmax / (N - 1);\n\n// esprit_type esprit(N, L, M);\n\n// esprit.fit(exact, 0.0, delta, eps);\n// expsum_type ret(esprit.exponents(), esprit.weights());\n\n// ret.remove_small_terms(eps / 100.0);\n\n// return ret;\n// }\n\nexpsum_type sph_bessel_kernel(int l, double xmax, double eps)\n{\n // using vector_type = arma::Col;\n expsum::sph_bessel_kernel body;\n body.compute(l, xmax, eps);\n\n expsum_type ret(body.exponents(), body.weights());\n\n return ret;\n}\n\nvoid sph_bessel_kernel_error(int l, double xmax, size_type n_samples,\n const expsum_type& ret)\n{\n using vector_type = arma::Col;\n\n vector_type x(arma::linspace(0.0, xmax, n_samples));\n vector_type exact(n_samples), approx(n_samples);\n\n for (size_type i = 0; i < n_samples; ++i)\n {\n exact(i) = boost::math::sph_bessel(l, x(i));\n approx(i) = ret(x(i));\n auto abserr = std::abs(exact(i) - approx(i));\n std::cout << std::setw(24) << x(i) << std::setw(24) << exact(i)\n << std::setw(24) << approx(i) << std::setw(24) << abserr\n << '\\n';\n }\n\n vector_type abserr(arma::abs(exact - approx));\n\n size_type imax = abserr.index_max();\n\n std::cout << \"\\n abs. error in interval [0,\" << xmax << \"]\\n\"\n << \" maximum : \" << abserr(imax) << '\\n'\n << \" averaged: \" << arma::sum(abserr) / n_samples << '\\n';\n}\n\nint main()\n{\n std::cout.precision(15);\n std::cout.setf(std::ios::scientific);\n\n const int lmax = 2;\n\n size_type N = 100001; // # of sampling points\n // size_type L = N / 2; // window length\n // size_type M = 1000; // max # of terms\n double xmax = 1.0e12;\n double eps = 1.0e-12;\n\n expsum_type ret;\n\n std::cout\n << \"# Approximation of spherical Bessel function by exponential sum\\n\";\n\n // for (int l = 0; l <= lmax; ++l)\n // {\n // std::cout << \"\\n# --- order \" << l << '\\n';\n // ret = sph_bessel_kernel(l, xmax, eps);\n // ret.print(std::cout);\n\n // sph_bessel_kernel_error(l, 10.0, N, ret);\n // sph_bessel_kernel_error(l, 1.0e8, N, ret);\n // }\n\n // for (int l = 0; l <= lmax; ++l)\n // {\n // std::cout << \"\\n# --- order \" << l << '\\n';\n // sph_bessel_kernel(l, xmax, eps);\n // }\n\n std::cout << \"\\n# --- order \" << lmax << '\\n';\n ret = sph_bessel_kernel(1, xmax, eps);\n ret.print(std::cout);\n std::cout << \"sum weights: \" << arma::sum(ret.weight()) << std::endl;\n sph_bessel_kernel_error(1, 1.0, 100001, ret);\n // sph_bessel_kernel_error(1, xmax, N, ret);\n\n return 0;\n}\n", "meta": {"hexsha": "6f68a738623d6904ef273792c472dc6d4be7c9ef", "size": 3739, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/sph_bessel_kernel.cpp", "max_stars_repo_name": "hide-ikeno/expsum", "max_stars_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/sph_bessel_kernel.cpp", "max_issues_repo_name": "hide-ikeno/expsum", "max_issues_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/sph_bessel_kernel.cpp", "max_forks_repo_name": "hide-ikeno/expsum", "max_forks_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.7615384615, "max_line_length": 80, "alphanum_fraction": 0.5629847553, "num_tokens": 1105, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543454, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.692718157335282}} {"text": "#include \n\n#include \n\nint main (int argc, char *argv[]){\n Eigen::MatrixXf m(2, 2);\n m << 1, 2, 3, 4;\n Eigen::VectorXf v(2);\n v << -1, 1;\n auto r = m * v;\n std::cout << r(0) << \" \" << r(1) << std::endl;\n return 0;\n}\n", "meta": {"hexsha": "7929d2df90c8c7d951a94b06632add817f22d23e", "size": 260, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Example.01/main.cpp", "max_stars_repo_name": "AndreyBuyanov/EigenExample", "max_stars_repo_head_hexsha": "fd05ed119a2e000f2d137c98b49bf927422276a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Example.01/main.cpp", "max_issues_repo_name": "AndreyBuyanov/EigenExample", "max_issues_repo_head_hexsha": "fd05ed119a2e000f2d137c98b49bf927422276a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Example.01/main.cpp", "max_forks_repo_name": "AndreyBuyanov/EigenExample", "max_forks_repo_head_hexsha": "fd05ed119a2e000f2d137c98b49bf927422276a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5714285714, "max_line_length": 50, "alphanum_fraction": 0.4807692308, "num_tokens": 104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765281148512, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.692378925173398}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"shtns.h\"\n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_vertex_base_with_info_2 Vb;\ntypedef CGAL::Triangulation_data_structure_2 Tds;\ntypedef CGAL::Delaunay_triangulation_2 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 Map3Xd;\n\nint main(){\n\n // Read the polydata\n vtkNew reader;\n reader->SetFileName(\"T7.vtk\");\n reader->Update();\n auto pointCloud = reader->GetOutput();\n int N = pointCloud->GetNumberOfPoints();\n\n //**********************************************************************//\n //SHTns: Generate quadrature points\n int lmax = std::floor( sqrt(N) - 1 );\n int mmax = lmax, nlat = 0, nphi = 0, mres = 1;\n shtns_cfg shtns;\n shtns_verbose(1);\n shtns_norm norm = static_cast(SHT_REAL_NORM | SHT_NO_CS_PHASE);\n shtns = shtns_create(lmax, mmax, mres, norm );\n shtns_type flags = static_cast( sht_gauss | SHT_NATIVE_LAYOUT);\n shtns_set_grid_auto(shtns, flags, 1e-14, 1, &nlat, &nphi );\n int NLM = shtns->nlm;\n int numQ = nphi*nlat;\n\n // Memory allocation\n double_t *f;\n f = static_cast(\n\t fftw_malloc( NSPAT_ALLOC(shtns)*sizeof(double_t) ));\n std::complex *Slm;\n Slm = static_cast*>(\n\t fftw_malloc( NLM*sizeof(std::complex) ));\n // Memory initialization\n for( auto lm = 0; lm < NLM; ++lm){\n\tSlm[lm] = 0.0;\n }\n\n // Calculate the quad point Q0\n Eigen::Matrix3Xd Q0(3,numQ);\n for( auto ip = 0; ip < nphi; ++ip){\n\tfor( auto it = 0; it < nlat; ++it){\n\t auto phi = ip*M_PI*2/nphi;\n\t Q0.col(it + ip*nlat) << shtns->st[it]*std::cos(phi),\n\t\tshtns->st[it]*std::sin(phi), shtns->ct[it];\n\t}\n }\n\n //************************* Some handy functions ***********************//\n\n // A lambda function to write a Eigen::Matrix3Xd to VTK file\n auto writeMatToVTK =\n\t[](Eigen::Matrix3Xd M, std::string file, bool Proj = false){\n\t vtkNew pts;\n\t vtkNew verts;\n\t for( auto b = 0; b < M.cols(); ++b ){\n\t\tdouble x, y, z;\n\t\tx = M(0,b);\n\t\ty = M(1,b);\n\t\tz = Proj? 0.0 : M(2,b);\n\t\tpts->InsertNextPoint(x, y, z);\n\t\tverts->InsertNextCell( 1 );\n\t\tverts->InsertCellPoint( b );\n\t }\n\t vtkNew poly;\n\t poly->SetPoints( pts );\n\t poly->SetVerts( verts );\n\t vtkNew wr;\n\t wr->SetInputData( poly );\n\t wr->SetFileName( file.c_str() );\n\t wr->Write();\n\t};\n\n //**********************************************************************//\n clock_t t = clock();\n\n for( auto z = 0; z < 1000; ++z ){\n\t// Copy the point coordinates into a matrix\n\tEigen::Map points((double_t*)pointCloud->GetPoints()\n\t\t->GetData()->GetVoidPointer(0),3,N);\n\n\t// Project points to unit sphere\n\tpoints.colwise().normalize();\n\n\t// Reset the center of the sphere to origin by translating\n\tVector3d center = points.rowwise().mean();\n\tpoints = points.colwise() - center;\n\n\t// Write original points to VTK\n\t//writeMatToVTK( points, \"BasePoints.vtk\" );\n\n\t// Rotate all points so that the point in 0th column is along z-axis\n\tVector3d c = points.col(0);\n\tdouble_t cos_t = c(2);\n\tdouble_t sin_t = std::sqrt( 1 - cos_t*cos_t );\n\tVector3d axis;\n\taxis << c(1), -c(0), 0.;\n\tMatrix3d rotMat, axis_cross, outer;\n\taxis_cross << 0. , -axis(2), axis(1),\n\t\t axis(2), 0., -axis(0),\n\t\t -axis(1), axis(0), 0.;\n\n\touter.noalias() = axis*axis.transpose();\n\n\trotMat = cos_t*Matrix3d::Identity() + sin_t*axis_cross + (1-cos_t)*outer;\n\tMatrix3Xd rPts(3,N);\n\trPts = rotMat*points; // The points on a sphere rotated\n\n\t// Write the rotated points to VTK\n\t//writeMatToVTK( rPts, \"RotBasePoints.vtk\" );\n\n\t// Calculate the stereographic projections\n\tVector3d p0;\n\tMap3Xd l0( &(rPts(0,1)), 3, N-1 );\n\tMatrix3Xd l(3,N-1), proj(3,N-1);\n\tp0 << 0,0,-1; // Point on the plane of projection\n\tc = rPts.col(0); // The point from which we are projecting\n\tl = (l0.colwise() - c).colwise().normalized(); // directions of projections\n\tfor( auto j=0; j < N-1; ++j ){\n\t proj.col(j) = ((p0(2) - l0(2,j))/l(2,j))*l.col(j) + l0.col(j);\n\t}\n\n\t// Write the rotated points to VTK\n\t//writeMatToVTK( proj, \"ProjBasePoints.vtk\", true );\n\n\t// Insert the projected points in a CGAL vertex_with_info vector\n\tstd::vector< std::pair< Point, unsigned> > verts;\n\tfor( auto j=0; j < N-1; ++j ){\n\t verts.push_back(std::make_pair(Point(proj(0,j),proj(1,j)),j+1));\n\t}\n\n\tDelaunay dt( verts.begin(), verts.end() );\n\n\t/*\n\t// Write the triangulation to file\n\tvtkNew sphereTri;\n\tfor( auto fc = dt.all_faces_begin(); fc != dt.all_faces_end(); ++fc ){\n\tsphereTri->InsertNextCell(3);\n\tfor( auto zz = 2; zz >= 0; --zz ){\n\tauto vid = dt.is_infinite( fc->vertex( zz ) )? 0 :\n\tfc->vertex(zz)->info();\n\tsphereTri->InsertCellPoint(vid);\n\t}\n\t}\n\tpointCloud->SetPolys( sphereTri );\n\tvtkNew wr;\n\twr->SetInputData( pointCloud );\n\twr->SetFileName( \"Sphere.vtk\" );\n\twr->Write();\n\t*/\n\n\t// Create the input scalar field f(theta,phi)\n\tstd::complex Qlm[NLM];\n\tfor(auto pp = 0; pp < NLM; ++pp)\n\t Qlm[pp] = 0.0;\n\tQlm[ LM(shtns, 0, 0) ] = std::complex(0,0);\n\tQlm[ LM(shtns, 1, 0) ] = std::complex(2,0);\n\tQlm[ LM(shtns, 1, 1) ] = std::complex(0,3);\n\tQlm[ LM(shtns, 7, 7) ] = std::complex(7,0);\n\n\tEigen::VectorXd finput(N);\n\tfor(auto i = 0; i < N; ++i){\n\t Eigen::Vector3d q;\n\t q = points.col(i);\n\t double_t x = q(0);\n\t double_t y = q(1);\n\t double_t z = q(2);\n\t auto phi = std::atan2(y,x);\n\t finput(i) = SH_to_point(shtns, Qlm, z, phi);\n\t}\n\n\t//Now we need to first identify which triangles each of the quadrature\n\t//points belongs to. For this, we need the coordinates of the points\n\tEigen::Matrix3Xd Qr(3,numQ);// Rotated quadrature points\n\tEigen::Matrix3Xd Qsp(3,numQ);// StereoProjection of quadrature points\n\n\n\t// Write Quadrature points to VTK file\n\t//writeMatToVTK( Q0, \"QuadPointsOrig.vtk\" );\n\n\t// Now we need to rotate and project the quadrature points\n\t// p0 is already defined as the z = -1 plane\n\t// c is the point from which we are projecting (calculated earlier)\n\tQr = rotMat*Q0; // Rotate the quadrature points\n\n\t// Write the rotated points to VTK\n\t//writeMatToVTK( Qr, \"RotQuadPoints.vtk\" );\n\n\tEigen::Matrix3Xd lQ(3,numQ);\n\tlQ = (Qr.colwise() - c).colwise().normalized();//projn dirn unit vectors\n\tfor( auto j=0; j < numQ; ++j ){\n\t Qsp.col(j) = ((p0(2) - Qr(2,j))/lQ(2,j))*lQ.col(j) + Qr.col(j);\n\t}\n\n\t// Write Stereographic projections of quadrature points to VTK file\n\t//writeMatToVTK( Qsp, \"ProjQuadPoints.vtk\", true );\n\n\t//Finally let's try to locate these points in the Triangulation and\n\t//interpolate it as per the weights\n\tEigen::Map fquad(f,numQ);\n\tauto interpolate = [&points, &Q0, &finput, &fquad](const size_t i,\n\t\tconst size_t j, const size_t k, const size_t q){\n\t Eigen::Vector3d v0 = points.col(i);\n\t Eigen::Vector3d v1 = points.col(j);\n\t Eigen::Vector3d v2 = points.col(k);\n\t Eigen::Vector3d qp = Q0.col(q);\n\t auto A0 = ((v1-qp).cross((v2-qp))).norm();\n\t auto A1 = ((v2-qp).cross((v0-qp))).norm();\n\t auto A2 = ((v0-qp).cross((v1-qp))).norm();\n\t auto A = A0 + A1 + A2;\n\t fquad(q) = (A0/A)*finput(i) + (A1/A)*finput(j) + (A2/A)*finput(k);\n\t};\n\tfor( auto j=0; j < numQ; ++j ){\n\t auto query = Point( Qsp(0,j), Qsp(1,j) );\n\t Delaunay::Locate_type lt;\n\t int li;\n\t Face_handle face = dt.locate( query, lt, li );\n\t switch(lt){\n\t\tcase Delaunay::FACE:\n\t\t {\n\t\t\tauto id0 = face->vertex(0)->info();\n\t\t\tauto id1 = face->vertex(1)->info();\n\t\t\tauto id2 = face->vertex(2)->info();\n\t\t\tinterpolate( id0, id1, id2, j );\n\t\t\tbreak;\n\t\t }\n\t\tcase Delaunay::EDGE:\n\t\t {\n\t\t\tauto id1 = face->vertex( (li + 1)%3 )->info();\n\t\t\tauto id2 = face->vertex( (li + 2)%3 )->info();\n\t\t\tEigen::Vector3d v1, v2, qp;\n\t\t\tv1 = points.col(id1);\n\t\t\tv2 = points.col(id2);\n\t\t\tqp = Q0.col(j);\n\t\t\tdouble_t ratio = (qp - v1).norm()/(qp - v2).norm();\n\t\t\tfquad(j) = (finput(id1) + ratio*finput(id2))/(1 + ratio);\n\t\t\tbreak;\n\t\t }\n\t\tcase Delaunay::VERTEX:\n\t\t fquad(j) = finput( face->vertex( li )->info() );\n\t\t break;\n\t\tcase Delaunay::OUTSIDE_CONVEX_HULL:\n\t\t {\n\t\t\tEigen::Vector3d v0, v1, v2;\n\t\t\tauto id0 = dt.is_infinite(face->vertex(0))?\n\t\t\t 0 : face->vertex(0)->info();\n\t\t\tauto id1 = dt.is_infinite(face->vertex(1))?\n\t\t\t 0 : face->vertex(1)->info();\n\t\t\tauto id2 = dt.is_infinite(face->vertex(2))?\n\t\t\t 0 : face->vertex(2)->info();\n\t\t\tinterpolate( id0, id1, id2, j );\n\t\t\tbreak;\n\t\t }\n\t\tdefault:\n\t\t std::cout<< \"Point \" << j << \" not found!\" << std::endl;\n\t }\n\t}\n\n\t/*\n\t std::cout<< \"Print interpolated values and actual values...\"< flm;\n\tif( m < 0){\n\tauto factor = (-m%2 == 0)? 1.0 : -1.0;\n\tflm = factor*std::conj(Slm[ LM(shtns,l,-m) ]);\n\t}\n\telse{\n\tflm = Slm[ LM(shtns,l,m) ];\n\t}\n\tstd::cout<< l << \" \" << m << \" \" << flm << std::endl;\n\t}\n\t}\n\t*/\n }\n std::cout<< \"Time for 1000 steps = \" \n\t<< ((float)(clock() - t))/CLOCKS_PER_SEC << std::endl;\n for( auto lm = 0; lm < NLM; ++lm){\n\tstd::cout<< Slm[ lm ] << std::endl;\n }\n return 0;\n}\n", "meta": {"hexsha": "f8f15c17d2265a6efc3799060cb01448cca3d8c3", "size": 10502, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "TestSHTNS.cxx", "max_stars_repo_name": "amit112amit/ops-spherical-harmonics", "max_stars_repo_head_hexsha": "27a0d5e6ed4635d9b1cd6cb1d625d3cc4147beed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-31T13:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-31T13:42:53.000Z", "max_issues_repo_path": "TestSHTNS.cxx", "max_issues_repo_name": "amit112amit/ops-spherical-harmonics", "max_issues_repo_head_hexsha": "27a0d5e6ed4635d9b1cd6cb1d625d3cc4147beed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TestSHTNS.cxx", "max_forks_repo_name": "amit112amit/ops-spherical-harmonics", "max_forks_repo_head_hexsha": "27a0d5e6ed4635d9b1cd6cb1d625d3cc4147beed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6325301205, "max_line_length": 79, "alphanum_fraction": 0.6140735098, "num_tokens": 3508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465062370312, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6923194928175932}} {"text": "// -*- coding: utf-8 -*-\n\n#define _USE_MATH_DEFINES\n#include \n#include \n#include \n#include \n#include \n#include \n\ndouble slp_laplace(const Eigen::Vector2d &xm, const Eigen::Vector2d &ym, const Eigen::Vector2d &y1,\n\t\t const Eigen::Vector2d &y2, const double &hy, const Eigen::Vector2d &yn){\n// Eigen::Vector2d ym;\n Eigen::Vector2d rr1;\n Eigen::Vector2d rr2;\n double r1;\n double r2;\n Eigen::Vector2d yt;\n double uk1, uk2, uk3, uk4, uk5;\n constexpr double arctwopi = 1.0/(2.0*std::acos(-1.0));\n\n// ym = 0.5*(y1 + y2);\n\n if((xm - ym).squaredNorm() < 1.0e-8){\n return hy*(1.0 - std::log(hy*0.5))*arctwopi;\n }\n else{\n rr1 = xm - y1;\n rr2 = xm - y2;\n r1 = rr1.norm();\n r2 = rr2.norm();\n yt(0) = -yn(1);\n yt(1) = yn(0);\n\n uk1 = rr1.dot(yn);\n uk2 = rr1.dot(yt);\n uk3 = rr2.dot(yn);\n uk4 = rr2.dot(yt);\n uk5 = std::atan2(uk3, uk4) - std::atan2(uk1, uk2);\n return (uk4*std::log(r2) - uk2*std::log(r1) + hy - uk1*uk5)*arctwopi;\n// std::cout << \"tes3 \" << std::endl; //dbg\n }\n}\n\ndouble dlp_laplace(const Eigen::Vector2d &xm, const Eigen::Vector2d &ym, const Eigen::Vector2d &y1,\n\t\t const Eigen::Vector2d &y2, const double &hy, const Eigen::Vector2d &yn,\n\t\t const int &exterior){\n\n// Eigen::Vector2d ym;\n Eigen::Vector2d rr1;\n Eigen::Vector2d rr2;\n double r1;\n double r2;\n Eigen::Vector2d yt;\n double uk1, uk2, uk3, uk4;\n constexpr double arctwopi = 1.0/(2.0*std::acos(-1.0));\n\n // ym = 0.5*(y1 + y2);\n\n if((xm - ym).squaredNorm() < 1.0e-8){\n if(exterior == 0){\n return 0.5;\n }else if(exterior == 1){\n return -0.5;\n }else{\n assert(false);\n }\n }\n else{\n rr1 = xm - y1;\n rr2 = xm - y2;\n r1 = rr1.norm();\n r2 = rr2.norm();\n yt(0) = -yn(1);\n yt(1) = yn(0);\n\n uk1 = rr1.dot(yn);\n uk2 = rr1.dot(yt);\n uk3 = rr2.dot(yn);\n uk4 = rr2.dot(yt);\n return arctwopi*(std::atan2(uk3, uk4) - std::atan2(uk1, uk2));\n }\n}\n\nint main(){\n int n;\n double rad;\n std::ifstream fr(\"input\");\n fr >> n >> rad;\n std::cout << \"n \" << n << std::endl;\n std::cout << \"rad \" << rad << std::endl;\n\n Eigen::MatrixXd x = Eigen::MatrixXd::Zero(2, n);\n Eigen::MatrixXd xn = Eigen::MatrixXd::Zero(2, n);\n Eigen::MatrixXi edge = Eigen::MatrixXi::Zero(2, n);\n Eigen::VectorXd hs = Eigen::VectorXd::Zero(n);\n Eigen::MatrixXd slp = Eigen::MatrixXd::Zero(n, n);\n Eigen::MatrixXd dlp = Eigen::MatrixXd::Zero(n, n);\n Eigen::VectorXd u = Eigen::VectorXd::Zero(n);\n Eigen::VectorXd kai = Eigen::VectorXd::Zero(n);\n Eigen::VectorXd xm = Eigen::VectorXd::Zero(2);\n Eigen::VectorXd ym = Eigen::VectorXd::Zero(2);\n\n constexpr double pi = std::acos(-1.0);\n\n int i;\n int j;\n double th;\n int i0;\n int i1;\n int j0;\n int j1;\n int exterior = 0;\n\n for(i = 0; i < n; i++){\n th = 2.0*pi*(i + 1.5)/n;\n x(0, i) = rad*cos(th);\n x(1, i) = rad*sin(th);\n edge(0, i) = i;\n edge(1, i) = (i + 1) % n;\n }\n\n Eigen::Vector2d rr1; //dbg\n Eigen::Vector2d rr2; //dbg\n double r1; //dbg\n double r2; //dbg\n Eigen::Vector2d yt; //dbg\n double uk1, uk2, uk3, uk4, uk5; //dbg\n constexpr double arctwopi = 1.0/(2.0*std::acos(-1.0)); //dbg\n\n for(i = 0; i < n; i++){\n i0 = edge(0, i);\n i1 = edge(1, i);\n xm = 0.5*(x.col(i0) + x.col(i1));\n\n if((i0 >= 0 && i0 < n) && (i1 >= 0 && i1 < n)){\n xn(0, i) = x(1, i1) - x(1, i0);\n xn(1, i) = x(0, i0) - x(0, i1);\n\n hs(i) = std::sqrt(std::pow(xn(0, i), 2.0) + std::pow(xn(1, i), 2.0));\n\n xn(0, i) = xn(0, i)/hs(i);\n xn(1, i) = xn(1, i)/hs(i);\n }\n else{\n assert(false);\n }\n // x**3*y - x*y**3\n u(i) = std::pow(xm(0), 3.0)*xm(1) - xm(0)*std::pow(xm(1), 3.0);\n\n // (3x**2*y - y**3)nx + (x**3 - 3xy**2)ny\n kai(i) = (3.0*std::pow(xm(0), 2.0)*xm(1) - std::pow(xm(1), 3.0))*xn(0, i)\n + (std::pow(xm(0), 3.0) - 3.0*xm(0)*std::pow(xm(1), 2.0))*xn(1, i);\n }\n\n for(j = 0; j < n; j++){\n j0 = edge(0, j);\n j1 = edge(1, j);\n ym = 0.5*(x.col(j0) + x.col(j1));\n for(i = 0; i < n; i++){\n i0 = edge(0, i);\n i1 = edge(1, i);\n xm = 0.5*(x.col(i0) + x.col(i1));\n\n slp(i, j) = slp_laplace(xm, ym, x.col(j0), x.col(j1), hs(j), xn.col(j));\n dlp(i, j) = dlp_laplace(xm, ym, x.col(j0), x.col(j1), hs(j), xn.col(j), exterior);\n }\n }\n\n u = slp.partialPivLu().solve(dlp*u);\n\n std::cout << \"relative error \" << std::sqrt(((u - kai).dot(u - kai))/kai.dot(kai)) << std::endl;\n}\n", "meta": {"hexsha": "4fff57c1b7897b0518071d1e7c4bf8324033afce", "size": 4452, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main.cc", "max_stars_repo_name": "ya-mat/2d_laplace", "max_stars_repo_head_hexsha": "9deb57b0e5831f4edb2f23ddd77d0a4434ee6b8d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cc", "max_issues_repo_name": "ya-mat/2d_laplace", "max_issues_repo_head_hexsha": "9deb57b0e5831f4edb2f23ddd77d0a4434ee6b8d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cc", "max_forks_repo_name": "ya-mat/2d_laplace", "max_forks_repo_head_hexsha": "9deb57b0e5831f4edb2f23ddd77d0a4434ee6b8d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5862068966, "max_line_length": 99, "alphanum_fraction": 0.524034142, "num_tokens": 1860, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6921885996226141}} {"text": "// SPDX-License-Identifier: MIT\n// Copyright (c) 2019-2021 Thomas Vanderbruggen \n\n#include \n#include \n#include \n#include \n\nint main() {\n Eigen::Matrix A;\n A << 0., 1., //\n 1., 1., //\n 2., 1., //\n 3., 1.;\n\n const std::array b{-1., 0.2, 0.9, 2.1};\n const auto x = scicpp::linalg::lstsq(A, b);\n scicpp::print(x);\n}", "meta": {"hexsha": "705a02085709211ff7b7b93c900f5953434ec828", "size": 447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/doc/linalg_lstsq.cpp", "max_stars_repo_name": "tvanderbruggen/SciCpp", "max_stars_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-08-02T09:03:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T11:58:05.000Z", "max_issues_repo_path": "examples/doc/linalg_lstsq.cpp", "max_issues_repo_name": "tvanderbruggen/SciCpp", "max_issues_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/doc/linalg_lstsq.cpp", "max_forks_repo_name": "tvanderbruggen/SciCpp", "max_forks_repo_head_hexsha": "09408506c8d0b49ca5dadb8cd1f3cb4db41c8c46", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5263157895, "max_line_length": 76, "alphanum_fraction": 0.5659955257, "num_tokens": 165, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069987088003, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6921213475064647}} {"text": "// Copyright (c) 2015\n// Author: Chrono Law\n#include \n#include \nusing namespace std;\n\n#include \nusing namespace boost::math;\n\n//////////////////////////////////////////\n\nvoid case1()\n{\n cout << setprecision(64);\n\n auto a = float_constants::pi * 2 * 2;\n cout << \"area \\t\\t= \" << a << endl;\n\n using namespace double_constants;\n\n auto x = root_two * root_three;\n cout << \"root 2 * 3 \\t= \" << x << endl;\n\n cout << \"root pi \\t= \" << root_pi << endl;\n cout << \"pi pow e \\t= \" << pi_pow_e << endl;\n}\n\n//////////////////////////////////////////\n#include \n\nvoid case2()\n{\n using namespace constants;\n\n typedef decltype(pi) pi_t;\n assert(is_function::value);\n\n assert(pi() == float_constants::pi);\n assert(pi() == double_constants::pi);\n\n typedef boost::multiprecision::cpp_dec_float_100 float_100;\n cout << setprecision(100)\n << pi() << endl;\n}\n\nint main()\n{\n case1();\n case2();\n}\n\n\n", "meta": {"hexsha": "d345868e2ef2de0431faed622d25f2980ea83948", "size": 1070, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "math/math_constants.cpp", "max_stars_repo_name": "xujungp02/boost_guide", "max_stars_repo_head_hexsha": "328516455d334506f824402455a17afc606ca3bc", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 355.0, "max_stars_repo_stars_event_min_datetime": "2015-03-06T12:03:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T04:15:00.000Z", "max_issues_repo_path": "math/math_constants.cpp", "max_issues_repo_name": "lak123456/boost_guide", "max_issues_repo_head_hexsha": "1886ec8014838717222484f0fe872ecebc324e91", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-10-04T18:14:17.000Z", "max_issues_repo_issues_event_max_datetime": "2017-10-09T02:38:12.000Z", "max_forks_repo_path": "math/math_constants.cpp", "max_forks_repo_name": "lak123456/boost_guide", "max_forks_repo_head_hexsha": "1886ec8014838717222484f0fe872ecebc324e91", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 202.0, "max_forks_repo_forks_event_min_datetime": "2015-03-23T16:16:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:55:48.000Z", "avg_line_length": 20.1886792453, "max_line_length": 63, "alphanum_fraction": 0.5682242991, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.6920782682940181}} {"text": "//==================================================================================================\n/*!\n @file\n\n @copyright 2016 NumScale SAS\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_CONSTANT_EULER_HPP_INCLUDED\n#define BOOST_SIMD_CONSTANT_EULER_HPP_INCLUDED\n\n/*!\n @ingroup group-constant\n @defgroup constant-Euler Euler (function template)\n\n Generates an approximation of the Euler-Mascheroni constant.\n\n @headerref{}\n\n @par Description\n\n 1. @code\n template T Euler();\n @endcode\n\n 2. @code\n template T Euler( boost::simd::as_ const& target );\n @endcode\n\n Generates a value of type @c T evaluating to the Euler-Mascheroni constant defined as:\n \\f$\\gamma = \\lim_{n \\rightarrow \\infty } \\left( 1+ \\frac{1}{2} + ... + \\frac{1}{n} - \\ln(n) \\right)\\f$.\n\n @par Parameters\n\n | Name | Description |\n |--------------------:|:--------------------------------------------------------------------|\n | **target** | a [placeholder](@ref type-as) value encapsulating the constant type |\n\n @par Return Value\n A value of type @c T that evaluates to `T(0.57721566490153286060651209008240243104215933593992359)`\n\n @par Requirements\n - **T** models IEEEValue\n**/\n\n#include \n#include \n\n#endif\n", "meta": {"hexsha": "450309bb5d577da23bf488a60ad1ae3d1f73d58c", "size": 1650, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/constant/euler.hpp", "max_stars_repo_name": "SylvainCorlay/pythran", "max_stars_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z", "max_issues_repo_path": "third_party/boost/simd/constant/euler.hpp", "max_issues_repo_name": "SylvainCorlay/pythran", "max_issues_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/constant/euler.hpp", "max_forks_repo_name": "SylvainCorlay/pythran", "max_forks_repo_head_hexsha": "908ec070d837baf77d828d01c3e35e2f4bfa2bfa", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z", "avg_line_length": 31.7307692308, "max_line_length": 105, "alphanum_fraction": 0.5454545455, "num_tokens": 383, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942173896132, "lm_q2_score": 0.7772998508568416, "lm_q1q2_score": 0.6920255623956549}} {"text": "#include \"physics.hpp\"\n\n#include \n\nphysics::physics()\n{\n\tthis->generator = std::mt19937_64(std::random_device{}());\n\n}\n\nphysics::~physics()\n{\n\n}\n\nvoid physics::step(double delta_t)\n{\n\ttotal_time += delta_t;\n\n\t// TODO: collision detection\n\t#pragma omp parallel for\n\tfor(int i = 0; i < obj_count; i++)\n\t{\n\t\t// Euler\n\t\t//a[current][i] = accel(x[current][i], i);\n\t\t//v[next][i] = a[current][i] * delta_t + v[current][i];\n\t\t//x[next][i] = v[next][i] * delta_t + x[current][i];\n\n\t\t// RK4 integration, see doc/grav_sim.tex\n\t\t// this is about 4x worse than Euler\n\t\tEigen::Vector3d xk1 = x[current][i];\n\t\tEigen::Vector3d vk1 = v[current][i];\n\t\tEigen::Vector3d ak1 = accel(xk1, i);\n\n\t\tEigen::Vector3d xk2 = x[current][i] + 0.5 * vk1 * delta_t;\n\t\tEigen::Vector3d vk2 = v[current][i] + 0.5 * ak1 * delta_t;\n\t\tEigen::Vector3d ak2 = accel(xk2, i);\n\n\t\tEigen::Vector3d xk3 = x[current][i] + 0.5 * vk2 * delta_t;\n\t\tEigen::Vector3d vk3 = v[current][i] + 0.5 * ak2 * delta_t;\n\t\tEigen::Vector3d ak3 = accel(xk3, i);\n\n\t\tEigen::Vector3d xk4 = x[current][i] + vk3 * delta_t;\n\t\tEigen::Vector3d vk4 = v[current][i] + ak3 * delta_t;\n\t\tEigen::Vector3d ak4 = accel(xk4, i);\n\n\t\tv[next][i] = v[current][i] + (delta_t / 6.0) *\n\t\t\t\t(ak1 + 2 * ak2 + 2 * ak3 + ak4);\n\t\tx[next][i] = x[current][i] + (delta_t / 6.0) *\n\t\t\t\t(vk1 + 2 * vk2 + 2 * vk3 + vk4);\n\t}\n\n\tcurrent = current ? 0 : 1;\n\tnext = next ? 0 : 1;\n}\n\nEigen::Vector3d physics::accel(Eigen::Vector3d x_i, uint16_t skip_index)\n{\n\tEigen::Vector3d a(0.0, 0.0, 0.0);\n\tfor(uint16_t j = 0; j < obj_count; j++)\n\t{\n\t\tif(skip_index == j)\n\t\t\tcontinue;\n\n\t\tEigen::Vector3d r = x[current][j] - x_i;\n\t\ta += G * m[j] * r.normalized() / r.squaredNorm();\n\t}\n\treturn a;\n}\n\nvoid physics::init(uint16_t obj_count)\n{\n\tthis->obj_count = obj_count;\n\n\tcurrent = 0;\n\tnext = 1;\n\ttotal_time = 0.0;\n\n\tx[0].resize(obj_count);\n\tx[1].resize(obj_count);\n\tv[0].resize(obj_count);\n\tv[1].resize(obj_count);\n\ta[0].resize(obj_count);\n\ta[1].resize(obj_count);\n\tr.resize(obj_count);\n\tm.resize(obj_count);\n\n\t// for now hard code some values\n\tmass_range[0] = 5e7;\n\tmass_range[1] = 1e8;\n\tradius_range[0] = 0.05;\n\tradius_range[1] = 0.25;\n\t//distance_range[0] = -radius_range[0] * 15.0;\n\t//distance_range[1] = radius_range[0] * 15.0;\n\tdistance_range[0] = -4.0;\n\tdistance_range[1] = 4.0;\n\n\t// random init stuff\n\tstd::uniform_real_distribution dist_m(mass_range[0],\n\t\tmass_range[1]);\n\tstd::uniform_real_distribution dist_r(radius_range[0],\n\t\tradius_range[1]);\n\tstd::uniform_real_distribution dist_d(distance_range[0],\n\t\tdistance_range[1]);\n\n\tfor(uint16_t i = 0; i < obj_count; i++)\n\t{\n\t\tr[i] = dist_r(generator);\n\t\tm[i] = dist_m(generator);\n\n\t\t// TODO: detect and avoid collisions here\n\t\tbool collision = true;\n\t\twhile(collision)\n\t\t{\n\t\t\t// generate a new point\n\t\t\tx[0][i] = Eigen::Vector3d(dist_d(generator),\n\t\t\t\t\t\t\t\t\tdist_d(generator),\n\t\t\t\t\t\t\t\t\tdist_d(generator));\n\n\t\t\t// look for a collision\n\t\t\tcollision = false;\n\t\t\tfor(uint16_t j = 0; j < i; j++)\n\t\t\t{\n\t\t\t\tif(i == j)\n\t\t\t\t\tcontinue;\n\n\t\t\t\t// direction unit vector\n\t\t\t\tEigen::Vector3d ji_uv = (x[0][i] - x[0][j]).normalized();\n\n\t\t\t\t// position plus radius in the direction of the other object\n\t\t\t\tEigen::Vector3d ji_r = x[0][j] + ji_uv * r[j];\n\n\t\t\t\tdouble distance_j = (x[0][i] - ji_r).norm();\n\t\t\t\t// if radius > distance to j object then collision\n\t\t\t\tif(r[i] > distance_j)\n\t\t\t\t{\n\t\t\t\t\tcollision = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tv[0][i] = Eigen::Vector3d(0.0, 0.0, 0.0);\n\t\ta[0][i] = Eigen::Vector3d(0.0, 0.0, 0.0);\n\t}\n}\n\nvoid physics::deinit()\n{\n\t// TODO: should we really use swap to force a deallocation and is this the\n\t// right way to do it?\n\n\tstd::vector n0, n1;\n\tx[0].clear();\n\tx[1].clear();\n\tx[0].swap(n0);\n\tx[1].swap(n1);\n\n\tstd::vector n2, n3;\n\tv[0].clear();\n\tv[1].clear();\n\tv[0].swap(n2);\n\tv[1].swap(n3);\n\n\tstd::vector n4, n5;\n\ta[0].clear();\n\ta[1].clear();\n\ta[0].swap(n4);\n\ta[1].swap(n5);\n\n\tstd::vector n6;\n\tr.clear();\n\tr.swap(n6);\n\n\tstd::vector n7;\n\tm.clear();\n\tm.swap(n7);\n}\n\n\n", "meta": {"hexsha": "5716422e1b92b4e91ad01476f6276b7bcfdb2107", "size": 4028, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "phy/physics.cpp", "max_stars_repo_name": "foxfire256/grav_sim", "max_stars_repo_head_hexsha": "bc5d4ca1250203a6b7654c04914bb3fe13cef67e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "phy/physics.cpp", "max_issues_repo_name": "foxfire256/grav_sim", "max_issues_repo_head_hexsha": "bc5d4ca1250203a6b7654c04914bb3fe13cef67e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phy/physics.cpp", "max_forks_repo_name": "foxfire256/grav_sim", "max_forks_repo_head_hexsha": "bc5d4ca1250203a6b7654c04914bb3fe13cef67e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2541436464, "max_line_length": 75, "alphanum_fraction": 0.6112214499, "num_tokens": 1469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045817875224, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6920132703298424}} {"text": "#include \n#include \n#include \n#include \"../config.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\npair entrenarPerceptron(const mat& patrones,\n const vec& salidaDeseada,\n int nEpocas,\n double tasaAprendizaje,\n double tolerancia,\n string tituloGrafica);\ndouble errorPerceptron(const vec& pesos,\n const mat& patrones,\n const vec& salidaDeseada);\n\nint main()\n{\n arma_rng::set_seed_random();\n\n mat datos;\n datos.load(config::sourceDir + \"/guia1/icgtp1datos/OR_trn.csv\");\n mat patronesEntOR = datos.head_cols(2);\n vec salidaDeseadaEntOR = datos.tail_cols(1);\n datos.load(config::sourceDir + \"/guia1/icgtp1datos/OR_tst.csv\");\n mat patronesPruebaOR = datos.head_cols(2);\n vec salidaDeseadaPruebaOR = datos.tail_cols(1);\n\n // OR\n // Entrenar la red graficando resultados intermedios (la recta)\n vec pesos;\n tie(pesos, ignore) = entrenarPerceptron(patronesEntOR,\n salidaDeseadaEntOR,\n 100,\n 0.1,\n 5,\n \"OR\");\n double tasaError = errorPerceptron(pesos, patronesPruebaOR, salidaDeseadaPruebaOR);\n cout << \"tasa de error del OR : \" << tasaError << endl;\n\n // XOR\n // Entrenar la red graficando resultados intermedios (la recta)\n // Prueba\n datos.load(config::sourceDir + \"/guia1/icgtp1datos/XOR_trn.csv\");\n mat patronesEntXOR = datos.head_cols(2);\n vec salidaDeseadaEntXOR = datos.tail_cols(1);\n datos.load(config::sourceDir + \"/guia1/icgtp1datos/XOR_tst.csv\");\n mat patronesPruebaXOR = datos.head_cols(2);\n vec salidaDeseadaPruebaXOR = datos.tail_cols(1);\n\n tie(pesos, ignore) = entrenarPerceptron(patronesEntXOR,\n salidaDeseadaEntXOR,\n 100,\n 0.4,\n 30,\n \"XOR\");\n tasaError = errorPerceptron(pesos, patronesPruebaXOR, salidaDeseadaPruebaXOR);\n cout << \"tasa de error del XOR : \" << tasaError << endl;\n\n return 0;\n}\n\nnamespace ic {\nint sign(double numero)\n{\n if (numero >= 0)\n return 1;\n else\n return -1;\n}\n}\n\npair entrenarPerceptron(const mat& patrones,\n const vec& salidaDeseada,\n int nEpocas,\n double tasaAprendizaje,\n double tolerancia,\n string tituloGrafica)\n{\n // Inicializar pesos y tasa de error\n vec pesos = randu(patrones.n_cols + 1) - 0.5;\n double tasaError = 0;\n\n // Extender las matrices de patrones con la entrada correspondiente al umbral\n const mat patronesExt = join_horiz(ones(patrones.n_rows) * (-1), patrones);\n\n // Separar patrones de entrenamiento en casos verdaderos y falsos\n // para graficarlos en colores distintos\n const mat verdaderos = patrones.rows(find(salidaDeseada == 1));\n const mat falsos = patrones.rows(find(salidaDeseada == -1));\n\n // Objeto para graficar\n Gnuplot gp;\n // Caracter usado para dejar de graficar\n const char caracterSalteo = 's';\n char caracter = ' ';\n\n // Ciclo de las epocas\n for (int epoca = 1; epoca <= nEpocas; ++epoca) {\n // Ciclo para una época\n for (unsigned int i = 0; i < patrones.n_rows; ++i) {\n double z = dot(patronesExt.row(i), pesos);\n int y = ic::sign(z);\n\n if (caracter != caracterSalteo) {\n cout << \"Patrón que entró: \" << patrones.row(i)\n << \"Salida para ese patrón: \" << y << '\\n'\n << \"Salida deseada: \" << salidaDeseada(i) << endl;\n\n caracter = getchar();\n }\n\n // Actualizar pesos\n // Tener en cuenta el orden en que colocamos la salida por la direccion del gradiente.\n pesos += tasaAprendizaje * 0.5 * (salidaDeseada(i) - y) * patronesExt.row(i).t();\n\n // Graficar recta\n double pendiente = -pesos(1) / pesos(2);\n double ordenadaOrigen = pesos(0) / pesos(2);\n mat puntosRecta = {{-2, -2 * pendiente + ordenadaOrigen},\n {2, 2 * pendiente + ordenadaOrigen}};\n\n if (caracter != caracterSalteo) {\n gp << \"set title '\" << tituloGrafica << \"' font ',13'\\n\"\n << \"set xlabel 'x_1'\\n\"\n << \"set ylabel 'x_2'\\n\"\n << \"set grid\\n\"\n << \"unset key\\n\"\n << \"plot \" << gp.file1d(verdaderos) << \"with points, \"\n << gp.file1d(falsos) << \"with points, \"\n << gp.file1d(puntosRecta) << \"with lines\" << endl;\n }\n }\n // Fin ciclo (época)\n\n // Parte de validación - Cálculo de la tasa de error para ver si dejamos de entrenar\n int errores = 0;\n\n for (unsigned int i = 0; i < patronesExt.n_rows; ++i) {\n double z = dot(patronesExt.row(i), pesos);\n int y = ic::sign(z);\n\n if (y != salidaDeseada(i))\n ++errores;\n }\n\n tasaError = static_cast(errores) / patrones.n_rows * 100;\n if (tasaError < tolerancia)\n break;\n }\n // Fin ciclo (epocas)\n\n return {pesos, tasaError};\n}\n\ndouble errorPerceptron(const vec& pesos,\n const mat& patrones,\n const vec& salidaDeseada)\n{\n // Se extiende la matriz de patrones con la entrada correspondiente al umbral\n const mat patronesExt = join_horiz(ones(patrones.n_rows) * (-1), patrones);\n\n int errores = 0;\n\n for (unsigned int i = 0; i < patronesExt.n_rows; ++i) {\n double z = dot(patronesExt.row(i), pesos);\n int y = ic::sign(z);\n\n if (y != salidaDeseada(i))\n ++errores;\n }\n\n double tasaError = static_cast(errores) / patronesExt.n_rows * 100;\n\n return tasaError;\n}\n", "meta": {"hexsha": "1daeb8a58c4dc8cdac36dca52cf6509a8926856b", "size": 6405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "guia1/ejercicio1.cpp", "max_stars_repo_name": "junrrein/ic2017", "max_stars_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "guia1/ejercicio1.cpp", "max_issues_repo_name": "junrrein/ic2017", "max_issues_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "guia1/ejercicio1.cpp", "max_forks_repo_name": "junrrein/ic2017", "max_forks_repo_head_hexsha": "e7ab09257093a56751c58a4633a049f7746f00e3", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.782122905, "max_line_length": 98, "alphanum_fraction": 0.5245901639, "num_tokens": 1634, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331751, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6919426162475755}} {"text": "#include \"DarkART/Special_Functions.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"arb_hypgeom.h\"\n\nnamespace DarkART\n{\n// using namespace std::complex_literals;\n\n// 1. Gaunt coefficients\ndouble Gaunt_Coefficient(int j1, int j2, int j3, int m1, int m2, int m3)\n{\n\treturn sqrt((2.0 * j1 + 1.0) * (2.0 * j2 + 1.0) * (2.0 * j3 + 1.0)) / sqrt(4.0 * M_PI) * gsl_sf_coupling_3j(2 * j1, 2 * j2, 2 * j3, 0, 0, 0) * gsl_sf_coupling_3j(2 * j1, 2 * j2, 2 * j3, 2 * m1, 2 * m2, 2 * m3);\n}\n\n// 2. Spherical Bessel function j_L\ndouble Spherical_Bessel_jL_arb(int L, double x)\n{\n\tdouble prefactor = sqrt(M_PI / 2.0 / x);\n\tdouble result;\n\tslong prec;\n\tarb_t J_arb, x_arb, n_arb;\n\tarb_init(J_arb);\n\tarb_init(x_arb);\n\tarb_init(n_arb);\n\tarb_set_d(x_arb, x);\n\tarb_set_d(n_arb, 1.0 * L + 0.5);\n\tfor(prec = 80;; prec *= 2)\n\t{\n\t\tarb_hypgeom_bessel_j(J_arb, n_arb, x_arb, prec);\n\t\tif(arb_rel_accuracy_bits(J_arb) >= 53)\n\t\t{\n\t\t\tresult = arf_get_d(arb_midref(J_arb), ARF_RND_NEAR);\n\t\t\tbreak;\n\t\t}\n\t\telse if(prec > 10000)\n\t\t{\n\t\t\tresult = NAN;\n\t\t\tbreak;\n\t\t}\n\t}\n\tarb_clear(J_arb);\n\tarb_clear(n_arb);\n\tarb_clear(x_arb);\n\treturn prefactor * result;\n}\n\ndouble Spherical_Bessel_jL(int L, double x)\n{\n\tif(L < 10)\n\t\treturn gsl_sf_bessel_jl(L, x);\n\telse\n\t\treturn Spherical_Bessel_jL_arb(L, x);\n}\n\n// 3. Coulomb wave\ndouble Coulomb_Wave_ARB(int L, double eta, double rho)\n{\n\tdouble result;\n\tslong prec;\n\tarb_t F, l, eta_2, rho_2;\n\tarb_init(F);\n\tarb_init(l);\n\tarb_init(eta_2);\n\tarb_init(rho_2);\n\tarb_set_d(l, L);\n\tarb_set_d(eta_2, eta);\n\tarb_set_d(rho_2, rho);\n\tfor(prec = 80;; prec *= 2)\n\t{\n\t\tarb_hypgeom_coulomb(F, NULL, l, eta_2, rho_2, prec);\n\t\tif(arb_rel_accuracy_bits(F) >= 53)\n\t\t{\n\t\t\tresult = arf_get_d(arb_midref(F), ARF_RND_NEAR);\n\t\t\tbreak;\n\t\t}\n\t\telse if(prec > 10000)\n\t\t{\n\t\t\tresult = NAN;\n\t\t\tbreak;\n\t\t}\n\t}\n\tarb_clear(F);\n\tarb_clear(eta_2);\n\tarb_clear(rho_2);\n\tarb_clear(l);\n\treturn result;\n}\n\ndouble Coulomb_Wave_GSL(int L, double eta, double rho, int& status)\n{\n\tdouble fc_array[1];\n\tdouble F_exponent[1];\n\tstatus = gsl_sf_coulomb_wave_F_array(L, 0, eta, rho, fc_array, F_exponent);\n\treturn fc_array[0];\n}\n\ndouble Coulomb_Wave(int L, double eta, double rho)\n{\n\tint status;\n\tdouble cw = Coulomb_Wave_GSL(L, eta, rho, status);\n\tif(status != 0 || std::isnan(cw))\n\t\tcw = Coulomb_Wave_ARB(L, eta, rho);\n\treturn cw;\n}\n\n}\t// namespace DarkART", "meta": {"hexsha": "d46530d3a6bf1c63901c1a4ae6112cbec91504a7", "size": 2505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Special_Functions.cpp", "max_stars_repo_name": "temken/DarkART", "max_stars_repo_head_hexsha": "7bf3b03e4bf89ec83edd5ca2c9e8e7ce5ee16081", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-15T13:58:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T13:58:28.000Z", "max_issues_repo_path": "src/Special_Functions.cpp", "max_issues_repo_name": "temken/DarkART", "max_issues_repo_head_hexsha": "7bf3b03e4bf89ec83edd5ca2c9e8e7ce5ee16081", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Special_Functions.cpp", "max_forks_repo_name": "temken/DarkART", "max_forks_repo_head_hexsha": "7bf3b03e4bf89ec83edd5ca2c9e8e7ce5ee16081", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5948275862, "max_line_length": 211, "alphanum_fraction": 0.6758483034, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632916317103, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6919419125917671}} {"text": "/*\n * prime_utils.cpp: Function definitions for working with primes. The following\n * methods are defined here:\n * - Miller-Rabin probabilistic primality test, with an iterative tester\n * method\n * - Modular addition, which is used by modular multiplication\n * - Modular multiplication and exponentiation, which are used by the\n * Miller-Rabin test\n * - Sieve of Atkin\n * - Integer square root, which is used by the Sieve\n *\n * Version: 1.0.0\n * License: MIT License (see LICENSE.txt for more details)\n * Author: Joshua Morrison (MrM21632)\n * Last Edited: 2/6/2018, 1:20am\n */\n\n#include \n#include \n#include \n#include \n#include \"prime_utils.h\"\n\n\nuint64_t isqrt(uint64_t n) {\n // Base Case: if n < 2, then sqrt(n) = n.\n if (n < 2) return n;\n \n // We calculate a \"small\" and \"large\" candidate for our return value:\n // 1. s, which is equal to 2 * isqrt(n / 4), is the small candidate.\n // 2. l, which is equal to one larger than s, is the large candidate.\n uint64_t s = isqrt(n >> 2) << 1;\n uint64_t l = s + 1;\n \n if (l*l > n)\n return s;\n else\n return l;\n}\n\n\nuint64_t mod_add(uint64_t a, uint64_t b, uint64_t n) {\n return ((a % n) + (b % n)) % n;\n}\n\n\nuint64_t mod_mult(uint64_t a, uint64_t b, uint64_t n) {\n uint64_t r = 0; // Remainder\n \n // If a is larger than the modulus, we need to reduce it in order to avoid\n // integer overflow.\n if (a >= n) a %= n;\n \n // Perform modular addition on r until the multiplier is 0.\n while (b > 0) {\n if (b & 1)\n r = mod_add(r, a, n);\n \n a = (a * 2) % n;\n b >>= 1;\n }\n \n // (a * b) mod n == ((a mod n) * (b mod n)) mod n. At this point, we have\n // calculated r = (a mod n) * (b mod n), so we now need to reduce r by mod\n // n, then return that result.\n return r % n;\n}\n\n\nuint64_t mod_pow(uint64_t a, uint64_t b, uint64_t n) {\n uint64_t r = 1; // Remainder\n \n // If a is larger than the modulus, we need to reduce it in order to avoid\n // integer overflow.\n if (a >= n) a %= n;\n \n // Perform modular multiplication on both the remainder and the base, until\n // our exponent is 0.\n while (b > 0) {\n if (b & 1)\n r = mod_mult(r, a, n);\n \n a = mod_mult(a, a, n);\n b >>= 1;\n }\n \n return r;\n}\n\n\nbool miller_rabin(uint64_t n, uint64_t d) {\n boost::random::random_device rd;\n boost::random::mt19937 mt(rd());\n boost::random::uniform_int_distribution dist(2, n-2);\n \n uint64_t a = dist(mt);\n uint64_t x = mod_pow(a, d, n);\n \n // Base Case: if a^d mod n is 1 or n-1, then we already know n is prime, so\n // we can return true.\n if (x == 1 || x == n-1)\n return true;\n \n // Perform modular multiplication on x until d is equal to n-1.\n while (d != (n - 1)) {\n x = mod_mult(x, x, n);\n d <<= 1;\n \n if (x == 1) return false;\n if (x == (n - 1)) return true;\n }\n \n // If we reach this point, we can safely say that n is not prime, so we\n // return false.\n return false;\n}\n\n\nbool is_prime(uint64_t n, uint64_t k) {\n // Base cases\n if (n <= 1) return false;\n if (n <= 3) return true;\n if (!(n & 1)) return false;\n \n // At this point, we know n is odd and greater than 1. Now, our goal is to\n // find an integer d such that n-1 = d * 2^r, where r >= 1. The loop divides\n // d by 2 until it is no longer even - at that point, we will have the value\n // we desire.\n uint64_t d = n - 1;\n while (!(d & 1))\n d >>= 1;\n \n // Call miller_rabin(n, d) k times. If any of the tests fail, we know that n\n // is not prime, so we return false.\n for (uint64_t i = 0; i < k; ++i) {\n if (!miller_rabin(n, d))\n return false;\n }\n \n // If we reach this point, we can safely assume (NOT guarantee!) n is prime,\n // so we return true.\n return true;\n}\n\n\nbool *sieve_of_atkin(uint64_t n) {\n bool *data = new bool[n + 1]();\n data[2] = true;\n data[3] = true;\n uint64_t lim = isqrt(n);\n \n // This loop runs for all x in [1, lim].\n for (uint64_t x = 1; x <= lim; ++x) {\n // This loop runs for all y in [1, lim].\n // \n // k is prime if any of the following are true:\n // 1. For k = 4*x^2 + y^2, k is prime iff k mod 12 = 1 or 5.\n // 2. For k = 3*x^2 + y^2, k is prime iff k mod 12 = 7.\n // 3. For k = 3*x^2 - y^2, k is prime iff k mod 12 = 11.\n // All of these also assume that k is not greater than n, and for the\n // third case, that k is not negative (i.e., that x > y).\n for (uint64_t y = 1; y <= lim; ++y) {\n uint64_t k = (4*x*x) + (y*y);\n if ((k <= n) && ((k % 12 == 1) || (k % 12 == 5)))\n data[k] = !data[k];\n \n k = (3*x*x) + (y*y);\n if ((k <= n) && (k % 12 == 7))\n data[k] = !data[k];\n \n k = (3*x*x) - (y*y);\n if ((x > y) && (k <= n) && (k % 12 == 11))\n data[k] = !data[k];\n }\n }\n \n // This loop runs for all j in [5, lim].\n // \n // We perform one last loop through the array. If j is prime, then we mark\n // all multiples of its square as composite, a la the standard Sieve of\n // Eratosthenes.\n for (uint64_t j = 5; j <= lim; ++j) {\n if (data[j]) {\n for (uint64_t k = j*j; k <= n; k += j*j)\n data[k] = false;\n }\n }\n \n return data;\n}\n", "meta": {"hexsha": "95273a467815072971a649109aa36011ca1d4dbb", "size": 5709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "factor/prime_utils.cpp", "max_stars_repo_name": "MrM21632/WinUtils", "max_stars_repo_head_hexsha": "1f8597ffbbea7ec8684fa723831cec2dc37900d0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "factor/prime_utils.cpp", "max_issues_repo_name": "MrM21632/WinUtils", "max_issues_repo_head_hexsha": "1f8597ffbbea7ec8684fa723831cec2dc37900d0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "factor/prime_utils.cpp", "max_forks_repo_name": "MrM21632/WinUtils", "max_forks_repo_head_hexsha": "1f8597ffbbea7ec8684fa723831cec2dc37900d0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.890052356, "max_line_length": 80, "alphanum_fraction": 0.5274128569, "num_tokens": 1796, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7931059560743422, "lm_q1q2_score": 0.691863893358926}} {"text": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n// 2008 Dresden University of Technology and the Trustees of Indiana University.\n// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n// With contributions from Cornelius Steinhardt\n\n#ifndef MTL_MATRIX_HOUSEHOLDER_INCLUDE\n#define MTL_MATRIX_HOUSEHOLDER_INCLUDE\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace mtl { namespace vector {\n\n\n/// Computes Householder vector v and scalar b for vector \\p y \n/** such that identity_matrix(size(y))-b*v*v' projects the vector y \n to a positive multiple of the first unit vector. **/\ntemplate \nstd::pair::value_type, parameters<> >, typename Collection::value_type>\ninline householder(Vector& y)\n{\n vampir_trace<2004> tracer;\n assert(size(y) > 0);\n typedef typename Collection::value_type value_type;\n // typedef typename Collection::size_type size_type;\n const value_type zero= math::zero(y[0]), one= math::one(y[0]);\n\n Vector v(y);\n v[0]= one;\n irange tail(1, imax); \n value_type s( dot(v[tail], v[tail]) ), b, v0;\n\n //evaluation of v and b\n if (s == zero)\n b= zero;\n else {\n\tvalue_type mu= sqrt(y[0] * y[0] + s);\n\tv0= v[0]= y[0] <= zero ? y[0] - mu : -s / (y[0] + mu); // complex < zero????\n\tb= 2 * v0 * v0 / (s + v0 * v0); // 2* complex???????\n\tv/= v0; // normalization of the first entry\n }\n \n return std::make_pair(v,b);\n}\n\n/// Computes Householder vector for vector \\p y \n/** More stable Householder transformation, also for non-square matrices. **/\ntemplate \ntypename mtl::vector::dense_vector::value_type, parameters<> >\ninline householder_s(Vector& y)\n{\n vampir_trace<2005> tracer;\n typedef typename Collection::value_type value_type;\n const value_type zero= math::zero(y[0]);\n\n Vector u(y);\n value_type nu(sqrt( dot(u, u) )), s;\n\n if (nu != zero){\n\tif(u[0] < 0){\n\t\ts= -1;\n\t} else {\n\t\ts= 1; \n\t}\n\tu[0]= u[0] + s * nu;\n\tu/= sqrt( dot(u, u) );\n }\n\n return u;\n}\n\n\n}} // namespace mtl::matrix\n\n#endif // MTL_MATRIX_HOUSEHOLDER_INCLUDE\n\n", "meta": {"hexsha": "d435b2b75b9ee32e806bce971b92eda43e751f41", "size": 2741, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/householder.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/operation/householder.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/operation/householder.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1208791209, "max_line_length": 142, "alphanum_fraction": 0.6395476104, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6917657969214323}} {"text": "\r\n\r\n#include \r\n\r\n#include \r\n\r\nNTL_START_IMPL\r\n\r\n\r\nFFTTablesType FFTTables;\r\n// a truly GLOBAL variable, shared among all threads\r\n\r\n\r\n\r\nlong IsFFTPrime(long n, long& w)\r\n{\r\n long m, x, y, z;\r\n long j, k;\r\n\r\n\r\n if (n <= 1 || n >= NTL_SP_BOUND) return 0;\r\n\r\n if (n % 2 == 0) return 0;\r\n\r\n if (n % 3 == 0) return 0;\r\n\r\n if (n % 5 == 0) return 0;\r\n\r\n if (n % 7 == 0) return 0;\r\n \r\n m = n - 1;\r\n k = 0;\r\n while ((m & 1) == 0) {\r\n m = m >> 1;\r\n k++;\r\n }\r\n\r\n for (;;) {\r\n x = RandomBnd(n);\r\n\r\n if (x == 0) continue;\r\n z = PowerMod(x, m, n);\r\n if (z == 1) continue;\r\n\r\n x = z;\r\n j = 0;\r\n do {\r\n y = z;\r\n z = MulMod(y, y, n);\r\n j++;\r\n } while (j != k && z != 1);\r\n\r\n if (z != 1 || y != n-1) return 0;\r\n\r\n if (j == k) \r\n break;\r\n }\r\n\r\n /* x^{2^k} = 1 mod n, x^{2^{k-1}} = -1 mod n */\r\n\r\n long TrialBound;\r\n\r\n TrialBound = m >> k;\r\n if (TrialBound > 0) {\r\n if (!ProbPrime(n, 5)) return 0;\r\n \r\n /* we have to do trial division by special numbers */\r\n \r\n TrialBound = SqrRoot(TrialBound);\r\n \r\n long a, b;\r\n \r\n for (a = 1; a <= TrialBound; a++) {\r\n b = (a << k) + 1;\r\n if (n % b == 0) return 0; \r\n }\r\n }\r\n\r\n /* n is an FFT prime */\r\n\r\n for (j = NTL_FFTMaxRoot; j < k; j++)\r\n x = MulMod(x, x, n);\r\n\r\n w = x;\r\n return 1;\r\n}\r\n\r\n\r\nstatic\r\nvoid NextFFTPrime(long& q, long& w, long index)\r\n{\r\n static long m = NTL_FFTMaxRootBnd + 1;\r\n static long k = 0;\r\n // m and k are truly GLOBAL variables, shared among\r\n // all threads. Access is protected by a critical section\r\n // guarding FFTTables\r\n\r\n static long last_index = -1;\r\n static long last_m = 0;\r\n static long last_k = 0;\r\n\r\n if (index == last_index) {\r\n // roll back m and k...part of a simple error recovery\r\n // strategy if an exception was thrown in the last \r\n // invocation of UseFFTPrime...probably of academic \r\n // interest only\r\n\r\n m = last_m;\r\n k = last_k;\r\n }\r\n else {\r\n last_index = index;\r\n last_m = m;\r\n last_k = k;\r\n }\r\n\r\n long t, cand;\r\n\r\n for (;;) {\r\n if (k == 0) {\r\n m--;\r\n if (m < 5) ResourceError(\"ran out of FFT primes\");\r\n k = 1L << (NTL_SP_NBITS-m-2);\r\n }\r\n\r\n k--;\r\n\r\n cand = (1L << (NTL_SP_NBITS-1)) + (k << (m+1)) + (1L << m) + 1;\r\n\r\n if (!IsFFTPrime(cand, t)) continue;\r\n q = cand;\r\n w = t;\r\n return;\r\n }\r\n}\r\n\r\n\r\nlong CalcMaxRoot(long p)\r\n{\r\n p = p-1;\r\n long k = 0;\r\n while ((p & 1) == 0) {\r\n p = p >> 1;\r\n k++;\r\n }\r\n\r\n if (k > NTL_FFTMaxRoot)\r\n return NTL_FFTMaxRoot;\r\n else\r\n return k; \r\n}\r\n\r\n\r\nvoid InitFFTPrimeInfo(FFTPrimeInfo& info, long q, long w, bool bigtab)\r\n{\r\n double qinv = 1/((double) q);\r\n\r\n long mr = CalcMaxRoot(q);\r\n\r\n info.q = q;\r\n info.qinv = qinv;\r\n info.zz_p_context = 0;\r\n\r\n\r\n info.RootTable.SetLength(mr+1);\r\n info.RootInvTable.SetLength(mr+1);\r\n info.TwoInvTable.SetLength(mr+1);\r\n info.TwoInvPreconTable.SetLength(mr+1);\r\n\r\n long *rt = &info.RootTable[0];\r\n long *rit = &info.RootInvTable[0];\r\n long *tit = &info.TwoInvTable[0];\r\n mulmod_precon_t *tipt = &info.TwoInvPreconTable[0];\r\n\r\n long j;\r\n long t;\r\n\r\n rt[mr] = w;\r\n for (j = mr-1; j >= 0; j--)\r\n rt[j] = MulMod(rt[j+1], rt[j+1], q);\r\n\r\n rit[mr] = InvMod(w, q);\r\n for (j = mr-1; j >= 0; j--)\r\n rit[j] = MulMod(rit[j+1], rit[j+1], q);\r\n\r\n t = InvMod(2, q);\r\n tit[0] = 1;\r\n for (j = 1; j <= mr; j++)\r\n tit[j] = MulMod(tit[j-1], t, q);\r\n\r\n for (j = 0; j <= mr; j++)\r\n tipt[j] = PrepMulModPrecon(tit[j], q, qinv);\r\n\r\n if (bigtab)\r\n info.bigtab.make();\r\n}\r\n\r\n\r\n#ifndef NTL_WIZARD_HACK\r\nSmartPtr Build_zz_pInfo(FFTPrimeInfo *info);\r\n#else\r\nSmartPtr Build_zz_pInfo(FFTPrimeInfo *info) { return 0; }\r\n#endif\r\n\r\nvoid UseFFTPrime(long index)\r\n{\r\n if (index < 0) LogicError(\"invalud FFT prime index\");\r\n if (index >= NTL_MAX_FFTPRIMES) ResourceError(\"FFT prime index too large\");\r\n\r\n do { // NOTE: thread safe lazy init\r\n FFTTablesType::Builder bld(FFTTables, index+1);\r\n long amt = bld.amt();\r\n if (!amt) break;\r\n\r\n long first = index+1-amt;\r\n // initialize entries first..index\r\n\r\n long i;\r\n for (i = first; i <= index; i++) {\r\n UniquePtr info;\r\n info.make();\r\n\r\n long q, w;\r\n NextFFTPrime(q, w, i);\r\n\r\n bool bigtab = false;\r\n\r\n#ifdef NTL_FFT_BIGTAB\r\n if (i < NTL_FFT_BIGTAB_LIMIT)\r\n bigtab = true;\r\n#endif\r\n\r\n InitFFTPrimeInfo(*info, q, w, bigtab);\r\n info->zz_p_context = Build_zz_pInfo(info.get());\r\n bld.move(info);\r\n }\r\n\r\n } while (0);\r\n}\r\n\r\n\r\n\r\n\r\n/*\r\n * Our FFT is based on the routine in Cormen, Leiserson, Rivest, and Stein.\r\n * For very large inputs, it should be relatively cache friendly.\r\n * The inner loop has been unrolled and pipelined, to exploit any\r\n * low-level parallelism in the machine.\r\n * \r\n * This version now allows input to alias output.\r\n */\r\n\r\n\r\n#define NTL_PIPELINE\r\n// Define to gets some software pipelining...actually seems\r\n// to help somewhat\r\n\r\n#define NTL_LOOP_UNROLL\r\n// Define to unroll some loops. Seems to help a little\r\n\r\n// FIXME: maybe the above two should be tested by the wizard\r\n\r\n\r\nstatic\r\nlong RevInc(long a, long k)\r\n{\r\n long j, m;\r\n\r\n j = k; \r\n m = 1L << (k-1);\r\n\r\n while (j && (m & a)) {\r\n a ^= m;\r\n m >>= 1;\r\n j--;\r\n }\r\n if (j) a ^= m;\r\n return a;\r\n}\r\n\r\n\r\n\r\nNTL_THREAD_LOCAL static \r\nVec brc_mem[NTL_FFTMaxRoot+1];\r\n// FIXME: This could potentially be shared across threads, using\r\n// a \"lazy table\".\r\n\r\n\r\n#if 0\r\n\r\n\r\nstatic\r\nvoid BitReverseCopy(long * NTL_RESTRICT A, const long * NTL_RESTRICT a, long k)\r\n{\r\n long n = 1L << k;\r\n long* NTL_RESTRICT rev;\r\n long i, j;\r\n\r\n rev = brc_mem[k].elts();\r\n if (!rev) {\r\n brc_mem[k].SetLength(n);\r\n rev = brc_mem[k].elts();\r\n for (i = 0, j = 0; i < n; i++, j = RevInc(j, k))\r\n rev[i] = j;\r\n }\r\n\r\n for (i = 0; i < n; i++)\r\n A[rev[i]] = a[i];\r\n}\r\n\r\n\r\nstatic\r\nvoid BitReverseCopy(unsigned long * NTL_RESTRICT A, const long * NTL_RESTRICT a, long k)\r\n{\r\n long n = 1L << k;\r\n long* NTL_RESTRICT rev;\r\n long i, j;\r\n\r\n rev = brc_mem[k].elts();\r\n if (!rev) {\r\n brc_mem[k].SetLength(n);\r\n rev = brc_mem[k].elts();\r\n for (i = 0, j = 0; i < n; i++, j = RevInc(j, k))\r\n rev[i] = j;\r\n }\r\n\r\n for (i = 0; i < n; i++)\r\n A[rev[i]] = a[i];\r\n}\r\n\r\n#else\r\n\r\n// A more cache-friendly bit-reverse copy algorithm.\r\n// The \"COBRA\" algorithm from Carter and Gatlin, \"Towards an\r\n// optimal bit-reversal permutation algorithm\", FOCS 1998.\r\n\r\n// NOTE: for basic poly mul, we could consider not doing any\r\n// bit-reverse copy; however, a number of other operations\r\n// depend on this, so it would not be easy to do.\r\n\r\n#define NTL_BRC_THRESH (12)\r\n#define NTL_BRC_Q (5)\r\n\r\n// Must have NTL_BRC_THRESH > 2*NTL_BRC_Q\r\n// Should also have (1L << (2*NTL_BRC_Q)) small enough\r\n// so that we can fit that many long's into the cache\r\n\r\n\r\nstatic\r\nlong *BRC_init(long k)\r\n{\r\n long n = (1L << k);\r\n brc_mem[k].SetLength(n);\r\n long *rev = brc_mem[k].elts();\r\n long i, j;\r\n for (i = 0, j = 0; i < n; i++, j = RevInc(j, k))\r\n rev[i] = j;\r\n return rev;\r\n}\r\n\r\n\r\nstatic\r\nvoid BasicBitReverseCopy(long * NTL_RESTRICT B, \r\n const long * NTL_RESTRICT A, long k)\r\n{\r\n long n = 1L << k;\r\n long* NTL_RESTRICT rev;\r\n long i, j;\r\n\r\n rev = brc_mem[k].elts();\r\n if (!rev) rev = BRC_init(k);\r\n\r\n for (i = 0; i < n; i++)\r\n B[rev[i]] = A[i];\r\n}\r\n\r\n\r\n\r\nstatic\r\nvoid COBRA(long * NTL_RESTRICT B, const long * NTL_RESTRICT A, long k)\r\n{\r\n NTL_THREAD_LOCAL static Vec BRC_temp;\r\n\r\n long q = NTL_BRC_Q;\r\n long k1 = k - 2*q;\r\n long * NTL_RESTRICT rev_k1, * NTL_RESTRICT rev_q;\r\n long *NTL_RESTRICT T;\r\n long a, b, c, a1, b1, c1;\r\n long i, j;\r\n\r\n rev_k1 = brc_mem[k1].elts();\r\n if (!rev_k1) rev_k1 = BRC_init(k1);\r\n\r\n rev_q = brc_mem[q].elts();\r\n if (!rev_q) rev_q = BRC_init(q);\r\n\r\n T = BRC_temp.elts();\r\n if (!T) {\r\n BRC_temp.SetLength(1L << (2*q));\r\n T = BRC_temp.elts();\r\n }\r\n\r\n for (b = 0; b < (1L << k1); b++) {\r\n b1 = rev_k1[b]; \r\n for (a = 0; a < (1L << q); a++) {\r\n a1 = rev_q[a]; \r\n for (c = 0; c < (1L << q); c++) \r\n T[(a1 << q) + c] = A[(a << (k1+q)) + (b << q) + c]; \r\n }\r\n\r\n for (c = 0; c < (1L << q); c++) {\r\n c1 = rev_q[c];\r\n for (a1 = 0; a1 < (1L << q); a1++) \r\n B[(c1 << (k1+q)) + (b1 << q) + a1] = T[(a1 << q) + c];\r\n }\r\n }\r\n}\r\n\r\nstatic\r\nvoid BitReverseCopy(long * NTL_RESTRICT B, const long * NTL_RESTRICT A, long k)\r\n{\r\n if (k <= NTL_BRC_THRESH) \r\n BasicBitReverseCopy(B, A, k);\r\n else\r\n COBRA(B, A, k);\r\n}\r\n\r\n\r\nstatic\r\nvoid BasicBitReverseCopy(unsigned long * NTL_RESTRICT B, \r\n const long * NTL_RESTRICT A, long k)\r\n{\r\n long n = 1L << k;\r\n long* NTL_RESTRICT rev;\r\n long i, j;\r\n\r\n rev = brc_mem[k].elts();\r\n if (!rev) rev = BRC_init(k);\r\n\r\n for (i = 0; i < n; i++)\r\n B[rev[i]] = A[i];\r\n}\r\n\r\n\r\n\r\nstatic\r\nvoid COBRA(unsigned long * NTL_RESTRICT B, const long * NTL_RESTRICT A, long k)\r\n{\r\n NTL_THREAD_LOCAL static Vec BRC_temp;\r\n\r\n long q = NTL_BRC_Q;\r\n long k1 = k - 2*q;\r\n long * NTL_RESTRICT rev_k1, * NTL_RESTRICT rev_q;\r\n unsigned long *NTL_RESTRICT T;\r\n long a, b, c, a1, b1, c1;\r\n long i, j;\r\n\r\n rev_k1 = brc_mem[k1].elts();\r\n if (!rev_k1) rev_k1 = BRC_init(k1);\r\n\r\n rev_q = brc_mem[q].elts();\r\n if (!rev_q) rev_q = BRC_init(q);\r\n\r\n T = BRC_temp.elts();\r\n if (!T) {\r\n BRC_temp.SetLength(1L << (2*q));\r\n T = BRC_temp.elts();\r\n }\r\n\r\n for (b = 0; b < (1L << k1); b++) {\r\n b1 = rev_k1[b]; \r\n for (a = 0; a < (1L << q); a++) {\r\n a1 = rev_q[a]; \r\n for (c = 0; c < (1L << q); c++) \r\n T[(a1 << q) + c] = A[(a << (k1+q)) + (b << q) + c]; \r\n }\r\n\r\n for (c = 0; c < (1L << q); c++) {\r\n c1 = rev_q[c];\r\n for (a1 = 0; a1 < (1L << q); a1++) \r\n B[(c1 << (k1+q)) + (b1 << q) + a1] = T[(a1 << q) + c];\r\n }\r\n }\r\n}\r\n\r\nstatic\r\nvoid BitReverseCopy(unsigned long * NTL_RESTRICT B, const long * NTL_RESTRICT A, long k)\r\n{\r\n if (k <= NTL_BRC_THRESH) \r\n BasicBitReverseCopy(B, A, k);\r\n else\r\n COBRA(B, A, k);\r\n}\r\n\r\n\r\n\r\n\r\n#endif\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nvoid FFT(long* A, const long* a, long k, long q, const long* root)\r\n// performs a 2^k-point convolution modulo q\r\n\r\n{\r\n if (k <= 1) {\r\n if (k == 0) {\r\n\t A[0] = a[0];\r\n\t return;\r\n }\r\n if (k == 1) {\r\n\t long a0 = AddMod(a[0], a[1], q);\r\n\t long a1 = SubMod(a[0], a[1], q);\r\n A[0] = a0;\r\n A[1] = a1;\r\n\t return;\r\n }\r\n }\r\n\r\n // assume k > 1\r\n\r\n \r\n\r\n NTL_THREAD_LOCAL static Vec wtab_store;\r\n NTL_THREAD_LOCAL static Vec wqinvtab_store;\r\n NTL_THREAD_LOCAL static Vec AA_store;\r\n\r\n wtab_store.SetLength(1L << (k-2));\r\n wqinvtab_store.SetLength(1L << (k-2));\r\n AA_store.SetLength(1L << k);\r\n\r\n long * NTL_RESTRICT wtab = wtab_store.elts();\r\n mulmod_precon_t * NTL_RESTRICT wqinvtab = wqinvtab_store.elts();\r\n long *AA = AA_store.elts();\r\n\r\n double qinv = 1/((double) q);\r\n\r\n wtab[0] = 1;\r\n wqinvtab[0] = PrepMulModPrecon(1, q, qinv);\r\n\r\n\r\n BitReverseCopy(AA, a, k);\r\n\r\n long n = 1L << k;\r\n\r\n long s, m, m_half, m_fourth, i, j, t, u, t1, u1, tt, tt1;\r\n\r\n long w;\r\n mulmod_precon_t wqinv;\r\n\r\n // s = 1\r\n\r\n for (i = 0; i < n; i += 2) {\r\n t = AA[i + 1];\r\n u = AA[i];\r\n AA[i] = AddMod(u, t, q);\r\n AA[i+1] = SubMod(u, t, q);\r\n }\r\n\r\n \r\n \r\n for (s = 2; s < k; s++) {\r\n m = 1L << s;\r\n m_half = 1L << (s-1);\r\n m_fourth = 1L << (s-2);\r\n\r\n w = root[s];\r\n wqinv = PrepMulModPrecon(w, q, qinv);\r\n\r\n // prepare wtab...\r\n\r\n if (s == 2) {\r\n wtab[1] = MulModPrecon(wtab[0], w, q, wqinv);\r\n wqinvtab[1] = PrepMulModPrecon(wtab[1], q, qinv);\r\n }\r\n else {\r\n // some software pipelining\r\n\r\n i = m_half-1; j = m_fourth-1;\r\n wtab[i-1] = wtab[j];\r\n wqinvtab[i-1] = wqinvtab[j];\r\n wtab[i] = MulModPrecon(wtab[i-1], w, q, wqinv);\r\n\r\n i -= 2; j --;\r\n\r\n for (; i >= 0; i -= 2, j --) {\r\n long wp2 = wtab[i+2];\r\n long wm1 = wtab[j];\r\n wqinvtab[i+2] = PrepMulModPrecon(wp2, q, qinv);\r\n wtab[i-1] = wm1;\r\n wqinvtab[i-1] = wqinvtab[j];\r\n wtab[i] = MulModPrecon(wm1, w, q, wqinv);\r\n }\r\n\r\n wqinvtab[1] = PrepMulModPrecon(wtab[1], q, qinv);\r\n }\r\n\r\n for (i = 0; i < n; i+= m) {\r\n\r\n long * NTL_RESTRICT AA0 = &AA[i];\r\n long * NTL_RESTRICT AA1 = &AA[i + m_half];\r\n\r\n\r\n// #ifdef NTL_LOOP_UNROLL\r\n#if 1\r\n \r\n t = AA1[0];\r\n u = AA0[0];\r\n t1 = MulModPrecon(AA1[1], w, q, wqinv);\r\n u1 = AA0[1];\r\n\r\n\r\n\r\n for (j = 0; j < m_half-2; j += 2) {\r\n long a02 = AA0[j+2];\r\n long a03 = AA0[j+3];\r\n long a12 = AA1[j+2];\r\n long a13 = AA1[j+3];\r\n long w2 = wtab[j+2];\r\n long w3 = wtab[j+3];\r\n mulmod_precon_t wqi2 = wqinvtab[j+2];\r\n mulmod_precon_t wqi3 = wqinvtab[j+3];\r\n\r\n tt = MulModPrecon(a12, w2, q, wqi2);\r\n long b00 = AddMod(u, t, q);\r\n long b10 = SubMod(u, t, q);\r\n t = tt;\r\n u = a02;\r\n\r\n tt1 = MulModPrecon(a13, w3, q, wqi3);\r\n long b01 = AddMod(u1, t1, q);\r\n long b11 = SubMod(u1, t1, q);\r\n t1 = tt1;\r\n u1 = a03;\r\n\r\n AA0[j] = b00;\r\n AA1[j] = b10;\r\n AA0[j+1] = b01;\r\n AA1[j+1] = b11;\r\n }\r\n\r\n\r\n AA0[j] = AddMod(u, t, q);\r\n AA1[j] = SubMod(u, t, q);\r\n AA0[j + 1] = AddMod(u1, t1, q);\r\n AA1[j + 1] = SubMod(u1, t1, q);\r\n\r\n\r\n#else\r\n\r\n \r\n t = AA1[0];\r\n u = AA0[0];\r\n\r\n for (j = 0; j < m_half-1; j++) {\r\n long a02 = AA0[j+1];\r\n long a12 = AA1[j+1];\r\n long w2 = wtab[j+1];\r\n mulmod_precon_t wqi2 = wqinvtab[j+1];\r\n\r\n tt = MulModPrecon(a12, w2, q, wqi2);\r\n long b00 = AddMod(u, t, q);\r\n long b10 = SubMod(u, t, q);\r\n t = tt;\r\n u = a02;\r\n\r\n AA0[j] = b00;\r\n AA1[j] = b10;\r\n }\r\n\r\n\r\n AA0[j] = AddMod(u, t, q);\r\n AA1[j] = SubMod(u, t, q);\r\n\r\n\r\n#endif\r\n }\r\n }\r\n\r\n\r\n // s == k...special case\r\n\r\n m = 1L << s;\r\n m_half = 1L << (s-1);\r\n m_fourth = 1L << (s-2);\r\n\r\n\r\n w = root[s];\r\n wqinv = PrepMulModPrecon(w, q, qinv);\r\n\r\n // j = 0, 1\r\n\r\n t = AA[m_half];\r\n u = AA[0];\r\n t1 = MulModPrecon(AA[1+ m_half], w, q, wqinv);\r\n u1 = AA[1];\r\n\r\n A[0] = AddMod(u, t, q);\r\n A[m_half] = SubMod(u, t, q);\r\n A[1] = AddMod(u1, t1, q);\r\n A[1 + m_half] = SubMod(u1, t1, q);\r\n\r\n for (j = 2; j < m_half; j += 2) {\r\n t = MulModPrecon(AA[j + m_half], wtab[j >> 1], q, wqinvtab[j >> 1]);\r\n u = AA[j];\r\n t1 = MulModPrecon(AA[j + 1+ m_half], wtab[j >> 1], q, \r\n wqinvtab[j >> 1]);\r\n t1 = MulModPrecon(t1, w, q, wqinv);\r\n u1 = AA[j + 1];\r\n\r\n A[j] = AddMod(u, t, q);\r\n A[j + m_half] = SubMod(u, t, q);\r\n A[j + 1] = AddMod(u1, t1, q);\r\n A[j + 1 + m_half] = SubMod(u1, t1, q);\r\n \r\n }\r\n}\r\n\r\n\r\n#if (!defined(NTL_FFT_LAZYMUL) || (!defined(NTL_SPMM_ULL) && !defined(NTL_SPMM_ASM)))\r\n\r\n// FFT with precomputed tables \r\n\r\n\r\nstatic\r\nvoid PrecompFFTMultipliers(long k, long q, const long *root, const FFTMultipliers& tab)\r\n{\r\n if (k < 1) LogicError(\"PrecompFFTMultipliers: bad input\");\r\n\r\n do { // NOTE: thread safe lazy init\r\n FFTMultipliers::Builder bld(tab, k+1);\r\n long amt = bld.amt();\r\n if (!amt) break;\r\n\r\n long first = k+1-amt;\r\n // initialize entries first..k\r\n\r\n\r\n double qinv = 1/((double) q);\r\n\r\n for (long s = first; s <= k; s++) {\r\n UniquePtr item;\r\n\r\n if (s == 0) {\r\n bld.move(item); // position 0 not used\r\n continue;\r\n }\r\n\r\n if (s == 1) {\r\n item.make();\r\n item->wtab_precomp.SetLength(1);\r\n item->wqinvtab_precomp.SetLength(1);\r\n item->wtab_precomp[0] = 1;\r\n item->wqinvtab_precomp[0] = PrepMulModPrecon(1, q, qinv);\r\n bld.move(item);\r\n continue;\r\n }\r\n\r\n item.make();\r\n item->wtab_precomp.SetLength(1L << (s-1));\r\n item->wqinvtab_precomp.SetLength(1L << (s-1));\r\n\r\n long m = 1L << s;\r\n long m_half = 1L << (s-1);\r\n long m_fourth = 1L << (s-2);\r\n\r\n const long *wtab_last = tab[s-1]->wtab_precomp.elts();\r\n const mulmod_precon_t *wqinvtab_last = tab[s-1]->wqinvtab_precomp.elts();\r\n\r\n long *wtab = item->wtab_precomp.elts();\r\n mulmod_precon_t *wqinvtab = item->wqinvtab_precomp.elts();\r\n\r\n for (long i = 0; i < m_fourth; i++) {\r\n wtab[i] = wtab_last[i];\r\n wqinvtab[i] = wqinvtab_last[i];\r\n } \r\n\r\n long w = root[s];\r\n mulmod_precon_t wqinv = PrepMulModPrecon(w, q, qinv);\r\n\r\n // prepare wtab...\r\n\r\n if (s == 2) {\r\n wtab[1] = MulModPrecon(wtab[0], w, q, wqinv);\r\n wqinvtab[1] = PrepMulModPrecon(wtab[1], q, qinv);\r\n }\r\n else {\r\n // some software pipelining\r\n long i, j;\r\n\r\n i = m_half-1; j = m_fourth-1;\r\n wtab[i-1] = wtab[j];\r\n wqinvtab[i-1] = wqinvtab[j];\r\n wtab[i] = MulModPrecon(wtab[i-1], w, q, wqinv);\r\n\r\n i -= 2; j --;\r\n\r\n for (; i >= 0; i -= 2, j --) {\r\n long wp2 = wtab[i+2];\r\n long wm1 = wtab[j];\r\n wqinvtab[i+2] = PrepMulModPrecon(wp2, q, qinv);\r\n wtab[i-1] = wm1;\r\n wqinvtab[i-1] = wqinvtab[j];\r\n wtab[i] = MulModPrecon(wm1, w, q, wqinv);\r\n }\r\n\r\n wqinvtab[1] = PrepMulModPrecon(wtab[1], q, qinv);\r\n }\r\n\r\n bld.move(item);\r\n }\r\n } while (0);\r\n}\r\n\r\n\r\n\r\nvoid FFT(long* A, const long* a, long k, long q, const long* root, const FFTMultipliers& tab)\r\n// performs a 2^k-point convolution modulo q\r\n\r\n{\r\n if (k <= 1) {\r\n if (k == 0) {\r\n\t A[0] = a[0];\r\n\t return;\r\n }\r\n if (k == 1) {\r\n\t long a0 = AddMod(a[0], a[1], q);\r\n\t long a1 = SubMod(a[0], a[1], q);\r\n A[0] = a0;\r\n A[1] = a1;\r\n\t return;\r\n }\r\n }\r\n\r\n\r\n\r\n // assume k > 1\r\n\r\n if (k >= tab.length()) PrecompFFTMultipliers(k, q, root, tab);\r\n\r\n NTL_THREAD_LOCAL static Vec AA_store;\r\n AA_store.SetLength(1L << k);\r\n long *AA = AA_store.elts();\r\n\r\n BitReverseCopy(AA, a, k);\r\n\r\n long n = 1L << k;\r\n\r\n long s, m, m_half, m_fourth, i, j, t, u, t1, u1, tt, tt1;\r\n\r\n // s = 1\r\n\r\n for (i = 0; i < n; i += 2) {\r\n t = AA[i + 1];\r\n u = AA[i];\r\n AA[i] = AddMod(u, t, q);\r\n AA[i+1] = SubMod(u, t, q);\r\n }\r\n \r\n \r\n for (s = 2; s < k; s++) {\r\n m = 1L << s;\r\n m_half = 1L << (s-1);\r\n m_fourth = 1L << (s-2);\r\n\r\n const long* wtab = tab[s]->wtab_precomp.elts();\r\n const mulmod_precon_t *wqinvtab = tab[s]->wqinvtab_precomp.elts();\r\n\r\n for (i = 0; i < n; i+= m) {\r\n\r\n long *AA0 = &AA[i];\r\n long *AA1 = &AA[i + m_half];\r\n\r\n#ifdef NTL_PIPELINE\r\n\r\n// pipelining: seems to be faster\r\n \r\n t = AA1[0];\r\n u = AA0[0];\r\n t1 = MulModPrecon(AA1[1], wtab[1], q, wqinvtab[1]);\r\n u1 = AA0[1];\r\n\r\n for (j = 0; j < m_half-2; j += 2) {\r\n long a02 = AA0[j+2];\r\n long a03 = AA0[j+3];\r\n long a12 = AA1[j+2];\r\n long a13 = AA1[j+3];\r\n long w2 = wtab[j+2];\r\n long w3 = wtab[j+3];\r\n mulmod_precon_t wqi2 = wqinvtab[j+2];\r\n mulmod_precon_t wqi3 = wqinvtab[j+3];\r\n\r\n tt = MulModPrecon(a12, w2, q, wqi2);\r\n long b00 = AddMod(u, t, q);\r\n long b10 = SubMod(u, t, q);\r\n\r\n tt1 = MulModPrecon(a13, w3, q, wqi3);\r\n long b01 = AddMod(u1, t1, q);\r\n long b11 = SubMod(u1, t1, q);\r\n\r\n AA0[j] = b00;\r\n AA1[j] = b10;\r\n AA0[j+1] = b01;\r\n AA1[j+1] = b11;\r\n\r\n\r\n t = tt;\r\n u = a02;\r\n t1 = tt1;\r\n u1 = a03;\r\n }\r\n\r\n\r\n AA0[j] = AddMod(u, t, q);\r\n AA1[j] = SubMod(u, t, q);\r\n AA0[j + 1] = AddMod(u1, t1, q);\r\n AA1[j + 1] = SubMod(u1, t1, q);\r\n }\r\n#else\r\n for (j = 0; j < m_half; j += 2) {\r\n const long a00 = AA0[j];\r\n const long a01 = AA0[j+1];\r\n const long a10 = AA1[j];\r\n const long a11 = AA1[j+1];\r\n\r\n const long w0 = wtab[j];\r\n const long w1 = wtab[j+1];\r\n const mulmod_precon_t wqi0 = wqinvtab[j];\r\n const mulmod_precon_t wqi1 = wqinvtab[j+1];\r\n\r\n const long tt = MulModPrecon(a10, w0, q, wqi0);\r\n const long uu = a00;\r\n const long b00 = AddMod(uu, tt, q); \r\n const long b10 = SubMod(uu, tt, q);\r\n\r\n const long tt1 = MulModPrecon(a11, w1, q, wqi1);\r\n const long uu1 = a01;\r\n const long b01 = AddMod(uu1, tt1, q); \r\n const long b11 = SubMod(uu1, tt1, q);\r\n\r\n AA0[j] = b00;\r\n AA0[j+1] = b01;\r\n AA1[j] = b10;\r\n AA1[j+1] = b11;\r\n }\r\n }\r\n#endif\r\n }\r\n\r\n\r\n // s == k, special case\r\n {\r\n m = 1L << s;\r\n m_half = 1L << (s-1);\r\n m_fourth = 1L << (s-2);\r\n\r\n const long* wtab = tab[s]->wtab_precomp.elts();\r\n const mulmod_precon_t *wqinvtab = tab[s]->wqinvtab_precomp.elts();\r\n\r\n for (i = 0; i < n; i+= m) {\r\n\r\n long *AA0 = &AA[i];\r\n long *AA1 = &AA[i + m_half];\r\n long *A0 = &A[i];\r\n long *A1 = &A[i + m_half];\r\n\r\n#ifdef NTL_PIPELINE\r\n\r\n// pipelining: seems to be faster\r\n \r\n t = AA1[0];\r\n u = AA0[0];\r\n t1 = MulModPrecon(AA1[1], wtab[1], q, wqinvtab[1]);\r\n u1 = AA0[1];\r\n\r\n for (j = 0; j < m_half-2; j += 2) {\r\n long a02 = AA0[j+2];\r\n long a03 = AA0[j+3];\r\n long a12 = AA1[j+2];\r\n long a13 = AA1[j+3];\r\n long w2 = wtab[j+2];\r\n long w3 = wtab[j+3];\r\n mulmod_precon_t wqi2 = wqinvtab[j+2];\r\n mulmod_precon_t wqi3 = wqinvtab[j+3];\r\n\r\n tt = MulModPrecon(a12, w2, q, wqi2);\r\n long b00 = AddMod(u, t, q);\r\n long b10 = SubMod(u, t, q);\r\n\r\n tt1 = MulModPrecon(a13, w3, q, wqi3);\r\n long b01 = AddMod(u1, t1, q);\r\n long b11 = SubMod(u1, t1, q);\r\n\r\n A0[j] = b00;\r\n A1[j] = b10;\r\n A0[j+1] = b01;\r\n A1[j+1] = b11;\r\n\r\n\r\n t = tt;\r\n u = a02;\r\n t1 = tt1;\r\n u1 = a03;\r\n }\r\n\r\n\r\n A0[j] = AddMod(u, t, q);\r\n A1[j] = SubMod(u, t, q);\r\n A0[j + 1] = AddMod(u1, t1, q);\r\n A1[j + 1] = SubMod(u1, t1, q);\r\n }\r\n#else\r\n for (j = 0; j < m_half; j += 2) {\r\n const long a00 = AA0[j];\r\n const long a01 = AA0[j+1];\r\n const long a10 = AA1[j];\r\n const long a11 = AA1[j+1];\r\n\r\n const long w0 = wtab[j];\r\n const long w1 = wtab[j+1];\r\n const mulmod_precon_t wqi0 = wqinvtab[j];\r\n const mulmod_precon_t wqi1 = wqinvtab[j+1];\r\n\r\n const long tt = MulModPrecon(a10, w0, q, wqi0);\r\n const long uu = a00;\r\n const long b00 = AddMod(uu, tt, q); \r\n const long b10 = SubMod(uu, tt, q);\r\n\r\n const long tt1 = MulModPrecon(a11, w1, q, wqi1);\r\n const long uu1 = a01;\r\n const long b01 = AddMod(uu1, tt1, q); \r\n const long b11 = SubMod(uu1, tt1, q);\r\n\r\n A0[j] = b00;\r\n A0[j+1] = b01;\r\n A1[j] = b10;\r\n A1[j+1] = b11;\r\n }\r\n }\r\n#endif\r\n }\r\n\r\n}\r\n\r\n\r\n#else\r\n\r\n// FFT with precomputed tables and David Harvey's lazy multiplication\r\n// strategy:\r\n// David Harvey.\r\n// Faster arithmetic for number-theoretic transforms.\r\n// J. Symb. Comp. 60 (2014) 113–119. \r\n\r\n\r\n\r\nstatic inline \r\nunsigned long LazyPrepMulModPrecon(long b, long n, double ninv)\r\n{\r\n unsigned long q, r;\r\n\r\n q = (long) ( (((double) b) * NTL_SP_FBOUND) * ninv ); \r\n r = (((unsigned long) b) << NTL_SP_NBITS ) - q * ((unsigned long) n);\r\n\r\n if (r >> (NTL_BITS_PER_LONG-1)) {\r\n q--;\r\n r += n;\r\n }\r\n else if (((long) r) >= n) {\r\n q++;\r\n r -=n;\r\n }\r\n\r\n unsigned long res = q << (NTL_BITS_PER_LONG - NTL_SP_NBITS);\r\n long qq, rr;\r\n\r\n rr = MulDivRem(qq, (long) r, 4, n, 4*ninv);\r\n\r\n res = res + (qq << (NTL_BITS_PER_LONG - NTL_SP_NBITS-2));\r\n\r\n return res;\r\n}\r\n\r\nstatic inline \r\nunsigned long LazyMulModPrecon(unsigned long a, unsigned long b, \r\n unsigned long n, unsigned long bninv)\r\n{\r\n unsigned long q = MulHiUL(a, bninv);\r\n unsigned long res = a*b - q*n;\r\n return res;\r\n}\r\n\r\n\r\nstatic inline \r\nunsigned long LazyReduce(unsigned long a, unsigned long q)\r\n{\r\n unsigned long res;\r\n#if (NTL_ARITH_RIGHT_SHIFT && defined(NTL_AVOID_BRANCHING) && !defined(NTL_CLEAN_INT))\r\n res = a - q;\r\n res += (((long) res) >> (NTL_BITS_PER_LONG-1)) & q; \r\n#elif (defined(NTL_AVOID_BRANCHING))\r\n res = a - q;\r\n res += (-(res >> (NTL_BITS_PER_LONG-1))) & q; \r\n#else\r\n if (a >= q)\r\n res = a - q;\r\n else\r\n res = a;\r\n#endif\r\n\r\n return res;\r\n}\r\n\r\n\r\nstatic\r\nvoid LazyPrecompFFTMultipliers(long k, long q, const long *root, const FFTMultipliers& tab)\r\n{\r\n if (k < 1) LogicError(\"LazyPrecompFFTMultipliers: bad input\");\r\n\r\n do { // NOTE: thread safe lazy init\r\n FFTMultipliers::Builder bld(tab, k+1);\r\n long amt = bld.amt();\r\n if (!amt) break;\r\n\r\n long first = k+1-amt;\r\n // initialize entries first..k\r\n\r\n\r\n double qinv = 1/((double) q);\r\n\r\n for (long s = first; s <= k; s++) {\r\n UniquePtr item;\r\n\r\n if (s == 0) {\r\n bld.move(item); // position 0 not used\r\n continue;\r\n }\r\n\r\n if (s == 1) {\r\n item.make();\r\n item->wtab_precomp.SetLength(1);\r\n item->wqinvtab_precomp.SetLength(1);\r\n item->wtab_precomp[0] = 1;\r\n item->wqinvtab_precomp[0] = LazyPrepMulModPrecon(1, q, qinv);\r\n bld.move(item);\r\n continue;\r\n }\r\n\r\n item.make();\r\n item->wtab_precomp.SetLength(1L << (s-1));\r\n item->wqinvtab_precomp.SetLength(1L << (s-1));\r\n\r\n long m = 1L << s;\r\n long m_half = 1L << (s-1);\r\n long m_fourth = 1L << (s-2);\r\n\r\n const long *wtab_last = tab[s-1]->wtab_precomp.elts();\r\n const mulmod_precon_t *wqinvtab_last = tab[s-1]->wqinvtab_precomp.elts();\r\n\r\n long *wtab = item->wtab_precomp.elts();\r\n mulmod_precon_t *wqinvtab = item->wqinvtab_precomp.elts();\r\n\r\n for (long i = 0; i < m_fourth; i++) {\r\n wtab[i] = wtab_last[i];\r\n wqinvtab[i] = wqinvtab_last[i];\r\n } \r\n\r\n long w = root[s];\r\n mulmod_precon_t wqinv = LazyPrepMulModPrecon(w, q, qinv);\r\n\r\n // prepare wtab...\r\n\r\n if (s == 2) {\r\n wtab[1] = LazyReduce(LazyMulModPrecon(wtab[0], w, q, wqinv), q);\r\n wqinvtab[1] = LazyPrepMulModPrecon(wtab[1], q, qinv);\r\n }\r\n else {\r\n // some software pipelining\r\n long i, j;\r\n\r\n i = m_half-1; j = m_fourth-1;\r\n wtab[i-1] = wtab[j];\r\n wqinvtab[i-1] = wqinvtab[j];\r\n wtab[i] = LazyReduce(LazyMulModPrecon(wtab[i-1], w, q, wqinv), q);\r\n\r\n i -= 2; j --;\r\n\r\n for (; i >= 0; i -= 2, j --) {\r\n long wp2 = wtab[i+2];\r\n long wm1 = wtab[j];\r\n wqinvtab[i+2] = LazyPrepMulModPrecon(wp2, q, qinv);\r\n wtab[i-1] = wm1;\r\n wqinvtab[i-1] = wqinvtab[j];\r\n wtab[i] = LazyReduce(LazyMulModPrecon(wm1, w, q, wqinv), q);\r\n }\r\n\r\n wqinvtab[1] = LazyPrepMulModPrecon(wtab[1], q, qinv);\r\n }\r\n\r\n bld.move(item);\r\n }\r\n } while (0);\r\n}\r\n\r\n\r\n\r\n\r\nvoid FFT(long* A, const long* a, long k, long q, const long* root, const FFTMultipliers& tab)\r\n\r\n// performs a 2^k-point convolution modulo q\r\n\r\n{\r\n if (k <= 1) {\r\n if (k == 0) {\r\n\t A[0] = a[0];\r\n\t return;\r\n }\r\n if (k == 1) {\r\n\t long a0 = AddMod(a[0], a[1], q);\r\n\t long a1 = SubMod(a[0], a[1], q);\r\n A[0] = a0;\r\n A[1] = a1;\r\n\t return;\r\n }\r\n }\r\n\r\n // assume k > 1\r\n\r\n if (k >= tab.length()) LazyPrecompFFTMultipliers(k, q, root, tab);\r\n\r\n NTL_THREAD_LOCAL static Vec AA_store;\r\n AA_store.SetLength(1L << k);\r\n unsigned long *AA = AA_store.elts();\r\n\r\n\r\n\r\n BitReverseCopy(AA, a, k);\r\n\r\n long n = 1L << k;\r\n\r\n\r\n /* we work with redundant representations, in the range [0, 4q) */\r\n\r\n\r\n\r\n long s, m, m_half, m_fourth, i, j; \r\n unsigned long t, u, t1, u1;\r\n\r\n long two_q = 2 * q; \r\n\r\n // s = 1\r\n\r\n for (i = 0; i < n; i += 2) {\r\n t = AA[i + 1];\r\n u = AA[i];\r\n AA[i] = u + t;\r\n AA[i+1] = u - t + q;\r\n }\r\n\r\n\r\n // s = 2\r\n\r\n {\r\n const long * NTL_RESTRICT wtab = tab[2]->wtab_precomp.elts();\r\n const mulmod_precon_t * NTL_RESTRICT wqinvtab = tab[2]->wqinvtab_precomp.elts();\r\n\r\n\r\n for (i = 0; i < n; i += 4) {\r\n\r\n unsigned long * NTL_RESTRICT AA0 = &AA[i];\r\n unsigned long * NTL_RESTRICT AA1 = &AA[i + 2];\r\n\r\n {\r\n const long w1 = wtab[0];\r\n const mulmod_precon_t wqi1 = wqinvtab[0];\r\n const unsigned long a11 = AA1[0];\r\n const unsigned long a01 = AA0[0];\r\n\r\n const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n const unsigned long uu1 = LazyReduce(a01, two_q);\r\n const unsigned long b01 = uu1 + tt1; \r\n const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n AA0[0] = b01;\r\n AA1[0] = b11;\r\n }\r\n {\r\n const long w1 = wtab[1];\r\n const mulmod_precon_t wqi1 = wqinvtab[1];\r\n const unsigned long a11 = AA1[1];\r\n const unsigned long a01 = AA0[1];\r\n\r\n const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n const unsigned long uu1 = LazyReduce(a01, two_q);\r\n const unsigned long b01 = uu1 + tt1; \r\n const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n AA0[1] = b01;\r\n AA1[1] = b11;\r\n }\r\n }\r\n }\r\n\r\n\r\n // s = 3..k\r\n\r\n for (s = 3; s <= k; s++) {\r\n m = 1L << s;\r\n m_half = 1L << (s-1);\r\n m_fourth = 1L << (s-2);\r\n\r\n const long* NTL_RESTRICT wtab = tab[s]->wtab_precomp.elts();\r\n const mulmod_precon_t * NTL_RESTRICT wqinvtab = tab[s]->wqinvtab_precomp.elts();\r\n\r\n for (i = 0; i < n; i += m) {\r\n\r\n unsigned long * NTL_RESTRICT AA0 = &AA[i];\r\n unsigned long * NTL_RESTRICT AA1 = &AA[i + m_half];\r\n\r\n#ifdef NTL_LOOP_UNROLL\r\n\r\n for (j = 0; j < m_half; j += 4) {\r\n {\r\n const long w1 = wtab[j+0];\r\n const mulmod_precon_t wqi1 = wqinvtab[j+0];\r\n const unsigned long a11 = AA1[j+0];\r\n const unsigned long a01 = AA0[j+0];\r\n\r\n const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n const unsigned long uu1 = LazyReduce(a01, two_q);\r\n const unsigned long b01 = uu1 + tt1; \r\n const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n AA0[j+0] = b01;\r\n AA1[j+0] = b11;\r\n }\r\n {\r\n const long w1 = wtab[j+1];\r\n const mulmod_precon_t wqi1 = wqinvtab[j+1];\r\n const unsigned long a11 = AA1[j+1];\r\n const unsigned long a01 = AA0[j+1];\r\n\r\n const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n const unsigned long uu1 = LazyReduce(a01, two_q);\r\n const unsigned long b01 = uu1 + tt1; \r\n const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n AA0[j+1] = b01;\r\n AA1[j+1] = b11;\r\n }\r\n {\r\n const long w1 = wtab[j+2];\r\n const mulmod_precon_t wqi1 = wqinvtab[j+2];\r\n const unsigned long a11 = AA1[j+2];\r\n const unsigned long a01 = AA0[j+2];\r\n\r\n const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n const unsigned long uu1 = LazyReduce(a01, two_q);\r\n const unsigned long b01 = uu1 + tt1; \r\n const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n AA0[j+2] = b01;\r\n AA1[j+2] = b11;\r\n }\r\n {\r\n const long w1 = wtab[j+3];\r\n const mulmod_precon_t wqi1 = wqinvtab[j+3];\r\n const unsigned long a11 = AA1[j+3];\r\n const unsigned long a01 = AA0[j+3];\r\n\r\n const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n const unsigned long uu1 = LazyReduce(a01, two_q);\r\n const unsigned long b01 = uu1 + tt1; \r\n const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n AA0[j+3] = b01;\r\n AA1[j+3] = b11;\r\n }\r\n }\r\n#else\r\n\r\n for (j = 0; j < m_half; j++) {\r\n const long w1 = wtab[j];\r\n const mulmod_precon_t wqi1 = wqinvtab[j];\r\n const unsigned long a11 = AA1[j];\r\n const unsigned long a01 = AA0[j];\r\n\r\n const unsigned long tt1 = LazyMulModPrecon(a11, w1, q, wqi1);\r\n const unsigned long uu1 = LazyReduce(a01, two_q);\r\n const unsigned long b01 = uu1 + tt1; \r\n const unsigned long b11 = uu1 - tt1 + two_q;\r\n\r\n AA0[j] = b01;\r\n AA1[j] = b11;\r\n }\r\n\r\n#endif\r\n\r\n }\r\n }\r\n\r\n /* need to reduce redundant representations */\r\n\r\n for (i = 0; i < n; i++) {\r\n unsigned long tmp = LazyReduce(AA[i], two_q);\r\n A[i] = LazyReduce(tmp, q);\r\n }\r\n}\r\n\r\n\r\n#endif\r\n\r\n\r\n\r\n\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "cb6881730b64c936dc0b7642f3787ab74136072e", "size": 34608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/FFT.cpp", "max_stars_repo_name": "Brainloop-Security/secret-sharing", "max_stars_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WinNTL-8_1_2/src/FFT.cpp", "max_issues_repo_name": "Brainloop-Security/secret-sharing", "max_issues_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WinNTL-8_1_2/src/FFT.cpp", "max_forks_repo_name": "Brainloop-Security/secret-sharing", "max_forks_repo_head_hexsha": "56cd3bc808c666b653cbe2b2a5fb2cb9fe760cdd", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.354679803, "max_line_length": 94, "alphanum_fraction": 0.4691400832, "num_tokens": 11419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898153067649, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.6917085090565984}} {"text": "#pragma once\n\n/*\n * This file declares and implements a class representing a cubic spline.\n * After instantiating a Spline points (x, y) can be added; call calculate()\n * to compute coefficients of the cubic polynomial for each interval.\n * Spline::operator()(double x) computes the corresponding value of y\n * according to the computed spline.\n * \n * This isn't an elegant or optimal implementation but it gets the job done\n * for my purposes. Eigen is a dependency to do an SVD factorization to\n * compute the spline coefficients (the matrix obtained in my use cases\n * is numerically low-rank).\n */\n\n#include \n#include \n\n#include \n\nnamespace {\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nVectorXd find_spline_coeffs(const std::vector& xs_, \n const std::vector& ys_)\n{\n assert(xs_.size() == ys_.size());\n unsigned nintervals = xs_.size() - 1;\n MatrixXd A = MatrixXd::Zero(nintervals*4, nintervals*4);\n VectorXd B = VectorXd::Zero(nintervals*4);\n\n A(0, 0) = 3*xs_[0]*xs_[0];\n A(0, 1) = 2*xs_[0];\n A(0, 2) = 1.0;\n A(1, 0) = xs_[0] * xs_[0] * xs_[0];\n A(1, 1) = xs_[0] * xs_[0];\n A(1, 2) = xs_[0];\n A(1, 3) = 1.0;\n B(1) = ys_[0];\n\n unsigned curr_row = 2;\n for (unsigned node = 1; node < nintervals; ++node) {\n double xn2 = xs_[node] * xs_[node];\n double xn3 = xn2 * xs_[node];\n unsigned j = (node - 1) * 4;\n A(curr_row, j) = xn3;\n A(curr_row, j+1) = xn2;\n A(curr_row, j+2) = xs_[node];\n A(curr_row, j+3) = 1.0;\n B(curr_row) = ys_[node];\n curr_row += 1;\n A(curr_row, j) = 3*xn2;\n A(curr_row, j+1) = 2*xs_[node];\n A(curr_row, j+2) = 1.0;\n A(curr_row, j+4) = -3*xn2;\n A(curr_row, j+5) = -2*xs_[node];\n A(curr_row, j+6) = -1.0;\n curr_row += 1;\n A(curr_row, j) = 6*xs_[node];\n A(curr_row, j+1) = 2.0;\n A(curr_row, j+4) = -6*xs_[node];\n A(curr_row, j+5) = -2.0;\n curr_row += 1;\n A(curr_row, j+4) = xn3;\n A(curr_row, j+5) = xn2;\n A(curr_row, j+6) = xs_[node];\n A(curr_row, j+7) = 1.0;\n B(curr_row) = ys_[node];\n curr_row += 1;\n }\n\n unsigned j = (nintervals - 1) * 4;\n A(curr_row, j) = xs_[nintervals] * xs_[nintervals] * xs_[nintervals];\n A(curr_row, j+1) = xs_[nintervals] * xs_[nintervals];\n A(curr_row, j+2) = xs_[nintervals];\n A(curr_row, j+3) = 1.0;\n B(curr_row++) = ys_[nintervals];\n A(curr_row, j) = 3*xs_[nintervals]*xs_[nintervals];\n A(curr_row, j+1) = 2 * xs_[nintervals];\n A(curr_row, j+2) = 1.0;\n\n return A.jacobiSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(B);\n}\n\n}\n\nclass Spline\n{\nprivate:\n struct Coefficients {\n double a; double b;\n double c; double d;\n };\n std::vector xs_;\n std::vector ys_;\n std::vector coeffs_;\n\n template \n It get_element_position(double x, It start, It end) const\n {\n if (end == start) {\n return start;\n } else if (end - start == 1) {\n return *start > x ? start : end;\n } else {\n It middle = start + (end - start) / 2;\n if (*middle > x) {\n return get_element_position(x, start, middle);\n } else {\n return get_element_position(x, middle, end);\n }\n }\n }\n\npublic:\n typedef std::pair Point;\n\n void add_point(Point p)\n {\n auto it = get_element_position(p.first, xs_.begin(), xs_.end());\n auto offset = it - xs_.begin();\n xs_.insert(it, p.first);\n ys_.insert(ys_.begin() + offset, p.second);\n }\n\n void reset()\n {\n *this = Spline();\n }\n\n void calculate()\n {\n assert(xs_.size() == ys_.size());\n // X is a vector of a, b, c, d for each interval in the spline\n // in that order.\n auto X = find_spline_coeffs(xs_, ys_);\n coeffs_.resize(xs_.size() - 1);\n for (unsigned i = 0; i < coeffs_.size()*4; i += 4)\n coeffs_[i/4] = Coefficients{ X(i), X(i + 1), X(i + 2), X(i + 3) };\n }\n\n double operator()(double x) const\n {\n auto it = get_element_position(x, xs_.begin(), xs_.end());\n assert(!(it == xs_.begin() || it == xs_.end()));\n const auto& coeffs = coeffs_[it - xs_.begin() - 1];\n return coeffs.a * x * x * x + coeffs.b * x * x + coeffs.c * x +\n coeffs.d;\n }\n};\n", "meta": {"hexsha": "e8733b9dbd7d56be98f718e7cc6c17921948e2f9", "size": 4518, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "spline.hpp", "max_stars_repo_name": "slmcbane/fractalmake", "max_stars_repo_head_hexsha": "80364c6048b4cb788383fe39b18913a339e1b4c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "spline.hpp", "max_issues_repo_name": "slmcbane/fractalmake", "max_issues_repo_head_hexsha": "80364c6048b4cb788383fe39b18913a339e1b4c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "spline.hpp", "max_forks_repo_name": "slmcbane/fractalmake", "max_forks_repo_head_hexsha": "80364c6048b4cb788383fe39b18913a339e1b4c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5294117647, "max_line_length": 78, "alphanum_fraction": 0.5442673749, "num_tokens": 1427, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6916974891021166}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \n#include \n\n\ndouble norm_1(Eigen::Matrix3d X)\n{\n double sum = 0;\n for ( int i = 0; i < 3; i++ )\n {\n for ( int j = 0; j < 3; j++ )\n {\n sum += abs(X(i,j));\n }\n }\n return sum;\n}\n\ndouble norm_inf(Eigen::Matrix3d X)\n{\n double max_abs = abs(X(0,0));\n for ( int i = 0; i < 3; i++ )\n {\n for ( int j = 0; j < 3; j++ )\n {\n double new_abs = abs(X(i,j));\n if ( new_abs > max_abs )\n {\n max_abs = new_abs;\n }\n }\n }\n return max_abs;\n}\n\ntemplate\nvoid polar_eigen(const Mat& A, Mat& R, bool& SVD)\n{\n typedef typename Mat::Scalar Scalar;\n typedef Eigen::Matrix Vec;\n\n const Scalar th = std::sqrt(Eigen::NumTraits::dummy_precision());\n\n Eigen::SelfAdjointEigenSolver eig;\n feclearexcept(FE_UNDERFLOW);\n eig.computeDirect(A.transpose()*A);\n\n if(fetestexcept(FE_UNDERFLOW) || eig.eigenvalues()(0)/eig.eigenvalues()(2)/100.0 svd;\n svd.compute(A, Eigen::ComputeFullU | Eigen::ComputeFullV );\n const Mat& u = svd.matrixU(); const Mat& v = svd.matrixV(); const Vec& w = svd.singularValues();\n R = u*v.transpose();\n SVD = true;\n return;\n }\n\n Vec S = eig.eigenvalues().cwiseSqrt();\n R = A * eig.eigenvectors() * S.asDiagonal().inverse()\n * eig.eigenvectors().transpose();\n SVD = false;\n}\n\n\nint main() {\n std::ifstream file;\n file.open(\"Polar_benchmark\");\n if (!file)\n {\n CGAL_TRACE_STREAM << \"Error loading file!\\n\";\n return 0;\n }\n\n Eigen::Matrix3d A, U, r;\n bool SVD = false;\n int num_svd = 0;\n int num_mtr = 0;\n\n CGAL_TRACE_STREAM << \"start polar decomposition...\\n\";\n while (!file.eof())\n {\n for (int j = 0; j < 3; j++)\n {\n for (int k = 0; k < 3; k++)\n {\n file >> A(j, k);\n }\n }\n num_mtr++;\n double det = A.determinant();\n if (A.determinant() > 0)\n {\n polar_eigen (A, U, SVD);\n if (SVD)\n num_svd++;\n U.transposeInPlace();\n double det_2 = U.determinant();\n if ( abs(det_2-1) > 1e-2 )\n {\n CGAL_TRACE_STREAM << \"error matrix: det = \" << det_2 << \"\\n\";\n }\n }\n }\n file.close();\n\n CGAL_TRACE_STREAM << \"done. \" << num_svd << \" SVD decompositions in \" << num_mtr << \" matrices\\n\";\n return 0;\n\n /*int ite = 200000;\n Eigen::JacobiSVD svd;\n Eigen::Matrix3d A, U, H, r;\n\n int matrix_idx = rand()%200;\n for (int i = 0; i < matrix_idx; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n for (int k = 0; k < 3; k++)\n {\n file >> A(j, k);\n }\n }\n }\n file.close();\n\n A(0,0) = 0.0014667022958104185; A(0,1) = 0.0024644551180079627; A(0,2) = 0.0040659871060825092;\n A(1,0) = 0.0028327558016991478; A(1,1) = 0.0054236820249146406; A(1,2) = 0.0079280090866983826;\n A(2,0) = 0.0039090073251031232; A(2,1) = 0.0066744523074963374; A(2,2) = 0.010848552426718550;\n A = A*10000;\n double det = A.determinant();\n\n CGAL::Timer task_timer;\n\n CGAL_TRACE_STREAM << \"Start SVD decomposition...\";\n task_timer.start();\n for (int i = 0; i < ite; i++)\n {\n if (A.determinant() > 0)\n {\n polar_eigen (A, U);\n U.transposeInPlace();\n double det_2 = U.determinant();\n r = U*U.transpose();\n }\n }\n task_timer.stop();\n\n\n CGAL_TRACE_STREAM << \"done: \" << task_timer.time() << \"s\\n\";\n\n return 0;*/\n}\n\n", "meta": {"hexsha": "6000307464a0348904dc71002be79ba9e4abf3fe", "size": 3649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Surface_mesh_deformation/benchmark/Surface_mesh_deformation/optimal_rotation/optimal_rotation_polar_eigen.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Surface_mesh_deformation/benchmark/Surface_mesh_deformation/optimal_rotation/optimal_rotation_polar_eigen.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Surface_mesh_deformation/benchmark/Surface_mesh_deformation/optimal_rotation/optimal_rotation_polar_eigen.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 22.3865030675, "max_line_length": 100, "alphanum_fraction": 0.5735818032, "num_tokens": 1267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086368, "lm_q2_score": 0.7549149923816046, "lm_q1q2_score": 0.6915848785054699}} {"text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nnamespace po = boost::program_options;\n\nstd::default_random_engine generator;\n\nstd::normal_distribution distribution1(0,1);\n\nstd::chi_squared_distribution distribution2(1.0);\n\nstd::student_t_distribution distribution3(1.0);\n\nstd::uniform_real_distribution distribution4(-1.0,1.0);\n\nstd::exponential_distribution distribution5(1.0);\n\nstd::geometric_distribution distribution6(0.5);\n\n\n//double laplace_random_number = distribution5(generator) ;\n//\n//if(distribution4(generator) < 0.0 )\n//\n// laplace_random_number = - laplace_random_number;\n\ndouble get_random_number(int distribution)\n{\n switch(distribution)\n {\n case 1: // Normal distribution\n return distribution1(generator);\n case 2: // chi-square\n return distribution2(generator);\n case 3: // student-t\n return distribution3(generator);\n case 4: // uniform\n return distribution4(generator);\n case 5: // exponential\n return distribution5(generator);\n case 6: // geometric\n return distribution6(generator);\n case 7:\n return distribution5(generator)*(distribution4(generator) < 0.0 ? -1 : 1);\n default:\n return 0.0;\n ;\n }\n}\n\nint get_distribution_code(const char* var_dist)\n{\n if(strcmp(var_dist,\"normal\") == 0)\n return 1;\n else if(strcmp(var_dist,\"chi-square\") == 0)\n return 2;\n else if(strcmp(var_dist,\"student-t\") == 0)\n return 3;\n else if(strcmp(var_dist,\"uniform\") == 0)\n return 4;\n else if(strcmp(var_dist,\"exponential\") == 0)\n return 5;\n else if(strcmp(var_dist,\"geometric\") == 0)\n return 6;\n else if(strcmp(var_dist, \"laplace\")== 0)\n return 7;\n return 0;\n}\n\nint main(int argc, char** argv)\n\n{\n //int64_t seed = time(NULL);\n //generator.seed(seed);\n generator.seed(std::chrono::system_clock::now().time_since_epoch().count());\n double signal_noise_ratio = 6.0;\n int num_vars = 2;\n int dependent_var_idx = 0;\n int distribution = 1; // 1 for normal distribution\n int noise_distribution = 1; \n std::string outputFile;\n int N = 1000;//sample size, number of rows\n std::string description = std::string(\"Generate a csv file. Example usage: \") + argv[0] + \" \";\n// po::options_description desc(description);\n// desc.add_options()\n// (\"signal,s\", po::value (&signal_noise_ratio), \"signal noise ratio\")\n// (\"output,o\", po::value (&outputFile), \"The output file. Second positional argument.\")\n// (\"num_independents,i\", po::value(&num_vars)->default_value(1), \"The number of independent variables\")\n// (\"distribution,d\", po::value(&distribution)->default_value(1)\n// , (std::string(\"The probability distributions\\n\\t 1 for normal distribution\\n2 for chi-square\")\n// // + \"\\n\\t 3 for student-t distribution\"\n// // + \"\\n\\t 4 for uniform distribution\"\n// // + \"\\n\\t 5 for exponential distribution\"\n// + \"\\n\\t 6 for geometric distribution\").c_str()\n// )\n// (\"noise_distribution,z\", po::value(&noise_distribution)->default_value(1), \"noise distribution\")\n// (\"sample size, n\", po::value(&N)->default_value(1000), \"number of rows\")\n// (\"help,h\", \"Show this help message.\")\n// ;\n\n// po::positional_options_description positionalOptions;\n// positionalOptions.add(\"input\", 1);\n// positionalOptions.add(\"output\", 1);\n\n// po::variables_map vm;\n// po::store(po::parse_command_line(argc, argv, desc), vm);\n// po::notify(vm);\n// if (vm.count(\"help\") || argc == 1) {\n// std::cout << desc;\n// return 0;\n// }\n \n // temporary solution due to program options not working\n if(argc < 4)\n {\n printf(\"Usage: %s num_vars distribution noise_distribution noise_strength\\n\", argv[0]);\n exit(1);\n }\n num_vars = atoi(argv[1]);\n distribution = get_distribution_code ( argv[2] );\n noise_distribution = get_distribution_code( argv[3] );\n \n double noise_strength = 1.0;\n if(argc > 4)\n noise_strength = atof(argv[4]);\n \n\n const int cols = num_vars + 1;\n\n double data[N][cols];\n\n //arma::vec error(N);\n\n\n\n double sumX=0.0;\n\n double sumX2=0.0;\n \n //dependent_var_idx = int((get_random_number(4)+1) * cols + 1) % cols;\n arma::vec beta(num_vars+1);\n //beta(dependent_var_idx) = 0.0;\n std::vector indices(cols);\n for(int j=0;j %d, %12.4f\\n\", indices[j-1], indices[j], beta(indices[j]));\n printf(\"\\n\");\n for(int i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nEigen::MatrixXd pinv_Eigen_SVD(Eigen::MatrixXd &origin) {\n\n const float er = 0;\n // perform svd decomposition\n Eigen::JacobiSVD svd_holder(origin, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n // Build SVD decomposition results\n Eigen::MatrixXd U = svd_holder.matrixU();\n Eigen::MatrixXd V = svd_holder.matrixV();\n Eigen::MatrixXd D = svd_holder.singularValues();\n\n // Build the S matrix\n Eigen::MatrixXd S(V.cols(), U.cols());\n S.setZero();\n\n for (unsigned int i = 0; i < D.size(); ++i) {\n\n if (D(i, 0) > er) {\n S(i, i) = 1 / D(i, 0);\n } else {\n S(i, i) = 0;\n }\n }\n\n // pinv_matrix = V * S * U^T\n return V * S * U.transpose();\n}\n\nint main()\n{\n std::vector values(10000);\n\n // Generate Random values\n auto f = []() -> int { return rand() % 10000; };\n\n // Fill up the vector\n generate(values.begin(), values.end(), f);\n\n // Get starting timepoint\n auto start = std::chrono::high_resolution_clock::now();\n\n // Call the function, here sort()\n Eigen::MatrixXd jacobian;\n\n// for ( int i(0); i<1; i++ ) {\n jacobian.setRandom(6,7);\n// Eigen::MatrixXd pinv_jacobian1 = pinv_Eigen_SVD(jacobian);\n// Eigen::MatrixXd pinv_jacobian2 = jacobian.completeOrthogonalDecomposition().pseudoInverse();\n Eigen::MatrixXd pinv_jacobian3 = jacobian.transpose() * (jacobian * jacobian.transpose()).inverse();\n// }\n\n // Get ending timepoint\n auto stop = std::chrono::high_resolution_clock::now();\n\n// std::cout << pinv_jacobian1 << std::endl << std::endl;\n// std::cout << pinv_jacobian2 << std::endl << std::endl;\n// std::cout << pinv_jacobian3 << std::endl << std::endl;\n\n // Get duration. Substart timepoints to\n // get durarion. To cast it to proper unit\n // use duration cast method\n auto duration = std::chrono::duration_cast(stop - start);\n\n std::cout << \"Time taken by function: \"\n << duration.count() << \" microseconds\" << std::endl;\n\n return 0;\n}", "meta": {"hexsha": "150b5ac609f4fadbd804aae5cdb81baa0a88ba5c", "size": 2224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/test_pinv_time.cpp", "max_stars_repo_name": "VinceGuan/Franka_Teleop", "max_stars_repo_head_hexsha": "4ba70157c7b60bead49585799cc5ede0c55a5264", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/test_pinv_time.cpp", "max_issues_repo_name": "VinceGuan/Franka_Teleop", "max_issues_repo_head_hexsha": "4ba70157c7b60bead49585799cc5ede0c55a5264", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/test_pinv_time.cpp", "max_forks_repo_name": "VinceGuan/Franka_Teleop", "max_forks_repo_head_hexsha": "4ba70157c7b60bead49585799cc5ede0c55a5264", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-06T14:25:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T14:25:37.000Z", "avg_line_length": 26.4761904762, "max_line_length": 104, "alphanum_fraction": 0.6456834532, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240090865198, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.691545760021906}} {"text": "#include \"wave.h\"\n#include \n\n/**\n * Hankel_n^{(1)} function\n * \n * @param n index\n * @param x argument\n * @return value\n */\nstd::complex\nhankel1(const int n, const double x) {\n double besselJ = boost::math::cyl_bessel_j(n, x);\n double besselY = boost::math::cyl_neumann(n, x);\n return besselJ + J1*besselY;\n}\n\n/**\n * Incident wave\n * \n * @param kvec incident wave vector\n * @param point target point\n * @return amplitude\n */\nstd::complex \nincident(const double kvec[], const double point[]) {\n return std::exp(J1*(kvec[0]*point[0] + kvec[1]*point[1]));\n}\n\n/**\n * Normal gradient of the incident wave, assumes incident wave is exp(1j * kvec.x)\n *\n * @param nvec normal vector pointing inwards\n * @param kvec incident wave vector\n * @param point (source) point\n * @return amplitude\n */\nstd::complex \ngradIncident(const double nvec[], const double kvec[], \n const double point[]) {\n return J1*(nvec[0]*kvec[0] + nvec[1]*kvec[1])*incident(kvec, point);\n}\n\n/**\n * Scattered wave contribution from a single segment\n *\n * @param kvec incident wave vector\n * @param p0 starting point of the segment\n * @param p1 end point of the segment\n * @param point observer point\n * @return wave contribution\n */\nstd::complex \ncomputeScatteredWaveElement(const double kvec[], const double p0[], \n const double p1[], const double point[]) {\n\n // xdot is anticlockwise\n double xdot[] = {p1[0] - p0[0], p1[1] - p0[1]};\n\n // mid point of the segment\n double pmid[] = {0.5*(p0[0] + p1[0]), 0.5*(p0[1] + p1[1])};\n\n // segment length\n double dsdt = std::sqrt(xdot[0]*xdot[0] + xdot[1]*xdot[1]);\n\n // normal vector, pointintg inwards and normalised\n double nvec[] = {-xdot[1]/dsdt, xdot[0]/dsdt, 0.};\n\n // from segment mid-point to observer\n double rvec[] = {point[0] - pmid[0], point[1] - pmid[1]};\n double r = std::sqrt(rvec[0]*rvec[0] + rvec[1]*rvec[1]);\n\n double kmod = std::sqrt(kvec[0]*kvec[0] + kvec[1]*kvec[1]);\n double kr = kmod * r;\n\n // Green functions and normal derivatives\n std::complex g = (J1/4.) * hankel1(0, kr);\n double nDotR = nvec[0]*rvec[0] + nvec[1]*rvec[1];\n std::complex dgdn = (-J1/4.) * hankel1(1, kr) * kmod * nDotR / r;\n\n // contribution from the gradient of the incident wave on the surface\n // of the obstacle. The normal derivative of the scattered wave is\n // - normal derivative of the incident wave.\n std::complex scattered_wave = - dsdt * g * gradIncident(nvec, kvec, pmid);\n\n // shadow side: total wave is nearly zero\n // => scattered wave amplitude = -incident wave ampl.\n //\n // illuminated side:\n // => scattered wave amplitude = +incident wave ampl.\n //\n double nDotK = nvec[0]*kvec[0] + nvec[1]*kvec[1]; \n double shadow = (nDotK > 0 ? 1.0 : -1.0);\n \n scattered_wave += shadow * dsdt * dgdn * incident(kvec, pmid);\n\n return scattered_wave;\n}\n\nextern \"C\" void\ncincident (const double kvec[], const double point[], double* real_part, double* imag_part) {\n std::complex res = incident(kvec, point);\n *real_part = res.real();\n *imag_part = res.imag();\n}\n\nextern \"C\" void computeScatteredWave(const double kvec[], int nc, const double xc[], const double yc[], \n const double point[], double* real_part, double* imag_part) {\n double res_real = 0;\n double res_imag = 0;\n // ADD OPENMP PRAGMA HERE\n for (int i = 0; i < nc - 1; ++i) {\n double p0[] = {xc[i], yc[i]};\n double p1[] = {xc[i + 1], yc[i + 1]};\n std::complex res = computeScatteredWaveElement(kvec, p0, p1, point);\n res_real += res.real();\n res_imag += res.imag();\n }\n *real_part = res_real;\n *imag_part = res_imag;\n}\n\n", "meta": {"hexsha": "817de27eda45678c3efbfb123a90be7c5f82935b", "size": 3912, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openmp/src/wave.cpp", "max_stars_repo_name": "pletzer/scatter", "max_stars_repo_head_hexsha": "0d747a47b28e4d1be0a0268cf46204f61a6dd527", "max_stars_repo_licenses": ["0BSD"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-01T06:49:51.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-05T19:47:05.000Z", "max_issues_repo_path": "openmp/src/wave.cpp", "max_issues_repo_name": "pletzer/scatter", "max_issues_repo_head_hexsha": "0d747a47b28e4d1be0a0268cf46204f61a6dd527", "max_issues_repo_licenses": ["0BSD"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-19T02:06:43.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-27T08:57:08.000Z", "max_forks_repo_path": "openmp/src/wave.cpp", "max_forks_repo_name": "pletzer/scatter", "max_forks_repo_head_hexsha": "0d747a47b28e4d1be0a0268cf46204f61a6dd527", "max_forks_repo_licenses": ["0BSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-21T03:58:39.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-19T01:53:46.000Z", "avg_line_length": 31.8048780488, "max_line_length": 104, "alphanum_fraction": 0.6129856851, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213826762113, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6914964861439815}} {"text": "// main.cpp\n#include \n#include \n#include \n#include \n#include \"sophus/so3.hpp\"\n#include \"sophus/common.hpp\"\n\n\nusing Eigen::MatrixXd;\nint main()\n{\n MatrixXd m(2,2);\n m(0,0) = 3;\n m(1,0) = 2.5;\n m(0,1) = -1;\n m(1,1) = m(1,0) + m(0,1);\n m(1,1) = 0;\n std::cout << m << std::endl;\n\n\n // The following demonstrates the group multiplication of rotation matrices\n\n // Create rotation matrices from rotations around the x and y and z axes:\n const double kPi = Sophus::Constants::pi();\n Sophus::SO3d R1 = Sophus::SO3d::rotX(kPi / 4);\n Sophus::SO3d R2 = Sophus::SO3d::rotY(kPi / 6);\n Sophus::SO3d R3 = Sophus::SO3d::rotZ(-kPi / 3);\n\n std::cout << \"The rotation matrices are\" << std::endl;\n std::cout << \"R1:\\n\" << R1.matrix() << std::endl;\n std::cout << \"R2:\\n\" << R2.matrix() << std::endl;\n std::cout << \"R3:\\n\" << R3.matrix() << std::endl;\n std::cout << \"Their product R1*R2*R3:\\n\"\n << (R1 * R2 * R3).matrix() << std::endl;\n std::cout << std::endl;\n\n // Rotation matrices can act on vectors\n Eigen::Vector3d x;\n x << 0.0, 0.0, 1.0;\n std::cout << \"Rotation matrices can act on vectors\" << std::endl;\n std::cout << \"x\\n\" << x << std::endl;\n std::cout << \"R2*x\\n\" << R2 * x << std::endl;\n std::cout << \"R1*(R2*x)\\n\" << R1 * (R2 * x) << std::endl;\n std::cout << \"(R1*R2)*x\\n\" << (R1 * R2) * x << std::endl;\n std::cout << std::endl;\n\n // SO(3) are internally represented as unit quaternions.\n std::cout << \"R1 in matrix form:\\n\" << R1.matrix() << std::endl;\n std::cout << \"R1 in unit quaternion form:\\n\"\n << R1.unit_quaternion().coeffs() << std::endl;\n // Note that the order of coefficiences of Eigen's quaternion class is\n // (imag0, imag1, imag2, real)\n std::cout << std::endl;\n // The following demonstrates the group multiplication of rotation matrices\n\n // Create rotation matrices from rotations around the x and y and z axes:\n // const double kPi = Sophus::Constants::pi();\n // Sophus::SO3d R1 = Sophus::SO3d::rotX(kPi / 4);\n // Sophus::SO3d R2 = Sophus::SO3d::rotY(kPi / 6);\n // Sophus::SO3d R3 = Sophus::SO3d::rotZ(-kPi / 3);\n\n // std::cout << \"The rotation matrices are\" << std::endl;\n // std::cout << \"R1:\\n\" << R1.matrix() << std::endl;\n // std::cout << \"R2:\\n\" << R2.matrix() << std::endl;\n // std::cout << \"R3:\\n\" << R3.matrix() << std::endl;\n // std::cout << \"Their product R1*R2*R3:\\n\"\n // << (R1 * R2 * R3).matrix() << std::endl;\n // std::cout << std::endl;\n\n // // Rotation matrices can act on vectors\n // Eigen::Vector3d x;\n // x << 0.0, 0.0, 1.0;\n // std::cout << \"Rotation matrices can act on vectors\" << std::endl;\n // std::cout << \"x\\n\" << x << std::endl;\n // std::cout << \"R2*x\\n\" << R2 * x << std::endl;\n // std::cout << \"R1*(R2*x)\\n\" << R1 * (R2 * x) << std::endl;\n // std::cout << \"(R1*R2)*x\\n\" << (R1 * R2) * x << std::endl;\n // std::cout << std::endl;\n\n // // SO(3) are internally represented as unit quaternions.\n // std::cout << \"R1 in matrix form:\\n\" << R1.matrix() << std::endl;\n // std::cout << \"R1 in unit quaternion form:\\n\"\n // << R1.unit_quaternion().coeffs() << std::endl;\n // // Note that the order of coefficiences of Eigen's quaternion class is\n // (imag0, imag1, imag2, real)\n std::cout << std::endl;\n\n}\n", "meta": {"hexsha": "f9208487b4e5f2b73d8c493433010010d84677fc", "size": 3296, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sqlite.cpp", "max_stars_repo_name": "ahtamjidi/learn_cpp", "max_stars_repo_head_hexsha": "bbfa6d1828c5eab601261a4f19259c9977c16236", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sqlite.cpp", "max_issues_repo_name": "ahtamjidi/learn_cpp", "max_issues_repo_head_hexsha": "bbfa6d1828c5eab601261a4f19259c9977c16236", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sqlite.cpp", "max_forks_repo_name": "ahtamjidi/learn_cpp", "max_forks_repo_head_hexsha": "bbfa6d1828c5eab601261a4f19259c9977c16236", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.6222222222, "max_line_length": 77, "alphanum_fraction": 0.5700849515, "num_tokens": 1185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6914389829481044}} {"text": "/*\n * Copyright 2017 Mahdi Khanalizadeh\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef HEADER_EXT_MATRIX2_HPP_INCLUDED\n#define HEADER_EXT_MATRIX2_HPP_INCLUDED\n\n#include \"vector2.hpp\"\n\n#include \n\n#include \n\n#include \n\nnamespace ext\n{\n\n\ttemplate \n\tclass Matrix2 :\n\t\tboost::equality_comparable,\n\t\tboost::ring_operators,\n\t\tboost::multipliable, T\n\t\t>>>\n\t{\n\tpublic:\n\t\tusing Type = T;\n\n\t\tType x[4];\n\t};\n\n\tusing Matrix2f = Matrix2;\n\tusing Matrix2d = Matrix2;\n\tusing Matrix2ld = Matrix2;\n\n\ttemplate \n\tbool operator==(Matrix2 const& m1, Matrix2 const& m2)\n\t{\n\t\treturn std::equal(m1.x, m1.x + (sizeof m1.x / sizeof m1.x[0]), m2.x);\n\t}\n\n\ttemplate \n\tMatrix2& operator+=(Matrix2& m1, Matrix2 const& m2)\n\t{\n\t\tstd::transform(m1.x, m1.x + (sizeof m1.x / sizeof m1.x[0]), m2.x, m1.x, [](T one, T two){ return one + two; });\n\t\treturn m1;\n\t}\n\n\ttemplate \n\tMatrix2& operator-=(Matrix2& m1, Matrix2 const& m2)\n\t{\n\t\tstd::transform(m1.x, m1.x + (sizeof m1.x / sizeof m1.x[0]), m2.x, m1.x, [](T one, T two){ return one - two; });\n\t\treturn m1;\n\t}\n\n\ttemplate \n\tMatrix2& operator*=(Matrix2& m1, Matrix2 const& m2)\n\t{\n\t\tauto const m = m1;\n\t\tm1.x[0] = m.x[0] * m2.x[0] + m.x[1] * m2.x[2];\n\t\tm1.x[1] = m.x[0] * m2.x[1] + m.x[1] * m2.x[3];\n\t\tm1.x[2] = m.x[2] * m2.x[0] + m.x[3] * m2.x[2];\n\t\tm1.x[3] = m.x[2] * m2.x[1] + m.x[3] * m2.x[3];\n\t\treturn m1;\n\t}\n\n\ttemplate \n\tMatrix2& operator*=(Matrix2& m, T const a)\n\t{\n\t\tstd::transform(m.x, m.x + (sizeof m.x / sizeof m.x[0]), m.x, [a](T x){ return x * a; });\n\t\treturn m;\n\t}\n\n\ttemplate \n\tVector2 operator * (Matrix2 const& m, Vector2 const& v)\n\t{\n\t\treturn {m.x[0] * v.x + m.x[1] * v.y, m.x[2] * v.x + m.x[3] * v.y};\n\t}\n\n\ttemplate \n\tVector2 operator * (Vector2 const& v, Matrix2 const& m)\n\t{\n\t\treturn {v.x * m.x[0] + v.y * m.x[2], v.x * m.x[1] + v.y * m.x[3]};\n\t}\n\n\ttemplate \n\tMatrix2 transpose(Matrix2 const& m)\n\t{\n\t\tauto t = m;\n\t\tt.x[1] = m.x[2];\n\t\tt.x[2] = m.x[1];\n\t\treturn t;\n\t}\n\n\ttemplate \n\tT trace(Matrix2 const& m)\n\t{\n\t\treturn m.x[0] + m.x[3];\n\t}\n\n\ttemplate \n\tT determinant(Matrix2 const& m)\n\t{\n\t\treturn m.x[0] * m.x[3] - m.x[1] * m.x[2];\n\t}\n\n\ttemplate \n\tMatrix2 inverse(Matrix2 const& m)\n\t{\n\t\tassert(determinant(m) != 0);\n\t\tMatrix2 n;\n\t\tn.x[0] = m.x[3];\n\t\tn.x[1] = -m.x[1];\n\t\tn.x[2] = -m.x[2];\n\t\tn.x[3] = m.x[0];\n\t\tn *= 1/determinant(m);\n\t\treturn n;\n\t}\n\n} // namespace ext\n\n#endif // !HEADER_EXT_MATRIX2_HPP_INCLUDED\n", "meta": {"hexsha": "b31c599a9a4310db75a16b95722b5bca5f654a34", "size": 3183, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ext/matrix2.hpp", "max_stars_repo_name": "Biolunar/ext", "max_stars_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ext/matrix2.hpp", "max_issues_repo_name": "Biolunar/ext", "max_issues_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ext/matrix2.hpp", "max_forks_repo_name": "Biolunar/ext", "max_forks_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5777777778, "max_line_length": 113, "alphanum_fraction": 0.6145146089, "num_tokens": 1128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.78793120560257, "lm_q1q2_score": 0.6913913405242378}} {"text": "#ifndef _LINEAR_ALGEBRA_HPP_\n#define _LINEAR_ALGEBRA_HPP_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing mimkl::definitions::Index;\n\nnamespace mimkl\n{\nnamespace linear_algebra\n{\n\n//! \\f$ K' = K / (tr(K) / n)\\f$\n/*!\ndevide matrix by a factor so that trace will equal the number of rows \\f$ tr(K')\n= n \\f$\n@param K square matrix to be trace_normalized by reference\n@return trace_factor \\f$ tr(K) / n\\f$\n*/\ntemplate \ntypename Derived::Scalar trace_normalize(Derived &K)\n{\n typename Derived::Scalar trace_factor = K.trace() / K.rows();\n K = K / trace_factor;\n return trace_factor;\n}\n\n//! \\f$ k^{*}(x,y) = \\fraq{k(x,y)}{\\sqrt{k(x,x) k(y,y)}}\\f$\ntemplate \nDerived normalize_kernel(const Derived &K)\n{\n COLUMN(typename Derived::Scalar) diag = 1 / K.diagonal().array().sqrt();\n return K.array() * (diag * diag.transpose()).array(); // outer product of\n // diagonal elements\n}\n\n//! \\f$ k^{*}(x,y) = \\fraq{k(x,y)}{\\sqrt{k(x,x) k(y,y)}}\\f$, where k(x,x) stems\n//! from the training data and k(y,y) from the test data\ntemplate \nDerived normalize_kernel_prediction(const Derived &K,\n const LhsDerived &lhs,\n const RhsDerived &rhs)\n{\n COLUMN(typename Derived::Scalar)\n diag_lhs = 1 / lhs.diagonal().array().sqrt();\n COLUMN(typename Derived::Scalar)\n diag_rhs = 1 / rhs.diagonal().array().sqrt();\n return K.array() *\n (diag_lhs * diag_rhs.transpose()).array(); // outer product of\n // diagonal elements\n}\n\n//! centralizing the data in feature space \\f$ \\mathbf{K}' = ( \\mathbf{I} -\n//! \\mathbf{1_N}) \\mathbf{K} ( \\mathbf{I} - \\mathbf{1_N}) = \\mathbf{K} -\n//! \\mathbf{1_N} \\mathbf{K} - \\mathbf{K} \\mathbf{1_N} + \\mathbf{1_N} \\mathbf{K}\n//! \\mathbf{1_N}\\f$\n/*!\nwhere \\f$\\mathbf{1_N}\\f$ denotes a N-by-N matrix for which each element takes\nvalue 1/N\n*/\ntemplate \nDerived centralize_kernel(const Derived &K)\n{ // TODO how to do for test data?\n Eigen::Matrix rowwise_mean =\n K.rowwise().mean();\n return ((K.colwise() - rowwise_mean).rowwise() - rowwise_mean.transpose())\n .array() +\n rowwise_mean.mean();\n}\n\ntemplate // TODO why does const & not compile?\nEigen::Map dlib_to_eigen(\nconst dlib::matrix &vector)\n{ // more general case\n // with template\n // specializations not\n // needed as of yet.\n spdlog::get(\"console\")->debug(\"sum over passed vector:\\n{}\",\n dlib::sum(vector));\n typedef COLUMN(Scalar) Column;\n typedef Eigen::Map MapColumn;\n // Map Dlib to Eigen\n const Scalar *dlib_ptr = vector.begin(); //&vector.data(0,0);\n if (dlib::is_row_major(vector) ^ (Column::Flags & Eigen::RowMajorBit))\n { // if XOR warn, for instance Y: Y.isRowMajor\n auto logger = spdlog::get(\"console\");\n logger->critical(\"make sure LibMat is in col-major or that mapping \"\n \"happens \"\n \"in row-major:\\n\"\n \"dlib::is_row_major(vector): {}\\n\"\n \"Column::Options: {}\\n\"\n \"(Column::Flags&Eigen::RowMajorBit): {}\",\n dlib::is_row_major(vector), Column::Options,\n (Column::Flags & Eigen::RowMajorBit));\n };\n return MapColumn(dlib_ptr, vector.nr(), 1);\n}\n\n//! squared euclidean distance of rows in X to itself: M_ij = x_i^T*x_i +\n//! x_j^T*x_j -\n//! 2*x_i^T*x_j\ntemplate \nvoid squared_euclidean_distances(const Eigen::MatrixBase &lhs,\n const Eigen::MatrixBase &distance_matrix)\n{\n MDerived lin_kernel = lhs * lhs.transpose();\n const_cast &>(distance_matrix) =\n ((-2 * lin_kernel.real()).colwise() + lin_kernel.diagonal()).rowwise() +\n lin_kernel.diagonal().adjoint();\n}\n\ntemplate \nMATRIX(Scalar)\nrowwise_soft_max(MATRIX(Scalar) M)\n{\n for (Index i = 0; i < M.rows(); i++)\n {\n Scalar max = M.row(i).maxCoeff(); // numerical stability\n Scalar sum = 0;\n for (Index j = 0; j < M.cols(); j++)\n {\n sum += std::exp(M(i, j) - max);\n }\n Scalar normalizer = std::log(sum); // numerical stability\n for (Index j = 0; j < M.cols(); j++)\n {\n M(i, j) = std::exp(M(i, j) - max - normalizer);\n }\n }\n return M;\n}\n\n// TODO documentation\ntemplate \nMATRIX(Scalar)\nsum_matrices(const std::vector &Ks)\n{\n // fold over Ks\n return std::accumulate(Ks.begin(), Ks.end(),\n MATRIX(Scalar)::Zero((*Ks.begin()).rows(),\n (*Ks.begin()).cols())\n .eval()); //, [](a,b){operator+(a,b)}\n}\n\ntemplate \nMATRIX(Scalar)\nsum_trace_normalized_matrices(const std::vector &Ks,\n std::vector &trace_factors)\n{\n // fold over Ks, trace_normalize K before summing and store its trace\n MATRIX(Scalar) acc; // not writing 0s\n MATRIX(Scalar) K; // temporary holding the trace_normalized kernel\n if (Ks.begin() != Ks.end())\n {\n Index i = 0;\n acc = Ks[i]; // non const copy\n trace_factors[i] = trace_normalize(acc);\n ++i;\n for (; i < Ks.size(); ++i)\n {\n K = Ks[i];\n trace_factors[i] = trace_normalize(K);\n acc += K;\n }\n }\n}\n\n// not using std::accumulate, see commented version below\ntemplate \nMATRIX(Scalar)\naggregate_kernels(const MATRIX(Scalar) & lhs,\n const MATRIX(Scalar) & rhs,\n const std::vector &Ks)\n{\n MATRIX(Scalar) acc; // not writing 0s\n if (Ks.begin() != Ks.end())\n {\n typename std::vector::const_iterator iter = Ks.begin();\n acc = (*iter)(lhs, rhs);\n ++iter;\n for (; iter != Ks.end(); ++iter)\n {\n acc += (*iter)(lhs, rhs);\n }\n } // TODO else { throw | warn | ....}\n return acc;\n}\n\ntemplate \nMATRIX(Scalar)\naggregate_trace_normalized_kernels(const MATRIX(Scalar) & lhs,\n const MATRIX(Scalar) & rhs,\n const std::vector &Ks,\n std::vector &trace_factors,\n bool update_trace_factors)\n{\n if (Ks.size() != trace_factors.size())\n throw std::length_error(\n \" number of functions does not match number of trace_factors\");\n MATRIX(Scalar) acc; // not writing 0s\n if (update_trace_factors)\n {\n MATRIX(Scalar) K; // temporary holding the trace_normalized kernel\n if (Ks.begin() != Ks.end())\n {\n Index i = 0;\n K = Ks[i](lhs, rhs); // non const copy\n trace_factors[i] = trace_normalize(K);\n acc = K;\n ++i;\n for (; i < Ks.size(); ++i)\n {\n K = Ks[i](lhs, rhs);\n trace_factors[i] = trace_normalize(K);\n acc += K;\n }\n }\n }\n else\n {\n if (Ks.begin() != Ks.end())\n {\n Index i = 0;\n acc = Ks[i](lhs, rhs) / trace_factors[i];\n ++i;\n for (; i < Ks.size(); ++i)\n {\n acc += Ks[i](lhs, rhs) / trace_factors[i];\n }\n }\n }\n return acc;\n}\n\n// TODO documentation\ntemplate \nMATRIX(Scalar)\nsum_weighted_matrices(const std::vector &Ks,\n const COLUMN(Scalar) & eta)\n{\n return std::inner_product(\n Ks.begin(), Ks.end(),\n eta.data(), // Eigen has no .begin() and .end()\n MATRIX(Scalar)::Zero((*Ks.begin()).rows(), (*Ks.begin()).cols()).eval());\n}\n\ntemplate \nMATRIX(Scalar)\naggregate_weighted_kernels(const MATRIX(Scalar) & lhs,\n const MATRIX(Scalar) & rhs,\n const std::vector &fs,\n const COLUMN(Scalar) & eta)\n{\n MATRIX(Scalar) acc; // not writing 0s\n if (fs.begin() != fs.end())\n {\n Index i = 0;\n acc = fs[i](lhs, rhs) * eta(i);\n ++i;\n for (; i < fs.size(); ++i)\n {\n acc += fs[i](lhs, rhs) * eta(i);\n }\n } // TODO else { throw | warn | ....}\n return acc;\n}\n\ntemplate \nMATRIX(Scalar)\naggregate_weighted_trace_normalized_kernels(const MATRIX(Scalar) & lhs,\n const MATRIX(Scalar) & rhs,\n const std::vector &Ks,\n std::vector &trace_factors,\n bool update_trace_factors, // update_trace_factors\n // or\n // read trace_factors\n const COLUMN(Scalar) & eta)\n{\n if (Ks.size() != trace_factors.size())\n throw std::length_error(\n \" number of functions does not match number of trace_factors\");\n MATRIX(Scalar) acc; // not writing 0s\n if (update_trace_factors)\n {\n MATRIX(Scalar) K; // temporary holding the trace_normalized kernel\n if (Ks.begin() != Ks.end())\n {\n Index i = 0;\n K = Ks[i](lhs, rhs); // non const copy\n trace_factors[i] = trace_normalize(K);\n acc = K * eta(i);\n ++i;\n for (; i < Ks.size(); ++i)\n {\n K = Ks[i](lhs, rhs);\n trace_factors[i] = trace_normalize(K);\n acc += K * eta(i);\n }\n }\n }\n else\n {\n if (Ks.begin() != Ks.end())\n {\n Index i = 0;\n acc = Ks[i](lhs, rhs) / trace_factors[i] * eta(i);\n ++i;\n for (; i < Ks.size(); ++i)\n {\n acc += Ks[i](lhs, rhs) / trace_factors[i] * eta(i);\n }\n }\n } // TODO else { throw | warn | ....}\n return acc;\n}\n\n//! fill a sparse diagonal matrix with a given value\n/*! only if elements don't exist already, else use coeffRef() instead of\ninsert()\n\\param I a sparse matrix of type Eigen::SparseMatrixBase.\n\\param value a value to fill the diagonal of type double.\n\\sa test/sparse_diagonal\n*/\ntemplate \nvoid fill_sparse_diagonal(Eigen::SparseMatrixBase const &I,\n const double value)\n{\n // size of diagonal\n const Index &m = I.rows();\n const Index &n = I.cols();\n Index d = (m < n ? m : n);\n Eigen::SparseMatrixBase &I_ =\n const_cast &>(I);\n for (Index i = 0; i < d; ++i)\n {\n I_.derived().insert(i, i) = value;\n }\n}\n\n// helpers for indexing an Eigen::Matrix\n// adapted from\n// http://eigen.tuxfamily.org/dox-devel/TopicCustomizing_NullaryExpr.html#title1\ntemplate \nclass IndexingFunctor\n{\n private:\n const ArgumentType &argument_;\n const RowIndexType &row_indices_;\n const ColumnIndexType &column_indices_;\n\n public:\n typedef Eigen::Matrix<\n typename ArgumentType::Scalar,\n RowIndexType::SizeAtCompileTime,\n ColumnIndexType::SizeAtCompileTime,\n ArgumentType::Flags & Eigen::RowMajorBit ? Eigen::RowMajor : Eigen::ColMajor,\n RowIndexType::MaxSizeAtCompileTime,\n ColumnIndexType::MaxSizeAtCompileTime>\n MatrixType;\n IndexingFunctor(const ArgumentType &argument,\n const RowIndexType &row_indices,\n const ColumnIndexType &column_indices)\n : argument_(argument),\n row_indices_(row_indices),\n column_indices_(column_indices)\n {\n }\n const typename ArgumentType::Scalar &\n operator()(Eigen::Index row, Eigen::Index column) const\n {\n return argument_(row_indices_[row], column_indices_[column]);\n }\n};\n\ntemplate \nEigen::CwiseNullaryOp<\nIndexingFunctor,\ntypename IndexingFunctor::MatrixType>\nindexing(const Eigen::MatrixBase &argument,\n const RowIndexType &row_indices,\n const ColumnIndexType &column_indices)\n{\n typedef IndexingFunctor Indexer;\n typedef typename Indexer::MatrixType MatrixType;\n return MatrixType::NullaryExpr(row_indices.size(), column_indices.size(),\n Indexer(argument.derived(), row_indices,\n column_indices));\n};\n} // namespace linear_algebra\n} // namespace mimkl\n\n#endif /*_LINEAR_ALGEBRA_HPP_*/\n", "meta": {"hexsha": "019c85d40a0ebe4769c3bb3f884301cacafccdd8", "size": 13649, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mimkl/linear_algebra.hpp", "max_stars_repo_name": "vishalbelsare/mimkl", "max_stars_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2019-05-28T23:18:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:00:03.000Z", "max_issues_repo_path": "include/mimkl/linear_algebra.hpp", "max_issues_repo_name": "vishalbelsare/mimkl", "max_issues_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2019-05-18T13:21:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:20:55.000Z", "max_forks_repo_path": "include/mimkl/linear_algebra.hpp", "max_forks_repo_name": "vishalbelsare/mimkl", "max_forks_repo_head_hexsha": "53a5a9db5aa09c6e8808ba5b845601c5768d23e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-24T09:39:41.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T14:40:27.000Z", "avg_line_length": 33.8684863524, "max_line_length": 94, "alphanum_fraction": 0.5623855227, "num_tokens": 3347, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6913913248905628}} {"text": "// Standard\n#include \n#include \n#include \n\n// Timer\n#include \n\n#include \n\n#include \n#include \n#include \n\n// #define MPC_PRINT_ALL\n// #define MPC_TIME_ALL\n\n// We are following the MPC formulation from:\n// Di Carlo, Jared, et al. \"Dynamic locomotion in the mit cheetah 3 through\n// convex model-predictive control.\" 2018 IEEE/RSJ International Conference on\n// Intelligent Robots and Systems (IROS). IEEE, 2018.\n\ninline Eigen::MatrixXd R_roll(const double& phi) {\n Eigen::MatrixXd Rx(3, 3);\n Rx.setZero();\n Rx << 1.0, 0.0, 0.0, 0.0, cos(phi), -sin(phi), 0.0, sin(phi), cos(phi);\n return Rx;\n}\n\ninline Eigen::MatrixXd R_pitch(const double& theta) {\n Eigen::MatrixXd Ry(3, 3);\n Ry.setZero();\n Ry << cos(theta), 0.0, sin(theta), 0.0, 1.0, 0.0, -sin(theta), 0.0,\n cos(theta);\n return Ry;\n}\n\ninline Eigen::MatrixXd R_yaw(const double& psi) {\n Eigen::MatrixXd Rz(3, 3);\n Rz.setZero();\n Rz << cos(psi), -sin(psi), 0.0, sin(psi), cos(psi), 0.0, 0.0, 0.0, 1.0;\n return Rz;\n}\n\ninline Eigen::MatrixXd skew_sym_mat(const Eigen::MatrixXd& r) {\n Eigen::MatrixXd cm(3, 3);\n cm << 0.f, -r(2), r(1), r(2), 0.f, -r(0), -r(1), r(0), 0.f;\n return cm;\n}\n\n// Transform input vector to nxm matrix. Vector must have dimension n*m.\nvoid assemble_vec_to_matrix(const int& n, const int& m,\n const Eigen::VectorXd& vec,\n Eigen::MatrixXd& mat_out) {\n mat_out = Eigen::MatrixXd::Zero(n, m);\n for (int j = 0; j < m; j++) {\n mat_out.col(j) = vec.segment(j * n, n);\n }\n // std::cout << \"mat_out:\" << std::endl;\n // std::cout << mat_out << std::endl;\n}\n\n// Given dt, current x state, f_Mat, and r_feet. Find the next state, x1\nvoid integrate_robot_dynamics(const double& dt,\n const Eigen::VectorXd& x_current,\n const Eigen::MatrixXd& f_Mat,\n const Eigen::MatrixXd& r_feet, const double& mass,\n const Eigen::MatrixXd& I_body,\n Eigen::VectorXd& x_next) {\n // x = [Theta, p, omega, pdot, g] \\in \\mathbf{R}^13\n double roll = x_current[0];\n double pitch = x_current[1];\n double yaw = x_current[2];\n // std::cout << \"x_current:\" << x_current.transpose() << std::endl;\n\n Eigen::VectorXd theta_prior = x_current.head(3);\n Eigen::VectorXd p_prior = x_current.segment(3, 3);\n Eigen::VectorXd omega_prior = x_current.segment(6, 3);\n Eigen::VectorXd pdot_prior = x_current.segment(9, 3);\n\n Eigen::MatrixXd Rx = R_roll(roll);\n Eigen::MatrixXd Ry = R_pitch(pitch);\n Eigen::MatrixXd Rz = R_yaw(yaw);\n\n Eigen::MatrixXd R_zyx = Rz * Ry * Rx;\n Eigen::MatrixXd I_world =\n R_zyx * I_body *\n R_zyx.transpose(); // Inertia matrix aligned to CoM frame.\n\n // CoM acceleration, velocity, and position\n Eigen::VectorXd pddot(3); // pddot = 1/m sum(f_i) - g\n Eigen::VectorXd pdot(3); // pdot = pddot*dt + pdot prior;\n Eigen::VectorXd p(3); // p = 0.5*pddot*dt*dt + pdot_prior*dt + p_prior;\n\n Eigen::VectorXd grav_vec(3);\n grav_vec.setZero();\n grav_vec[2] = -9.81;\n pddot.setZero();\n pddot += grav_vec;\n for (int i = 0; i < f_Mat.cols(); i++) {\n pddot += ((1.0 / mass) * f_Mat.col(i));\n }\n pdot = pddot * dt + pdot_prior; // CoM velocity\n p = 0.5 * pddot * dt * dt + pdot_prior * dt + p_prior; // CoM position\n\n // Angular Acceleration, velocity, and new orientation\n Eigen::VectorXd omega_dot(3); // omega_dot = I_inv * (sum(skew(r_i)*f_i)\n // -skew(omega_prior)*I*omega_prior\n Eigen::VectorXd omega(3); // omega = omega_dot*dt + omega_prior;\n Eigen::VectorXd theta; // theta = Omega_Rate*(0.5*omega_dot*dt +\n // omega_prior)*dt + theta_prior\n\n // ZYX from ZYX rates integration\n Eigen::MatrixXd omega_to_zyx_rate(3, 3);\n omega_to_zyx_rate << cos(yaw) / cos(pitch), sin(yaw) / cos(pitch), 0,\n -sin(yaw), cos(yaw), 0, cos(yaw) * sin(pitch) / cos(pitch),\n sin(yaw) * sin(pitch) / cos(pitch), 1;\n\n Eigen::VectorXd moments(3);\n moments.setZero();\n for (int i = 0; i < f_Mat.cols(); i++) {\n moments += skew_sym_mat(r_feet.col(i)) * f_Mat.col(i);\n }\n omega_dot = I_world.inverse() *\n (moments - skew_sym_mat(omega_prior) * (I_world * omega_prior));\n omega = omega_dot * dt + omega_prior;\n theta = omega_to_zyx_rate * (0.5 * omega_dot * dt + omega_prior) * dt +\n theta_prior;\n\n // std::cout << \"pddot:\" << pddot.transpose() << std::endl;\n // std::cout << \"pdot:\" << pdot.transpose() << std::endl;\n // std::cout << \"p_prior:\" << p_prior.transpose() << std::endl;\n // std::cout << \"p_post:\" << p.transpose() << std::endl;\n\n // std::cout << std::endl;\n // std::cout << \"omega_dot:\" << omega_dot.transpose() << std::endl;\n // std::cout << \"omega:\" << omega.transpose() << std::endl;\n\n // std::cout << \"omega_to_zyx_rate\" << std::endl;\n // std::cout << omega_to_zyx_rate << std::endl;\n\n // std::cout << \"theta_prior:\" << theta_prior.transpose() << std::endl;\n // std::cout << \"theta_post:\" << theta.transpose() << std::endl;\n\n // Set new x_next;\n x_next.head(3) = theta;\n x_next.segment(3, 3) = p;\n x_next.segment(6, 3) = omega;\n x_next.segment(9, 3) = pdot;\n x_next[12] = -9.81;\n\n // std::cout << \"x_next:\" << x_next.transpose() << std::endl;\n}\n\n// Inputs: m, I, current yaw, and footstep locations.\n// Output: A, B matrix to be used for zero-order hold MPC\nvoid cont_time_state_space(const double& mass, const Eigen::MatrixXd& I_body,\n const double& psi_in, const Eigen::MatrixXd& r_feet,\n Eigen::MatrixXd& A, Eigen::MatrixXd& B) {\n // Get System State: Current Robot yaw\n Eigen::MatrixXd Rz = R_yaw(psi_in);\n\n Eigen::MatrixXd I_world =\n Rz * I_body * Rz.transpose(); // Inertia matrix aligned to CoM frame.\n Eigen::MatrixXd I_inv = I_world.inverse(); // Inverse\n\n // Number of reaction forces equal to number of feet contacts\n\n int n_Fr = r_feet.cols();\n\n // x = [Theta, p, omega, pdot, g] \\in \\mathbf{R}^13\n // There is an additional gravity state.\n // Populate A matrix\n A = Eigen::MatrixXd::Zero(13, 13);\n A.block(0, 6, 3, 3) = Rz;\n A.block(3, 9, 3, 3) = Eigen::MatrixXd::Identity(3, 3);\n A(11, 12) = 1.0; // Gravity vector\n\n // Populate B matrix\n B = Eigen::MatrixXd::Zero(13, 3 * n_Fr);\n Eigen::MatrixXd eye3 = Eigen::MatrixXd::Identity(3, 3);\n for (int i = 0; i < n_Fr; i++) {\n B.block(6, i * 3, 3, 3) = I_inv * skew_sym_mat(r_feet.col(i));\n B.block(9, i * 3, 3, 3) = eye3 * 1.0 / mass;\n }\n\n#ifdef MPC_PRINT_ALL\n std::cout << \"Rz:\" << std::endl;\n std::cout << Rz << std::endl;\n\n std::cout << \"I_body:\" << std::endl;\n std::cout << I_body << std::endl;\n\n std::cout << \"I_world:\" << std::endl;\n std::cout << I_world << std::endl;\n\n std::cout << \"I_inv:\" << std::endl;\n std::cout << I_inv << std::endl;\n\n std::cout << \"r_feet:\" << std::endl;\n std::cout << r_feet << std::endl;\n\n std::cout << \"A:\" << std::endl;\n std::cout << A << std::endl;\n\n std::cout << \"B:\" << std::endl;\n std::cout << B << std::endl;\n\n std::cout << \"A.exp()\" << std::endl;\n std::cout << A.exp() << std::endl;\n#endif\n}\n\n// Returns the discretized matrices for a given A and B matrix.\nvoid discrete_time_state_space(const double& dt, const Eigen::MatrixXd& A,\n const Eigen::MatrixXd& B, Eigen::MatrixXd& Adt,\n Eigen::MatrixXd& Bdt) {\n // p.215 Raymond DeCarlo: Linear Systems: A State Variable Approach with\n // Numerical Implementation, Prentice Hall, NJ, 1989\n int n = A.cols() + B.cols();\n Eigen::MatrixXd AB(n, n);\n Eigen::MatrixXd expAB(n, n);\n AB.setZero();\n AB.block(0, 0, A.cols(), A.cols()) = A;\n AB.block(0, A.cols(), A.cols(), B.cols()) = B;\n\n expAB = (AB * dt).exp();\n\n Adt = expAB.block(0, 0, A.cols(), A.cols());\n Bdt = expAB.block(0, A.cols(), A.cols(), B.cols());\n\n#ifdef MPC_PRINT_ALL\n std::cout << \"Adt\" << std::endl;\n std::cout << Adt << std::endl;\n\n std::cout << \"Bdt\" << std::endl;\n std::cout << Bdt * dt << std::endl;\n#endif\n}\n\n// Zero order hold qp matrices\nvoid qp_matrices(const int& horizon, const Eigen::MatrixXd& Adt,\n const Eigen::MatrixXd& Bdt, Eigen::MatrixXd& Aqp,\n Eigen::MatrixXd& Bqp) {\n if (horizon < 1) {\n std::cerr << \"Error! MPC horizon must be at least 1 timestep long.\"\n << std::endl;\n }\n\n int n = Adt.cols();\n int m = Bdt.cols();\n std::vector powerMats;\n for (int i = 0; i < horizon + 1; i++) {\n powerMats.push_back(Eigen::MatrixXd::Identity(n, n));\n }\n\n // Construct power matrices foe Adt\n for (int i = 1; i < horizon + 1; i++) {\n powerMats[i] = powerMats[i - 1] * Adt;\n }\n\n // Construct Aqp and Bqp matrices\n Aqp.setZero();\n Bqp.setZero();\n\n for (int i = 0; i < horizon; i++) {\n Aqp.block(i * n, 0, n, n) = powerMats[i + 1]; // Adt.pow(i+1);\n for (int j = 0; j < horizon; j++) {\n if (i >= j) {\n int a_num = i - j;\n Bqp.block(i * n, j * m, n, m) =\n powerMats[a_num] * Bdt; // Adt.pow(a_num)*Bdt;\n }\n }\n }\n\n // Print power matrices for Adt\n // for(int i = 0; i < horizon; i++){\n // \tstd::cout << \"powerMats[\" << i << \"]\" << std::endl;\n // \tstd::cout << powerMats[i] << std::endl;\n // }\n\n#ifdef MPC_PRINT_ALL\n std::cout << \"Aqp\" << std::endl;\n std::cout << Aqp << std::endl;\n\n std::cout << \"Bqp\" << std::endl;\n std::cout << Bqp << std::endl;\n#endif\n}\n\nvoid get_desired_x(const int& horizon, Eigen::VectorXd& X_ref) {\n Eigen::VectorXd x_des(13);\n\n x_des.setZero();\n x_des[0] = 0.0; // M_PI/8; //des roll orientation\n x_des[1] = 0.0; //-M_PI/8; //des pitch orientation\n x_des[2] = M_PI / 12; // Yaw orientation\n\n x_des[3] =\n -0.1; //;0.75; // Set desired z height to be 0.75m from the ground\n x_des[5] =\n 0.75; //;0.75; // Set desired z height to be 0.75m from the ground\n\n X_ref = Eigen::VectorXd(horizon * 13);\n X_ref.setZero();\n for (int i = 0; i < horizon; i++) {\n X_ref.segment(13 * i, 13) = x_des;\n // X_ref[13*i + 5] = x_des[5]; // Set constant desired z-height\n }\n\n#ifdef MPC_PRINT_ALL\n std::cout << \"X_ref \" << std::endl;\n std::cout << X_ref.transpose() << std::endl;\n#endif\n}\n\nvoid get_force_constraints(const int& n_Fr, Eigen::MatrixXd& CMat,\n Eigen::VectorXd& cvec) {\n // Unilateral constraints on the force vector\n // CMat * u + cvec >= 0\n double mu = 0.9; // coefficient of friction\n double fz_max = 500; // maximum z reaction force for one force vector.\n\n Eigen::MatrixXd cfmat(\n 6, 3); // the constraint matrix for a single force vector\n Eigen::VectorXd cfvec(\n 6); // the constraint vector for a single force vector\n\n cfmat.setZero();\n cfvec.setZero();\n\n // -mu*fz <= fx <= mu*fz\n cfmat(0, 0) = -1;\n cfmat(0, 2) = mu;\n cfmat(1, 0) = 1;\n cfmat(1, 2) = mu;\n\n // -mu*fz <= fy <= mu*fz\n cfmat(2, 1) = -1;\n cfmat(2, 2) = mu;\n cfmat(3, 1) = 1;\n cfmat(3, 2) = mu;\n\n // fz_min = 0.0 <= fz <= fz_max\n cfmat(4, 2) = -1.0;\n cfvec[4] = fz_max; // -fz + fz_max >= 0\n cfmat(5, 2) = 1.0;\n\n#ifdef MPC_PRINT_ALL\n\n std::cout << \"cfmat \" << std::endl;\n std::cout << cfmat << std::endl;\n\n std::cout << \"cfvec \" << std::endl;\n std::cout << cfvec << std::endl;\n#endif\n\n // Populate constraint matrix\n CMat.setZero();\n cvec.setZero();\n for (int i = 0; i < n_Fr; i++) {\n CMat.block(6 * i, 3 * i, 6, 3) = cfmat;\n cvec.segment(6 * i, 6) = cfvec;\n }\n\n#ifdef MPC_PRINT_ALL\n std::cout << \"CMat \" << std::endl;\n std::cout << CMat << std::endl;\n\n std::cout << \"cvec \" << std::endl;\n std::cout << cvec << std::endl;\n#endif\n}\n\nvoid get_qp_constraints(const int& horizon, const Eigen::MatrixXd& CMat,\n const Eigen::VectorXd& cvec, Eigen::MatrixXd& Cqp,\n Eigen::VectorXd& cvec_qp) {\n Cqp.setZero();\n cvec_qp.setZero();\n\n int num_rows = CMat.rows();\n int num_cols = CMat.cols();\n\n // Set the force constraints over the horizon\n // To DO: add 0 upperbound when reaction force should be 0.0 depending on\n // the gate cycle.\n for (int i = 0; i < horizon; i++) {\n Cqp.block(i * num_rows, i * num_cols, num_rows, num_cols) = CMat;\n cvec_qp.segment(i * num_rows, num_rows) = cvec;\n }\n\n#ifdef MPC_PRINT_ALL\n std::cout << \"Cqp\" << std::endl;\n std::cout << Cqp.rows() << \"x\" << Cqp.cols() << std::endl;\n std::cout << Cqp << std::endl;\n\n std::cout << \"cvec_qp\" << std::endl;\n std::cout << cvec_qp << std::endl;\n#endif\n}\n\nvoid get_qp_costs(const int& n, const int& m, const int& horizon,\n const Eigen::VectorXd& vecS_cost, const double& control_alpha,\n Eigen::MatrixXd& Sqp, Eigen::MatrixXd& Kqp) {\n Eigen::MatrixXd S_cost = vecS_cost.asDiagonal();\n Sqp.setZero();\n for (int i = 0; i < horizon; i++) {\n Sqp.block(n * i, n * i, n, n) = S_cost;\n }\n\n Kqp = control_alpha * Eigen::MatrixXd::Identity(m * horizon, m * horizon);\n\n#ifdef MPC_PRINT_ALL\n std::cout << \"S_cost\" << std::endl;\n std::cout << S_cost << std::endl;\n\n std::cout << \"Sqp\" << std::endl;\n std::cout << Sqp << std::endl;\n\n std::cout << \"Kqp\" << std::endl;\n std::cout << Kqp << std::endl;\n#endif\n}\n\nvoid solve_mpc_qp(const Eigen::MatrixXd& Aqp, const Eigen::MatrixXd& Bqp,\n const Eigen::VectorXd& X_ref, const Eigen::VectorXd& x0,\n const Eigen::MatrixXd& Sqp, const Eigen::MatrixXd& Kqp,\n const Eigen::MatrixXd& Cqp, const Eigen::VectorXd& cvec_qp,\n Eigen::VectorXd& f_vec_out) {\n#ifdef MPC_TIME_ALL\n std::chrono::high_resolution_clock::time_point t_qp_prep_start;\n std::chrono::high_resolution_clock::time_point t_qp_prep_end;\n double dur_qp_prep = 0.0;\n\n std::chrono::high_resolution_clock::time_point t_qp_mult_start;\n std::chrono::high_resolution_clock::time_point t_qp_mult_end;\n double dur_qp_mult = 0.0;\n\n t_qp_prep_start = std::chrono::high_resolution_clock::now();\n t_qp_mult_start = std::chrono::high_resolution_clock::now();\n#endif\n\n Eigen::MatrixXd H(Bqp.cols(), Bqp.cols());\n Eigen::VectorXd g_qp(Bqp.cols());\n\n // For some reason g_qp evaluates slow unless we do these operations first\n // std::cout << \"x0\" << x0.transpose() << std::endl;\n Eigen::MatrixXd BqpT = Bqp.transpose();\n Eigen::MatrixXd m1;\n m1.noalias() = BqpT * Sqp;\n Eigen::MatrixXd m2;\n m2.noalias() = 2.0 * m1;\n Eigen::VectorXd v1 = (Aqp * x0).eval() - X_ref;\n\n H = 2.0 * (m1 * Bqp + Kqp);\n g_qp.noalias() = m1 * v1;\n\n#ifdef MPC_TIME_ALL\n t_qp_mult_end = std::chrono::high_resolution_clock::now();\n#endif\n\n // std::cout << \"H\" << std::endl;\n // std::cout << H << std::endl;\n\n // std::cout << \"g\" << std::endl;\n // std::cout << g.transpose() << std::endl;\n\n // Quadprog matrices vectors\n GolDIdnani::GMatr G, CE, CI;\n GolDIdnani::GVect g0, ce0, ci0, x;\n int n_quadprog_ = 1;\n int p_quadprog_ = 0;\n int m_quadprog_ = 0;\n\n // Quadprog size setup\n n_quadprog_ = Bqp.cols(); // number of decision variables\n m_quadprog_ = 0; // number of equality constraints\n p_quadprog_ = cvec_qp.size(); // number of inequality constraints\n // (unilateral force constraints).\n\n // std::cout << \"n_quadprog_\" << n_quadprog_ << std::endl;\n // std::cout << \"p_quadprog_\" << p_quadprog_ << std::endl;\n\n f_vec_out.resize(n_quadprog_);\n\n x.resize(n_quadprog_); // Decision Variables\n // Objective\n G.resize(n_quadprog_, n_quadprog_);\n g0.resize(n_quadprog_);\n // Equality Constraints\n CE.resize(n_quadprog_, m_quadprog_);\n ce0.resize(m_quadprog_);\n // Inequality Constraints\n CI.resize(n_quadprog_, p_quadprog_);\n ci0.resize(p_quadprog_);\n\n // Solve the following QP:\n // min (1/2)*U^T*H*U + U^T*g\n // st. C*U <= cvec_qp\n // where U is the decision variable (vector of forces)\n\n // Populate G Cost Matrix\n // G = P\n for (int i = 0; i < n_quadprog_; i++) {\n for (int j = 0; j < n_quadprog_; j++) {\n G[i][j] = H(i, j);\n }\n }\n\n // Populate g0 cost vector\n for (int i = 0; i < n_quadprog_; i++) {\n g0[i] = g_qp[i];\n }\n\n // No equality constraints. So CE and ce0 are untouched.\n\n // Populate Inequality Constraint Matrix\n for (int i = 0; i < p_quadprog_; i++) {\n for (int j = 0; j < n_quadprog_; j++) {\n CI[j][i] = Cqp(i, j);\n }\n }\n\n // Populate Inequality Constraint Vector\n // ci0 = h_\n for (int i = 0; i < p_quadprog_; i++) {\n ci0[i] = cvec_qp[i];\n }\n\n#ifdef MPC_TIME_ALL\n\n t_qp_prep_end = std::chrono::high_resolution_clock::now();\n dur_qp_mult = std::chrono::duration_cast >(\n t_qp_mult_end - t_qp_mult_start)\n .count();\n dur_qp_prep = std::chrono::duration_cast >(\n t_qp_prep_end - t_qp_prep_start)\n .count();\n\n std::cout << \"QP mult took \" << dur_qp_mult << \" seconds.\" << std::endl;\n std::cout << \"QP mult rate \" << (1.0 / dur_qp_mult) << \" Hz\" << std::endl;\n std::cout << \"QP prep took \" << dur_qp_prep << \" seconds.\" << std::endl;\n std::cout << \"QP prep rate \" << (1.0 / dur_qp_prep) << \" Hz\" << std::endl;\n\n // Time the QP solve\n std::chrono::high_resolution_clock::time_point t_qp_solve_start;\n std::chrono::high_resolution_clock::time_point t_qp_solve_end;\n double dur_qp_solve = 0.0;\n\n // Start\n t_qp_solve_start = std::chrono::high_resolution_clock::now();\n#endif\n\n double qp_result = solve_quadprog(G, g0, CE, ce0, CI, ci0, x);\n\n#ifdef MPC_TIME_ALL\n // End\n t_qp_solve_end = std::chrono::high_resolution_clock::now();\n dur_qp_solve = std::chrono::duration_cast >(\n t_qp_solve_end - t_qp_solve_start)\n .count();\n#endif\n\n // Populate qd result from QP answer\n for (int i = 0; i < n_quadprog_; i++) {\n f_vec_out[i] = x[i];\n }\n // std::cout << \"qp_result = \" << qp_result << std::endl;\n // std::cout << \"f_vec_out = \" << f_vec_out.transpose() << std::endl;\n\n#ifdef MPC_TIME_ALL\n std::cout << \"QP took \" << dur_qp_solve << \" seconds.\" << std::endl;\n std::cout << \"QP rate \" << (1.0 / dur_qp_solve) << \" Hz\" << std::endl;\n#endif\n}\n\nvoid print_f_vec(int& horizon, int& n_Fr, const Eigen::VectorXd& f_vec_out) {\n for (int i = 0; i < horizon; i++) {\n std::cout << \"horizon:\" << i + 1 << std::endl;\n\n for (int j = 0; j < n_Fr; j++) {\n std::cout << \" f\" << j << \":\"\n << f_vec_out.segment(3 * i * n_Fr + 3 * j, 3).transpose()\n << std::endl;\n }\n }\n}\n\nvoid solve_mpc(const Eigen::VectorXd& x0, const Eigen::VectorXd& X_des,\n const Eigen::MatrixXd& r_feet, const double& robot_mass,\n const Eigen::MatrixXd& I_body, const int& horizon,\n const double& mpc_dt, Eigen::VectorXd& f_vec_out) {\n#ifdef MPC_TIME_ALL\n // Time the QP solve\n std::chrono::high_resolution_clock::time_point t_mat_setup_start;\n std::chrono::high_resolution_clock::time_point t_mat_setup_end;\n double dur_mat_setup = 0.0;\n // Start\n t_mat_setup_start = std::chrono::high_resolution_clock::now();\n#endif\n\n int n_Fr = r_feet.cols();\n\n // create continuous time state space matrices\n double psi_yaw = x0[2];\n Eigen::MatrixXd A(13, 13);\n A.setZero();\n Eigen::MatrixXd B(13, 3 * n_Fr);\n B.setZero();\n int n = A.cols();\n int m = B.cols();\n cont_time_state_space(robot_mass, I_body, psi_yaw, r_feet, A, B);\n\n // create discrete time state space matrices\n Eigen::MatrixXd Adt(n, n);\n Adt.setZero();\n Eigen::MatrixXd Bdt(n, m);\n Bdt.setZero();\n discrete_time_state_space(mpc_dt, A, B, Adt, Bdt);\n\n // create A and B QP matrices\n Eigen::MatrixXd Aqp(n * horizon, n);\n Aqp.setZero();\n Eigen::MatrixXd Bqp(n * horizon, m * horizon);\n Bqp.setZero();\n qp_matrices(horizon, Adt, Bdt, Aqp, Bqp);\n\n // create force constraint matrices and vectors\n Eigen::MatrixXd CMat(\n 6 * n_Fr,\n 3 * n_Fr); // the QP constraint matrix for n_Fr reaction forces\n Eigen::VectorXd cvec(\n 6 * n_Fr); // the constraint matrix for n_Fr reaction forces\n get_force_constraints(n_Fr, CMat, cvec);\n\n Eigen::MatrixXd Cqp(horizon * 6 * n_Fr, horizon * 3 * n_Fr);\n Eigen::VectorXd cvec_qp(horizon * 6 * n_Fr);\n get_qp_constraints(horizon, CMat, cvec, Cqp, cvec_qp);\n\n // Cost matrices (Values similar to cheetah 3)\n Eigen::MatrixXd Sqp(n * horizon, n * horizon);\n Eigen::MatrixXd Kqp(m * horizon, m * horizon);\n\n Eigen::VectorXd vecS_cost(n);\n // << th1, th2, th3, px, py, pz, w1, w2, w3, dpx, dpy,\n // dpz, g\n // vecS_cost << 0.25, 0.25, 10.0, 2.0, 2.0, 50.0, 0.05, 0.05, 0.30, 0.20,\n // 0.2, 0.10, 0.0;\n vecS_cost << 1.0, 1.0, 10.0, 2.0, 2.0, 50.0, 0.05, 0.05, 0.30, 0.20, 0.2,\n 0.10, 0.0;\n Eigen::MatrixXd S_cost = vecS_cost.asDiagonal();\n double control_alpha = 4e-5;\n get_qp_costs(n, m, horizon, vecS_cost, control_alpha, Sqp, Kqp);\n\n#ifdef MPC_TIME_ALL\n // End\n t_mat_setup_end = std::chrono::high_resolution_clock::now();\n dur_mat_setup = std::chrono::duration_cast >(\n t_mat_setup_end - t_mat_setup_start)\n .count();\n\n std::cout << \"QP matrices setup took \" << dur_mat_setup << \" seconds.\"\n << std::endl;\n std::cout << \"QP matrices setup rate \" << (1.0 / dur_mat_setup) << \" Hz\"\n << std::endl;\n\n std::cout << \"robot state x_cur:\" << x0.transpose() << std::endl;\n std::cout << \" x_des:\" << X_des.head(n).transpose() << std::endl;\n std::cout << \"horizon steps = \" << horizon\n << \", horizon_time = \" << horizon * mpc_dt << std::endl;\n#endif\n\n // Solve MPC\n solve_mpc_qp(Aqp, Bqp, X_des, x0, Sqp, Kqp, Cqp, cvec_qp, f_vec_out);\n}\n\nvoid simulate_mpc() {\n // System Params\n double robot_mass = 10; // kg mass of the robot\n Eigen::MatrixXd I_body =\n Eigen::MatrixXd::Identity(3, 3); // Body Inertia matrix\n I_body(0, 0) = 5;\n I_body(0, 1) = 2;\n I_body(1, 0) = 2;\n I_body(1, 1) = 5;\n I_body(2, 2) = 2.5;\n\n // starting robot state\n // Current reduced state of the robot\n // x = [Theta, p, omega, pdot, g] \\in \\mathbf{R}^13\n Eigen::VectorXd x0(13);\n x0.setZero();\n x0[2] = 0.0; // M_PI/24.0;; // Yaw orientation\n x0[3] = 0.0; // x translation error\n x0[4] = 0.0; // y translation error\n x0[5] = 0.75; // Height\n x0[12] = -9.81;\n\n // Feet Configuration\n // Set Foot contact locations\n Eigen::MatrixXd r_feet(3, 4); // Each column is a reaction force in x,y,z\n r_feet.setZero();\n double foot_length = 0.05; // 5cm distance between toe and heel\n double nominal_width = 0.1; // 10cm distance between left and right feet\n\n // Flat ground contact, z = 0.0\n // 2 Contact Configuration\n // // Right Foot\n // r_feet(0, 0) = 0.0; // x\n // r_feet(1, 0) = -nominal_width/2.0; //y\n // // Left Foot\n // r_feet(0, 1) = 0.0; // x\n // r_feet(1, 1) = nominal_width/2.0; //y\n\n // 4 Contact Configuration\n // Right Foot Front\n r_feet(0, 0) = foot_length / 2.0; // x\n r_feet(1, 0) = -nominal_width / 2.0; // y\n // Right Foot Back\n r_feet(0, 1) = -foot_length / 2.0; // x\n r_feet(1, 1) = -nominal_width / 2.0; // y\n // Left Foot Front\n r_feet(0, 2) = foot_length / 2.0; // x\n r_feet(1, 2) = nominal_width / 2.0; // y\n // Left Foot Back\n r_feet(0, 3) = -foot_length / 2.0; // x\n r_feet(1, 3) = nominal_width / 2.0; // y\n\n int horizon = 10;\n double mpc_dt = 0.025;\n\n int n_Fr = r_feet.cols(); // Number of contacts\n int n = 13;\n int m = 3 * n_Fr;\n\n Eigen::VectorXd f_vec_out(m * horizon);\n Eigen::MatrixXd f_Mat(3, n_Fr);\n f_Mat.setZero();\n\n // Get desired reference\n Eigen::VectorXd X_des(n * horizon);\n get_desired_x(horizon, X_des);\n\n // Solve the MPC\n solve_mpc(x0, X_des, r_feet, robot_mass, I_body, horizon, mpc_dt,\n f_vec_out);\n print_f_vec(horizon, n_Fr, f_vec_out);\n // Populate force output from 1 horizon.\n assemble_vec_to_matrix(3, n_Fr, f_vec_out.head(3 * n_Fr), f_Mat);\n\n // Simulate MPC for one time step\n double sim_dt = 1e-3;\n Eigen::VectorXd x_prev(n);\n x_prev = x0;\n Eigen::VectorXd x_next(n);\n x_next.setZero();\n integrate_robot_dynamics(sim_dt, x_prev, f_Mat, r_feet, robot_mass, I_body,\n x_next);\n\n // Simulate MPC for x seconds\n double total_sim_time = 7.0;\n int sim_steps = static_cast(total_sim_time / sim_dt);\n std::cout << \"sim_steps:\" << sim_steps << std::endl;\n\n double last_control_time = 0.0;\n double cur_time = 0.0;\n\n std::cout << \"x_start:\" << x0.transpose() << std::endl;\n Eigen::VectorXd f_cmd(12);\n f_cmd.setZero();\n\n bool print_for_plots = false;\n\n if (print_for_plots) {\n printf(\n \"t, r, p, y, x, y, z, wx, wy, wz, dx, dy, dz, f0x, f0y, f0z, f1x, \"\n \"f1y, f1z, f2x, f2y, f2z, f3x, f3y, f3z\\n\");\n }\n for (int i = 0; i < sim_steps; i++) {\n // Solve new MPC every mpc control tick\n if ((cur_time - last_control_time) > mpc_dt) {\n solve_mpc(x_prev, X_des, r_feet, robot_mass, I_body, horizon,\n mpc_dt, f_vec_out);\n assemble_vec_to_matrix(3, n_Fr, f_vec_out.head(3 * n_Fr), f_Mat);\n last_control_time = cur_time;\n f_cmd.head(m) = f_vec_out.head(m);\n\n if (!print_for_plots) {\n std::cout << \" Computed MPC Forces\" << std::endl;\n printf(\" f0:(%0.3f,%0.3f,%0.3f)\\n\", f_cmd[0], f_cmd[1],\n f_cmd[2]);\n printf(\" f1:(%0.3f,%0.3f,%0.3f)\\n\", f_cmd[3], f_cmd[4],\n f_cmd[5]);\n if (n_Fr > 2) {\n printf(\" f2:(%0.3f,%0.3f,%0.3f)\\n\", f_cmd[6], f_cmd[7],\n f_cmd[8]);\n printf(\" f3:(%0.3f,%0.3f,%0.3f)\\n\", f_cmd[9], f_cmd[10],\n f_cmd[11]);\n }\n }\n }\n\n // Integrate the robot dynamics\n integrate_robot_dynamics(sim_dt, x_prev, f_Mat, r_feet, robot_mass,\n I_body, x_next);\n // Update x\n x_prev = x_next;\n // Increment time\n cur_time += sim_dt;\n\n if (print_for_plots) {\n printf(\n \"%0.3f, %0.3f, %0.3f, %0.3f, %0.3f, %0.3f, %0.3f, %0.3f, \"\n \"%0.3f, %0.3f, %0.3f, %0.3f, %0.3f, %0.3f,%0.3f,%0.3f, \"\n \"%0.3f,%0.3f,%0.3f, %0.3f,%0.3f,%0.3f, %0.3f,%0.3f,%0.3f \\n\",\n cur_time, x_next[0], x_next[1], x_next[2], x_next[3], x_next[4],\n x_next[5], x_next[6], x_next[7], x_next[8], x_next[9],\n x_next[10], x_next[11], f_cmd[0], f_cmd[1], f_cmd[2], f_cmd[3],\n f_cmd[4], f_cmd[5], f_cmd[6], f_cmd[7], f_cmd[8], f_cmd[9],\n f_cmd[10], f_cmd[11]);\n } else {\n printf(\n \"t:%0.3f, (R,P,Y):(%0.3f, %0.3f, %0.3f), (x,y,z):(%0.3f, \"\n \"%0.3f, %0.3f), (wx, wy, wz):(%0.3f, %0.3f, %0.3f), (dx, dy, \"\n \"dz):(%0.3f, %0.3f, %0.3f) \\n\",\n cur_time, x_next[0], x_next[1], x_next[2], x_next[3], x_next[4],\n x_next[5], x_next[6], x_next[7], x_next[8], x_next[9],\n x_next[10], x_next[11]);\n }\n\n // std::cout << \" f:\" << f_vec_out.head(m).transpose() << std::endl;\n // for(int j = 0; j < n_Fr; j++){\n // std::cout << \" f\" << j << \":\" << f_vec_out.segment(3*j,\n // 3).transpose() << std::endl;\n // }\n // std::cout << \"cur_time:\" << cur_time << \" last_control_time:\" <<\n // last_control_time << std::endl;\n }\n std::cout << \"x_des\" << X_des.tail(n).transpose() << std::endl;\n}\n\nint main(int argc, char** argv) {\n simulate_mpc();\n return 0;\n}\n", "meta": {"hexsha": "07bc4ea3ae143e16a479bd50425cbb75e7451464", "size": 28939, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PnC/MPC/test_mpc.cpp", "max_stars_repo_name": "stevenjj/PnC", "max_stars_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-04T22:36:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-04T22:36:54.000Z", "max_issues_repo_path": "PnC/MPC/test_mpc.cpp", "max_issues_repo_name": "stevenjj/PnC", "max_issues_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PnC/MPC/test_mpc.cpp", "max_forks_repo_name": "stevenjj/PnC", "max_forks_repo_head_hexsha": "e1e417dbd507f174bb2661247cb4360b6ee0ada7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1664698937, "max_line_length": 80, "alphanum_fraction": 0.5547531014, "num_tokens": 9285, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037302939516, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6911513325621575}} {"text": "#ifndef HH_PRE_HPP_INCLUDED\n#define HH_PRE_HPP_INCLUDED\n\n#include \n#include \n#include \n#include \n\n//UNITS: sec, V, A, M\n\n//DECLARATIONS FOR HH_PRE_MODEL\n\nclass HH_PRE\n{\n private:\n const double pi = boost::math::constants::pi();\n double Cm = 1.0; // F/m^2 Specific capacitance\n //----Reversal potentials for Na, K, channels in mV\n double ENa = 50.0; // Reversal potential for Sodium currents in Volts\n double EK = -85.0; // Reversal potential for Potassium currents in Volts\n double ELeak = -81; // Reversal potential for Leak currents in Volts\n\n double GNa = 100; // Maximum conductance for Sodium channels S/m^2\n double GK = 36; // Maximum conductance for Potassium channels S/m^2\n double GLeak = 0.5; // Maximum conductance for Leak channels S/m^2\n\n public:\n double IExt = 0.0; //extern current in Amps\n double Area = 0.0;\n double Cap = 0.0;\n double V = 0.0; // Membrane voltage V\n /* NEURON class explicit constructor */\n HH_PRE( double Area_ = 500E-08): Area(Area_)\n {\n Cap = Cm * Area;\n };\n //---Equations for bouton Na Channel (Ref: Dominique Engel & Peter Jonas, 2005, Neuron)\n double alpha_Na_act(const double V);\n double beta_Na_act(const double V);\n double alpha_Na_inact(const double V);\n double beta_Na_inact(const double V);\n //---Equations for bouton K Channel (Ref: Dominique Engel & Peter Jonas, 2005, Neuron)\n double alpha_K_act(const double V);\n double beta_K_act(const double V);\n //---Declaration of the ODE solver\n template \n void operator() ( const State &x, Deriv &dxdt , const double t );\n};\n//Function declarations\n//------------- Na+ channels --- implimented from classical HH (1952)\ndouble HH_PRE::alpha_Na_act(const double V)\n{\n double a = 0.1;\n double b = 45;\n double c = 10;\n double val = (- a * ( (V + b) / (exp( -(V + b) / c ) - 1 ) ) );\n\n double A = 93.82;\n double B = -105;\n double C = 17;\n double VAL = (- A * ( (V + B) / (exp( -(V + B) / C ) - 1 ) ) );\n return (VAL);\n}\ndouble HH_PRE::beta_Na_act(const double V)\n{\n double a = 4;\n double b = 70;\n double c = 18;\n double val = ( a * ( exp( - (V + b) / c )) );\n\n double A = 0.168;\n double C = 23.27;\n double VAL = ( A * exp( - V / C ) );\n\n return (VAL);\n}\ndouble HH_PRE::alpha_Na_inact(const double V)\n{\n double val = 0.07 * exp( -( V + 70) /20 );\n\n double A = 0.0001;\n double C = 18.706;\n double VAL = ( A * exp( - (V + 0) / C ) );\n\n return (VAL);\n}\ndouble HH_PRE::beta_Na_inact(const double V)\n{\n double val = ( 1 / ( exp( - (V + 40) / 10) + 1) );\n\n double A = 6.6;\n double B = 17.6;\n double C = 13.3;\n double VAL = ( A / ( (exp( -(V + B) / C ) + 1 ) ) );\n\n return (VAL);\n}\n//--------K+ channel alpha & beta\ndouble HH_PRE::alpha_K_act(const double V)\n{\n double val = -0.01 * (V + 60) / ( exp( -(V + 60) / 10) - 1 );\n double VAL = -0.01 * (V + 55) / ( exp( -(V + 55) / 10) - 1 );\n return (VAL);\n};\ndouble HH_PRE::beta_K_act(const double V)\n{\n double val = 0.125 * exp (- (V + 70) / 80);\n double VAL = 0.125 * exp (- (V + 65) / 80);\n return (VAL);\n};\n//-------HH_PRE class ODE Function\n\ntemplate \nvoid HH_PRE::operator() ( const State &x, Deriv &dxdt , const double t )\n{\n //typename boost::range_iterator< const State >::type x_it = boost::begin( x_ );\n //typename boost::range_iterator< Deriv >::type dxdt_it = boost::begin( dxdt_ );\n\n dxdt[0] = ( alpha_Na_act(x[3]) * (1 - x[0]) ) - (beta_Na_act(x[3]) * x[0]); // Na activation\n dxdt[1] = ( alpha_Na_inact(x[3]) * (1 - x[1]) ) - (beta_Na_inact(x[3]) * x[1]); // Na inactivation\n dxdt[2] = ( alpha_K_act(x[3]) * (1 - x[2]) ) - (beta_K_act(x[3]) * x[2]); // K activation\n double INa = -(Area * GNa * pow(x[0],3) * x[1] * (x[3] - ENa) );\n double IK = -(Area * GK * pow(x[2],4) * (x[3] - EK) );\n double ILeak = -(Area * GLeak * (x[3] - ELeak) );\n dxdt[3] = (1/Cap) * (INa + IK + ILeak + (IExt * Area) );\n};\n\n#endif // HH_PRE_HPP_INCLUDED\n\n", "meta": {"hexsha": "97821f63849b83815ff675221acf7d87b1ec6f1f", "size": 4163, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/hh_pre_det_model.hpp", "max_stars_repo_name": "anupgp/astron", "max_stars_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/old/src/old/hh_pre_det_model.hpp", "max_issues_repo_name": "anupgp/astron", "max_issues_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/old/src/old/hh_pre_det_model.hpp", "max_forks_repo_name": "anupgp/astron", "max_forks_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0230769231, "max_line_length": 101, "alphanum_fraction": 0.5741052126, "num_tokens": 1418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037262250327, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.691151324297171}} {"text": "#include \"icp.h\"\n\n#include \n\n#include \n\nusing FloatType = double;\nusing IndexType = int64_t;\nusing EigenMatrix = Eigen::MatrixXd;\nusing EigenVector = Eigen::VectorXd;\n\n#include \"common/io.h\"\n#include \"common/kdtree.h\"\n#include \"common/debug.h\"\n#include \"svd.h\"\n\n// Custom struct for KD tree\nstruct Point : public Vec3 {\n Point() {}\n Point(const Vec3 &v, int index = -1) : Vec3(v), i(index) {}\n int i;\n};\n\n// Rodrigues rotation matrix\nEigenMatrix rodrigues(const EigenVector &w, const double theta) {\n const double c = std::cos(theta);\n const double s = std::sin(theta);\n\n const double wx = w(0);\n const double wy = w(1);\n const double wz = w(2);\n EigenMatrix K(3, 3);\n K << 0.0, -wz, wy, wz, 0.0, -wx, -wy, wx, 0.0;\n\n EigenMatrix I = EigenMatrix::Identity(3, 3);\n return I + K * s + (K * K) * (1.0 - c);\n}\n\n//! single point to point ICP step\nvoid point2pointICP_step(const std::vector &target, const std::vector &source, EigenMatrix *rotMat,\n EigenVector *trans) {\n // Construct Kd-tree to find closest points\n KDTree tree;\n tree.construct(target);\n\n // {{ NOT_IMPL_ERROR();\n\n // Match closest point pairs\n // Hint:\n // Construct here that two matrices X and P,\n // whose elements are positions of source vertices (X),\n // and those for closest points of the sources (P)\n const int nPoints = (int)source.size();\n EigenMatrix X(nPoints, 3);\n EigenMatrix P(nPoints, 3);\n for (int i = 0; i < nPoints; i++) {\n const Vec3 &v = source[i];\n const Vec3 u = tree.nearest(v);\n X.row(i) << v.x, v.y, v.z;\n P.row(i) << u.x, u.y, u.z;\n }\n\n // Subtract xMean, pMean from X, P\n // Hint:\n // Row-wise or column-wise mean (also sum, max, min etc.) of Eigen matrices\n // can be easily calculate using \"rowwise()\" or \"colwise()\".\n const EigenVector xMean = X.colwise().mean();\n const EigenVector pMean = P.colwise().mean();\n X.rowwise() -= xMean.transpose();\n P.rowwise() -= pMean.transpose();\n\n // Solve with SVD to obtain R\n // Hint:\n // An SVD method \"eigenSVD\" is already given in \"svd.h\".\n // See its arguments carefully when using it.\n const EigenMatrix M = P.transpose() * X;\n EigenMatrix U, V;\n EigenVector sigma;\n eigenSVD(M, U, sigma, V);\n const double detVU = (U * V.transpose()).determinant();\n\n // Revise sign of determinant\n EigenVector diagH(3);\n diagH << 1.0, 1.0, detVU;\n\n // Output\n // Hint:\n // Be careful that arguments for output matrices and vectors\n // are represented as \"pointers\". Therefore, you should insert\n // values for them with \"asterisk\" like \"*lhs = rhs\".\n *rotMat = U * diagH.asDiagonal() * V.transpose();\n *trans = pMean - (*rotMat) * xMean;\n\n // }}\n}\n\n//! single point to plane ICP step\nvoid point2planeICP_step(const std::vector &target, const std::vector &targetNorm,\n const std::vector &source, Eigen::MatrixXd *rotMat, Eigen::VectorXd *trans) {\n // Construct Kd-tree to find closest points\n std::vector points;\n for (int i = 0; i < (int)target.size(); i++) {\n points.emplace_back(target[i], i);\n }\n\n KDTree tree;\n tree.construct(points);\n\n // {{ NOT_IMPL_ERROR();\n\n // Construct linear system\n // Hint:\n // prepare matrix A and vector b\n // A is 6x6 matrix, and b is 6-D vector\n const int nPoints = (int)source.size();\n EigenMatrix A(6, 6);\n EigenVector b(6);\n A.setZero();\n b.setZero();\n for (int i = 0; i < nPoints; i++) {\n const Vec3 &x = source[i];\n const Point pt = tree.nearest(x);\n const Vec3 &p = Vec3(pt.x, pt.y, pt.z);\n const Vec3 &n = targetNorm[pt.i];\n const Vec3 x_cross_n = cross(x, n);\n EigenVector v(6);\n v << x_cross_n.x, x_cross_n.y, x_cross_n.z, n.x, n.y, n.z;\n A += v * v.transpose();\n b += v * (dot(n, p - x));\n }\n\n // Solve\n // Hint:\n // Use \"Eigen::PartialPivLU\" to solve the system\n Eigen::PartialPivLU lu(A);\n EigenVector u = lu.solve(b);\n\n // Substitute to instances a, t\n // Hint:\n // Eigen matrices and vectors can be initialized\n // with its elements by \"<<\" operator.\n EigenVector a(3);\n a << u(0), u(1), u(2);\n EigenVector t(3);\n t << u(3), u(4), u(5);\n\n // Reproduce rotation matrix\n // Hint:\n // Remember that vector \"a\" is the multiple of\n // the direction of rotation axis and\n // the degree of rotation angle.\n const double theta = a.norm();\n const EigenVector w = a / theta;\n *rotMat = rodrigues(w, theta);\n *trans = t;\n\n // }}\n}\n\nvoid rigidICP(const std::vector &target, const std::vector &targetNorm, std::vector &source,\n std::vector &sourceNorm, ICPMetric metric, int maxIters, double tolerance, bool verbose) {\n // Point-to-point ICP\n for (int it = 0; it < maxIters; it++) {\n Eigen::MatrixXd R(3, 3);\n Eigen::VectorXd t(3);\n switch (metric) {\n case ICPMetric::Point2Point:\n point2pointICP_step(target, source, &R, &t);\n break;\n\n case ICPMetric::Point2Plane:\n point2planeICP_step(target, targetNorm, source, &R, &t);\n break;\n\n default:\n throw std::runtime_error(\"Unknown ICP metric type!\");\n }\n\n // Apply rigid transformation\n for (int i = 0; i < (int)source.size(); i++) {\n Eigen::VectorXd v(3);\n v << source[i].x, source[i].y, source[i].z;\n Eigen::VectorXd u = R * v + t;\n source[i] = Vec3(u(0), u(1), u(2));\n\n Eigen::VectorXd n(3);\n n << sourceNorm[i].x, sourceNorm[i].y, sourceNorm[i].z;\n Eigen::VectorXd m = R * n;\n sourceNorm[i] = Vec3(m(0), m(1), m(2));\n }\n\n // Check current error\n const double error = t.norm() + (R - Eigen::MatrixXd::Identity(3, 3)).norm();\n\n // Report\n if (verbose) {\n printf(\"*** %d iteration ***\\n\", it + 1);\n printf(\"R = \\n\");\n std::cout << R << std::endl;\n printf(\"t = \\n\");\n std::cout << t << std::endl;\n printf(\"error = %f\\n\", error);\n printf(\"\\n\");\n }\n\n char outfile[256];\n sprintf(outfile, \"intermediate_%03d.off\", it);\n write_off(std::string(outfile), source, sourceNorm);\n\n if (error < tolerance) {\n break;\n }\n }\n}\n", "meta": {"hexsha": "ba76ac5a897a6485e6e4fe1bb0a7bdb03bfea1c7", "size": 6551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "_programs/cpp/src/icp/icp.cpp", "max_stars_repo_name": "tatsy/cpp-python-beginners", "max_stars_repo_head_hexsha": "66ee72571bda1f623f2032122fb9657d3776bce3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-23T12:35:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-23T12:35:56.000Z", "max_issues_repo_path": "_programs/cpp/src/icp/icp.cpp", "max_issues_repo_name": "tatsy/cpp-python-beginners", "max_issues_repo_head_hexsha": "66ee72571bda1f623f2032122fb9657d3776bce3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "_programs/cpp/src/icp/icp.cpp", "max_forks_repo_name": "tatsy/cpp-python-beginners", "max_forks_repo_head_hexsha": "66ee72571bda1f623f2032122fb9657d3776bce3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-10T10:20:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-20T09:04:47.000Z", "avg_line_length": 30.4697674419, "max_line_length": 111, "alphanum_fraction": 0.5660204549, "num_tokens": 1868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6911408099607699}} {"text": "/*\n utils.cxx\n\n Copyright (c) 2018 Guy Skinner\n\n This file is distributed under the terms of the MIT license.\n Please see the file 'LICENCE.txt' in the root directory\n or http://opensource.org/licenses/mit-license.php for information.\n*/\n\n#include \n#include \n\n#include \"utils.hxx\"\n\ndouble det3(ublas::matrix a) {\n /* Fast Determinant of 3x3 Matrix */\n double det = a(0,0)*(a(1,1)*a(2,2) - a(1,2)*a(2,1))\n - a(0,1)*(a(1,0)*a(2,2) - a(1,2)*a(2,0))\n + a(0,2)*(a(1,0)*a(2,1) - a(1,1)*a(2,0));\n return det;\n}\n\nublas::vector cross3(ublas::vector a,\n ublas::vector b) {\n\n /* Cross Product for Three-Dimensional Vectors */\n if (a.size() != 3 or b.size() != 3) {\n std::cout << \"Exit(1): Vector dimensions not compatible for cross product\\n\";\n exit(1);\n }\n ublas::vector c(3);\n c(0) = a(1)*b(2) - a(2)*b(1);\n c(1) = a(2)*b(0) - a(0)*b(2);\n c(2) = a(0)*b(1) - a(1)*b(0);\n return c;\n}\n\nublas::matrix inv3(ublas::matrix a) {\n\n /* Matrix Inversion for Three-Dimensional Vectors */\n ublas::matrix ia(a.size1(),a.size2());\n double det = det3(a);\n \n ia(0,0) = a(1,1)*a(2,2) - a(1,2)*a(2,1);\n ia(0,1) = a(0,2)*a(2,1) - a(0,1)*a(2,2);\n ia(0,2) = a(0,1)*a(1,2) - a(0,2)*a(1,1);\n \n ia(1,0) = a(1,2)*a(2,0) - a(1,0)*a(2,2);\n ia(1,1) = a(0,0)*a(2,2) - a(0,2)*a(2,0);\n ia(1,2) = a(0,2)*a(1,0) - a(0,0)*a(1,2);\n \n ia(2,0) = a(1,0)*a(2,1) - a(1,1)*a(2,0);\n ia(2,1) = a(0,1)*a(2,0) - a(0,0)*a(2,1);\n ia(2,2) = a(0,0)*a(1,1) - a(1,0)*a(0,1);\n \n return ia/det;\n}\n\nlong linear_search(const std::vector& vec,\n\t\t double a,\n\t\t double tol) {\n\n for (long i = 0; i < vec.size(); i++) {\n double value = fabs(vec[i] - a);\n if (value < tol) {\n return i;\n }\n }\n \n return vec.size();\n}\n\n//inline long product(ublas::vector vec) {\n// return boost::accumulate(vec,1,std::multiplies());\n//}\n", "meta": {"hexsha": "e11c1e43a26dc100587e29592259f14e4a39f7a9", "size": 1972, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/utils.cxx", "max_stars_repo_name": "gcgs1/cxx.sqs", "max_stars_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.cxx", "max_issues_repo_name": "gcgs1/cxx.sqs", "max_issues_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.cxx", "max_forks_repo_name": "gcgs1/cxx.sqs", "max_forks_repo_head_hexsha": "6b656a2f604385cb28ad4211c4d52ed992b459ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6103896104, "max_line_length": 81, "alphanum_fraction": 0.5385395538, "num_tokens": 834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6911407975017393}} {"text": "#include \"openbr/plugins/openbr_internal.h\"\n#include \"openbr/core/opencvutils.h\"\n#include \"openbr/core/eigenutils.h\"\n\n#include \n\n#include \n\nusing namespace Eigen;\nusing namespace cv;\n\nnamespace br\n{\n\nclass ShapeAxisRatioTransform : public UntrainableTransform\n{\n Q_OBJECT\n\n void project(const Template &src, Template &dst) const\n {\n dst = src;\n\n Mat indices;\n findNonZero(src,indices);\n\n dst.m() = Mat(1,1,CV_32FC1);\n\n if (indices.total() > 0) {\n MatrixXd data(indices.total(),2);\n\n for (size_t i=0; i(i).y;\n data(i,1) = indices.at(i).x;\n }\n\n MatrixXd centered = data.rowwise() - data.colwise().mean();\n MatrixXd cov = (centered.adjoint() * centered) / double(data.rows() - 1);\n\n SelfAdjointEigenSolver eSolver(cov);\n MatrixXd D = eSolver.eigenvalues();\n\n if (eSolver.info() == Success)\n dst.m().at(0,0) = D(0)/D(1);\n else\n dst.file.fte = true;\n } else {\n dst.file.fte = true;\n qWarning(\"No mask content for %s.\",qPrintable(src.file.baseName()));\n }\n }\n};\n\nBR_REGISTER(Transform, ShapeAxisRatioTransform)\n\n} // namespace br\n\n#include \"imgproc/shapeaxisratio.moc\"\n", "meta": {"hexsha": "31d561d6b2dfe64693b7850ad1a2e3d5ac15abab", "size": 1433, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "openbr/plugins/imgproc/shapeaxisratio.cpp", "max_stars_repo_name": "kassemitani/openbr", "max_stars_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2016-01-27T04:23:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-19T20:45:16.000Z", "max_issues_repo_path": "openbr/plugins/imgproc/shapeaxisratio.cpp", "max_issues_repo_name": "kassemitani/openbr", "max_issues_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-04-09T13:55:15.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-21T03:08:08.000Z", "max_forks_repo_path": "openbr/plugins/imgproc/shapeaxisratio.cpp", "max_forks_repo_name": "kassemitani/openbr", "max_forks_repo_head_hexsha": "7b453f7abc6f997839a858f4b7686bc5e21ef7b2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2016-01-27T13:07:47.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T17:19:18.000Z", "avg_line_length": 24.7068965517, "max_line_length": 85, "alphanum_fraction": 0.5764131193, "num_tokens": 362, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.901920681802153, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6911360898465019}} {"text": "/*\nCopyright (c) 2019, NVIDIA CORPORATION. All rights reserved.\n\nNVIDIA CORPORATION and its licensors retain all intellectual property\nand proprietary rights in and to this software, related documentation\nand any modifications thereto. Any use, reproduction, disclosure or\ndistribution of this software and related documentation without an express\nlicense agreement from NVIDIA CORPORATION is strictly prohibited.\n*/\n\n#include \"packages/pnp/gems/epnp/epnp.hpp\"\n\n#include \n\n#include \n#include \n\nnamespace isaac {\nnamespace pnp {\nnamespace epnp {\n\n// High-level function that implements the full EPnP pipeline\npnp::Status ComputeCameraPose(double focal_u, double focal_v, double principal_u,\n double principal_v, const Matrix3Xd& points3,\n const Matrix2Xd& points2, epnp::Result* result) {\n if (result == nullptr) {\n return pnp::Status::kErrorBadInputParams;\n }\n\n // Make sure focal lengths in pixels are non-zero.\n // There is no restriction on the principal point location.\n if (focal_u == 0 || focal_v == 0) {\n return pnp::Status::kErrorBadInputParams;\n }\n\n // At least 6 2D-3D point correspondences are required currently.\n // TODO: extend to 5 and 4 (requires complicated relinearization)\n if (points2.cols() != points3.cols() || points3.cols() < 6) {\n return pnp::Status::kErrorBadNumInputPoints;\n }\n\n // Compute control points in world coordinates. They represent a chosen 3D basis.\n constexpr double tol = 1e-3;\n result->ctl_points_world = ChooseBasis(points3, tol);\n\n // The dimensionality of the point cloud is the number of control points minus one because\n // the first control point is always the centroid.\n // Except when zero input points passed to ChooseBasis().\n result->input_dims = result->ctl_points_world.cols();\n if (result->input_dims) {\n result->input_dims--;\n }\n\n // Only planar and 3D input point cloud shapes are useful for camera pose estimation.\n if (result->input_dims < 2 || result->input_dims > 3) {\n return pnp::Status::kErrorDegenerateGeom;\n }\n\n // Compute barycentric coordinates of all input 3D points with respect to chosen basis.\n result->bary_coeffs = ComputeBaryCoords(points3, result->ctl_points_world);\n if (result->bary_coeffs.cols() == 0) {\n return pnp::Status::kErrorDegenerateGeom;\n }\n\n // Calculate space of the control point camera coordinates such that all\n // projection constraints are approximately satisified.\n if (!SolveProjConstraints(focal_u, focal_v, principal_u, principal_v, result->bary_coeffs,\n points2, &result->proj_coeffs, &result->solution_basis,\n &result->singular_values)) {\n return pnp::Status::kErrorDegenerateGeom;\n }\n\n // Precompute distances between control points in the world frame.\n VectorXd ctl_distances = ComputeDistances(result->ctl_points_world);\n\n // Construct calibration matrix needed for reprojections at residual calculation.\n Matrix3d calib_matrix;\n calib_matrix << focal_u, 0, principal_u, 0, focal_v, principal_v, 0, 0, 1;\n\n // Given the solution basis, solve for control point camera coordinates.\n // Solve for various possible dimensions of the solution space and retain\n // the resulting pose that has the least reprojection error.\n const int max_solution_dims = 3; // Only 1,2,3 are supported\n double min_rss_error = Inf;\n result->rss_repr_errors = VectorXd::Constant(max_solution_dims, Inf);\n for (int k = 0; k < max_solution_dims; k++) {\n const int sol_dims = k + 1;\n\n // Compute weights that describe the concrete solution in the solution space.\n Vector4d weights = SolveControlPoints(result->solution_basis, sol_dims, ctl_distances);\n if (weights == Vector4d::Zero()) {\n continue;\n }\n\n // Calculate control points in camera frame given the weights and the base vectors.\n Matrix3Xd ctl_points_cam = ReshapeToMatrix3xN(result->solution_basis * weights);\n\n // Compute rigid-body transform between control points in world and in camera frame.\n // The resulting transformation is the sought camera pose.\n Matrix3d rotation;\n Vector3d translation;\n if (!pnp::RegisterPointsEucl(result->ctl_points_world, ctl_points_cam, &rotation,\n &translation)) {\n continue;\n }\n\n // Compute squared reprojection errors of the input points, given the computed camera pose.\n VectorXd repr_errors = pnp::ColwiseSquaredNorms(\n points2 - pnp::EuclideanFromHomogeneous(calib_matrix *\n ((rotation * points3).colwise() + translation)));\n\n // Calculate reprojection Residual Sum of Squares (RSS).\n double rss_error = repr_errors.sum();\n result->rss_repr_errors(k) = rss_error;\n\n // Keep the best solution in terms of reprojection RSS.\n if (rss_error < min_rss_error) {\n min_rss_error = rss_error;\n result->ctl_points_cam = ctl_points_cam;\n result->rotation = rotation;\n result->translation = translation;\n result->solution_dims = sol_dims;\n }\n }\n\n // Solution could not be found with any dimensionality of the solution space.\n if (min_rss_error == Inf) {\n return pnp::Status::kErrorDegenerateGeom;\n }\n\n return pnp::Status::kSuccess;\n}\n\n// Choose a suitable 3D basis to represent the input 3D points in (via barycentric coordinates).\n// Principal Component Analysis of the 3D point cloud.\nMatrix3Xd ChooseBasis(const Matrix3Xd& points3, double tol) {\n // The output basis will be represented by a small set of 3D control points (up to 4).\n Matrix3Xd ctl_points;\n ctl_points.resize(3, 0);\n\n // At least 1 input point is required for further calculations to make sense.\n const int num_points = points3.cols();\n if (num_points < 1) {\n return ctl_points;\n }\n\n // Calculate centroid of the point cloud - requires at least 1 point.\n Vector3d centroid = points3.rowwise().sum() / num_points;\n\n // Center the point cloud - requires at least 1 point\n Matrix3Xd centered_points3 = points3;\n for (int i = 0; i < num_points; i++) {\n centered_points3.col(i) -= centroid;\n }\n\n // Compute principal components.\n // Singular values are sorted in decreasing order.\n Eigen::JacobiSVD svd;\n svd.compute(centered_points3, Eigen::ComputeFullU | Eigen::ComputeThinV);\n const VectorXd& singular_values = svd.singularValues();\n const MatrixXd& principal_directions = svd.matrixU();\n\n // Determine the number of non-vanishing principal components given a tolerance.\n int dims = 0;\n for (int i = 0; i < singular_values.rows(); i++) {\n if (singular_values(i) > tol) {\n dims++;\n }\n }\n\n // The output matrix is always of size 3-by-(dims+1) with the first column being the centroid\n // of the input point cloud.\n ctl_points = Matrix3Xd::Zero(3, dims + 1);\n ctl_points.col(0) = centroid;\n\n // Scale the other control points with respect to the centroid along the principal directions\n // such that their distance from the centroid equals the square root of the point variance.\n // This is only done for non-vanishing principal directions.\n const double factor = 1.0 / std::sqrt(static_cast(num_points));\n for (int i = 0; i < dims; i++) {\n ctl_points.col(i + 1) = principal_directions.col(i) * factor * singular_values(i) + centroid;\n }\n\n return ctl_points;\n}\n\n// Compute barycentric coords of points with respect to a basis defined by 3 or 4 control points.\n// Solves the linear problem A*X = B for X where:\n// B is the 4xN matrix of homogeneous 3D points (3xN matrix points3 extended by a row of 1's)\n// A is the 4x3 or 4x4 homogenenous matrix of control point coordinates,\n// X is the 3xN or 4xN matrix of barycentric coordinates.\n// Since the last columns of A and B are all 1's, the column sums of X are 1.\nMatrixXd ComputeBaryCoords(const Matrix3Xd& points3, const Matrix3Xd& ctl_points) {\n MatrixXd bary_coords;\n bary_coords.resize(ctl_points.cols(), 0);\n if (points3.cols() && (ctl_points.cols() == 3 || ctl_points.cols() == 4)) {\n Matrix4Xd basis = pnp::HomogeneousFromEuclidean(ctl_points);\n\n // Solve the problem A*X = B\n bary_coords = basis.householderQr().solve(pnp::HomogeneousFromEuclidean(points3));\n }\n return bary_coords;\n}\n\n// Solve the projection equations via Singular-Value Decomposition and\n// find the solution space of the control point camera coordinates.\nbool SolveProjConstraints(double focal_u, double focal_v, double principal_u, double principal_v,\n const MatrixXd& bary_coords, const Matrix2Xd points2,\n MatrixXd* proj_coeffs, MatrixXd* sol_basis, VectorXd* singular_values) {\n if (proj_coeffs == nullptr || sol_basis == nullptr || singular_values == nullptr) {\n return false;\n }\n\n proj_coeffs->resize(0, 0);\n\n // At least 6 input points are required, each generating 2 equations.\n int num_points = points2.cols();\n if (num_points < 6) {\n return false;\n }\n if (bary_coords.cols() != num_points) {\n return false;\n }\n\n // Focal lengths should be non-zero.\n if (focal_u == 0 || focal_v == 0) {\n return false;\n }\n\n // Shorthands to make it easier to visually verify projection coefficients below.\n const double fu = focal_u;\n const double fv = focal_v;\n const double uc = principal_u;\n const double vc = principal_v;\n\n // Non-planar case with 4 control points (12 unknowns)\n if (bary_coords.rows() == 4) {\n // Construct the 2Nx12 coefficient matrix\n proj_coeffs->resize(2 * num_points, 12);\n for (int i = 0; i < num_points; i++) {\n // Shorthands to make it easier to check coefficient matrix\n const double u = points2(0, i);\n const double v = points2(1, i);\n const double b1 = bary_coords(0, i);\n const double b2 = bary_coords(1, i);\n const double b3 = bary_coords(2, i);\n const double b4 = bary_coords(3, i);\n proj_coeffs->row(2 * i + 0) << b1 * fu, 0, b1 * (uc - u), b2 * fu, 0, b2 * (uc - u), b3 * fu,\n 0, b3 * (uc - u), b4 * fu, 0, b4 * (uc - u);\n proj_coeffs->row(2 * i + 1) << 0, b1 * fv, b1 * (vc - v), 0, b2 * fv, b2 * (vc - v), 0,\n b3 * fv, b3 * (vc - v), 0, b4 * fv, b4 * (vc - v);\n }\n\n // Planar case with 3 control points (9 unknowns)\n } else if (bary_coords.rows() == 3) {\n // Construct the 2Nx9 coefficient matrix\n proj_coeffs->resize(2 * num_points, 9);\n for (int i = 0; i < num_points; i++) {\n // Shorthands to make it easier to check coefficient matrix\n const double u = points2(0, i);\n const double v = points2(1, i);\n const double b1 = bary_coords(0, i);\n const double b2 = bary_coords(1, i);\n const double b3 = bary_coords(2, i);\n proj_coeffs->row(2 * i + 0) << b1 * fu, 0, b1 * (uc - u), b2 * fu, 0, b2 * (uc - u), b3 * fu,\n 0, b3 * (uc - u);\n proj_coeffs->row(2 * i + 1) << 0, b1 * fv, b1 * (vc - v), 0, b2 * fv, b2 * (vc - v), 0,\n b3 * fv, b3 * (vc - v);\n }\n\n // Cases that are not solved with the current implementation.\n } else {\n return false;\n }\n\n // Solve the homogeneous linear problem by SVD\n // Matrix V is 9x9 (planar case) or 12x12 (non-planar case)\n // There are 9 (planar case) or 12 singular values (non-planar case)\n Eigen::JacobiSVD svd;\n svd.compute(*proj_coeffs, Eigen::ComputeThinU | Eigen::ComputeFullV);\n *singular_values = svd.singularValues();\n const MatrixXd& singular_vectors = svd.matrixV();\n\n // Output the last 4 columns of V in reverse order\n sol_basis->resize(singular_vectors.rows(), 4);\n for (int i = 0; i < 4; i++) {\n sol_basis->col(i) = singular_vectors.col(singular_vectors.cols() - i - 1);\n }\n\n // Put singular values in increasing order\n for (int i = 0; i < singular_values->size() / 2; i++) {\n std::swap((*singular_values)(i), (*singular_values)(singular_values->size() - 1 - i));\n }\n\n return true;\n}\n\n// Convert a solution vector of control point coordinates of length 3*C to a 3xC matrix for C=3,4\n// such that the input vector contains the elements of the output matrix column-wise.\nMatrix3Xd ReshapeToMatrix3xN(const VectorXd& vec) {\n Matrix3Xd matrix;\n if (vec.size() % 3) {\n return matrix; // return a 3x0 matrix\n }\n matrix.resize(3, vec.size() / 3);\n for (int i = 0; i < matrix.cols(); i++) {\n matrix.col(i) = vec.block(3 * i, 0, 3, 1);\n }\n\n return matrix;\n}\n\n// Project points directly given in camera coordinates to the image\nMatrix2Xd ProjectPoints(const Matrix3d& calib_matrix, const Matrix3Xd& points3) {\n Matrix2Xd points2;\n points2.resize(2, points3.cols());\n for (int i = 0; i < points3.cols(); i++) {\n Vector3d proj = calib_matrix * points3.col(i);\n if (proj(2) == 0) {\n // Avoids NaNs due to 0/0.\n points2(0, i) = Inf;\n points2(1, i) = Inf;\n } else {\n // Division by homogeneous coordinate.\n points2(0, i) = proj(0) / proj(2);\n points2(1, i) = proj(1) / proj(2);\n }\n }\n return points2;\n}\n\n// Compute distances between all possible pairs (i,j) of input points (in matrix columns).\nVectorXd ComputeDistances(const MatrixXd& points) {\n int num_points = points.cols();\n if (num_points < 2) {\n return VectorXd(0);\n }\n\n VectorXd distances(num_points * (num_points - 1) / 2);\n int k = 0;\n for (int i = 0; i < points.cols(); i++) {\n for (int j = i + 1; j < points.cols(); j++) {\n distances[k++] = (points.col(i) - points.col(j)).norm();\n }\n }\n\n return distances;\n}\n\n// Compute the weights that correspond to a concrete solution for the control point camera\n// coordinates in the basis given as input.\nVector4d SolveControlPoints(const MatrixXd& sol_basis, int sol_dims, const VectorXd& distances) {\n Vector4d weights = Vector4d::Zero();\n if (sol_basis.cols() != 4) {\n return weights;\n }\n if (sol_basis.rows() != 12 && sol_basis.rows() != 9) {\n return weights;\n }\n\n // non-planar case\n if (sol_basis.rows() == 12 && distances.size() != 6) {\n return weights;\n }\n\n // planar case\n if (sol_basis.rows() == 9 && distances.size() != 3) {\n return weights;\n }\n\n // Planar and non-planar case for 1-dimensional solution space\n if (sol_dims == 1) {\n // Only use singular vector corresponding to the least singular value.\n // Solution space is 1-dimensional -> only need to find a single global scale.\n\n // Calculate the unscaled camera coordinates of the control points.\n Matrix3Xd v = ReshapeToMatrix3xN(sol_basis.col(0));\n\n // Calculate distances between the unscaled control points.\n VectorXd distances_cam = ComputeDistances(v);\n\n // Calculate the unknown scale from the distances between control points in the world frame\n // and the corresponding distances in the camera frame.\n double scale = distances.dot(distances_cam) / distances_cam.dot(distances_cam);\n\n // Find sign of the scale such that a majority of control points are in front of the camera.\n int num_points_behind = (v.row(2).array() < 0).count();\n if (num_points_behind > 1) {\n scale = -scale;\n }\n\n weights(0) = scale;\n\n // Planar and non-planar for 2-dimensional solution space\n } else if (sol_dims == 2) {\n // Reshape the two basis vectors of the solution space into two 3xN matrices.\n // The sought matrix ctl_points_cam is a linear combination of these matrices.\n // ctl_points_cam = w1*v1 + w2*v2, where the weights w1 and w2 are still unknown.\n Matrix3Xd v1 = ReshapeToMatrix3xN(sol_basis.col(0));\n Matrix3Xd v2 = ReshapeToMatrix3xN(sol_basis.col(1));\n\n // Looking for the linear combination preserving the distances between control points.\n // This is a non-linear problem in the linear combination weights (w1,w2).\n // Strategy:\n // (Step1) Solve for (w11,w22,w12) = (w1*w1, w2*w2, w1*w2) (linearized problem)\n // (Step2) Extract (w1,w2) from (w11,w22,w12).\n // Both steps are over-determined problems.\n\n // Construct coefficient matrix of linearized problem (see Eq.13 in the paper).\n // This matrix is 6x4 in the non-planar case.\n const int num_points = v1.cols();\n const int num_equations = num_points * (num_points - 1) / 2;\n int k = 0;\n MatrixXd coeff_matrix(num_equations, 3);\n for (int i = 0; i < num_points; i++) {\n for (int j = i + 1; j < num_points; j++) {\n Vector3d d1 = v1.col(i) - v1.col(j);\n Vector3d d2 = v2.col(i) - v2.col(j);\n coeff_matrix.row(k++) << d1.dot(d1), d2.dot(d2), 2 * d1.dot(d2);\n }\n }\n\n // Step1: Compute least squares solution to the linearized problem.\n VectorXd squared_distances = distances.cwiseProduct(distances);\n VectorXd lin_sol =\n coeff_matrix.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(squared_distances);\n\n // Solution of the linearized problem.\n const double w11 = lin_sol(0);\n const double w22 = lin_sol(1);\n const double w12 = lin_sol(2);\n\n // Step2: Calculate weights w1 and w2 (denoted beta_i in the EPnP paper)\n // from the non-linear constraints (w11,w22,w12) = (w1*w1, w2*w2, w1*w2).\n // There are always two solutions, (w1,w2) and (-w1,-w2) -> sign is solved further below.\n // Over-constrained quadratic problem - least-squares solution has no simple closed form.\n // Empirical tests show that solution order largely affects pose accuracy.\n // Strategy: we exactly match the larger magnitude wij and hope for less overall alg. error.\n double w1, w2;\n w1 = w2 = 0;\n if (w11 >= w22 && w11 > 0) {\n w1 = std::sqrt(w11);\n if (w22 > std::abs(w12)) {\n w2 = std::sqrt(w22);\n } else {\n w2 = w12 / w1;\n }\n } else if (w11 <= w22 && w22 > 0) {\n w2 = std::sqrt(w22);\n if (w11 > std::abs(w12)) {\n w1 = std::sqrt(w11);\n } else {\n w1 = w12 / w2;\n }\n }\n\n // There are always two solutions: (w1,w2) and (-w1,-w2) but\n // one corresponds to control points behind the camera.\n // Find sign such that a majority all control points are in front of the camera.\n VectorXd ctl_point_depths = w1 * v1.row(2) + w2 * v2.row(2);\n int num_points_behind = (ctl_point_depths.array() < 0).count();\n if (num_points_behind > int{num_points / 2}) {\n weights << -w1, -w2, 0, 0;\n } else {\n weights << w1, w2, 0, 0;\n }\n\n // Non-planar case for 2-dimensional solution space\n } else if (sol_dims == 3 && sol_basis.rows() == 12) {\n // Reshape the 3 basis vectors of the solution space into three 3xN matrices.\n // The sought matrix ctl_points_cam is a linear combination of these matrices.\n // ctl_points_cam = w1*v1 + w2*v2 + w3*v3, where the weights (w1,w2,w3) are still unknown.\n Matrix3Xd v1 = ReshapeToMatrix3xN(sol_basis.col(0));\n Matrix3Xd v2 = ReshapeToMatrix3xN(sol_basis.col(1));\n Matrix3Xd v3 = ReshapeToMatrix3xN(sol_basis.col(2));\n\n // Looking for the linear combination preserving the distances between control points.\n // This is a non-linear problem in the linear combination weights (w1,w2,w3).\n // Strategy:\n // (Step1) Solve for (w11,w22,w33,w12,w13,w23) = (w1*w1, w2*w2, w3*w3, w1*w2, w1*w3, w2*w3)\n // (linearized problem).\n // (Step2) Extract (w1,w2,w3) from (w11,w22,w33,w12,w13,w23).\n\n // Step1: Construct coefficient matrix of linearized problem (Case N=3 in the paper).\n // This matrix is 6x6 in the non-planar case.\n const int num_points = v1.cols();\n const int num_equations = num_points * (num_points - 1) / 2;\n int k = 0;\n MatrixXd coeff_matrix(num_equations, 6);\n for (int i = 0; i < num_points; i++) {\n for (int j = i + 1; j < num_points; j++) {\n Vector3d d1 = v1.col(i) - v1.col(j);\n Vector3d d2 = v2.col(i) - v2.col(j);\n Vector3d d3 = v3.col(i) - v3.col(j);\n coeff_matrix.row(k++) << d1.dot(d1), d2.dot(d2), d3.dot(d3), 2 * d1.dot(d2), 2 * d1.dot(d3),\n 2 * d2.dot(d3);\n }\n }\n\n // Step1: Compute least squares solution to the linearized problem.\n VectorXd squared_distances = distances.cwiseProduct(distances);\n VectorXd lin_sol =\n coeff_matrix.bdcSvd(Eigen::ComputeThinU | Eigen::ComputeThinV).solve(squared_distances);\n\n // Solution of the linearized problem.\n const double w11 = lin_sol(0);\n const double w22 = lin_sol(1);\n const double w33 = lin_sol(2);\n const double w12 = lin_sol(3);\n const double w13 = lin_sol(4);\n const double w23 = lin_sol(5);\n\n // Calculate weights w1, w2, w3 from the non-linear constraints\n // (w11, w22, w33, w12, w13, w23) = (w1*w1, w2*w2, w3*w3, w1*w2, w1*w3, w2*w3).\n // There are always two solutions (w1,w2,w3) and (-w1,-w2,-w3) -> sign solved further below.\n // Over-constrained quadratic problem - leats-squares solution has no simple closed form.\n // Empirical tests show that solution order largely affects pose accuracy.\n // Strategy: we exactly match the larger magnitude wij and hope for less overall alg. error.\n double w1 = 0, w2 = 0, w3 = 0;\n if (w11 > w22 && w11 > w33 && w11 > 0) {\n w1 = std::sqrt(w11);\n if (w22 > std::abs(w12)) {\n w2 = std::sqrt(w22);\n } else {\n w2 = w12 / w1;\n }\n if (w33 > std::abs(w13)) {\n w3 = std::sqrt(w33);\n } else {\n w3 = w13 / w1;\n }\n } else if (w22 > w11 && w22 > w33 && w22 > 0) {\n w2 = std::sqrt(w22);\n if (w11 > std::abs(w12)) {\n w1 = std::sqrt(w11);\n } else {\n w1 = w12 / w2;\n }\n if (w33 > std::abs(w23)) {\n w3 = std::sqrt(w33);\n } else {\n w3 = w23 / w2;\n }\n } else if (w33 > w11 && w33 > w22 && w33 > 0) {\n w3 = std::sqrt(w33);\n if (w11 > std::abs(w13)) {\n w1 = std::sqrt(w11);\n } else {\n w1 = w13 / w3;\n }\n if (w22 > std::abs(w23)) {\n w2 = std::sqrt(w22);\n } else {\n w2 = w23 / w3;\n }\n }\n\n // There are always two solutions: (w1,w2,w3) and (-w1,-w2,-w3) but\n // one corresponds to control points behind the camera.\n // Find sign such that a majority all control points are in front of the camera.\n VectorXd ctl_point_depths = w1 * v1.row(2) + w2 * v2.row(2) + w3 * v3.row(2);\n int num_points_behind = (ctl_point_depths.array() < 0).count();\n if (num_points_behind > int{num_points / 2}) {\n weights << -w1, -w2, -w3, 0;\n } else {\n weights << w1, w2, w3, 0;\n }\n }\n\n // TODO: planar N=3 case using relinearization\n // TODO: non-planar N=4 (affine camera) case using relinearization\n // planar N=4 case is underconstrained = ambiguous (3 equations but 4 unknowns)\n\n return weights;\n}\n\n} // namespace epnp\n} // namespace pnp\n} // namespace isaac\n", "meta": {"hexsha": "ac59b3cc1c92f0c6c5f537c0c8793d2e99a082a6", "size": 22583, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/packages/pnp/gems/epnp/epnp.cpp", "max_stars_repo_name": "ddr95070/RMIsaac", "max_stars_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdk/packages/pnp/gems/epnp/epnp.cpp", "max_issues_repo_name": "ddr95070/RMIsaac", "max_issues_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/packages/pnp/gems/epnp/epnp.cpp", "max_forks_repo_name": "ddr95070/RMIsaac", "max_forks_repo_head_hexsha": "ee3918f685f0a88563248ddea11d089581077973", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-01-28T16:37:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-28T16:37:51.000Z", "avg_line_length": 38.9362068966, "max_line_length": 100, "alphanum_fraction": 0.6520834256, "num_tokens": 6480, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6911360858061321}} {"text": "/**\n * TSAI 1999 Hand-eye calibration\n * Emanuele Ruffaldi 2016\n *\n * Copyright Scuola Superiore Sant'Anna (2016) \n * Emanuele Ruffaldi, e.ruffaldi@sssup.it\n */\n#pragma once\n\n#include \n#include \n#include \n\n\ntemplate \n using Vector3 = Eigen::Matrix;\n\ntemplate \n using Matrix3 = Eigen::Matrix;\n\ntemplate \n using Matrix4 = Eigen::Matrix;\n\n\n/**\n * Computes Tsai calibration: four frames\n *\t R = robot root\n * \t E = robot end-effector\n * C = camera\n * M = marker\n *\n * The objective is EC\n * We move E wrt R and keep R and M fixed each other\n */\n\nfloat calibrationTsai(const std::vector & cMm,\n const std::vector & rMe,\n Eigen::Matrix4f &eMc, bool computeResidual = false);\n\ndouble calibrationTsai(const std::vector & cMm,\n const std::vector & rMe,\n Eigen::Matrix4d &eMc, bool computeResidual = false);\n\n/*\n * These are internal functions used for testing the Tsai\n * They mainly deal with the specific Tsai parametrization of the vector that is more robust to small values than the regular one\n */\ntemplate \nEigen::Matrix paratsaiprime2paratsai(const Eigen::Matrix & a);\ntemplate \nEigen::Matrix paratsai2paratsaiprime(const Eigen::Matrix & a);\ntemplate \nEigen::Matrix paratsai2rot(const Eigen::Matrix & a);\ntemplate \nEigen::Quaternion paratsai2quat(const Eigen::Matrix & a);\ntemplate \nEigen::Matrix quat2paratsai(const Eigen::Quaternion & q);\ntemplate \nT paratsaiprime2theta(const Eigen::Matrix & x);\ntemplate \nT paratsai2theta(const Eigen::Matrix & x);\n\n\n/// returns the skew of the vector\ntemplate \ninline Matrix3 skewtsai(const Vector3 & a)\n{\n Matrix3 r;\n r << 0, -a(2), a(1), a(2),0,-a(0),-a(1),a(0),0;\n return r;\n}\n\n\ntemplate \nVector3 paratsaiprime2paratsai(const Vector3 & a)\n{\n return 2*a/sqrt(1+a.squaredNorm()); // equation 14\n}\n\ntemplate \nVector3 paratsai2paratsaiprime(const Vector3 & a)\n{\n return a/sqrt(4-a.squaredNorm());\n}\n\n/// converts the parametric in tsai form to rotation\n/// NO NEED OF TRIGONOMETRICS\n/// equation 10\ntemplate \nMatrix3 paratsai2rot(const Vector3 & a)\n{\n T sn = a.squaredNorm();\n T alpha = sqrt(4-sn);\n return (1-sn/2)*Matrix3::Identity() + 0.5*(a*a.transpose() + alpha * skewtsai(a));\n}\n\n/// converts the parametric in tsai form to rotation\n/// NO NEED OF TRIGONOMETRICS\n/// equation 9 modified NOT USED\ntemplate \nEigen::Quaternion paratsai2quat(const Vector3 & a)\n{\n double sinthetahalf = a.norm()/2; // 2 * sin(theta)/2 => sin(theta)/2\n return Eigen::Quaternion(sqrt(1-sinthetahalf*sinthetahalf),a.x()/2,a.y()/2,a.z()/2); // cos(theta/2)\n}\n\ntemplate \nT paratsai2theta(const Vector3 & x)\n{\n return 2*asin(x.norm()/2); // eq. 9 \n}\n", "meta": {"hexsha": "e0f51d168be926af96e961ac854ad0c902ca553e", "size": 3054, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tsai.hpp", "max_stars_repo_name": "eruffaldi/tsai_calib_eigen", "max_stars_repo_head_hexsha": "a0ea47e81740ff55ced287c77e526f36aa53131d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-12-15T03:19:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T07:15:11.000Z", "max_issues_repo_path": "tsai.hpp", "max_issues_repo_name": "eruffaldi/tsai_calib_eigen", "max_issues_repo_head_hexsha": "a0ea47e81740ff55ced287c77e526f36aa53131d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tsai.hpp", "max_forks_repo_name": "eruffaldi/tsai_calib_eigen", "max_forks_repo_head_hexsha": "a0ea47e81740ff55ced287c77e526f36aa53131d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-03-02T07:19:46.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T03:20:33.000Z", "avg_line_length": 27.2678571429, "max_line_length": 129, "alphanum_fraction": 0.6696136215, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6907862572904733}} {"text": "#include\n#include \n#include \n#include \n#include \n\nusing namespace std;\nEigen::MatrixXf pseudoinverse(Eigen::MatrixXf m)\n{\n //Eigen::Matrix m;\n // m<<0.68,0.597,-0.211, 0.823,0.566,-0.605;\n // m<<1,2,3,4,5,6;\n cout< svd =m.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);\n // Eigen::JacobiSVD svd(m, Eigen::ComputeThinU | Eigen::ComputeThinV); \n const Eigen::MatrixXf singularValues = svd.singularValues();\n\tEigen::Matrix singularValuesInv(m.cols(), m.rows());\n\tsingularValuesInv.setZero();\n\tdouble pinvtoler = 1.e-6; // choose your tolerance wisely\n\tfor (unsigned int i = 0; i < singularValues.size(); ++i) {\n\t \tif (singularValues(i) > pinvtoler)\n\t \t\tsingularValuesInv(i, i) = 1.0f / singularValues(i);\n\t \telse\n\t \t\tsingularValuesInv(i, i) = 0.f;\n\t }\n Eigen::MatrixXf pinvmat = svd.matrixV() * singularValuesInv * svd.matrixU().transpose();\n std::cout << pinvmat << std::endl;\n\treturn pinvmat;\n}\nint main(int argc, char **argv){\n Eigen::Matrix error;\n for(int i=0; i<6;i++)\n for (int j = 0; j < 1; j++)\n {\n error(i,j)=1;\n std::cout<ve;\n ve.push_back(1);\n ve.push_back(2);\n cout<arr={2,6,7.11,8.23};\n\n Eigen::Map>m2(arr.data());\n cout< name=Eigen::Matrix::Random();\n // Eigen::Matrix res;\n // for (int i = 0; i < res.rows(); i++)\n // {\n // for (int j = 0; j < res.cols(); j++)\n // {\n // res(i,j)=name(i,j);\n // }\n // }\n // cout< m2;\n// m2<<0.68,0.597,-0.211, 0.823,0.566,-0.605;\n// m2<<1,2,3,4,5,6;\n// cout<\n#include \n\n// QR decomposition using Gram-Schmit orthogonalization\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate bool qr(const ub::matrix& in, ub::matrix& q, ub::matrix& r)\n{\n\tint i, j, k;\n\tint n;\n\tub::vector v;\n\tT tmp;\n\n\tn = in.size1();\n\tif (n != in.size2()) return false;\n\n\tq.resize(n, n);\n\tr.resize(n, n);\n\tv.resize(n);\n\n\tfor (i=0; i\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nnamespace openOR {\n\tnamespace Math {\n\n\t\tstruct no_inverse_matrix_error : public std::runtime_error {\n\t\t\tno_inverse_matrix_error() : std::runtime_error(\"Could not get matrix inverse\") {\n\t\t\t\tLOG(Log::Level::Debug, Log::noAttribs, Log::msg(\"Exception thrown: Could not get matrix inverse\") );\n\t\t\t}\n\t\t};\n\n\t\tnamespace Impl {\n\n\t\t\ttemplate \n\t\t\tstruct Inverse {\n\t\t\t\tstatic Type get(const Type& mat) {\n\t\t\t\t\t// function has to be specialized\n\t\t\t\t\tBOOST_MPL_ASSERT((boost::is_same));\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\ttemplate \n\t\t\tstruct Inverse {\n\t\t\t\tstatic Type get(const Type& mat) {\n\t\t\t\t\tType matResult;\n\t\t\t\t\tMath::get<0, 0>(matResult) = Math::get<1, 1>(mat);\n\t\t\t\t\tMath::get<0, 1>(matResult) = -Math::get<0, 1>(mat);\n\t\t\t\t\tMath::get<1, 0>(matResult) = -Math::get<1, 0>(mat);\n\t\t\t\t\tMath::get<1, 1>(matResult) = Math::get<0, 0>(mat);\n\t\t\t\t\tmatResult /= Math::determinant(mat);\n\t\t\t\t\treturn matResult;\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\ttemplate \n\t\t\tstruct Inverse {\n\t\t\t\tstatic Type get(const Type& mat) {\n\t\t\t\t\tType matResult;\n\t\t\t\t\tMath::get<0, 0>(matResult) = Math::get<1, 1>(mat) * Math::get<2, 2>(mat) - Math::get<1, 2>(mat) * Math::get<2, 1>(mat);\n\t\t\t\t\tMath::get<0, 1>(matResult) = Math::get<0, 2>(mat) * Math::get<2, 1>(mat) - Math::get<0, 1>(mat) * Math::get<2, 2>(mat);\n\t\t\t\t\tMath::get<0, 2>(matResult) = Math::get<0, 1>(mat) * Math::get<1, 2>(mat) - Math::get<0, 2>(mat) * Math::get<1, 1>(mat);\n\n\t\t\t\t\tMath::get<1, 0>(matResult) = Math::get<1, 2>(mat) * Math::get<2, 0>(mat) - Math::get<1, 0>(mat) * Math::get<2, 2>(mat);\n\t\t\t\t\tMath::get<1, 1>(matResult) = Math::get<0, 0>(mat) * Math::get<2, 2>(mat) - Math::get<0, 2>(mat) * Math::get<2, 0>(mat);\n\t\t\t\t\tMath::get<1, 2>(matResult) = Math::get<0, 2>(mat) * Math::get<1, 0>(mat) - Math::get<0, 0>(mat) * Math::get<1, 2>(mat);\n\n\t\t\t\t\tMath::get<2, 0>(matResult) = Math::get<1, 0>(mat) * Math::get<2, 1>(mat) - Math::get<1, 1>(mat) * Math::get<2, 0>(mat);\n\t\t\t\t\tMath::get<2, 1>(matResult) = Math::get<0, 1>(mat) * Math::get<2, 0>(mat) - Math::get<0, 0>(mat) * Math::get<2, 1>(mat);\n\t\t\t\t\tMath::get<2, 2>(matResult) = Math::get<0, 0>(mat) * Math::get<1, 1>(mat) - Math::get<0, 1>(mat) * Math::get<1, 0>(mat);\n\n\t\t\t\t\tmatResult /= Math::determinant(mat);\n\t\t\t\t\treturn matResult;\n\t\t\t\t}\n\t\t\t};\n\n\n\t\t\ttemplate \n\t\t\tstruct Inverse {\n\t\t\t\tstatic Type get(const Type& mat) {\n\t\t\t\t\tType inverse;\n\n\t\t\t\t\tusing namespace boost::numeric::ublas;\n\t\t\t\t\ttypedef permutation_matrix pmatrix;\n\n\t\t\t\t\t// create a working copy of the input\n\t\t\t\t\tType A(mat);\n\n\t\t\t\t\t// create a permutation matrix for the LU-factorization\n\t\t\t\t\tpmatrix pm(A.size1());\n\n\t\t\t\t\t// perform LU-factorization\n\t\t\t\t\tint res = lu_factorize(A,pm);\n\t\t\t\t\tif( res != 0 ) { throw no_inverse_matrix_error(); }\n\n\t\t\t\t\t// create identity matrix of \"inverse\"\n\t\t\t\t\tinverse.assign( Math::MatrixTraits::IDENTITY );\n\n\t\t\t\t\t// backsubstitute to get the inverse\n\t\t\t\t\tlu_substitute(A, pm, inverse);\n\n\t\t\t\t\treturn inverse;\n\t\t\t\t}\n\t\t\t};\n\n\t\t}\n\t}\n}\n\n\n#endif\n", "meta": {"hexsha": "50f771664a88ad8f7c56ec2e4d02ffa5d4b254b7", "size": 3865, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/core/include/openOR/Math/detail/inverse_impl.hpp", "max_stars_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_stars_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/core/include/openOR/Math/detail/inverse_impl.hpp", "max_issues_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_issues_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/core/include/openOR/Math/detail/inverse_impl.hpp", "max_forks_repo_name": "avinfinity/UnmanagedCodeSnippets", "max_forks_repo_head_hexsha": "2bd848db88d7b271209ad30017c8f62307319be3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7542372881, "max_line_length": 124, "alphanum_fraction": 0.579301423, "num_tokens": 1270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7634837527911057, "lm_q1q2_score": 0.6906859855033097}} {"text": "#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::FT FT;\ntypedef K::Weighted_point_2 Weighted_point;\n\ntypedef CGAL::Regular_triangulation_2 Triangulation;\n\ntypedef boost::graph_traits::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits::vertex_iterator vertex_iterator;\ntypedef boost::graph_traits::edge_descriptor edge_descriptor;\n\ntemplate \nstruct Compute_edge_weight\n{\n const T& t_;\n\n Compute_edge_weight(const T& t) : t_(t) { }\n\n typedef typename boost::graph_traits::vertex_descriptor vertex_descriptor;\n typedef typename boost::graph_traits::edge_descriptor edge_descriptor;\n\n FT operator()(const edge_descriptor ed) const {\n vertex_descriptor svd = source(ed, t_);\n vertex_descriptor tvd = target(ed, t_);\n typename T::Vertex_handle sv = svd;\n typename T::Vertex_handle tv = tvd;\n return CGAL::power_product(sv->point(), tv->point());\n }\n};\n\n// The BGL makes use of indices associated to the vertices\n// We use a std::map to store the index\ntypedef std::map VertexIndexMap;\n\n// A std::map is not a property map, because it is not lightweight\ntypedef boost::associative_property_map VertexIdPropertyMap;\n\nint main(int argc,char* argv[])\n{\n const char* filename = (argc > 1) ? argv[1] : \"data/weighted_points.xyw\";\n std::ifstream input(filename);\n Triangulation tr;\n\n Weighted_point wp;\n while(input >> wp)\n tr.insert(wp);\n\n // Note that with the input \"data/weighted_points.xyw\", there is one hidden vertex\n std::cout << \"number of hidden vertices: \" << tr.number_of_hidden_vertices() << std::endl;\n\n // Associate indices to the vertices\n VertexIndexMap vertex_id_map;\n VertexIdPropertyMap vertex_index_pmap(vertex_id_map);\n int index = 0;\n\n for(vertex_descriptor vd : vertices(tr))\n vertex_id_map[vd]= index++;\n\n // We use a custom edge length property map that computes the power distance\n // between the extremities of an edge of the regular triangulation\n typedef Compute_edge_weight Edge_weight_functor;\n\n // In the function call you can see a named parameter: vertex_index_map\n std::list mst;\n boost::kruskal_minimum_spanning_tree(tr, std::back_inserter(mst),\n vertex_index_map(vertex_index_pmap)\n .weight_map(CGAL::internal::boost_::make_function_property_map<\n edge_descriptor, FT, Edge_weight_functor>(Edge_weight_functor(tr))));\n\n std::cout << \"The edges of the Euclidean mimimum spanning tree:\" << std::endl;\n for(edge_descriptor ed : mst)\n {\n vertex_descriptor svd = source(ed, tr);\n vertex_descriptor tvd = target(ed, tr);\n Triangulation::Vertex_handle sv = svd;\n Triangulation::Vertex_handle tv = tvd;\n std::cout << \"[ \" << sv->point() << \" | \" << tv->point() << \" ] \" << std::endl;\n }\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "40f9af43377274fedeb3c71efe1a66c0bce26bd9", "size": 3456, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/examples/BGL_triangulation_2/emst_regular.cpp", "max_stars_repo_name": "josuehfa/DAASystem", "max_stars_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T01:13:02.000Z", "max_issues_repo_path": "CoreSystem/lib/CGAL/examples/BGL_triangulation_2/emst_regular.cpp", "max_issues_repo_name": "josuehfa/DAASystem", "max_issues_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoreSystem/lib/CGAL/examples/BGL_triangulation_2/emst_regular.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 37.1612903226, "max_line_length": 111, "alphanum_fraction": 0.6996527778, "num_tokens": 811, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009503523291, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6906724490098937}} {"text": "/**\n * \\file Chebyshev1Filter.hxx\n */\n\n#include \n#include \n\n#include \n#include \n\nnamespace Chebyshev1Utilities\n{\n template\n void create_chebyshev1_analog_coefficients(int order, DataType ripple, EQUtilities::ZPK& zpk)\n {\n zpk.z.clear(); // no zeros for this filter type\n zpk.p.clear();\n if(ripple == 0)\n {\n return;\n }\n if(order == 0)\n {\n zpk.k = static_cast(std::pow(10, (-ripple / 20)));\n return;\n }\n \n DataType eps = static_cast(std::sqrt(std::pow(10, (0.1 * ripple)) - 1.0));\n DataType mu = static_cast(1.0 / order * boost::math::asinh(1 / eps));\n \n for(gsl::index i = -order+1; i < order; i += 2)\n {\n DataType theta = boost::math::constants::pi() * i / (2*order);\n zpk.p.push_back(-std::sinh(std::complex(mu, theta)));\n }\n\n std::complex f = 1;\n \n for(gsl::index i = 0; i < zpk.p.size(); ++i)\n {\n f *= -zpk.p[i];\n }\n zpk.k = f.real();\n if(order % 2 == 0)\n {\n zpk.k = zpk.k / std::sqrt(1 + eps * eps);\n }\n }\n \n template\n void create_default_chebyshev1_coeffs(size_t order, DataType ripple, DataType Wn, Container& coefficients_in, Container& coefficients_out)\n {\n EQUtilities::ZPK zpk;\n\n int fs = 2;\n create_chebyshev1_analog_coefficients(static_cast(order), ripple, zpk);\n EQUtilities::populate_lp_coeffs(Wn, fs, order, zpk, coefficients_in, coefficients_out);\n }\n \n template\n void create_bp_chebyshev1_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, Container& coefficients_in, Container& coefficients_out)\n {\n EQUtilities::ZPK zpk;\n\n int fs = 2;\n create_chebyshev1_analog_coefficients(static_cast(order/2), ripple, zpk);\n EQUtilities::populate_bp_coeffs(wc1, wc2, fs, order, zpk, coefficients_in, coefficients_out);\n }\n \n template\n void create_bs_chebyshev1_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, Container& coefficients_in, Container& coefficients_out)\n {\n EQUtilities::ZPK zpk;\n\n int fs = 2;\n create_chebyshev1_analog_coefficients(static_cast(order/2), ripple, zpk);\n EQUtilities::populate_bs_coeffs(wc1, wc2, fs, order, zpk, coefficients_in, coefficients_out);\n }\n}\n\nnamespace ATK\n{\n template \n Chebyshev1LowPassCoefficients::Chebyshev1LowPassCoefficients(gsl::index nb_channels)\n :Parent(nb_channels, nb_channels)\n {\n }\n \n template \n void Chebyshev1LowPassCoefficients::set_ripple(CoeffDataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev1LowPassCoefficients::CoeffDataType Chebyshev1LowPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n \n template \n void Chebyshev1LowPassCoefficients::set_cut_frequency(CoeffDataType cut_frequency)\n {\n if(cut_frequency <= 0)\n {\n throw std::out_of_range(\"Frequency can't be negative\");\n }\n this->cut_frequency = cut_frequency;\n setup();\n }\n \n template \n typename Chebyshev1LowPassCoefficients::CoeffDataType Chebyshev1LowPassCoefficients::get_cut_frequency() const\n {\n return cut_frequency;\n }\n \n template \n void Chebyshev1LowPassCoefficients::set_order(unsigned int order)\n {\n if(order == 0)\n {\n throw std::out_of_range(\"Order can't be null\");\n }\n in_order = out_order = order;\n setup();\n }\n \n template \n unsigned int Chebyshev1LowPassCoefficients::get_order() const\n {\n return in_order;\n }\n\n template \n void Chebyshev1LowPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n Chebyshev1Utilities::create_default_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template \n Chebyshev1HighPassCoefficients::Chebyshev1HighPassCoefficients(gsl::index nb_channels)\n :Parent(nb_channels, nb_channels)\n {\n }\n \n template \n void Chebyshev1HighPassCoefficients::set_cut_frequency(CoeffDataType cut_frequency)\n {\n if(cut_frequency <= 0)\n {\n throw std::out_of_range(\"Frequency can't be negative\");\n }\n this->cut_frequency = cut_frequency;\n setup();\n }\n \n template \n typename Chebyshev1HighPassCoefficients::CoeffDataType Chebyshev1HighPassCoefficients::get_cut_frequency() const\n {\n return cut_frequency;\n }\n \n template \n void Chebyshev1HighPassCoefficients::set_ripple(CoeffDataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev1HighPassCoefficients::CoeffDataType Chebyshev1HighPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n\n template \n void Chebyshev1HighPassCoefficients::set_order(unsigned int order)\n {\n if(order == 0)\n {\n throw std::out_of_range(\"Order can't be null\");\n }\n in_order = out_order = order;\n setup();\n }\n \n template \n unsigned int Chebyshev1HighPassCoefficients::get_order() const\n {\n return in_order;\n }\n\n template \n void Chebyshev1HighPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n Chebyshev1Utilities::create_default_chebyshev1_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);\n for(gsl::index i = in_order - 1; i >= 0; i -= 2)\n {\n coefficients_in[i] = - coefficients_in[i];\n coefficients_out[i] = - coefficients_out[i];\n }\n }\n \n template \n Chebyshev1BandPassCoefficients::Chebyshev1BandPassCoefficients(gsl::index nb_channels)\n :Parent(nb_channels, nb_channels)\n {\n }\n \n template \n void Chebyshev1BandPassCoefficients::set_cut_frequencies(std::pair cut_frequencies)\n {\n if(cut_frequencies.first <= 0 || cut_frequencies.second <= 0)\n {\n throw std::out_of_range(\"Frequencies can't be negative\");\n }\n this->cut_frequencies = cut_frequencies;\n setup();\n }\n \n template \n void Chebyshev1BandPassCoefficients::set_cut_frequencies(CoeffDataType f0, CoeffDataType f1)\n {\n set_cut_frequencies(std::make_pair(f0, f1));\n }\n \n template \n std::pair::CoeffDataType, typename Chebyshev1BandPassCoefficients::CoeffDataType> Chebyshev1BandPassCoefficients::get_cut_frequencies() const\n {\n return cut_frequencies;\n }\n \n template \n void Chebyshev1BandPassCoefficients::set_ripple(CoeffDataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev1BandPassCoefficients::CoeffDataType Chebyshev1BandPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n\n template \n void Chebyshev1BandPassCoefficients::set_order(unsigned int order)\n {\n if(order == 0)\n {\n throw std::out_of_range(\"Order can't be null\");\n }\n in_order = out_order = 2 * order;\n setup();\n }\n \n template \n unsigned int Chebyshev1BandPassCoefficients::get_order() const\n {\n return in_order / 2;\n }\n\n template \n void Chebyshev1BandPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n Chebyshev1Utilities::create_bp_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template \n Chebyshev1BandStopCoefficients::Chebyshev1BandStopCoefficients(gsl::index nb_channels)\n :Parent(nb_channels, nb_channels)\n {\n }\n \n template \n void Chebyshev1BandStopCoefficients::set_cut_frequencies(std::pair cut_frequencies)\n {\n if(cut_frequencies.first <= 0 || cut_frequencies.second <= 0)\n {\n throw std::out_of_range(\"Frequencies can't be negative\");\n }\n this->cut_frequencies = cut_frequencies;\n setup();\n }\n \n template \n void Chebyshev1BandStopCoefficients::set_cut_frequencies(CoeffDataType f0, CoeffDataType f1)\n {\n set_cut_frequencies(std::make_pair(f0, f1));\n }\n \n template \n std::pair::CoeffDataType, typename Chebyshev1BandStopCoefficients::CoeffDataType> Chebyshev1BandStopCoefficients::get_cut_frequencies() const\n {\n return cut_frequencies;\n }\n \n template \n void Chebyshev1BandStopCoefficients::set_ripple(CoeffDataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev1BandStopCoefficients::CoeffDataType Chebyshev1BandStopCoefficients::get_ripple() const\n {\n return ripple;\n }\n\n template \n void Chebyshev1BandStopCoefficients::set_order(unsigned int order)\n {\n if(order == 0)\n {\n throw std::out_of_range(\"Order can't be null\");\n }\n in_order = out_order = 2 * order;\n setup();\n }\n \n template \n unsigned int Chebyshev1BandStopCoefficients::get_order() const\n {\n return in_order / 2;\n }\n\n template \n void Chebyshev1BandStopCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n Chebyshev1Utilities::create_bs_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n }\n}\n", "meta": {"hexsha": "3c973c244f7fcbf255a032cd32ded3ddde0afde8", "size": 10729, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ATK/EQ/Chebyshev1Filter.hxx", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/EQ/Chebyshev1Filter.hxx", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/EQ/Chebyshev1Filter.hxx", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 30.4801136364, "max_line_length": 216, "alphanum_fraction": 0.7222481126, "num_tokens": 2916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.690672432334221}} {"text": "#ifndef CONSTANTS_HPP_\n#define CONSTANTS_HPP_\n\n#include \n#include \n#include // constant::i\n#include // constant::omega\n#include // constant::omega\n\nnamespace constant {\n\ntemplate T alladi_grinstead() {\n\tT c = 0, last;\n\n\tfor(std::size_t n = 1; n == 1 || c != last; ++n) {\n\t\tlast = c;\n\t\tc += (boost::math::zeta(n + 1) - 1) / n;\n\t}\n\n\tstatic const T ALLADI_GRINSTEAD = exp(c - 1);\n\treturn ALLADI_GRINSTEAD;\n}\n\ntemplate T aperys() {\n\tstatic const T APERYS = boost::math::constants::zeta_three();\n\treturn APERYS;\n}\n\ntemplate T buffons() {\n\tstatic const T BUFFONS = 2 / boost::math::constants::pi();\n\treturn BUFFONS;\n}\n\ntemplate T catalans() {\n\tstatic const T PI_SQR = boost::math::constants::pi_sqr(),\n\t\tCATALANS = 0.125 * (boost::math::trigamma(0.25) - PI_SQR);\n\treturn CATALANS;\n}\n\ntemplate T delian() {\n\tstatic const T DELIAN = boost::math::cbrt(2);\n\treturn DELIAN;\n}\n\ntemplate T e() {\n\tstatic const T E = boost::math::constants::e();\n\treturn E;\n}\n\ntemplate T erdos_borwein() {\n\tT e = 0, last;\n\n\tfor(std::size_t n = 1; n == 1 || e != last; ++n) {\n\t\tlast = e;\n\t\te += 1 / (exp2(static_cast(n)) - 1);\n\t}\n\n\tstatic const T ERDOS_BORWEIN = e;\n\treturn ERDOS_BORWEIN;\n}\n\ntemplate T euler_mascheroni() {\n\tstatic const T EULER_MASCHERONI = boost::math::constants::euler();\n\treturn EULER_MASCHERONI;\n}\n\ntemplate T gauss() {\n\tstatic const T ROOT_TWO = boost::math::constants::root_two(),\n\t\tPI = boost::math::constants::pi(),\n\t\tGAUSS = pow(boost::math::tgamma(0.25), 2)\n\t\t\t/ (2 * ROOT_TWO * pow(PI, static_cast(1.5)));\n\treturn GAUSS;\n}\n\ntemplate T gelfond_schneider() {\n\tstatic const T ROOT_TWO = boost::math::constants::root_two(),\n\t\tGELFOND_SCHNEIDER = exp2(ROOT_TWO);\n\treturn GELFOND_SCHNEIDER;\n}\n\ntemplate T gelfonds() {\n\tstatic const T GELFONDS = boost::math::constants::e_pow_pi();\n\treturn GELFONDS;\n}\n\ntemplate T giesekings() {\n\tstatic const T ROOT_THREE = boost::math::constants::root_three(),\n\t\tGIESEKINGS = (9 - boost::math::trigamma(2 / static_cast(3))\n\t\t\t+ boost::math::trigamma(4 / static_cast(3)))\n\t\t\t/ (4 * ROOT_THREE);\n\treturn GIESEKINGS;\n}\n\ntemplate T glaisher_kinkelin() {\n\tstatic const T GLAISHER_KINKELIN = boost::math::constants::glaisher();\n\treturn GLAISHER_KINKELIN;\n}\n\ntemplate T golden_ratio() {\n\tstatic const T GOLDEN_RATIO = boost::math::constants::phi();\n\treturn GOLDEN_RATIO;\n}\n\ntemplate std::complex i() {\n\tstatic const std::complex I(0, 1);\n\treturn I;\n}\n\ntemplate T inverse_golden_ratio() {\n\tstatic const T INVERSE_GOLDEN_RATIO = boost::math::constants::phi() - 1;\n\treturn INVERSE_GOLDEN_RATIO;\n}\n\ntemplate T khinchin() {\n\tstatic const T KHINCHIN = boost::math::constants::khinchin();\n\treturn KHINCHIN;\n}\n\n// Not Levy constant\ntemplate T khinchin_levy() {\n\tstatic const T PI_SQR = boost::math::constants::pi_sqr(),\n\t\tLN_TWO = boost::math::constants::ln_two(),\n\t\tKHINCHIN_LEVY = PI_SQR / (12 * LN_TWO);\n\treturn KHINCHIN_LEVY;\n}\n\n// Not Glaisher-Kinkelin constant\ntemplate T kinkelin() {\n\tstatic const T GLAISHER_KINKELIN = boost::math::constants::glaisher(),\n\t\tKINKELIN = 1 / static_cast(12) - log(GLAISHER_KINKELIN);\n\treturn KINKELIN;\n}\n\ntemplate T knuth() {\n\tstatic const T ROOT_THREE = boost::math::constants::root_three(),\n\t\tKNUTH = (1 - (1 / ROOT_THREE)) / 2;\n\treturn KNUTH;\n}\n\ntemplate T levys() {\n\tstatic const T PI_SQR = boost::math::constants::pi_sqr(),\n\t\tLN_TWO = boost::math::constants::ln_two(),\n\t\tLEVYS = exp(PI_SQR / (12 * LN_TWO));\n\treturn LEVYS;\n}\n\ntemplate T liebs() {\n\tstatic const T ROOT_THREE = boost::math::constants::root_three(),\n\t\tLIEBS = (8 * ROOT_THREE) / 9;\n\treturn LIEBS;\n}\n\ntemplate T lochs() {\n\tstatic const T LN_TWO = boost::math::constants::ln_two(),\n\t\tLN_TEN = boost::math::constants::ln_ten(),\n\t\tPI_SQR = boost::math::constants::pi_sqr(),\n\t\tLOCHS = (6 * LN_TWO * LN_TEN) / PI_SQR;\n\treturn LOCHS;\n}\n\ntemplate T niven() {\n\tT c = 1, last;\n\n\tfor(std::size_t j = 2; j == 2 || c != last; ++j) {\n\t\tlast = c;\n\t\tc += 1 - 1/boost::math::zeta(j);\n\t}\n\n\tstatic const T NIVEN = c;\n\treturn NIVEN;\n}\n\ntemplate T nortons() {\n\tstatic const T PI_SQR = boost::math::constants::pi_sqr(),\n\t\tLN_PI = log(boost::math::constants::pi()),\n\t\tEULER = boost::math::constants::euler(),\n\t\tLN_GLAISHER_KINKELIN = log(boost::math::constants::glaisher()),\n\t\tLN_TWO = boost::math::constants::ln_two(),\n\t\tNORTONS = (6 * LN_TWO\n\t\t\t* (24 * LN_GLAISHER_KINKELIN - 3 + 2 * EULER + LN_TWO - 2 * LN_PI)\n\t\t\t- PI_SQR) / PI_SQR;\n\treturn NORTONS;\n}\n\ntemplate T omega() {\n\tT w = 0;\n\tstd::string w_pre, w_post;\n\n\tw_pre.reserve(std::numeric_limits::digits10);\n\tw_post.reserve(std::numeric_limits::digits10);\n\n\tdo {\n\t\tw_pre = static_cast(w);\n\t\tw_pre.resize(std::numeric_limits::digits10);\n\n\t\tconst T e_w = exp(w);\n\n\t\tw -= ((w * e_w) - 1)\n\t\t\t/ (e_w * (w + 1) - ((w + 2) * (w * e_w - 1) / ((w * 2) + 2)));\n\n\t\tw_post = static_cast(w);\n\t\tw_post.resize(std::numeric_limits::digits10);\n\t} while (w_pre != w_post);\n\n\tstatic const T OMEGA = w;\n\treturn OMEGA;\n}\n\ntemplate T one() {\n\tstatic const T ONE = 1;\n\treturn ONE;\n}\n\ntemplate T pi() {\n\tstatic const T PI = boost::math::constants::pi();\n\treturn PI;\n}\n\ntemplate T plastic_number() {\n\tstatic const T PLASTIC_NUMBER = (boost::math::cbrt(108 + 12\n\t\t* sqrt(static_cast(69))) + boost::math::cbrt(108 - 12\n\t\t* sqrt(static_cast(69)))) / static_cast(6);\n\treturn PLASTIC_NUMBER;\n}\n\ntemplate T pogsons() {\n\tstatic const T POGSONS = pow(10, 2 / static_cast(5));\n\treturn POGSONS;\n}\n\ntemplate T polyas_random_walk() {\n\tstatic const T PI_CUBED = boost::math::constants::pi_cubed(),\n\t\tROOT_SIX = sqrt(static_cast(6)),\n\t\tPOLYAS_RANDOM_WALK = 1 - 1/((ROOT_SIX / (32 * PI_CUBED))\n\t\t\t* boost::math::tgamma(1 / static_cast(24))\n\t\t\t* boost::math::tgamma(5 / static_cast(24))\n\t\t\t* boost::math::tgamma(7 / static_cast(24))\n\t\t\t* boost::math::tgamma(11 / static_cast(24)));\n\treturn POLYAS_RANDOM_WALK;\n}\n\ntemplate T porters() {\n\tstatic const T LN_TWO = boost::math::constants::ln_two(),\n\t\tLN_GLAISHER_KINKELIN = log(boost::math::constants::glaisher()),\n\t\tLN_PI = log(boost::math::constants::pi()),\n\t\tPI_SQR = boost::math::constants::pi_sqr(),\n\t\tPORTERS = (6 * LN_TWO * (48 * LN_GLAISHER_KINKELIN\n\t\t\t- LN_TWO - 4 * LN_PI - 2)) / PI_SQR - 0.5;\n\treturn PORTERS;\n}\n\ntemplate T prince_ruperts_cube() {\n\tstatic const T ROOT_TWO = boost::math::constants::root_two(),\n\t\tPRINCE_RUPERTS_CUBE = (3 * ROOT_TWO) / 4;\n\treturn PRINCE_RUPERTS_CUBE;\n}\n\ntemplate T pythagoras() {\n\tstatic const T PYTHAGORAS = boost::math::constants::root_two();\n\treturn PYTHAGORAS;\n}\n\ntemplate T robbins() {\n\tstatic const T PI = boost::math::constants::pi(),\n\t\tROOT_TWO = boost::math::constants::root_two(),\n\t\tROOT_THREE = boost::math::constants::root_three(),\n\t\tROBBINS = ((4 + 17 * ROOT_TWO - 6 * ROOT_THREE - 7 * PI) / 105)\n\t\t\t+ (log1p(ROOT_TWO) / 5) + ((2 * log(2 + ROOT_THREE)) / 5);\n\treturn ROBBINS;\n}\n\ntemplate T sierpinski_k() {\n\tstatic const T PI = boost::math::constants::pi(),\n\t\tPI_CUBED = boost::math::constants::pi_cubed(),\n\t\tEULER = boost::math::constants::euler(),\n\t\tSIERPINSKI_K = PI * log((4 * PI_CUBED * exp(2 * EULER))\n\t\t\t/ pow(boost::math::tgamma(0.25), 4));\n\treturn SIERPINSKI_K;\n}\n\ntemplate T sierpinski_s() {\n\tstatic const T PI_CUBED = boost::math::constants::pi_cubed(),\n\t\tEULER = boost::math::constants::euler(),\n\t\tSIERPINSKI_S = log((4 * PI_CUBED * exp(2 * EULER))\n\t\t\t/ pow(boost::math::tgamma(0.25), 4));\n\treturn SIERPINSKI_S;\n}\n\ntemplate T silver_ratio() {\n\tstatic const T SILVER_RATIO = boost::math::constants::root_two() + 1;\n\treturn SILVER_RATIO;\n}\n\ntemplate T theodorus() {\n\tstatic const T THEODORUS = boost::math::constants::root_three();\n\treturn THEODORUS;\n}\n\ntemplate T twenty_vertex_entropy() {\n\tstatic const T ROOT_THREE = boost::math::constants::root_three(),\n\t\tTWENTY_VERTEX_ENTROPY = (3 * ROOT_THREE) / 2;\n\treturn TWENTY_VERTEX_ENTROPY;\n}\n\ntemplate T weierstrass() {\n\tstatic const T ROOT_PI = boost::math::constants::root_pi(),\n\t\tPI = boost::math::constants::pi(),\n\t\tWEIERSTRASS = (exp2(static_cast(1.25)) * ROOT_PI\n\t\t\t* exp(PI / 8)) / pow(boost::math::tgamma(0.25), 2);\n\treturn WEIERSTRASS;\n}\n\ntemplate T wylers() {\n\tstatic const T PI = boost::math::constants::pi(),\n\t\tWYLERS = (9 / (8 * pow(PI, 4))) * pow(pow(PI, 5) / 1920, 0.25);\n\treturn WYLERS;\n}\n\ntemplate T zero() {\n\tstatic const T ZERO = 0;\n\treturn ZERO;\n}\n\n} // namespace constant\n\nnamespace constant {\nnamespace func {\n\n// use std::uint_fastNN_t if you believe it helps\ntemplate\nT champernowne(const A & b = 10) {\n\tT c = 0, last;\n\n\tfor(std::size_t n = 1; n == 1 || c != last; ++n) {\n\t\tT sub = 0;\n\n\t\tfor(std::size_t k = 1; k <= n; ++k) {\n\t\t\tsub += floor(log(k) / log(b));\n\t\t}\n\n\t\tlast = c;\n\t\tc += n / pow(b, n + sub);\n\t}\n\n\treturn c;\n}\n\n// throws error if r is negative and even\ntemplate\nT favard(const A & r = 2) {\n\tstatic const T PI = boost::math::constants::pi();\n\n\tif (r == 0) {\n\t\treturn 1;\n\t} else if (r % 2) { // odd (dirichlet lambda)\n\t\treturn (4 / PI) * ((1 - exp2(-(static_cast(r) + 1)))\n\t\t\t* boost::math::zeta(r + 1));\n\t} else { // even (dirichlet beta)\n\t\treturn (-4 / PI) * (pow(-2, static_cast(-2) * (r + 1))\n\t\t\t/ boost::math::tgamma(r + 1))\n\t\t\t* (boost::math::polygamma(r, 0.25)\n\t\t\t- boost::math::polygamma(r, 0.75));\n\t}\n}\n\n\n} // namespace func\n} // namespace constant\n\n#endif // CONSTANTS_HPP_\n", "meta": {"hexsha": "f6a521aef83659f30a8845483151eb1f7819885a", "size": 10082, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "constants.hpp", "max_stars_repo_name": "esote/mathematical-constants", "max_stars_repo_head_hexsha": "278ef920f1aeb8fb37a56103c40bcbd7e88e458f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "constants.hpp", "max_issues_repo_name": "esote/mathematical-constants", "max_issues_repo_head_hexsha": "278ef920f1aeb8fb37a56103c40bcbd7e88e458f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "constants.hpp", "max_forks_repo_name": "esote/mathematical-constants", "max_forks_repo_head_hexsha": "278ef920f1aeb8fb37a56103c40bcbd7e88e458f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1752021563, "max_line_length": 76, "alphanum_fraction": 0.651458044, "num_tokens": 3333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897542390751, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.690652134767157}} {"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n// 2008 Dresden University of Technology and the Trustees of Indiana University.\n// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include \n#include \n#include \n#include \n\nstruct poisson2D_dirichlet\n{\n poisson2D_dirichlet(int m, int n) : m(m), n(n) {}\n\n template \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 \n {\ttypedef nonscal type; };\n}}\n\nint main(int, char**)\n{\n using namespace std;\n \n mtl::compressed2D A0;\n laplacian_setup(A0, 4, 5);\n cout << \"A0 is\\n\" << A0 << endl;\n\n mtl::dense_vector v(20);\n iota(v);\n cout << \"v is \" << v << endl;\n\n mtl::dense_vector w1(A0 * v);\n cout << \"A0 * v is \" << w1 << endl;\n\n poisson2D_dirichlet A(4, 5);\n mtl::dense_vector w2(A * v);\n cout << \"A * v is \" << w2 << endl;\n\n w1-= w2;\n if (one_norm(w1) > 0.001) throw \"Wrong result\";\n\n return 0;\n}\n", "meta": {"hexsha": "afb153e2dcb68134ff7e9c6fda3a67deb8f527be", "size": 1751, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/matrix_free_1_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/matrix_free_1_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/matrix_free_1_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 24.661971831, "max_line_length": 94, "alphanum_fraction": 0.5830953741, "num_tokens": 580, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6906431907697526}} {"text": "//////////////////////////////////\n//\n// Compile: g++ -std=c++14 -O3 ex5.cxx -o ex5 -lboost_timer\n//\n//////////////////////////////////\n\n#include \t\t// std::cout\n#include \t\t// std::ifsteam\n#include \t\t// std::pair\n#include \t\t// std::vector\n#include \n#include \n#include \n#include \n#include \n\nint main(int argc, char*argv[]){\n \n if (argc != 2)\n {\n std::cerr << \"No file!!!\" << std::endl;\n return -1;\n }\n \n std::ifstream file(argv[1]); // std::ifstream::in ??\n std::string str;\n \n boost::timer::cpu_timer timer;\n\n /* start get number of edges */\n getline(file, str);\n\n using namespace boost::spirit;\n using qi::int_;\n using qi::double_;\n using qi::parse;\n \n int n;\n\n auto it = str.begin();\n bool r = parse(it, str.end(),\n\t\t int_[([&n](int i){n = i;})] >> int_); \n /* end get number of edges */\n \n \n /* start get list of edges and weights */\n typedef std::pair Edge;\n std::vector Edges; // vector to store std::pair of edges.\n std::vector Weights; // vector to weights as integers.\n \n while (getline(file,str)){ // get graph line-by-line.\n int Vert1;\n int Vert2;\n double Weight; // are all weights integer-valued ??\n \n auto it = str.begin(); // initialize iterator for qi::parse. \n \n bool r = parse(it, str.end(), // parse graph.\n\t\t int_[([&Vert1](int i){Vert1 = i;})] >> qi::space >> int_[([&Vert2](int i){Vert2 = i;})] >> qi::space >> double_[([&Weight](double i){Weight = i;})]); \n \n Edge edge = std::make_pair(Vert1, Vert2); // make edge-pair out of vertices.\n Edges.push_back(edge);\n Weights.push_back(Weight);\n }\n /* end get list of edges and weights */\n \n \n typedef boost::property EdgeWeightProperty; // initialize type to store weights on edges.\n // adjacency_list\n typedef boost::adjacency_list Graph; // create graph.\n\n Graph g(Edges.begin(),Edges.end(), Weights.begin(), n); // populate graph.\n \n \n // here, the graph should be built... Find shortest path.\n typedef boost::graph_traits::vertex_descriptor vertex_descriptor;\n vertex_descriptor source = boost::vertex(1, g); // define source vertex as vertex with index == 1.\n std::vector parents(boost::num_vertices(g)); // initialize vectors for predecessor and distances.\n std::vector distances(boost::num_vertices(g));\n \n \n // find shortest distances.\n boost::dijkstra_shortest_paths(g, source, boost::predecessor_map(&parents[0]).distance_map(&distances[0]));\n\n /* start find longest-shortest path */\n int maxDistance = 0;\n int maxVertex = 0;\n \n // create iterator over vertices.\n // vertexPair.first is the iterated element, and .second is the end-index of all vertices.\n typedef boost::graph_traits ::vertex_iterator vertex_iter;\n std::pair vertexPair;\n \n for (vertexPair = boost::vertices(g); vertexPair.first != vertexPair.second; ++vertexPair.first) // vertexPair = boost::vertices loops over all vertices in g.\n {\n // replace maxDistance if a greater distance is found, and maxDistance must be less than \"infinity\" (of 32-bit signed integer).\n if ((distances[*vertexPair.first] > maxDistance) && (distances[*vertexPair.first] < 2147483647)){\n maxDistance = distances[*vertexPair.first];\n maxVertex = *vertexPair.first;\n }\n // if distance == maxDistance, check if vertex index is smaller.\n if ((distances[*vertexPair.first] == maxDistance) && (*vertexPair.first < maxVertex)){\n maxVertex = *vertexPair.first;\n }\n }\n \n boost::timer::cpu_times times = timer.elapsed();\n \n // output vertex and distance of the longest-shortest path.\n std::cout << \"RESULT VERTEX \" << maxVertex << std::endl;\n std::cout << \"RESULT DIST \" << maxDistance << std::endl;\n /* end find longest-shortest path */\n\n // print CPU- and Wall-Time. \n // boost::timer::cpu_times returns tuple of wall, system and user times in nanoseconds.\n std::cout << std::endl;\n std::cout << \"WALL-CLOCK \" << times.wall / 1e9 << \"s\" << std::endl;\n std::cout << \"USER TIME \" << times.user / 1e9 << \"s\" << std::endl;\n \n file.close(); \n return 0;\n}\n", "meta": {"hexsha": "a4bde7f12e04a09af3071fd22e1446b2fa02d508", "size": 4477, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "RayChew/Ex5/ex5.cxx", "max_stars_repo_name": "appfs/appfs", "max_stars_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2017-04-21T11:39:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T20:25:18.000Z", "max_issues_repo_path": "RayChew/Ex5/ex5.cxx", "max_issues_repo_name": "appfs/appfs", "max_issues_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 69.0, "max_issues_repo_issues_event_min_datetime": "2017-04-26T09:30:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-01T11:31:21.000Z", "max_forks_repo_path": "RayChew/Ex5/ex5.cxx", "max_forks_repo_name": "appfs/appfs", "max_forks_repo_head_hexsha": "8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 53.0, "max_forks_repo_forks_event_min_datetime": "2017-04-20T16:16:11.000Z", "max_forks_repo_forks_event_max_datetime": "2017-07-19T12:53:01.000Z", "avg_line_length": 36.3983739837, "max_line_length": 160, "alphanum_fraction": 0.6537860174, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894689081711, "lm_q2_score": 0.7718434873426302, "lm_q1q2_score": 0.6906374241195428}} {"text": "/**\n * \\file SinusGeneratorFilter.cpp\n */\n\n#include \"SinusGeneratorFilter.h\"\n\n#include \n\n#include \n\nnamespace ATK\n{\n template\n SinusGeneratorFilter::SinusGeneratorFilter()\n :Parent(0, 2), volume(1), offset(0), frequency(0), frequ_cos(1), frequ_sin(0), cos(1), sin(0)\n {\n }\n \n template\n SinusGeneratorFilter::~SinusGeneratorFilter()\n {\n }\n \n template\n void SinusGeneratorFilter::set_frequency(DataType_ frequency)\n {\n this->frequency = frequency;\n this->frequ_cos = std::cos(2 * boost::math::constants::pi() * frequency / output_sampling_rate);\n this->frequ_sin = std::sin(2 * boost::math::constants::pi() * frequency / output_sampling_rate);\n Parent::setup();\n }\n \n template\n DataType_ SinusGeneratorFilter::get_frequency() const\n {\n return frequency;\n }\n\n template\n void SinusGeneratorFilter::set_volume(DataType_ volume)\n {\n this->volume = volume;\n }\n \n template\n DataType_ SinusGeneratorFilter::get_volume() const\n {\n return volume;\n }\n \n template\n void SinusGeneratorFilter::set_offset(DataType_ offset)\n {\n this->offset = offset;\n }\n \n template\n DataType_ SinusGeneratorFilter::get_offset() const\n {\n return offset;\n }\n\n template\n void SinusGeneratorFilter::full_setup()\n {\n Parent::full_setup();\n cos = 1;\n sin = 0;\n }\n\n template\n void SinusGeneratorFilter::process_impl(int64_t size) const\n {\n DataType* ATK_RESTRICT output_cos = outputs[0];\n DataType* ATK_RESTRICT output_sin = outputs[1];\n\n for(int64_t i = 0; i < size; ++i)\n {\n auto new_cos = cos * frequ_cos - sin * frequ_sin;\n auto new_sin = cos * frequ_sin + sin * frequ_cos;\n auto norm = (new_cos * new_cos + new_sin * new_sin);\n\n cos = new_cos / norm;\n sin = new_sin / norm;\n\n *(output_cos++) = volume * cos + offset;\n *(output_sin++) = volume * sin + offset;\n }\n }\n \n template class SinusGeneratorFilter;\n template class SinusGeneratorFilter;\n}\n", "meta": {"hexsha": "6a8c1014e8cc799e467f4e4af4731e40ab380ac4", "size": 2337, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/Tools/SinusGeneratorFilter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "ATK/Tools/SinusGeneratorFilter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ATK/Tools/SinusGeneratorFilter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 24.8617021277, "max_line_length": 111, "alphanum_fraction": 0.6884895165, "num_tokens": 609, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218348550491, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6905998683094975}} {"text": "#include \n#include \n\n// Set the parameters |i|, |j|, and |k| to be the indices of the grid cell\n// containing the point |p| for a grid with lower corner |lc| and grid cell\n// width (spacing) |dx|.\ninline void floor(const Eigen::Vector3d& p, const Eigen::Vector3d& lc,\n double dx, int& i, int& j, int& k) {\n // Compute |p|'s location relative to |lc|.\n // Dividing by |dx| yields a 3D vector indicating the number of grid\n // cells (including fractions of grid cells, as the vector elements are\n // floating-point values) away from |lc| that |p| is located.\n Eigen::Vector3d p_lc_over_dx = (p - lc) / dx;\n\n // Set the indices to the floor of |p_lc_over_dx|'s elements.\n i = static_cast(p_lc_over_dx[0]);\n j = static_cast(p_lc_over_dx[1]);\n k = static_cast(p_lc_over_dx[2]);\n}\n\nint main(int argc, char** argv) {\n // Make a grid with spacing of 2 with lower corner (1, 2, 3).\n double dx = 2.0;\n Eigen::Vector3d lc(1, 2, 3);\n\n // (i, j, k) should be (floor((6-1)/2), floor((4-2)/2), floor((3-3)/2)),\n // which is (floor(2.5), floor(1), floor(0)) = (2, 1, 0).\n Eigen::Vector3d p1(6, 4, 3);\n int i, j, k;\n floor(p1, lc, dx, i, j, k);\n std::cout << \"i = \" << i << \", j = \" << j << \", k = \" << k << std::endl;\n\n // (i, j, k) should be (3, 8, 9).\n Eigen::Vector3d p2(7, 18, 22);\n floor(p2, lc, dx, i, j, k);\n std::cout << \"i = \" << i << \", j = \" << j << \", k = \" << k << std::endl;\n\n // (i, j, k) should be (-1, 0, 0)--wait, negative indices aren't\n // allowed, right?!\n Eigen::Vector3d p3(-1, 2, 3);\n floor(p3, lc, dx, i, j, k);\n std::cout << \"i = \" << i << \", j = \" << j << \", k = \" << k << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "aa3797d8ed932b2b0a53cf64d7a1949214e58467", "size": 1692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "incremental0/GridIndexing_Bad.cpp", "max_stars_repo_name": "unusualinsights/flip_pic_examples", "max_stars_repo_head_hexsha": "3314dd4c67a681d2600feb342c88527e7618bc10", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "incremental0/GridIndexing_Bad.cpp", "max_issues_repo_name": "unusualinsights/flip_pic_examples", "max_issues_repo_head_hexsha": "3314dd4c67a681d2600feb342c88527e7618bc10", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "incremental0/GridIndexing_Bad.cpp", "max_forks_repo_name": "unusualinsights/flip_pic_examples", "max_forks_repo_head_hexsha": "3314dd4c67a681d2600feb342c88527e7618bc10", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.7826086957, "max_line_length": 75, "alphanum_fraction": 0.5638297872, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6904868463278476}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// select the kernel type\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;\ntypedef Kernel::Point_2 Point_2;\ntypedef Kernel::Direction_2 Direction_2;\n\n/* define the struct for edge property */\nstruct Edge_property {\n /* record the Euclidean length of the edge */\n double euclidean_length;\n};\n\n// define the Graph (e.g., to be undirected,\n// and to use Edge_property as the edge property, etc.)\ntypedef boost::adjacency_list Graph;\n\nint main(int argc, char ** argv)\n{\n const std::string fname = argc!=3 ? \"data/n20.cin\" : argv[2];\n unsigned int k = argc!=3 ? 6 : atoi(argv[1]);\n\n if (argc != 3) {\n std::cout << \"Usage: \" << argv[0] << \" \" << std::endl;\n std::cout << \"Using default values \" << k << \" \" << fname << \"\\n\";\n }\n\n if (k<2) {\n std::cout << \"The number of cones should be larger than 1!\" << std::endl;\n return 1;\n }\n // open the file containing the vertex list\n std::ifstream inf(fname);\n if (!inf) {\n std::cout << \"Cannot open file \" << argv[1] << \"!\" << std::endl;\n return 1;\n }\n\n // iterators for reading the vertex list file\n std::istream_iterator< Point_2 > input_begin( inf );\n std::istream_iterator< Point_2 > input_end;\n\n // initialize the functor\n // If the initial direction is omitted, the x-axis will be used\n CGAL::Construct_theta_graph_2 theta(k);\n // create an adjacency_list object\n Graph g;\n // construct the theta graph on the vertex list\n theta(input_begin, input_end, g);\n\n // select a source vertex for dijkstra's algorithm\n boost::graph_traits::vertex_descriptor v0;\n v0 = vertex(0, g);\n std::cout << \"The source vertex is: \" << g[v0] << std::endl;\n\n std::cout << \"The index of source vertex is: \" << v0 << std::endl;\n\n // calculating edge length in Euclidean distance and store them in the edge property\n boost::graph_traits::edge_iterator ei, ei_end;\n for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\n boost::graph_traits::edge_descriptor e = *ei;\n boost::graph_traits::vertex_descriptor u = source(e, g);\n boost::graph_traits::vertex_descriptor v = target(e, g);\n const Point_2& pu = g[u];\n const Point_2& pv = g[v];\n\n double dist = CGAL::sqrt( CGAL::to_double(CGAL::squared_distance(pu,pv)) );\n g[e].euclidean_length = dist;\n std::cout << \"Edge (\" << g[u] << \", \" << g[v] << \"): \" << dist << std::endl;\n }\n\n // calculating the distances from v0 to other vertices\n boost::graph_traits::vertices_size_type n = num_vertices(g);\n // vector for storing the results\n std::vector distances(n);\n // Calling the Dijkstra's algorithm implementation from boost.\n boost::dijkstra_shortest_paths(g,\n v0,\n boost::weight_map(get(&Edge_property::euclidean_length, g)).\n distance_map(CGAL::make_property_map(distances)) );\n\n std::cout << \"distances are:\" << std::endl;\n for (unsigned int i=0; i < n; ++i) {\n std::cout << \"distances[\" << i << \"] = \" << distances[i] << \", (x,y)=\" << g[vertex(i, g)];\n std::cout << \" at Vertex \" << i << std::endl;\n }\n\n return 0;\n}\n", "meta": {"hexsha": "52f382fa6083bef97444bd394db58c518e3d34bb", "size": 3835, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Cone_spanners_2/examples/Cone_spanners_2/dijkstra_theta.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Cone_spanners_2/examples/Cone_spanners_2/dijkstra_theta.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Cone_spanners_2/examples/Cone_spanners_2/dijkstra_theta.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 36.5238095238, "max_line_length": 94, "alphanum_fraction": 0.6276401565, "num_tokens": 1011, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637361282707, "lm_q2_score": 0.8031737963569016, "lm_q1q2_score": 0.6904593865365009}} {"text": "//==================================================================================================\n/*!\n @file\n\n @copyright 2016 NumScale SAS\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_POW_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_POW_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n @ingroup group-exponential\n Function object implementing pow capabilities\n\n Computes \\f$x^y\\f$\n\n @par Semantic:\n\n For every parameters of floating types respectively T, U:\n\n @code\n T r = pow(x,y);\n @endcode\n\n is similar to:\n\n @code\n T r = exp(y*log(x));\n @endcode\n\n The pow function is conformant to std:pow considering the limits behaviours\n defined by the standard:\n\n - pow(+0, y), where y is a negative odd integer, returns +Inf\n - pow(-0, y), where y is a negative odd integer, returns -Inf\n - pow(+/-0, y), where y is negative, finite, and is an even integer or a non-integer, returns +Inf\n - pow(+/-0, -Inf) returns +inf\n - pow(+0, y), where y is a positive odd integer, returns +0\n - pow(-0, y), where y is a positive odd integer, returns -0\n - pow(+/-0, y), where y is positive non-integer or a positive even integer, returns +0\n - pow(-1, +/-Inf) returns 1\n - pow(+1, y) returns 1 for any y, even when y is Nan\n - pow(x, +/-0) returns 1 for any x, even when x is Nan\n - pow(x, y) returns Nan if x is finite and negative and y is finite and non-integer.\n - pow(x, -Inf) returns +Inf for any |x|<1\n - pow(x, -Inf) returns +0 for any |x|>1\n - pow(x, +Inf) returns +0 for any |x|<1\n - pow(x, +Inf) returns +Inf for any |x|>1\n - pow(-Inf, y) returns -0 if y is a negative odd integer\n - pow(-Inf, y) returns +0 if y is a negative non-integer or even integer\n - pow(-Inf, y) returns -Inf if y is a positive odd integer\n - pow(-Inf, y) returns +Inf if y is a positive non-integer or even integer\n - pow(+Inf, y) returns +0 for any negative y\n - pow(+Inf, y) returns +Inf for any positive y\n\n But return a value of the same type as the first parameter, which is necessary for good SIMD behaviour.\n\n @par Decorators\n\n -std_ decorator provides access to std:pow\n\n -fast_ decorator almost nearly uses the naive formula and so doesnot really care for limits and leads to lower\n\n **/\n Value pow(Value const & v0, Value const& y);\n} }\n#endif\n\n#include \n#include \n\n#endif\n", "meta": {"hexsha": "2c76258003b3296bf76029540253497e0ba8a337", "size": 2824, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/pow.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-01-14T12:49:14.000Z", "max_stars_repo_stars_event_max_datetime": "2018-01-14T12:49:14.000Z", "max_issues_repo_path": "third_party/boost/simd/function/pow.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/function/pow.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 34.8641975309, "max_line_length": 118, "alphanum_fraction": 0.5913597734, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6904014959675703}} {"text": "// IIR_Butterworth.cpp : This file contains the 'main' function. Program execution begins and ends there.\r\n//Calculate the coefficients of the butterworth filter. It follows the steps as described in Matlab. \r\n//The same symbols as in Matlab are used to facilitate the writing of the code\r\n#define _CRTDBG_MAP_ALLOC\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"IIR_Butterworth.h\"\r\n\r\n#define ARMA_DONT_USE_CXX11\r\n#include \r\n\r\n#ifdef _DEBUG\r\n#define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ )\r\n// Replace _NORMAL_BLOCK with _CLIENT_BLOCK if you want the\r\n// allocations to be of _CLIENT_BLOCK type\r\n#else\r\n#define DBG_NEW new\r\n#endif\r\n\r\n#define PI 3.141592653589793\r\n\r\nint main()\r\n{\r\n \r\n\r\n double f1 = 100; //High Pass\r\n double f2 = 300; //Low Pass\r\n double sf = 2048; //Sampling frequency\r\n int order_filt = 2; //Order\r\n double Nyquist_F = sf / 2;\r\n \r\n std::vector > coeff_final(2);\r\n\r\n int type_filt = 0;\r\n IIR_B_F::IIR_Butterworth ir_b;\r\n \r\n bool check_stability_flag;\r\n\r\n //_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);\r\n //_CrtSetBreakAlloc(154);\r\n //_CrtSetBreakAlloc(155);\r\n //_CrtSetBreakAlloc(156);\r\n\r\n int coeff_numb = 0;\r\n switch (type_filt)\r\n {\r\n case 0:\r\n \r\n coeff_numb = 2*(size_t)order_filt + 1;\r\n\r\n\r\n for (int i = 0; i < 2; i++)\r\n {\r\n\r\n coeff_final[i].resize(coeff_numb);\r\n\r\n }\r\n \r\n \r\n _CrtDumpMemoryLeaks();\r\n\r\n coeff_final = ir_b.lp2bp(f1 / Nyquist_F, f2 / Nyquist_F, order_filt);\r\n \r\n check_stability_flag = ir_b.check_stability_iir(coeff_final);\r\n\r\n if (check_stability_flag)\r\n {\r\n\r\n std::cout << \"The filter is stable\" << std::endl;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n std::cout << \"The filter is unstable\" << std::endl;\r\n\r\n }\r\n\r\n for (int kk = 0; kk < 2; kk++)\r\n {\r\n if (kk == 0)\r\n {\r\n\r\n std::cout << \"Numerator: \" << std::ends;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n std::cout << \"Denumerator: \" << std::ends;\r\n\r\n }\r\n\r\n for (int ll = 0; ll < coeff_numb; ll++)\r\n\r\n {\r\n std::cout << coeff_final[kk][ll] << \"\\t\" << std::ends;\r\n\r\n }\r\n\r\n std::cout << std::endl;\r\n\r\n }\r\n \r\n break;\r\n\r\n case 1:\r\n\r\n coeff_numb = 2 * order_filt + 1;\r\n\r\n\r\n for (int i = 0; i < 2; i++)\r\n {\r\n\r\n coeff_final[i].resize(coeff_numb);\r\n\r\n }\r\n\r\n _CrtDumpMemoryLeaks();\r\n coeff_final = ir_b.lp2bs(f1 / Nyquist_F, f2 / Nyquist_F, order_filt);\r\n \r\n\r\n check_stability_flag = ir_b.check_stability_iir(coeff_final);\r\n\r\n if (check_stability_flag)\r\n {\r\n\r\n std::cout << \"The filter is stable\" << std::endl;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n std::cout << \"The filter is unstable\" << std::endl;\r\n\r\n }\r\n\r\n for (int kk = 0; kk < 2; kk++)\r\n {\r\n\r\n if (kk == 0)\r\n {\r\n\r\n std::cout << \"Numerator: \" << std::ends;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n std::cout << \"Denumerator: \" << std::ends;\r\n\r\n }\r\n\r\n for (int ll = 0; ll < coeff_numb; ll++)\r\n\r\n {\r\n\r\n std::cout << coeff_final[kk][ll] << \"\\t\" << std::ends;\r\n\r\n }\r\n\r\n std::cout << std::endl;\r\n\r\n }\r\n\r\n break;\r\n\r\n case 2:\r\n\r\n coeff_numb = order_filt + 1;\r\n\r\n for (int i = 0; i < 2; i++)\r\n {\r\n\r\n coeff_final[i].resize(coeff_numb);\r\n\r\n }\r\n\r\n _CrtDumpMemoryLeaks();\r\n coeff_final = ir_b.lp2hp(f1 / Nyquist_F, order_filt);\r\n \r\n check_stability_flag = ir_b.check_stability_iir(coeff_final);\r\n\r\n if (check_stability_flag)\r\n {\r\n\r\n std::cout << \"The filter is stable\" << std::endl;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n std::cout << \"The filter is unstable\" << std::endl;\r\n\r\n }\r\n\r\n for (int kk = 0; kk < 2; kk++)\r\n {\r\n\r\n if (kk == 0)\r\n {\r\n\r\n std::cout << \"Numerator: \" << std::ends;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n std::cout << \"Denumerator: \" << std::ends;\r\n\r\n }\r\n\r\n for (int ll = 0; ll < coeff_numb; ll++)\r\n\r\n {\r\n\r\n std::cout << coeff_final[kk][ll] << \"\\t\" << std::ends;\r\n\r\n }\r\n\r\n std::cout << std::endl;\r\n }\r\n\r\n break;\r\n\r\n case 3:\r\n coeff_numb = order_filt + 1;\r\n\r\n for (int i = 0; i < 2; i++)\r\n {\r\n\r\n coeff_final[i].resize(coeff_numb);\r\n\r\n }\r\n\r\n _CrtDumpMemoryLeaks();\r\n coeff_final = ir_b.lp2lp(f2 / Nyquist_F, order_filt);\r\n\r\n check_stability_flag = ir_b.check_stability_iir(coeff_final);\r\n\r\n if (check_stability_flag)\r\n {\r\n\r\n std::cout << \"The filter is stable\" << std::endl;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n std::cout << \"The filter is unstable\" << std::endl;\r\n\r\n }\r\n\r\n for (int kk = 0; kk < 2; kk++)\r\n {\r\n\r\n if (kk == 0)\r\n {\r\n\r\n std::cout << \"Numerator: \" << std::ends;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n std::cout << \"Denumerator: \" << std::ends;\r\n\r\n }\r\n\r\n for (int ll = 0; ll < coeff_numb; ll++)\r\n\r\n {\r\n\r\n std::cout << coeff_final[kk][ll] << \"\\t\" << std::ends;\r\n\r\n }\r\n\r\n std::cout << std::endl;\r\n\r\n }\r\n\r\n break;\r\n\r\n\r\n }\r\n \r\n //Create a complex sine wave\r\n std::vector test_sin(sf,0.0);\r\n double sf_1 = 20;\r\n double sf_2 = 60;\r\n for (double kk = 0; kk < sf; kk++)\r\n {\r\n\r\n test_sin[kk] = sin(2*PI*kk*sf_1/sf) + sin(2*PI*kk*sf_2/sf);\r\n\r\n }\r\n\r\n std::vector filt_sign = ir_b.Filter_Data(coeff_final,test_sin);\r\n \r\n}\r\n", "meta": {"hexsha": "ffddfa94601e277f8cf4b64db0c5d2fc43511c67", "size": 6224, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "IIR_Butterworth.cpp", "max_stars_repo_name": "InterTriplete2010/IIR_Butterworth_Filter_cpp", "max_stars_repo_head_hexsha": "b8b4a3ca31956da40dfa9bf41d37e8f58a67d18b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IIR_Butterworth.cpp", "max_issues_repo_name": "InterTriplete2010/IIR_Butterworth_Filter_cpp", "max_issues_repo_head_hexsha": "b8b4a3ca31956da40dfa9bf41d37e8f58a67d18b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IIR_Butterworth.cpp", "max_forks_repo_name": "InterTriplete2010/IIR_Butterworth_Filter_cpp", "max_forks_repo_head_hexsha": "b8b4a3ca31956da40dfa9bf41d37e8f58a67d18b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7587301587, "max_line_length": 106, "alphanum_fraction": 0.4546915167, "num_tokens": 1588, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431002, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6904014890635484}} {"text": "/* ----------------------------------------------------------------------------\n * Copyright 2022, Jeferson Lima\n * All Rights Reserved\n * See LICENSE for the license information\n * -------------------------------------------------------------------------- */\n\n/**\n * @file examples/rotation_ex.cpp\n * @author Jeferson Lima\n * @brief Rotation Matrix Example \n * @date Mar 7, 2022\n **/\n\n#include \n#include \n\nvoid rot2dVec(const Eigen::Matrix& v,\n Eigen::Matrix& r,\n\t float theta)\n{\n\n Eigen::Matrix rotation;\n rotation << std::cos(theta), -std::sin(theta), 0.0, 0.0, \n std::sin(theta), std::cos(theta), 0.0, 0.0,\n\t 0.0, 0.0, 1.0, 0.0,\n\t 0.0, 0.0, 0.0, 1.0;\n\n std::cout << \"v values: \\n\" << v << std::endl;\n std::cout << \"rotation values: \\n\" << rotation << std::endl;\n\n r = rotation * v;\n\n}\n\n\nint main(int argc, char* argv[])\n{\n\n Eigen::Matrix v;\n Eigen::Matrix r;\n float theta;\n\n // init matrix\n v << 0.5, 0.5, 0.0, 1.0;\n theta = 0.785398; // 45 degree -> radian\n\n rot2dVec(v, r, theta);\n\n std::cout << \"r values:\\n\" << r << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "932725b7fe1a1188bdda81414eea168ced484ce3", "size": 1251, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/1/rotation_ex.cpp", "max_stars_repo_name": "jefersonjlima/robotics-codes", "max_stars_repo_head_hexsha": "6a15e29d53d1693bb08e590a40fac5b1c828c107", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/examples/1/rotation_ex.cpp", "max_issues_repo_name": "jefersonjlima/robotics-codes", "max_issues_repo_head_hexsha": "6a15e29d53d1693bb08e590a40fac5b1c828c107", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/1/rotation_ex.cpp", "max_forks_repo_name": "jefersonjlima/robotics-codes", "max_forks_repo_head_hexsha": "6a15e29d53d1693bb08e590a40fac5b1c828c107", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.6037735849, "max_line_length": 80, "alphanum_fraction": 0.4684252598, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8198933315126791, "lm_q1q2_score": 0.6902072279706828}} {"text": "#ifndef TRIUMF_NMR_UTILITIES_HPP\n#define TRIUMF_NMR_UTILITIES_HPP\n\n#include \n\n#include \n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// nuclear magnetic resonance\nnamespace nmr {\n\n// miscellaneous helper functions\nnamespace utilities {\n\n// calculate the gyromagnetic ratio (MHz / T) of an NMR probe nucleus from its\n// magnetic dipole moment (nm) and spin quantum number\ntemplate \nconstexpr T calculate_gamma(T magnetic_dipole_moment, T spin_quantum_number) {\n return 1e6 * boost::math::constants::two_pi() *\n triumf::constants::codata_2018::nuclear_magneton_in_MHz_T::value() *\n magnetic_dipole_moment / spin_quantum_number;\n}\n\n} // namespace utilities\n\n} // namespace nmr\n\n} // namespace triumf\n\n#endif // TRIUMF_NMR_UTILITIES_HPP\n", "meta": {"hexsha": "e4cf06b2aa9ace158d71259b9a06875e9498f52b", "size": 862, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/nmr/utilities.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/triumf/nmr/utilities.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/triumf/nmr/utilities.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1212121212, "max_line_length": 80, "alphanum_fraction": 0.7656612529, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533107374443, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6901780290619267}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n// need pangolin for plotting trajectory\n#include \nusing namespace std;\nusing namespace Eigen;\n\nstring TrajectoryFile = \"../compare.txt\";\nvoid ICP(vector pts_est, vector pts_gt, Matrix3d &R, Vector3d &t);\nvoid DrawTrajectory(vector poses1, vector poses2, string winName=\"Trajectory Viewer\");\n\nint main(){\n ifstream fin(TrajectoryFile);\n vector pts_est,pts_gt;\n vector poses_gt, poses_est;\n while(!fin.eof()){\n double time, tx,ty,tz,qx,qy,qz,qw;\n fin>>time>>tx>>ty>>tz>>qx>>qy>>qz>>qw;\n Quaterniond q(qw,qx,qy,qz);\n Vector3d t_est(tx,ty,tz);\n Sophus::SE3d SE3_est(q,t_est);\n pts_est.push_back(t_est);\n poses_est.push_back(SE3_est);\n\n fin>>time>>tx>>ty>>tz>>qx>>qy>>qz>>qw;\n Quaterniond q2(qw,qx,qy,qz);\n Vector3d t_gt(tx,ty,tz);\n Sophus::SE3d SE3_gt(q2,t_gt);\n poses_gt.push_back(SE3_gt);\n pts_gt.push_back(t_gt);\n }\n Matrix3d R;\n Vector3d t;\n ICP(pts_est, pts_gt, R, t);\n Sophus::SE3d SE3_E2G(R, t);\n\n int N = poses_gt.size();\n vector poses_after(N);\n for(int i=0;i Vector6d;\n Vector6d se3_differ = SE3_differ.log();\n error += se3_differ.dot(se3_differ);\n }\n double RMSE = sqrt(error/N);\n cout<<\"RMSE: \"< pts_est, vector pts_gt, Matrix3d &R, Vector3d &t){\n Vector3d pe(0,0,0), pg(0,0,0);\n int N = pts_est.size();\n for(int i=0;i q_est(N), q_gt(N);\n for (int i=0;i svd(W, ComputeFullU|ComputeFullV);\n Matrix3d U = svd.matrixU();\n Matrix3d V = svd.matrixV();\n cout<<\"U=\"< poses1, vector poses2, string winName) {\n\n // create pangolin window and plot the trajectory\n pangolin::CreateWindowAndBind(winName, 1024, 768);\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n pangolin::OpenGlRenderState s_cam(\n pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n );\n\n pangolin::View &d_cam = pangolin::CreateDisplay()\n .SetBounds(0.0, 1.0, pangolin::Attach::Pix(175), 1.0, -1024.0f / 768.0f)\n .SetHandler(new pangolin::Handler3D(s_cam));\n\n\n while (pangolin::ShouldQuit() == false) {\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n d_cam.Activate(s_cam);\n glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n\n glLineWidth(2);\n for (size_t i = 0; i < poses1.size() - 1; i++) {\n glColor3f(1, 0.0f, 0);\n glBegin(GL_LINES);\n auto p1 = poses1[i], p2 = poses1[i + 1];\n glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n glEnd();\n }\n for (size_t i = 0; i < poses2.size() - 1; i++) {\n glColor3f(0, 0.0f, 1);\n glBegin(GL_LINES);\n auto p1 = poses2[i], p2 = poses2[i + 1];\n glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n glEnd();\n }\n\n pangolin::FinishFrame();\n usleep(5000); // sleep 5 ms\n }\n\n}", "meta": {"hexsha": "594a6f7253464ecc2e83de1eb5c412b0a4d92188", "size": 4556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "slamhw5/icp.cpp", "max_stars_repo_name": "Yaozhuwa/slambook-homework", "max_stars_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-04-23T03:27:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-20T15:29:10.000Z", "max_issues_repo_path": "slamhw5/icp.cpp", "max_issues_repo_name": "Yaozhuwa/slambook-homework", "max_issues_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "slamhw5/icp.cpp", "max_forks_repo_name": "Yaozhuwa/slambook-homework", "max_forks_repo_head_hexsha": "0c0ede6df828e9bd03445545a1e4552f9148a7cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2054794521, "max_line_length": 114, "alphanum_fraction": 0.5862598771, "num_tokens": 1481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122288794594, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6901476489251218}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace NTL;\n\n//ex. compile:\n//g++ -o remainder_alg_first_pass.cpp -std=c++11 -march=native -O2 -lntl -lgmp -lgmpxx -pthread\n\n\n// to compile and run on linux use\n// g++ -o remainder_alg_first_pass.cpp\n// ./\n\n\n//note that everywhere it says 'int' we will eventually want to use GMP or whatnot\n//ints are too small...\n\n//translates indices in trees to indices in arrays\n//if you want left child of (i,j), do (i+1, 2*j)\n//right child is (i+1, 2*j+1), and parent is (i-1, j//2)\nint flatten_index(int i, int j)\n{\n\tassert (j <= pow(2,i) - 1);\n\treturn pow(2,i) +j-1;\n}\n\n//gives tree indices from array index\ntuple lift_index(int k)\n{\n\tint i = log2(k+1);\n\tint j = k + 1 - pow(2,i);\n\n\treturn make_tuple(i,j);\n}\n\n\nvoid print_tree(Vec & X)\n{\n\tcout << endl;\n\tfor (int i = 0; i < X.length(); i++)\n\t{\n\t\tcout << X[i] << \" , \";\n\t}\n\tcout << endl;\n}\n\n\nZZ mtree_val(int i, int j, const Vec &m)\n{\n\tint N = m.length();\n\tint depth = log2(N);\n\tassert ((i <= depth) and (j < pow(2, i)));\n\n\tif (i == depth)\n\t{\n\t\treturn m[j];\n\t}\n\n\telse\n\t{\n\t\treturn mtree_val(i+1, 2*j, m)*mtree_val(i+1, 2*j+1, m);\n\t}\n}\n\nZZ Atree_val(int i, int j, const Vec &A)\n{\n\tint N = A.length();\n\tint depth = log2(N);\n\tassert ((i <= depth) and (j < pow(2,i)));\n\n\tif ((i == depth) or (j == 0))\n\t{\n\t\treturn A[j];\n\t}\n\n\telse\n\t{\n\t\treturn Atree_val(i+1, 2*j-1, A)*Atree_val(i+1, 2*j, A);\n\t}\n}\n\n\n//k will be approx log log N (it's the space-time tradeoff)\n//when k = 0 we have normal remainder tree\nVec RemTree(const Vec &A, const Vec &m, const ZZ &V = ZZ(1))\n{\n\tint N = A.length();\n\tassert (N == m.length());\n\tint depth = log2(N);\n\n\t//assume the input is of size a power of 2\n\tVec mtree;\n\tmtree.SetLength(2*N-1);\n\n\t//initialize leaves\n\tfor (int j = 0; j < pow(2, depth); j++)\n\t{\n\t\tint leaf = flatten_index(depth,j);\n\t\tmtree[leaf] = m[j];\n\t}\n\n\t//build up the product tree recursively\n\tfor (int i = depth-1; i >= 0; i--)\n\t{\n\t\tfor (int j = 0; j < pow(2,i); j++)\n\t\t{\n\t\t\tint parent = flatten_index(i,j);\n\t\t\tint left = 2*parent + 1;\n\t\t\tint right = left + 1;\n\n\t\t\t//padding is not necessary if on this step we catch IndexError with 1\n\t\t\tmtree[parent] = mtree[left]*mtree[right];\n\t\t}\n\t}\n\n\n\n\tVec Atree;\n\tAtree.SetLength(2*N-1);\n\n\t//initialize leaves\n\tfor (int j = 0; j < pow(2, depth); j++)\n\t{\n\t\tint leaf = flatten_index(depth, j);\n\t\tAtree[leaf] = A[j];\n\t}\n\n\t//build up the 'product' tree recursively\n\tfor (int i = depth-1; i >= 0; i--)\n\t{\n\t\tint leftmost = flatten_index(i,0);\n\t\tint leftmost_child = 2*leftmost + 1;\n\t\tAtree[leftmost] = A[leftmost_child];\n\n\t\tfor (int j = 1; j < pow(2, i); j++)\n\t\t{\n\t\t\tint parent = flatten_index(i,j);\n\t\t\tint superleft = 2*parent;\n\t\t\tint left = superleft + 1;\n\n\t\t\tAtree[parent] = Atree[superleft]*Atree[left];\n\t\t}\n\t}\n\n\tVec remtree;\n\tremtree.SetLength(2*N-1);\n\n\tremtree[0] = (V*A[0])%mtree[0];\n\n\tfor (int i = 0; i < depth; i++)\n\t{\n\t\t//notice it goes every two!\n\t\tfor (int j = 0; j < pow(2, i); j++)\n\t\t{\t\n\t\t\tint parent = flatten_index(i,j);\n\t\t\tint left = 2*parent + 1;\n\t\t\tint right = left + 1;\n\n\t\t\tremtree[left] = remtree[parent]%mtree[left];\n\t\t\tremtree[right] = (remtree[parent]*Atree[right])%mtree[right];\n\t\t}\n\t}\n\n\tVec remainders;\n\tremainders.SetLength(N);\n\n\tint leftmost_leaf = flatten_index(depth, 0);\n\tfor (int j = 0; j < N; j++)\n\t{\n\t\tremainders[j] = remtree[leftmost_leaf+j];\n\t}\n\treturn remainders;\n}\n\n//searches up to N for Wilson primes\nVec WilsonRemainders(long N, long interval)\n{\n\tVec A;\n\tVec m;\n\n\tA.SetLength(interval);\n\tm.SetLength(interval);\n\n\tVec remainders;\n\tremainders.SetLength(N);\n\n\tZZ V = ZZ(1);\n\n\tfor (int b = 0; b*interval < N; b++)\n\t{\n\t\tfor (int i = 0; i < interval; i++)\n\t\t{\n\t\t\tZZ val = ZZ(b*interval+(i+1));\n\n\t\t\tA[i] = val-1;\n\t\t\tif (val == 1)\n\t\t\t{\n\t\t\t\tA[i] += 1;\n\t\t\t}\n\n\t\t\tif (ProbPrime(val))\n\t\t\t{\n\t\t\t\tm[i] = val*val;\n\t\t\t}\n\n\t\t\telse\n\t\t\t{\n\t\t\t\tm[i] = 1;\n\t\t\t}\n\t\t}\n\n\t\tVec interval_remainders = RemTree(A, m, V);\n\t\tfor (int i = 0; i < interval; i++)\n\t\t{\n\t\t\tremainders[b*interval+i] = interval_remainders[i];\n\t\t\tV *= A[i];\n\t\t}\n\t}\n\n\treturn remainders;\n}\n\nint main()\n{\n\tlong N = pow(2,1);\n\n\tVec A;\n\tVec m;\n\n\tA.SetLength(N);\n\tm.SetLength(N);\n\n\trandom_device rd;\n\tmt19937 mt(rd());\n\tuniform_int_distribution dist(1, N);\n\n\tfor(int i = 0; i < N; i++){\n\t\tint bitsize = log2(i+1)+2;\n\n\t\t\n\t\tA[i] = dist(mt);\n\t\tm[i] = dist(mt);\n\n\t}\n\n\n\t//Vec ztree = zero_vector(2*N);\n\n\t//print_tree(A);\n\t//print_tree(m);\n\n\tauto start = chrono::high_resolution_clock::now();\n\tVec remainders = RemTree(A,m);\n\tVec WREM = WilsonRemainders(pow(2,18), pow(2,18));\n\tauto finish = chrono::high_resolution_clock::now();\n\n\tchrono::duration runtime = finish-start;\n\n\t//print_tree(WREM);\n\tcout << remainders[0] << endl;\n\tcout << WREM[562] << \" , \" << 563*563 << endl;\n\tcout << runtime.count() << endl;\n\n\n\n\n}\n", "meta": {"hexsha": "1e9fef8ca2fbb1e9e808fda88c54e76fc7591470", "size": 4998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "archives/cppfiles/RemTree_alternate.cpp", "max_stars_repo_name": "adienes/remainder-tree", "max_stars_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "archives/cppfiles/RemTree_alternate.cpp", "max_issues_repo_name": "adienes/remainder-tree", "max_issues_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "archives/cppfiles/RemTree_alternate.cpp", "max_forks_repo_name": "adienes/remainder-tree", "max_forks_repo_head_hexsha": "0aa76214ab6f2a4389ec45a239ea660749989a90", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.1086956522, "max_line_length": 101, "alphanum_fraction": 0.5942376951, "num_tokens": 1748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266013, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6900702662613903}} {"text": "// Compression methods for vectors\n// Author: Max Schwarz \n\n#include \n\n#include \n\n#include \"contrib/angles.h\"\n\n#include \n\n#define DEBUG 0\n\nnamespace vector_compression\n{\n\n// The \"hemi-oct\" compression scheme is taken from\n// Cigolle, Zina H., Sam Donow, and Daniel Evangelakos.\n// \"A survey of efficient representations for independent unit vectors.\"\n// Journal of Computer Graphics Techniques Vol 3.2 (2014).\n\n// Assume normalized input on +Z hemisphere.\n// Output is [-1, 1]\nstatic Eigen::Vector2f float32x3_to_hemioct(const Eigen::Vector3f& v)\n{\n\t// Project the hemisphere onto the hemi-octahedron,\n\t// and then project into the xy plane\n\tEigen::Vector2f p = v.head<2>() * (1.0f / (fabsf(v.x()) + fabsf(v.y()) + v.z()));\n\n\t// Rotate and scale the center diamond to the unit square\n\treturn Eigen::Vector2f(p.x() + p.y(), p.x() - p.y());\n}\n\nstatic Eigen::Vector3f hemioct_to_float32x3(const Eigen::Vector2f& e)\n{\n\t// Rotate and scale the unit square back to the center diamond\n\tEigen::Vector2f temp = 0.5f * Eigen::Vector2f(e.x() + e.y(), e.x() - e.y());\n\tEigen::Vector3f v;\n\tv << temp, 1.0 - fabsf(temp.x()) - fabsf(temp.y());\n\n\treturn v.normalized();\n}\n\nint32_t float_to_snormb(float v, int b)\n{\n\treturn std::round(std::min(1.0f, std::max(-1.0f, v)) * ((1 << (b-1)) - 1));\n}\n\nfloat snormb_to_float(int32_t v, int b)\n{\n\t// Sign extend\n\tif(v & (1 << (b-1)))\n\t\tv |= 0xFFFFFFFF & ~((1 << b) - 1);\n\n\treturn std::min(1.0f, std::max(-1.0f, ((float)v) / ((1 << (b-1)) - 1)));\n}\n\nvoid encodeQuaternion(const Eigen::Quaternionf& quat, uint8_t* dest)\n{\n\t// Recover rotation angle & axis\n\tfloat angle = 2.0f * acosf(quat.w());\n\tangle = angles::normalize_angle(angle);\n\n\tfloat norm = sqrtf(1.0f - quat.w()*quat.w());\n\n\tEigen::Vector3f axis;\n\n\tif(norm != 0)\n\t{\n\t\taxis << quat.x() / norm, quat.y() / norm, quat.z() / norm;\n\t}\n\telse\n\t\taxis << 0.0f, 0.0f, 0.0f;\n\n\t// Map to the upper hemisphere\n\tif(axis.z() < 0)\n\t{\n\t\taxis *= -1.0f;\n\t\tangle = -angle;\n\t}\n\n\tEigen::Vector2f hemi = float32x3_to_hemioct(axis);\n\n\tint32_t hemi_a = float_to_snormb(hemi.x(), 12);\n\tint32_t hemi_b = float_to_snormb(hemi.y(), 12);\n\n\tint32_t angle_sn = float_to_snormb(angle / M_PI, 16);\n\n#if DEBUG\n\tprintf(\"encode: %f, %f, %f, angle_sn: %u (0x%X)\\n\", hemi.x(), hemi.y(), angle, angle_sn, angle_sn);\n\tprintf(\"angle scale: %d\\n\", ((1 << (16-1)) - 1));\n#endif\n\n\tdest[0] = hemi_a;\n\tdest[1] = ((hemi_a >> 8) & 0xF) | ((hemi_b & 0xF) << 4);\n\tdest[2] = hemi_b >> 4;\n\tdest[3] = angle_sn;\n\tdest[4] = angle_sn >> 8;\n}\n\nEigen::Quaternionf decodeQuaternion(const uint8_t* src)\n{\n\tint32_t hemi_a = src[0] | (((uint32_t)src[1] & 0xF) << 8);\n\tint32_t hemi_b = (src[1] >> 4) | (((uint32_t)src[2]) << 4);\n\tint32_t angle_sn = src[3] | (((uint32_t)src[4]) << 8);\n\n\tEigen::Vector2f hemi(\n\t\tsnormb_to_float(hemi_a, 12), snormb_to_float(hemi_b, 12)\n\t);\n\n\tEigen::Vector3f axis = hemioct_to_float32x3(hemi);\n\n\tfloat angle = snormb_to_float(angle_sn, 16) * M_PI;\n\n#if DEBUG\n\tprintf(\"decode: %f, %f, %f, angle_sn: %d\\n\", hemi.x(), hemi.y(), angle, angle_sn);\n#endif\n\n\treturn Eigen::Quaternionf(Eigen::AngleAxisf(angle, axis));\n}\n\nEigen::Vector3f latticeToVector(const Eigen::Vector3i& lattice, float r)\n{\n\treturn r * Eigen::Vector3f(\n\t\tlattice.y() + lattice.z(),\n\t\tlattice.x() + lattice.z(),\n\t\tlattice.x() + lattice.y()\n\t);\n}\n\nEigen::Vector3f alignedLatticeToVector(const Eigen::Vector3i& lattice, float r)\n{\n\tEigen::Vector3f m = lattice.cast();\n\n\tEigen::Vector3f x = m + m.y() * Eigen::Vector3f::UnitY() + ((lattice.x() + lattice.z()) % 2) * Eigen::Vector3f::UnitY();\n\n\tx *= r;\n\n\treturn x;\n}\n\nstatic inline int sgn(float x)\n{\n\tif(x >= 0)\n\t\treturn 1;\n\telse\n\t\treturn -1;\n}\n\nstatic inline float roundFloat(float x)\n{\n\treturn std::round(x);\n}\n\nEigen::Vector3i vectorToAlignedLattice(const Eigen::Vector3f& p, float r)\n{\n\tEigen::Vector3f m = p / r;\n\n\tEigen::Vector3f cartesian_lattice = m.unaryExpr(std::ptr_fun(roundFloat));\n\tEigen::Vector3i lattice_int = cartesian_lattice.cast();\n\n\tif(lattice_int.sum() % 2 != 0)\n\t{\n\t\tEigen::Vector3f local = m - cartesian_lattice;\n\t\tint c;\n\t\tlocal.array().abs().maxCoeff(&c);\n\n\t\tlattice_int[c] += sgn(local[c]);\n\t}\n\n\tlattice_int.y() = (lattice_int.y() - ((lattice_int.x() + lattice_int.z()) % 2)) / 2;\n\n\treturn lattice_int;\n}\n\nEigen::Vector3i vectorToLattice(const Eigen::Vector3f& p, float r)\n{\n\tEigen::Vector3f normalized = p / r;\n\n\tEigen::Vector3f cartesian_lattice = normalized.unaryExpr(std::ptr_fun(roundFloat));\n\tEigen::Vector3i lattice_int = cartesian_lattice.cast();\n\n\tif(lattice_int.sum() % 2 != 0)\n\t{\n\t\tEigen::Vector3f local = normalized - cartesian_lattice;\n\t\tint c;\n\t\tlocal.array().abs().maxCoeff(&c);\n\n\t\tlattice_int[c] += sgn(local[c]);\n\t}\n\n\tEigen::Matrix3i inv;\n\tinv <<\n\t\t-1, 1, 1,\n\t\t1, -1, 1,\n\t\t1, 1, -1\n\t;\n\n\treturn (inv * lattice_int) / 2;\n}\n\nvoid encode3DVector6(const Eigen::Vector3f& vec, float extent, uint8_t* dest)\n{\n\t// We are using 16 bit resolution per lattice index.\n\tfloat lattice_r = extent / (2.0f * ((1 << 15)-1));\n\n\tEigen::Vector3i lattice = vectorToLattice(vec, lattice_r);\n\n\tfor(int i = 0; i < 3; ++i)\n\t{\n\t\tlattice[i] = std::min(32767, std::max(-32768, lattice[i]));\n\t\tdest[2*i] = lattice[i];\n\t\tdest[2*i+1] = lattice[i] >> 8;\n\t}\n}\n\nEigen::Vector3f decode3DVector6(float extent, const uint8_t* src)\n{\n\t// We are using 16 bit resolution per lattice index.\n\tfloat lattice_r = extent / (2.0f * ((1 << 15)-1));\n\n\tEigen::Vector3i lattice;\n\tfor(int i = 0; i < 3; ++i)\n\t{\n\t\tint16_t idx = src[2*i] | (((uint16_t)src[2*i+1]) << 8);\n\t\tlattice[i] = idx;\n\t}\n\n\treturn latticeToVector(lattice, lattice_r);\n}\n\nVectorCompression::VectorCompression(unsigned int bits)\n : m_bits(bits)\n{\n\tsetExtent(Eigen::Vector3f(1.0, 1.0, 1.0));\n}\n\nvoid VectorCompression::setExtent(const Eigen::Vector3f& extent)\n{\n\tm_extent = extent;\n\n\tm_r = powf(sqrtf(2.0) * extent.x() * extent.y() * extent.z() / (1LL << m_bits), 1.0f / 3.0f) * sqrtf(2.0);\n\n\tm_latticeExtent.x() = std::floor(extent.x() / m_r);\n\tm_latticeExtent.y() = std::floor(extent.y() / m_r / 2.0f);\n\tm_latticeExtent.z() = std::floor(extent.z() / m_r);\n\n\tuint64_t high = 8 * m_latticeExtent.x() * m_latticeExtent.y() * m_latticeExtent.z();\n\tif(high > (1ULL << m_bits))\n\t{\n\t\tstd::cerr << \"lattice overflow: \" << high << \" > \" << (1LL << 24) << \"\\n\";\n\t\tstd::cerr << \"calculated radius: \" << m_r;\n\t\tthrow std::runtime_error(\"lattice overflow\");\n\t}\n}\n\nuint64_t VectorCompression::compress(const Eigen::Vector3f& vec) const\n{\n\tEigen::Vector3i lattice = vectorToAlignedLattice(vec, m_r);\n\n\t// Shift to [0, 2*m_latticeExtent]\n\tlattice += m_latticeExtent;\n\n\t// Constrain\n\tlattice.x() = std::max(0, std::min(2*m_latticeExtent.x(), lattice.x()));\n\tlattice.y() = std::max(0, std::min(2*m_latticeExtent.y(), lattice.y()));\n\tlattice.z() = std::max(0, std::min(2*m_latticeExtent.z(), lattice.z()));\n\n\tuint64_t index = lattice.x() + lattice.y() * 2 * m_latticeExtent.x() + lattice.z() * 4 * m_latticeExtent.x() * m_latticeExtent.y();\n\n\t// Sanity check\n\tif(index >= (1ULL << m_bits))\n\t{\n\t\tstd::cerr << \"lattice overflow while compressing \" << vec.transpose() << \"\\n\";\n\t\tstd::cerr << \"radius: \" << m_r << \"\\n\";\n\t\tstd::cerr << \"lattice extents: \" << m_latticeExtent.transpose() << \"\\n\";\n\t\tstd::cerr << \"lattice coords: \" << lattice.transpose() << \"\\n\";\n\t\tstd::cerr << \"=> index: \" << index << \"\\n\";\n\t\tindex = (1 << m_bits) - 1;\n\t}\n\n\treturn index;\n}\n\nEigen::Vector3f VectorCompression::uncompress(uint64_t compressed) const\n{\n\tEigen::Vector3i lattice;\n\n\tlattice.z() = compressed / (4 * m_latticeExtent.x() * m_latticeExtent.y());\n\n\tuint64_t remainder = compressed % (4 * m_latticeExtent.x() * m_latticeExtent.y());\n\n\tlattice.y() = remainder / (2*m_latticeExtent.x());\n\tlattice.x() = remainder % (2*m_latticeExtent.x());\n\n\t// Shift to [-extent, extent]\n\tlattice -= m_latticeExtent;\n\n\treturn alignedLatticeToVector(lattice, m_r);\n}\n\nfloat VectorCompression::guaranteedPrecision() const\n{\n\treturn sqrt(2.0f) * m_r;\n}\n\n}\n", "meta": {"hexsha": "2c2bf181d50fffd6212e80df06996e556da246ef", "size": 7933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/vector_compression.cpp", "max_stars_repo_name": "AIS-Bonn/vector_compression", "max_stars_repo_head_hexsha": "b1975c924989949d5b4039e30ce50dbc873974a5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-04-01T12:33:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T15:13:58.000Z", "max_issues_repo_path": "src/vector_compression.cpp", "max_issues_repo_name": "AIS-Bonn/vector_compression", "max_issues_repo_head_hexsha": "b1975c924989949d5b4039e30ce50dbc873974a5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vector_compression.cpp", "max_forks_repo_name": "AIS-Bonn/vector_compression", "max_forks_repo_head_hexsha": "b1975c924989949d5b4039e30ce50dbc873974a5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-09-25T05:38:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T05:05:09.000Z", "avg_line_length": 25.7564935065, "max_line_length": 132, "alphanum_fraction": 0.6442707677, "num_tokens": 2668, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297887874625, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6900702573637083}} {"text": "// MIT License\n\n// Copyright (c) 2018 Benjamin Bercovici\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef STATE_HEADER \n#define STATE_HEADER\n\n#include \n\nnamespace OC{\n\n\tclass State{\n\n\tpublic:\n\n\t\tState(arma::vec state,double mu);\n\n\n\t\t/**\n\t\tComputes true anomaly from eccentric anomaly \n\t\t@param ecc eccentric anomaly\n\t\t@param e eccentricity (0 =< e < 1)\n\t\t@return true anomaly\n\t\t*/\n\t\tstatic double f_from_ecc(const double & ecc,const double & e);\n\n\t\t/**\n\t\tComputes eccentric anomaly eccentric from true anomaly\n\t\t@param f true anomaly\n\t\t@param e eccentricity (0 =< e < 1)\n\t\t@return eccentric anomaly\n\t\t*/\n\t\tstatic double ecc_from_f(const double & f,const double & e);\n\n\t\t/**\n\t\tComputes hyperbolic anomaly from true anomaly \n\t\t@param f true anomaly\n\t\t@param e eccentricity (1 < e)\n\t\t@return hyperbolic anomaly\n\t\t*/\n\t\tstatic double H_from_f(const double & f,const double & e);\n\n\t\t/**\n\t\tComputes true anomaly from hyperbolic anomaly\n\t\t@param H hyperbolic anomaly\n\t\t@param e eccentricity (1 < e)\n\t\t@return true anomaly\n\t\t*/\n\t\tstatic double f_from_H(const double & H,const double & e); \n\n\t\t/**\n\t\tComputes true anomaly from mean anomaly\n\t\t@param M mean anomaly\n\t\t@param e eccentricity (0 =< e < 1)\n\t\t@return true anomaly\n\t\t*/\n\t\tstatic double f_from_M(const double & M,const double & e);\n\n\t\t/**\n\t\tComputes eccentric anomaly eccentric from mean anomaly\n\t\t@param M mean anomaly\n\t\t@param e eccentricity (0 =< e < 1)\n\t\t@param pedantic if true, will print out convergence details\n\t\t@return eccentric anomaly\n\t\t*/\n\t\tstatic double ecc_from_M(const double & M,const double & e,const bool & pedantic = false);\n\t\t\n\n\t\t/**\n\t\tComputes hyperbolic anomaly eccentric from mean anomaly\n\t\t@param M mean anomaly\n\t\t@param e eccentricity (1 < e)\n\t\t@param pedantic if true, will print out convergence details\n\t\t@return hyperbolic anomaly\n\t\t*/\n\t\tstatic double H_from_M(const double & M,const double & e,const bool & pedantic = false);\n\t\t\n\n\t\t/**\n\t\tComputes mean anomaly from eccentric anomaly \n\t\t@param ecc eccentric anomaly\n\t\t@param e eccentricity (0 =< e < 1)\n\t\t@return mean anomaly\n\t\t*/\n\t\tstatic double M_from_ecc(const double & ecc,const double & e);\n\n\t\t/**\n\t\tComputes mean anomaly from hyperbolic anomaly \n\t\t@param H hyperbolic anomaly\n\t\t@param e eccentricity (1 < e)\n\t\t@return mean anomaly\n\t\t*/\n\t\tstatic double M_from_H(const double & H,const double & e);\n\n\t\t/**\n\t\tComputes mean anomaly from true anomaly \n\t\t@param f true anomaly\n\t\t@param e eccentricity (0 =< e < 1)\n\t\t@return mean anomaly\n\t\t*/\n\t\tstatic double M_from_f(const double & f,const double & e);\n\n\t\tvirtual double get_momentum() const = 0;\n\t\tvirtual double get_energy() const = 0;\n\t\tvirtual double get_a() const = 0;\n\t\tvirtual double get_eccentricity() const = 0;\n\n\n\t\t/**\n\t\tGet the state vector\n\t\t@return 6x1 state vector (either cartesian state or keplerian state) \n\t\t*/\n\t\tarma::vec get_state() const;\n\n\t\t/**\n\t\tGet mean motion\n\t\t@return mean motion (rad/s)\n\t\t*/\n\t\tdouble get_n() const;\n\n\n\t\t/**\n\t\tGet ellipse parameter\n\t\t@return ellipse parameter (m)\n\t\t*/\n\t\tdouble get_parameter() const;\n\n\n\t\t/**\n\t\tGet standard gravitational parameter\n\t\t@return standard gravitational parameter (kg^3/s^2)\n\t\t*/\n\t\tdouble get_mu() const;\n\n\n\t\t/**\n\t\tSet standard gravitational parameter\n\t\t@param mu standard gravitational parameter (kg^3/s^2)\n\t\t*/\n\t\tvoid set_mu(double mu);\n\n\t\t/**\n\t\tSets the state to the prescribed value\n\t\t@param state 6x1 state\n\t\t*/\n\t\tvoid set_state(arma::vec state) ;\n\n\n\n\tprotected:\n\t\tarma::vec state;\n\t\tdouble mu;\n\n\t};\n\n}\n\n#endif", "meta": {"hexsha": "5cccdb6e04092b061abd5c90eae3c045b7b3b755", "size": 4507, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/OrbitConversions/State.hpp", "max_stars_repo_name": "bbercovici/OrbitConversions", "max_stars_repo_head_hexsha": "c4cdc4604d91e90d89cfa6aa7739bef8cdb18739", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/OrbitConversions/State.hpp", "max_issues_repo_name": "bbercovici/OrbitConversions", "max_issues_repo_head_hexsha": "c4cdc4604d91e90d89cfa6aa7739bef8cdb18739", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/OrbitConversions/State.hpp", "max_forks_repo_name": "bbercovici/OrbitConversions", "max_forks_repo_head_hexsha": "c4cdc4604d91e90d89cfa6aa7739bef8cdb18739", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6079545455, "max_line_length": 92, "alphanum_fraction": 0.7080097626, "num_tokens": 1176, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.690059882735106}} {"text": "// lu_decomposition.cpp example program comparing float vs posit equation solver\n//\n// Copyright (C) 2017-2019 Stillwater Supercomputing, Inc.\n//\n// This file is part of the universal numbers project, which is released under an MIT Open Source license.\n\n#include \"common.hpp\"\n\n#include \n#include \n\n#include \n#include \n\nusing namespace std;\nusing namespace sw::unum;\n\n// Turn it off for now\n#define USE_POSIT\n\nint main(int argc, char** argv)\ntry {\n\tconst size_t nbits = 16;\n\tconst size_t es = 1;\n\tconst size_t vecSize = 32;\n\n#ifdef USE_POSIT\n\tusing Matrix = mtl::dense2D< posit >;\n\tusing Vector = mtl::dense_vector< posit >;\n#else\n\tusing Matrix = mtl::dense2D;\n\tusing Vector = mtl::dense_vector;\n#endif\n\n\n\tMatrix A(4, 4), L(4, 4), U(4, 4), AA(4, 4);\n\tVector\tv(4);\n\tdouble \tc = 1.0;\n\t\n\tfor (unsigned i = 0; i < 4; i++)\n\t\tfor (unsigned j = 0; j < 4; j++) {\n\t\t\tU[i][j] = i <= j ? c * (i + j + 2) : (0);\n\t\t\tL[i][j] = i > j ? c * (i + j + 1) : (i == j ? (1) : (0));\n\t\t}\n\n\tstd::cout << \"L is:\\n\" << L << \"U is:\\n\" << U;\n\tA = L * U;\n\tstd::cout << \"A is:\\n\" << A;\n\tAA = adjoint(A);\n\n\tfor (unsigned i = 0; i < 4; i++)\n\t\tv[i] = double(i);\n\n\tVector b(A*v), b2(adjoint(A)*v);\n\n\tMatrix LU(A);\n\tlu(LU);\n\tstd::cout << \"LU decomposition of A is:\\n\" << LU;\n\n\tMatrix B(lu_f(A));\n\tstd::cout << \"LU decomposition of A (as function result) is:\\n\" << B;\n\n\tVector v1(lu_solve_straight(A, b));\n\tstd::cout << \"v1 is \" << v1 << \"\\n\";\n\n\tVector v2(lu_solve(A, b));\n\tstd::cout << \"v2 is \" << v2 << \"\\n\";\n\n\tmtl::dense_vector P;\n\tlu(A, P);\n\tstd::cout << \"LU with pivoting is \\n\" << with_format(A, 5, 2) << \"Permutation is \" << P << \"\\n\";\n\tVector v3(lu_apply(A, P, b));\n\tstd::cout << \"v3 is \" << v3 << \"\\n\";\n\n\tVector v4(lu_adjoint_apply(A, P, b2));\n\tstd::cout << \"v4 is \" << v4 << \"\\n\";\n\n\tVector v5(lu_adjoint_solve(AA, b));\n\tstd::cout << \"v5 is \" << v5 << \"\\n\";\n\n\tint nrOfFailedTestCases = 0;\n\treturn nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS;\n}\ncatch (char const* msg) {\n\tcerr << msg << endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_internal_exception& err) {\n\tstd::cerr << \"Uncaught posit internal exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (std::runtime_error& err) {\n\tstd::cerr << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tcerr << \"caught unknown exception\" << endl;\n\treturn EXIT_FAILURE;\n}\n", "meta": {"hexsha": "f6f1d86ae1f1bd88a553515b6527c6c32d1e1217", "size": 2731, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/blas/lu_decomposition.cpp", "max_stars_repo_name": "fossabot/hpr-blas", "max_stars_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "applications/blas/lu_decomposition.cpp", "max_issues_repo_name": "fossabot/hpr-blas", "max_issues_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "applications/blas/lu_decomposition.cpp", "max_forks_repo_name": "fossabot/hpr-blas", "max_forks_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.287037037, "max_line_length": 106, "alphanum_fraction": 0.6151592823, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7956581000631542, "lm_q1q2_score": 0.6898640307983782}} {"text": "// Group A - Exact Pricing Methods\r\n//\r\n// by Scott Sidoli\r\n//\r\n// 6-9-19\r\n//\r\n// NormalDistribution.hpp\r\n//\r\n// Function pertaining to the normal distribution including the CDF and PDF.\r\n// Used in option pricing. \r\n\r\n#ifndef NormalDistribution_hpp\r\n#define NormalDistribution_hpp\r\n\r\n#include \r\n\r\nusing namespace std;\r\n#include \r\n#include \r\nusing namespace boost::math;\r\n\r\n\r\ndouble N(double x)\r\n{\r\n\r\n\tnormal_distribution<> myNormal(0.0, 1.0);\r\n\r\n\treturn cdf(myNormal, x);\r\n\r\n}\r\n\r\ndouble n(double x)\r\n{\r\n\r\n\tnormal_distribution<> myNormal(0.0, 1.0);\r\n\r\n\treturn pdf(myNormal, x);\r\n\r\n}\r\n\r\n#endif\r\n", "meta": {"hexsha": "d6c37ce871d3b1d81bdfd907de28961b2be5bb94", "size": 672, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "GroupA/GroupA/NormalDistribution.hpp", "max_stars_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_stars_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T08:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T08:14:37.000Z", "max_issues_repo_path": "GroupA/GroupA/NormalDistribution.hpp", "max_issues_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_issues_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GroupA/GroupA/NormalDistribution.hpp", "max_forks_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_forks_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.0, "max_line_length": 77, "alphanum_fraction": 0.6785714286, "num_tokens": 158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765140114859, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6897480935762412}} {"text": "#ifndef TRIUMF_SUPERCONDUCTIVITY_PHENOMENOLOGY_HPP\n#define TRIUMF_SUPERCONDUCTIVITY_PHENOMENOLOGY_HPP\n\n#include \n\n#include \n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n//\nnamespace superconductivity {\n\n// purely phenomenological relations in superconductivity\nnamespace phenomenology {\n\n// temperature dependence of the (reduced) penetration depth\ntemplate \nT reduced_penetration_depth(T reduced_temperature, T exponent) {\n if (reduced_temperature >= 1.0) {\n return std::numeric_limits::infinity();\n } else if (reduced_temperature <= 0.0) {\n return 1.0;\n } else {\n return 1.0 / std::sqrt(1.0 - std::pow(reduced_temperature, exponent));\n }\n}\n\n// temperature dependence of the (reduced) penetration depth\ntemplate \nT reduced_penetration_depth(T temperature, T critical_temperature, T exponent) {\n return reduced_penetration_depth(temperature / critical_temperature,\n exponent);\n}\n\n// temperature dependence of the penetration depth\ntemplate \nT penetration_depth(T temperature, T critical_temperature, T exponent,\n T lambda_0) {\n return lambda_0 * reduced_penetration_depth(\n temperature, critical_temperature, exponent);\n}\n\n// reduced gap\n// after Halbritter ca. 1970\ntemplate T reduced_gap(T reduced_temperature) {\n if (reduced_temperature >= 1.0) {\n return 0.0;\n } else if (reduced_temperature <= 0.0) {\n return 1.0;\n } else {\n return std::cos(boost::math::constants::half_pi() *\n std::pow(reduced_temperature, 2));\n }\n}\n\n/// The superconducting transition temperature T_c (K) as a function of applied\n/// magnetic field. The calculation assumes a \"parabolic\" relationship by\n/// default (i.e., exponent = 0.5).\ntemplate \nT critical_temperature(T applied_field, T critical_temperature_0,\n T critical_field, T exponent = 0.5) {\n if (applied_field < 0.0) {\n // don't consider negative fields\n return critical_temperature_0;\n } else if (applied_field > critical_field) {\n // no superconductivity above the critical field\n return 0.0;\n } else {\n // the phenomenological field dependence\n return critical_temperature_0 *\n std::pow(1.0 - (applied_field / critical_field), exponent);\n }\n}\n\n/// The superconducting transition temperature T_c (K) as a function of applied\n/// magnetic field. The calculation assumes a relationship obtained from\n/// inverting: Hc2(T) / Hc2(0) = [1 - (T / Tc)^2] / [1 + (T / Tc)^2]. See e.g.,:\n/// M. Tinkham, Phys. Rev. 129, 2413 (1963).\n/// https://doi.org/10.1103/PhysRev.129.2413\ntemplate \nT critical_temperature_II(T applied_field, T critical_temperature_0,\n T upper_critical_field) {\n if (applied_field < 0.0) {\n // don't consider negative fields\n return critical_temperature_0;\n } else if (applied_field > upper_critical_field) {\n // no superconductivity above the critical field\n return 0.0;\n } else {\n // reduced field\n T reduced_field = applied_field / upper_critical_field;\n // the phenomenological field dependence\n return critical_temperature_0 *\n std::sqrt((1.0 - reduced_field * reduced_field) /\n (1.0 + reduced_field * reduced_field));\n }\n}\n\n} // namespace phenomenology\n\n} // namespace superconductivity\n\n} // namespace triumf\n\n#endif // TRIUMF_SUPERCONDUCTIVITY_PHENOMENOLOGY_HPP\n", "meta": {"hexsha": "77acadf0f98b620bb2af06fb9efeb07a38097311", "size": 3591, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/superconductivity/phenomenology.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/triumf/superconductivity/phenomenology.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/triumf/superconductivity/phenomenology.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5607476636, "max_line_length": 80, "alphanum_fraction": 0.693678641, "num_tokens": 885, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032941988938413, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6896504545682296}} {"text": "//\n// Created by tomlucas on 26.06.20.\n//\n\n#include \"types/SO3.h\"\n#include \n#include \"GaussianNoiseVector.h\"\n#include \"adekf_viz.h\"\n#include \n\n#define max_iterations 100\n#define weighted_mean_epsilon 1e-12\nusing namespace adekf;\n\n/**\n * Calculate the weighted mean of quaternions\n * @param quats list of quaternions\n * @param probs the corresponding probabilities\n * @return The weighted mean of quats\n */\nSO3d weightedMean(std::vector &quats, std::vector &probs)\n{\n SO3d sum = quats[0];\n SO3d old_sum = sum;\n decltype(sum - old_sum) diff_sum = diff_sum.Zero();\n decltype(sum - old_sum) selector_weights = selector_weights.Zero();\n\n int iterations = 0;\n do\n {\n iterations++;\n old_sum = sum;\n diff_sum = diff_sum.Zero();\n for (int i = 0; i < quats.size(); i++)\n {\n diff_sum = diff_sum + probs[i] * (quats[i] - sum); //.cwiseProduct(selectors[filter_bank[i].second]);\n }\n sum = sum + diff_sum; //.cwiseQuotient(selector_weights);\n } while (iterations <= max_iterations && (sum - old_sum).norm() > weighted_mean_epsilon);\n if (iterations > max_iterations)\n printf(\"Warning: stopped due to excess of iterations\");\n return sum;\n}\n\n/**\n * Calculate the weighted covariance of quaternion distributions\n * @param quats The list of mean points of the distributions\n * @param covs The covariances of the distributions\n * @param probs The weights of the distributions\n * @param target The weighted mean of the means\n * @return The weighted covariance sum\n */\nEigen::Matrix3d weightedCovarianceSum(std::vector &quats, std::vector &covs, std::vector &probs, const SO3d &target)\n{\n Eigen::Matrix3d sum = Eigen::Matrix3d::Zero();\n Eigen::Matrix3d weights = Eigen::Matrix3d::Zero();\n for (size_t i = 0; i < quats.size(); i++)\n {\n if (probs[i] > 0.)\n {\n auto diff = (quats[i] - target).eval();\n auto plus_diff = eval((quats[i] + getDerivator<3>()) - target);\n Eigen::Matrix D(3, 3);\n //Initialise the Jacobian\n for (size_t j = 0; j < 3; ++j)\n D.col(j) = plus_diff[j].v; //write to cols since col major (transposes matrix )\n //Covariance select = selectors[filter_bank[i].second] * selectors[filter_bank[i].second].transpose() * probabilities(i);\n sum += probs[i] * (D.transpose() * (covs[i]) * D + diff * diff.transpose());\n //weights += select;\n }\n }\n assert(sum.determinant() > 0.);\n return sum;\n}\n\n/**\n * Calculates the weighted mean of quaternions with naive/improper mixing (in parameter space)\n * @param quats The quaternions to mix\n * @param probs The weights\n * @return Weighted mean of quats\n */\nSO3d badWeightedMean(std::vector &quats, std::vector &probs)\n{\n Eigen::Vector4d sum = sum.Zero();\n for (int i = 0; i < quats.size(); i++)\n {\n sum += quats[i].coeffs() * probs[i];\n }\n sum = sum.normalized();\n return SO3d(sum.data());\n}\n/**\n * Calculates a numeric gold standard Variance of quats.\n *\n * Uses a list of uniformly sampled quaternions from the distributions and combines them with the proper mixing\n *\n * @param quats The list of uniformly sampled quaternions\n * @param probs The probabilities of the quaternioms\n * @param target The weighted mean of means of the distributions\n * @return The weighted covariance sum\n */\nEigen::Matrix3d goldWeightedCovarianceSum(std::vector &quats, std::vector &probs, const SO3d &target)\n{\n\n Eigen::Matrix3d sum = Eigen::Matrix3d::Zero();\n for (size_t i = 0; i < quats.size(); i++)\n {\n if (probs[i] > 0.)\n {\n auto diff = (quats[i] - target).eval();\n sum += probs[i] * (diff * diff.transpose());\n }\n }\n return sum;\n}\n\n/**\n * Improper way of the weighted sum of covariances.\n *\n * Uses the naive approach from the original IMM\n * @param quats The list of quaternion means\n * @param covs The covariances\n * @param probs The weights of the quaternions\n * @param target The weighted mean of means\n * @return The naive weighted covariance sum\n */\nEigen::Matrix3d badWeightedCovarianceSum(std::vector &quats, std::vector &covs, std::vector &probs, const SO3d &target)\n{\n\n Eigen::Matrix3d sum = Eigen::Matrix3d::Zero();\n for (size_t i = 0; i < quats.size(); i++)\n {\n if (probs[i] > 0.)\n {\n auto diff = (quats[i] - target).eval();\n sum += probs[i] * (covs[i] + diff * diff.transpose());\n }\n }\n return sum;\n}\n\n/**\n * Calculates the difference between the bp-weighted mean and the naive weighted mean\n * @param quats List of quaternions\n * @param probs weights\n * @return BPMean-NaiveMean\n */\ndouble diff(std::vector &quats, std::vector &probs)\n{\n return (weightedMean(quats, probs) - badWeightedMean(quats, probs)).norm();\n}\n\n/**\n * Plots the naive mixing vs the boxplus mixing\n * @param argc command line argument counter\n * @param argv command line arguments\n */\nvoid plot_bad_vs_bp()\n{\n std::vector quats;\n std::vector> probs;\n std::vector covs;\n covs.push_back(Eigen::Matrix3d::Identity() * 0.01);\n covs.push_back(Eigen::Matrix3d::Identity() * 0.02);\n\n quats.push_back(SO3d(Eigen::Vector3d(0, 0, 0)));\n quats.push_back(SO3d(Eigen::Vector3d(0, 0, 0.0)));\n std::vector trial{0.7, 0.3};\n std::cout << weightedMean(quats, trial) << std::endl;\n //return 0;\n //list of probability pairs\n for (double prob = 0.5; prob <= 1.; prob += 0.05)\n {\n probs.push_back(std::vector(2));\n probs.back()[0] = prob;\n probs.back()[1] = 1. - prob;\n }\n //compute for different sigmas\n for (double sigma = 0.0; sigma < 3.; sigma += 0.01)\n {\n quats[1] = SO3d{Eigen::Vector3d(0, 0, sigma)};\n Eigen::Matrix diffs = diffs.Zero(probs.size());\n //compute mean diff for different probabilities\n for (int i = 0; i < probs.size(); i++)\n {\n diffs(i) = diff(quats, probs[i]);\n }\n std::cout << \"Sigma: \" << sigma << \" Max diff: \" << diffs.maxCoeff() << \" Diffs: \" << diffs.transpose() << std::endl;\n adekf::viz::plotVector(diffs, \"Mean diff\", 300, \"abcdefghiklmn\");\n //compute covariance diff for different probabilities\n for (int i = 0; i < probs.size(); i++)\n {\n diffs(i) = (weightedCovarianceSum(quats, covs, probs[i], weightedMean(quats, probs[i])) - badWeightedCovarianceSum(quats, covs, probs[i], badWeightedMean(quats, probs[i]))).norm();\n }\n std::cout << \"Sigma: \" << sigma << \" Max diff: \" << diffs.maxCoeff() << \" Diffs: \" << diffs.transpose() << std::endl;\n adekf::viz::plotVector(diffs, \"Sigma diff\", 300, \"abcdefghiklmn\");\n }\n}\n\n/**\n * Calculates the likelihood of a vector given the covariance of the distribution\n * @param delta the vector to check the likelihood of\n * @param sigma The covariance\n * @return N(delta; 0, sigma)\n */\ndouble likelihood(const Eigen::Vector3d &delta, const Eigen::Matrix3d &sigma)\n{\n return exp(-0.5 * (delta).transpose() * sigma.inverse() * delta) / sqrt(sigma.determinant() * pow((2 * M_PI), sigma.rows()));\n}\n\n/**\n * Plots a numeric gold standard mixing against the naive mixing and the bp-mixing\n * @param argc command line argument counter\n * @param argv command line arguments\n */\nvoid plot_real_gold_vs_()\n{\n std::vector quats(2);\n std::vector probs{0.7, 0.3};\n\n std::vector covs;\n covs.push_back(Eigen::Matrix3d::Identity() * 0.01);\n covs.push_back(Eigen::Matrix3d::Identity() * 0.02);\n //Compute for different sigmas\n for (double sigma = 0.0; sigma < 3.; sigma += 0.05)\n {\n quats[0] = (SO3d(Eigen::Vector3d(0, 0, 0)));\n quats[1] = (SO3d(Eigen::Vector3d(0, 0, sigma)));\n //return 0;\n\n const double max = M_PI / 2;\n const double step = 0.02;\n const int steps = max / step;\n std::vector gold_quats(pow(steps, 3));\n std::vector gold_probs(pow(steps, 3));\n //uniform sample of quaternions from distributions\n for (int l = 0; l < probs.size(); ++l)\n {\n\n for (int i = -steps; i < steps; i++)\n {\n for (int j = -steps; j < steps; j++)\n {\n for (int k = -steps; k < steps; ++k)\n {\n Eigen::Vector3d delta = step * Eigen::Vector3d(i, j, k);\n gold_quats.push_back(quats[l] + delta);\n gold_probs.push_back(likelihood(delta, covs[l]) * probs[l]);\n }\n }\n }\n }\n double sum = 0;\n //normalise probabilities of sampled quats\n for (const auto &prob : gold_probs)\n {\n sum += prob;\n }\n for (auto &prob : gold_probs)\n {\n prob /= sum;\n }\n sum = 0;\n //compute means\n auto mean = weightedMean(quats, probs);\n auto badMean = badWeightedMean(quats, probs);\n auto goldMean = weightedMean(gold_quats, gold_probs);\n Eigen::Matrix diffs = diffs.Zero();\n diffs(0) = (mean - goldMean).norm();\n diffs(1) = (badMean - goldMean).norm();\n adekf::viz::plotVector(diffs, \"Gold Mean diff\", 305, \"mb\");\n auto goldCov = goldWeightedCovarianceSum(gold_quats, gold_probs, goldMean);\n diffs(0) = (weightedCovarianceSum(quats, covs, probs, mean) - goldCov).norm();\n diffs(1) = (badWeightedCovarianceSum(quats, covs, probs, badMean) - goldCov).norm();\n adekf::viz::plotVector(diffs, \"Gold Sigma diff\", 305, \"mb\");\n }\n}\n\nEigen::Vector3d weightedRefMean(aligned_vector &quats, std::vector &probs, SO3d ref)\n{\n Eigen::Vector3d sum = sum.Zero();\n\n for (int i = 0; i < quats.size(); i++)\n {\n sum = sum + probs[i] * (quats[i] - ref);\n }\n return sum;\n}\n\n/**\n * Calculates a numeric gold standard Variance of quats.\n *\n * Uses a list of uniformly sampled quaternions from the distributions and combines them with the proper mixing\n *\n * @param quats The list of uniformly sampled quaternions\n * @param probs The probabilities of the quaternioms\n * @param target The weighted mean of means of the distributions\n * @return The weighted covariance sum\n */\nEigen::Matrix3d goldWeightedCovarianceSumRef(aligned_vector &quats, std::vector &probs, const SO3d &ref)\n{\n\n Eigen::Matrix3d sum = Eigen::Matrix3d::Zero();\n Eigen::Vector3d mu_ref = weightedRefMean(quats, probs, ref);\n for (size_t i = 0; i < quats.size(); i++)\n {\n if (probs[i] > 0.)\n {\n auto diff = ((quats[i] - ref) - mu_ref).eval();\n sum += probs[i] * (diff * diff.transpose());\n }\n }\n return sum;\n}\n\n/**\n * Plots a numeric gold standard mixing against the naive mixing and the bp-mixing\n * @param argc command line argument counter\n * @param argv command line arguments\n */\nvoid plot_covariance_centered()\n{\n SO3d r1, r2; //r1 r2\n\n Eigen::Matrix3d cov = cov.Identity() * 0.1;\n //Compute for different sigmas\n for (double sigma = 0.0; sigma < 3.; sigma += 0.05)\n {\n r1 = (SO3d(Eigen::Vector3d(0, 0, 0)));\n r2 = (SO3d(Eigen::Vector3d(0, 0, sigma)));\n Eigen::Vector3d diff = r2 - r1;\n const double max = M_PI / 2;\n const double step = 0.02;\n const int steps = max / step;\n aligned_vector gold_quats(pow(steps, 3));\n std::vector gold_probs(pow(steps, 3));\n //uniform sample of quaternions from distribution\n\n for (int i = -steps; i < steps; i++)\n {\n for (int j = -steps; j < steps; j++)\n {\n for (int k = -steps; k < steps; ++k)\n {\n Eigen::Vector3d delta = step * Eigen::Vector3d(i, j, k);\n gold_quats.push_back(r1 + (diff + delta));\n gold_probs.push_back(likelihood(delta, cov));\n }\n }\n }\n double sum = 0;\n //normalise probabilities of sampled quats\n for (const auto &prob : gold_probs)\n {\n sum += prob;\n }\n for (auto &prob : gold_probs)\n {\n prob /= sum;\n }\n sum = 0;\n //compute means\n\n Eigen::Matrix diffs = diffs.Zero();\n auto goldCov = goldWeightedCovarianceSumRef(gold_quats, gold_probs, r2);\n auto transform = transformReferenceJacobian(r1, r2, diff);\n auto linearCov = transform * cov * transform.transpose();\n diffs(0)=(linearCov-goldCov).norm();\n diffs(1)=(cov-goldCov).norm();\n //diffs(0) = goldCov.determinant();\n adekf::viz::plotVector(diffs, \"Covariance transform centered\", 61, \"mb\");\n }\n}\n\nvoid plot_covariance_displaced()\n{\n SO3d r1, r2; //r1 r2\n\n Eigen::Matrix3d cov = cov.Identity() * 0.1;\n //Compute for different sigmas\n for (double sigma = 0.0; sigma < 3.; sigma += 0.05)\n {\n r1 = (SO3d(Eigen::Vector3d(0, 0, 0)));\n r2 = (SO3d(Eigen::Vector3d(0, 0, sigma)));\n Eigen::Vector3d diff = r2 - r1;\n const double max = M_PI / 2;\n const double step = 0.02;\n const int steps = max / step;\n aligned_vector gold_quats(pow(steps, 3));\n std::vector gold_probs(pow(steps, 3));\n //uniform sample of quaternions from distribution\n\n for (int i = -steps; i < steps; i++)\n {\n for (int j = -steps; j < steps; j++)\n {\n for (int k = -steps; k < steps; ++k)\n {\n Eigen::Vector3d delta = step * Eigen::Vector3d(i, j, k);\n gold_quats.push_back(r1 + (delta));\n gold_probs.push_back(likelihood(delta, cov));\n }\n }\n }\n double sum = 0;\n //normalise probabilities of sampled quats\n for (const auto &prob : gold_probs)\n {\n sum += prob;\n }\n for (auto &prob : gold_probs)\n {\n prob /= sum;\n }\n sum = 0;\n //compute means\n\n Eigen::Matrix diffs = diffs.Zero();\n auto goldCov = goldWeightedCovarianceSumRef(gold_quats, gold_probs, r2);\n auto transform = transformReferenceJacobian(r1, r2);\n auto linearCov = transform * cov * transform.transpose();\n diffs(0)=(linearCov-goldCov).norm();\n diffs(1)=(cov-goldCov).norm();\n //diffs(0) = goldCov.determinant();\n adekf::viz::plotVector(diffs, \"Covariance transform displaced\", 61, \"mb\");\n }\n}\n\n\nvoid plot_covariance_gold()\n{\n SO3d r1, r2; //r1 r2\n\n Eigen::Matrix3d cov = cov.Identity() * 0.1;\n //Compute for different sigmas\n for (double sigma = 0.0; sigma < 3.; sigma += 0.05)\n {\n r1 = (SO3d(Eigen::Vector3d(0, 0, 0)));\n r2 = (SO3d(Eigen::Vector3d(0, 0, sigma)));\n Eigen::Vector3d diff = r2 - r1;\n const double max = M_PI / 2;\n const double step = 0.02;\n const int steps = max / step;\n aligned_vector gold_quats_centered(pow(steps, 3));\n \n aligned_vector gold_quats_displaced(pow(steps, 3));\n \n std::vector gold_probs(pow(steps, 3));\n\n //uniform sample of quaternions from distribution\n\n for (int i = -steps; i < steps; i++)\n {\n for (int j = -steps; j < steps; j++)\n {\n for (int k = -steps; k < steps; ++k)\n {\n Eigen::Vector3d delta = step * Eigen::Vector3d(i, j, k);\n gold_quats_displaced.push_back(r1 + (delta));\n gold_quats_centered.push_back(r1+(diff+delta));\n gold_probs.push_back(likelihood(delta, cov));\n }\n }\n }\n double sum = 0;\n //normalise probabilities of sampled quats\n for (const auto &prob : gold_probs)\n {\n sum += prob;\n }\n for (auto &prob : gold_probs)\n {\n prob /= sum;\n }\n sum = 0;\n //compute means\n\n Eigen::Matrix diffs = diffs.Zero();\n auto goldCovDisplaced = goldWeightedCovarianceSumRef(gold_quats_displaced, gold_probs, r2);\n auto goldCovCentered=goldWeightedCovarianceSumRef(gold_quats_centered,gold_probs,r2);\n diffs(0)=goldCovDisplaced.determinant()/cov.determinant();\n diffs(1)=goldCovCentered.determinant()/cov.determinant();\n diffs(2)=diffs(0)*diffs(1);\n\n\n //diffs(0) = goldCov.determinant();\n adekf::viz::plotVector(diffs, \"Covariance transform gold\", 61, \"DCM\");\n auto transform = transformReferenceJacobian(r1, r2);\n auto linearCov = (transform * cov * transform.transpose()).eval();\n diffs(0)=linearCov.determinant()/cov.determinant();\n transform=transformReferenceJacobian(r1,r2,diff);\n linearCov = transform * cov * transform.transpose();\n diffs(1)=linearCov.determinant()/cov.determinant();\n diffs(2)=diffs(0)*diffs(1);\n adekf::viz::plotVector(diffs, \"Covariance transform linear\", 61, \"DCM\");\n }\n}\n\nstd::vector threads;\nauto parallel=[](auto function){ threads.emplace_back(function);};\nint main(int argc, char *argv[])\n{\n viz::initGuis(argc, argv);\n \n //Choose some to plot\n //parallel(plot_bad_vs_bp);\n //parallel(plot_real_gold_vs_);//takes really long ~10 min\n //parallel(plot_covariance_displaced);\n //parallel(plot_covariance_centered); \n parallel(plot_covariance_gold);\n viz::runGuis();\n for(auto & thread: threads) thread.join();\n return 0;\n}", "meta": {"hexsha": "ea56ee99dc7a8fa29f35797ee9fc3529ffb0cf23", "size": 17908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QuatMixing.cpp", "max_stars_repo_name": "TomLKoller/Boxplus-IMM", "max_stars_repo_head_hexsha": "4f610967b8b9d3ed5b7110db7019d2acbc8ca57b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T08:50:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-13T13:45:56.000Z", "max_issues_repo_path": "QuatMixing.cpp", "max_issues_repo_name": "TomLKoller/Boxplus-IMM", "max_issues_repo_head_hexsha": "4f610967b8b9d3ed5b7110db7019d2acbc8ca57b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-07-16T06:50:19.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-04T13:37:04.000Z", "max_forks_repo_path": "QuatMixing.cpp", "max_forks_repo_name": "TomLKoller/Boxplus-IMM", "max_forks_repo_head_hexsha": "4f610967b8b9d3ed5b7110db7019d2acbc8ca57b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-07-17T08:39:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-17T08:39:15.000Z", "avg_line_length": 34.8404669261, "max_line_length": 192, "alphanum_fraction": 0.5869443824, "num_tokens": 5015, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818986, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6896240167433088}} {"text": "/*\n * euclidean.hpp\n *\n * Created on: Aug 16, 2009\n * Author: stewie\n */\n\n#ifndef EUCLIDEAN_HPP_\n#define EUCLIDEAN_HPP_\n\n#include \n#include // for std::plus\n#include // for std::inner_product\n\n#include \n#include \n\n/**\n * @ingroup lab\n *\n * @file euclidean.hpp\n *\n * This file contains routines for computing various kinds of distances between\n * attractors and other objects.\n */\n\nnamespace bn {\n\nnamespace detail {\n\n/**\n * @private\n * Helper class to compute a squared difference.\n */\nstruct SquareDifference {\n\t/**\n\t * Result type of this function object.\n\t */\n\ttypedef double result_type;\n\n\t/**\n\t * Computes a squared difference.\n\t * @param x an object\n\t * @param y another object\n\t * @return the squared difference\n\t */\n\ttemplate result_type operator()(const T& x, const T& y) const {\n\t\treturn std::pow(x - y, 2);\n\t}\n};\n\n}\n\n/**\n * @ingroup lab\n *\n * Computes the euclidean distance between two ranges.\n *\n * The second range shall have at least as many elements as the first.\n * @param first1 input iterator to the initial position of the first range\n * @param last1 input iterator to the final position of the first range\n * @param first2 input iterator to the initial position of the second range\n * @return the euclidean distance\n */\ntemplate double euclidean_distance(\n\t\tconst InputIterator first1, const InputIterator last1,\n\t\tconst InputIterator first2) {\n\treturn std::sqrt(std::inner_product(first1, last1, first2, 0.0, std::plus<\n\t\t\tdouble>(), detail::SquareDifference()));\n}\n\n/**\n * @ingroup lab\n *\n * Computes the euclidean distance between two ranges.\n *\n * The second range shall have at least as many elements as the first. This\n * overload uses concepts from \n * The Boost Range Library. Practically it is syntactic sugar which replaces:\n * @code\n * vector v1 = ...\n * vector v2 = ...\n * euclidean_distance(v1.begin(), v1.end(), v2.begin());\n * @endcode\n * with the tighter:\n * @code\n * vector v1 = ...\n * vector v2 = ...\n * euclidean_distance(v1, v2);\n * @endcode\n * @param x first input range\n * @param y second input range\n * @return the euclidean distance\n */\ntemplate double euclidean_distance(\n\t\tconst SinglePassRange& x, const SinglePassRange& y) {\n\treturn euclidean_distance(boost::begin(x), boost::end(x), boost::begin(y));\n}\n\n/**\n * @ingroup lab\n *\n * A function object to compute the euclidean distance between objects.\n *\n * This is particularly useful in STL algorithms since it is cumbersome (or\n * simply impossible) to pass template function pointers as arguments.\n *\n * For example:\n * @code\n * vector expr = ...\n * util::Matrix m = make_distance_matrix(expr.begin(),\n * \texpr.end(), &euclidean_distance);\n * @endcode\n * is wrong because the compiler cannot determine which overload to choose; also\n * that function is a template so you have to explicitly instantiate its\n * parameters to take a pointer. On the contrary, this is simpler and correct:\n * @code\n * vector expr = ...\n * util::Matrix m = make_distance_matrix(expr.begin(),\n * \texpr.end(), Euclidean());\n * @endcode\n */\nstruct Euclidean {\n\t/**\n\t * Result type of this function object.\n\t */\n\ttypedef double result_type;\n\n\t/**\n\t * Computes the euclidean distance between two vector of the same length.\n\t * @param x the first vector\n\t * @param y the second vector\n\t * @return the euclidean distance\n\t */\n\ttemplate result_type operator()(const T& x, const T& y) const {\n\t\treturn euclidean_distance(x, y);\n\t}\n};\n\n}\n\n#endif /* EUCLIDEAN_HPP_ */\n", "meta": {"hexsha": "7c5f66f9782f98d011b105729586cea4a4059be4", "size": 3730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/include/BnSimulator/lab/euclidean.hpp", "max_stars_repo_name": "Markfrancisrogers/BooleanNetwork", "max_stars_repo_head_hexsha": "62e755d938b70e5907e8561909a0637f0682b9b4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-04T14:57:48.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-04T19:03:51.000Z", "max_issues_repo_path": "booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/include/BnSimulator/lab/euclidean.hpp", "max_issues_repo_name": "Markfrancisrogers/BooleanNetwork", "max_issues_repo_head_hexsha": "62e755d938b70e5907e8561909a0637f0682b9b4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "booleannetwork-code-66-trunk/booleannetwork-code-66-trunk/include/BnSimulator/lab/euclidean.hpp", "max_forks_repo_name": "Markfrancisrogers/BooleanNetwork", "max_forks_repo_head_hexsha": "62e755d938b70e5907e8561909a0637f0682b9b4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0839160839, "max_line_length": 81, "alphanum_fraction": 0.7032171582, "num_tokens": 910, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171069, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6896240166838986}} {"text": "/* Copyright (C) 2012-2017 IBM Corp.\n * This program is Licensed under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. See accompanying LICENSE file.\n */\n/* EncryptedArray.cpp - Data-movement operations on arrays of slots\n */\n#include \nNTL_CLIENT\n#include \"EncryptedArray.h\"\n#include \"polyEval.h\"\n\nstatic void buildDigitPolynomial(ZZX& result, long p, long e);\n\n\n// extractDigits assumes that the slots of *this contains integers mod p^r\n// i.e., that only the free terms are nonzero. (If that assumptions does\n// not hold then the result will not be a valid ciphertext anymore.)\n// \n// It returns in the slots of digits[j] the j'th-lowest gigits from the\n// integers in the slots of the input. Namely, the i'th slot of digits[j]\n// contains the j'th digit in the p-base expansion of the integer in the\n// i'th slot of the *this.\n//\n// If the shortCut flag is set then digits[j] contains the j'th digits wrt\n// mod-p plaintext space and the highest possible level (for all j). Otherwise\n// digits[j] still contains the j'th digit in the base-p expansion, but wrt\n// mod-p^{r-j} plaintext space, and all the ciphertexts are at the same level.\nvoid extractDigits(vector& digits, const Ctxt& c, long r, bool shortCut)\n{\n FHEcontext& context = (FHEcontext&) c.getContext();\n long rr = c.effectiveR();\n if (r<=0 || r>rr) r = rr; // how many digits to extract\n\n long p = context.zMStar.getP();\n ZZX x2p;\n if (p>3) { \n buildDigitPolynomial(x2p, p, r);\n }\n\n Ctxt tmp(c.getPubKey(), c.getPtxtSpace());\n digits.resize(r, tmp); // allocate space\n vector w(r, tmp);\n for (long i=0; i p2e/2) y[j] -= p2e;\n while (y[j] < -(p2e/2)) y[j] += p2e;\n }\n interpolateMod(result, x, y, p, e);\n assert(deg(result)\n#include \n\n#include \n#include \n\nnamespace Chebyshev2Utilities\n{\n template\n void create_chebyshev2_analog_coefficients(int order, DataType ripple, EQUtilities::ZPK& zpk)\n {\n zpk.z.clear(); // no zeros for this filter type\n zpk.p.clear();\n \n DataType de = static_cast(1.0 / std::sqrt(std::pow(10, (0.1 * ripple)) - 1));\n DataType mu = static_cast(boost::math::asinh(1.0 / de) / order);\n \n for(gsl::index i = -order+1; i < order; i += 2)\n {\n std::complex p1 = -std::complex(std::cos(i * boost::math::constants::pi() / (2 * order)), std::sin(i * boost::math::constants::pi() / (2 * order)));\n std::complex p2 = std::complex(std::sinh(mu) * p1.real(), std::cosh(mu) * p1.imag());\n \n zpk.p.push_back(std::complex(1, 0) / p2);\n \n if(i == 0)\n {\n continue;\n }\n \n zpk.z.push_back(std::complex(0, 1 / std::sin(i * boost::math::constants::pi() / (2 * order))));\n }\n \n std::complex f = 1;\n for(gsl::index i = 0; i < zpk.p.size(); ++i)\n {\n f *= - zpk.p[i];\n }\n for(gsl::index i = 0; i < zpk.z.size(); ++i)\n {\n f /= - zpk.z[i];\n }\n zpk.k = f.real();\n }\n \n template\n void create_default_chebyshev2_coeffs(size_t order, DataType ripple, DataType Wn, Container& coefficients_in, Container& coefficients_out)\n {\n EQUtilities::ZPK zpk;\n\n int fs = 2;\n create_chebyshev2_analog_coefficients(static_cast(order), ripple, zpk);\n EQUtilities::populate_lp_coeffs(Wn, fs, order, zpk, coefficients_in, coefficients_out);\n }\n \n template\n void create_bp_chebyshev2_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, Container& coefficients_in, Container& coefficients_out)\n {\n EQUtilities::ZPK zpk;\n\n int fs = 2;\n create_chebyshev2_analog_coefficients(static_cast(order/2), ripple, zpk);\n EQUtilities::populate_bp_coeffs(wc1, wc2, fs, order, zpk, coefficients_in, coefficients_out);\n }\n \n template\n void create_bs_chebyshev2_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, Container& coefficients_in, Container& coefficients_out)\n {\n EQUtilities::ZPK zpk;\n\n int fs = 2;\n create_chebyshev2_analog_coefficients(static_cast(order/2), ripple, zpk);\n EQUtilities::populate_bs_coeffs(wc1, wc2, fs, order, zpk, coefficients_in, coefficients_out);\n }\n}\n\nnamespace ATK\n{\n template \n Chebyshev2LowPassCoefficients::Chebyshev2LowPassCoefficients(gsl::index nb_channels)\n :Parent(nb_channels, nb_channels)\n {\n }\n \n template \n void Chebyshev2LowPassCoefficients::set_ripple(CoeffDataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev2LowPassCoefficients::CoeffDataType Chebyshev2LowPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n \n template \n void Chebyshev2LowPassCoefficients::set_cut_frequency(CoeffDataType cut_frequency)\n {\n if(cut_frequency <= 0)\n {\n throw std::out_of_range(\"Frequency can't be negative\");\n }\n this->cut_frequency = cut_frequency;\n setup();\n }\n \n template \n typename Chebyshev2LowPassCoefficients::CoeffDataType Chebyshev2LowPassCoefficients::get_cut_frequency() const\n {\n return cut_frequency;\n }\n \n template \n void Chebyshev2LowPassCoefficients::set_order(unsigned int order)\n {\n if(order == 0)\n {\n throw std::out_of_range(\"Order can't be null\");\n }\n in_order = out_order = order;\n setup();\n }\n \n template \n unsigned int Chebyshev2LowPassCoefficients::get_order() const\n {\n return in_order;\n }\n\n template \n void Chebyshev2LowPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n Chebyshev2Utilities::create_default_chebyshev2_coeffs(in_order, ripple, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template \n Chebyshev2HighPassCoefficients::Chebyshev2HighPassCoefficients(gsl::index nb_channels)\n :Parent(nb_channels, nb_channels)\n {\n }\n \n template \n void Chebyshev2HighPassCoefficients::set_cut_frequency(CoeffDataType cut_frequency)\n {\n if(cut_frequency <= 0)\n {\n throw std::out_of_range(\"Frequency can't be negative\");\n }\n this->cut_frequency = cut_frequency;\n setup();\n }\n \n template \n typename Chebyshev2HighPassCoefficients::CoeffDataType Chebyshev2HighPassCoefficients::get_cut_frequency() const\n {\n return cut_frequency;\n }\n \n template \n void Chebyshev2HighPassCoefficients::set_ripple(CoeffDataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev2HighPassCoefficients::CoeffDataType Chebyshev2HighPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n \n template \n void Chebyshev2HighPassCoefficients::set_order(unsigned int order)\n {\n if(order == 0)\n {\n throw std::out_of_range(\"Order can't be null\");\n }\n in_order = out_order = order;\n setup();\n }\n \n template \n unsigned int Chebyshev2HighPassCoefficients::get_order() const\n {\n return in_order;\n }\n\n template \n void Chebyshev2HighPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n Chebyshev2Utilities::create_default_chebyshev2_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);\n for(gsl::index i = in_order - 1; i >= 0; i -= 2)\n {\n coefficients_in[i] = - coefficients_in[i];\n coefficients_out[i] = - coefficients_out[i];\n }\n }\n \n template \n Chebyshev2BandPassCoefficients::Chebyshev2BandPassCoefficients(gsl::index nb_channels)\n :Parent(nb_channels, nb_channels)\n {\n }\n \n template \n void Chebyshev2BandPassCoefficients::set_cut_frequencies(std::pair cut_frequencies)\n {\n if(cut_frequencies.first <= 0 || cut_frequencies.second <= 0)\n {\n throw std::out_of_range(\"Frequencies can't be negative\");\n }\n this->cut_frequencies = cut_frequencies;\n setup();\n }\n \n template \n void Chebyshev2BandPassCoefficients::set_cut_frequencies(CoeffDataType f0, CoeffDataType f1)\n {\n set_cut_frequencies(std::make_pair(f0, f1));\n }\n \n template \n std::pair::CoeffDataType, typename Chebyshev2BandPassCoefficients::CoeffDataType> Chebyshev2BandPassCoefficients::get_cut_frequencies() const\n {\n return cut_frequencies;\n }\n \n template \n void Chebyshev2BandPassCoefficients::set_ripple(CoeffDataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev2BandPassCoefficients::CoeffDataType Chebyshev2BandPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n \n template \n void Chebyshev2BandPassCoefficients::set_order(unsigned int order)\n {\n if(order == 0)\n {\n throw std::out_of_range(\"Order can't be null\");\n }\n in_order = out_order = 2 * order;\n setup();\n }\n \n template \n unsigned int Chebyshev2BandPassCoefficients::get_order() const\n {\n return in_order / 2;\n }\n\n template \n void Chebyshev2BandPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n Chebyshev2Utilities::create_bp_chebyshev2_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template \n Chebyshev2BandStopCoefficients::Chebyshev2BandStopCoefficients(gsl::index nb_channels)\n :Parent(nb_channels, nb_channels)\n {\n }\n \n template \n void Chebyshev2BandStopCoefficients::set_cut_frequencies(std::pair cut_frequencies)\n {\n if(cut_frequencies.first <= 0 || cut_frequencies.second <= 0)\n {\n throw std::out_of_range(\"Frequencies can't be negative\");\n }\n this->cut_frequencies = cut_frequencies;\n setup();\n }\n \n template \n void Chebyshev2BandStopCoefficients::set_cut_frequencies(CoeffDataType f0, CoeffDataType f1)\n {\n set_cut_frequencies(std::make_pair(f0, f1));\n }\n \n template \n std::pair::CoeffDataType, typename Chebyshev2BandStopCoefficients::CoeffDataType> Chebyshev2BandStopCoefficients::get_cut_frequencies() const\n {\n return cut_frequencies;\n }\n \n template \n void Chebyshev2BandStopCoefficients::set_ripple(CoeffDataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev2BandStopCoefficients::CoeffDataType Chebyshev2BandStopCoefficients::get_ripple() const\n {\n return ripple;\n }\n \n template \n void Chebyshev2BandStopCoefficients::set_order(unsigned int order)\n {\n if(order == 0)\n {\n throw std::out_of_range(\"Order can't be null\");\n }\n in_order = out_order = 2 * order;\n setup();\n }\n \n template \n unsigned int Chebyshev2BandStopCoefficients::get_order() const\n {\n return in_order / 2;\n }\n\n template \n void Chebyshev2BandStopCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n Chebyshev2Utilities::create_bs_chebyshev2_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n }\n}\n", "meta": {"hexsha": "80a3bb8c55fc76a45d436aefe3f31055eb07c31d", "size": 10986, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "ATK/EQ/Chebyshev2Filter.hxx", "max_stars_repo_name": "D-J-Roberts/AudioTK", "max_stars_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 249.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T13:36:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T18:47:46.000Z", "max_issues_repo_path": "ATK/EQ/Chebyshev2Filter.hxx", "max_issues_repo_name": "D-J-Roberts/AudioTK", "max_issues_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 22.0, "max_issues_repo_issues_event_min_datetime": "2015-07-28T15:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-11T14:18:19.000Z", "max_forks_repo_path": "ATK/EQ/Chebyshev2Filter.hxx", "max_forks_repo_name": "D-J-Roberts/AudioTK", "max_forks_repo_head_hexsha": "accf009d7238f32702eb1d5ee23c5148fc68e3bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2015-08-15T12:08:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T02:33:07.000Z", "avg_line_length": 31.2991452991, "max_line_length": 216, "alphanum_fraction": 0.718459858, "num_tokens": 3000, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787564, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6895382521933583}} {"text": "#ifndef THIN_PLATE_SPLINE_HPP\n#define THIN_PLATE_SPLINE_HPP\n\n#include \n#include \n#include \"arc_utilities/arc_exceptions.hpp\"\n#include \"arc_utilities/eigen_helpers.hpp\"\n\nnamespace arc_utilities {\n// Note that DIMENSIONS must be 2 or 3, not something like `Eigen::Dynamic`\ntemplate \nclass ThinPlateSpline {\n public:\n typedef Eigen::Matrix PointSet;\n typedef Eigen::Matrix HomogeneousPointSet;\n\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n static_assert(DIMENSIONS > 1, \"Using TPS only makes sense for 2 or more dimensions\");\n static_assert(DIMENSIONS <= 3,\n \"The choice of kernel function for DIMENSIONS >= 4 is not clear.\"\n \" See note after equation (29) in \"\n \"https://www.geometrictools.com/Documentation/ThinPlateSplines.pdf\");\n\n ThinPlateSpline() : solved_(false) {}\n\n /**\n * @brief ThinPlateSpline::ThinPlateSpline An arbitrary dimensional thin\n * plate spline for interpolation between points.\n * @param template_points A (DIMINESION x NUMPOINTS) matrix which define\n * the starting points that control the warping. I.e. the template is\n * warped to the target\n * @param target_points A (DIMINESION x NUMPOINTS) matrix which define\n * the target points that control the warping. I.e. the template is\n * warped to the target\n */\n template \n ThinPlateSpline(const Eigen::MatrixBase& template_points, const Eigen::MatrixBase& target_points)\n : solved_(false) {\n setTemplatePoints(template_points);\n setTargetPoints(target_points);\n solveForCoeffs();\n }\n\n /**\n * @note Checking for the vailidty of the input data is put off until\n * the warping function is solved\n */\n template \n void setTemplatePoints(const Eigen::MatrixBase& template_points) {\n using namespace Eigen;\n static_assert(\n MatrixBase::RowsAtCompileTime == DIMENSIONS || MatrixBase::RowsAtCompileTime == Dynamic,\n \"INVALID DATA DIMENSIONS FOR template_points\");\n\n homogeneous_template_points_.resize(DIMENSIONS + 1, template_points.cols());\n homogeneous_template_points_ << template_points, RowVectorXd::Ones(template_points.cols());\n solved_ = false;\n }\n\n /**\n * @note Checking for the vailidty of the input data is put off until\n * the warping function is solved\n */\n template \n void setTargetPoints(const Eigen::MatrixBase& target_points) {\n using namespace Eigen;\n static_assert(\n MatrixBase::RowsAtCompileTime == DIMENSIONS || MatrixBase::RowsAtCompileTime == Dynamic,\n \"INVALID DATA DIMENSIONS FOR target_points\");\n\n target_points_ = target_points;\n solved_ = false;\n }\n\n void solveForCoeffs() {\n using namespace Eigen;\n if (homogeneous_template_points_.cols() < 1 || target_points_.cols() < 1) {\n throw_arc_exception(std::invalid_argument, \"template and target points must have valid data before solving\");\n }\n if (homogeneous_template_points_.cols() != target_points_.cols()) {\n throw_arc_exception(std::invalid_argument, \"template and target points must have the same number of points\");\n }\n\n const auto NUMPOINTS = homogeneous_template_points_.cols();\n\n // Calculate the kernel matrix for the template (control) points\n const MatrixXd Rsquared = EigenHelpers::CalculateSquaredDistanceMatrix(homogeneous_template_points_);\n const MatrixXd kernel = Rsquared.unaryExpr(&ThinPlateSpline::KernelFunction);\n\n // Form the system: A * params = B\n // A = [K, template'\n // template, 0]\n // B = [target'\n // 0 ]\n MatrixXd A(NUMPOINTS + DIMENSIONS + 1, NUMPOINTS + DIMENSIONS + 1);\n A << kernel, homogeneous_template_points_.transpose(), homogeneous_template_points_,\n MatrixXd::Zero(DIMENSIONS + 1, DIMENSIONS + 1);\n MatrixXd B(NUMPOINTS + DIMENSIONS + 1, DIMENSIONS);\n B << target_points_.transpose(), MatrixXd::Zero(DIMENSIONS + 1, DIMENSIONS);\n\n // params = A \\ B\n const Matrix params = A.colPivHouseholderQr().solve(B).eval();\n warping_coeffs_ = params.topRows(NUMPOINTS).transpose();\n affine_coeffs_ = params.bottomRows(DIMENSIONS + 1).transpose();\n solved_ = true;\n }\n\n template \n Eigen::Matrix interpolate(\n const Eigen::MatrixBase& interpolation_points) {\n using namespace Eigen;\n static_assert(\n MatrixBase::RowsAtCompileTime == DIMENSIONS || MatrixBase::RowsAtCompileTime == Dynamic,\n \"INVALID DATA DIMENSIONS FOR interpolation_points\");\n\n if (!solved_) {\n solveForCoeffs();\n }\n\n const auto num_points = interpolation_points.cols();\n HomogeneousPointSet homogeneous_interpolation_points(DIMENSIONS + 1, num_points);\n homogeneous_interpolation_points << interpolation_points, RowVectorXd::Ones(num_points);\n\n // Calculate the kenerl matrix comparing the new points to the template (control) points\n const MatrixXd Rsquared =\n EigenHelpers::SquaredDistancesBetweenPointSets(homogeneous_template_points_, homogeneous_interpolation_points);\n const MatrixXd kernel = Rsquared.unaryExpr(&ThinPlateSpline::KernelFunction);\n\n return affine_coeffs_ * homogeneous_interpolation_points + warping_coeffs_ * kernel;\n }\n\n protected:\n static double KernelFunction(const double r_sq) {\n // Equations taken from\n // https://www.geometrictools.com/Documentation/ThinPlateSplines.pdf\n // with coefficient (alpha) dropped as it is absorbed by warping_coeffs_\n switch (DIMENSIONS) {\n case 2:\n // This should be r^2 * log(r). We do not take the square root\n // because the factor of 2 gets absorbed by warping_coeffs_\n return r_sq == 0.0 ? 0.0 : r_sq * std::log(r_sq);\n case 3:\n // The negative is kept here for consistency with\n // https://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntpThinPlateSpline3.h\n // and other TPS implementations found online\n return r_sq == 0.0 ? 0.0 : -std::sqrt(r_sq);\n default:\n static_assert(DIMENSIONS == 2 || DIMENSIONS == 3, \"Only 2 and 3 dimensional kernels are implemented\");\n }\n }\n\n HomogeneousPointSet homogeneous_template_points_;\n PointSet target_points_;\n Eigen::Matrix affine_coeffs_;\n PointSet warping_coeffs_;\n bool solved_;\n};\n} // namespace arc_utilities\n\n#endif // THIN_PLATE_SPLINE_HPP\n", "meta": {"hexsha": "f3ccbb8f069f31f481c8d85f6bbc43361bf02fde", "size": 6673, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/arc_utilities/thin_plate_spline.hpp", "max_stars_repo_name": "UM-ARM-Lab/arc_utilities", "max_stars_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2017-01-09T14:37:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:02:08.000Z", "max_issues_repo_path": "include/arc_utilities/thin_plate_spline.hpp", "max_issues_repo_name": "UM-ARM-Lab/arc_utilities", "max_issues_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 62.0, "max_issues_repo_issues_event_min_datetime": "2017-05-25T16:52:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T20:05:09.000Z", "max_forks_repo_path": "include/arc_utilities/thin_plate_spline.hpp", "max_forks_repo_name": "UM-ARM-Lab/arc_utilities", "max_forks_repo_head_hexsha": "e21bd5062983b25e61e33f832ec66b937540ba10", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2017-08-04T13:06:17.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:02:11.000Z", "avg_line_length": 41.1913580247, "max_line_length": 119, "alphanum_fraction": 0.7151206354, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.6895224062845285}} {"text": "#include \"SimplePly.h\"\n#include \"rply.h\"\n#include \n#include \n#include \n#include \n\n/**Calculates the distance the point is from the plane\n @param point a single point's position.\n @param planeEq plane Equation.\n @return distance between point and plane.\n */\nfloat distToPlane(Eigen::Vector3f point, Eigen::Vector4f planeEq){\n float distance = planeEq(0)*point(0) + planeEq(1)*point(1) + planeEq(2)*point(2) + planeEq(3);\n distance /= std::sqrt(std::pow(planeEq(0),2) + std::pow(planeEq(1),2) + std::pow(planeEq(2),2));\n distance = std::abs(distance);\n return distance;\n}\n\n/**builds a plane out of 3 points\n @param point list of point positions.\n @return the equation of the plane.\n */\nEigen::Vector4f calcPlane(std::vector points){\n Eigen::Vector3f vectAB = points[1] - points[0], vectAC = points[2] - points[0];\n Eigen::Vector3f planeNorm = vectAB.cross(vectAC);\n float planeConst = -points[0].dot(planeNorm);\n Eigen::Vector4f planeEquation(planeNorm(0),planeNorm(1),planeNorm(2),planeConst);\n return planeEquation;\n}\n\n/**finds the distance that a point (with the greatest distance from the plane) has\n @param points list of points positions.\n @param planeEq the equation for the plane.\n @return the max distance between any point and the plane.\n */ \nfloat maxDistance(std::vector points, Eigen::Vector4f planeEq){\n float maxDist = 0, dist = 0;\n for(int i = 0; i < points.size(); i++){\n if((dist = distToPlane(points[i], planeEq)) > maxDist){\n maxDist = dist;\n }\n }\n return maxDist;\n}\n\n/**calculates the centroid of the points given.\n @param points list of points positions.\n @return the centroid of the points positions.\n */\nEigen::Vector3f calcCentroid(std::vector points){\n float aveX = 0, aveY = 0, aveZ = 0;\n Eigen::Vector3f centroid;\n for(int i = 0; i < points.size(); i++){\n aveX += points[i](0);\n aveY += points[i](1);\n aveZ += points[i](2);\n }\n //averaging the values.\n aveX/=points.size();\n aveY/=points.size();\n aveZ/=points.size();\n centroid(0) = aveX;\n centroid(1) = aveY;\n centroid(2) = aveZ;\n return centroid;\n}\n\n/** Preforms orthogonal least squares on the points given to find the best plane. Then the\n method projects the points onto the plane.\n @param points list of points location.\n @param plyPoints list of points in ply format.\n*/\nvoid leastSquares(std::vector points, std::vector &plyPoints){\n Eigen::MatrixXf pointsMat(points.size(),3), pointsV;\n Eigen::Vector3f centroid = calcCentroid(points), planeNorm, adjustedPoint;\n Eigen::Vector4f planeEq;\n float planeNormNorm = 0, dist = 0;\n //builds matrix to use SVD on.\n for(int i = 0; i < points.size(); i++){\n for(int j = 0; j < 3; j++){\n pointsMat(i,j) = points[i](j) - centroid(j);\n }\n }\n //preforms SVD\n Eigen::JacobiSVD svd(pointsMat, Eigen::ComputeFullV);\n pointsV = svd.matrixV();\n //builds plane based off of the SVD eigen vector and the centroid.\n for(int i = 0; i < 3; i++){\n planeEq(i) = pointsV(i,0);\n planeEq(3) -= planeEq(i)*centroid(i);\n }\n //finds normal of the plane normal.\n for(int i = 0; i < 3; i++){\n planeNormNorm += std::pow(planeEq(i),2);\n }\n planeNormNorm = std::sqrt(planeNormNorm);\n //builds a normalised plane normal vector.\n for(int i = 0; i < 3; i++){\n planeNorm(i) = planeEq(i)/planeNormNorm;\n }\n //projects points positions onto the calcuated Plane.\n for(int i = 0; i < plyPoints.size(); i++){\n dist = distToPlane(points[i],planeEq);\n \n adjustedPoint(0)= points[i](0) - (dist*planeNorm(0));\n adjustedPoint(1)= points[i](1) - (dist*planeNorm(1));\n adjustedPoint(2)= points[i](2) - (dist*planeNorm(2));\n if(dist < distToPlane(adjustedPoint,planeEq)){\n adjustedPoint(0)= points[i](0) + (2*dist*planeNorm(0));\n adjustedPoint(1)= points[i](1) + (2*dist*planeNorm(1));\n adjustedPoint(2)= points[i](2) + (2*dist*planeNorm(2));\n }\n \n (*plyPoints[i]).location(0) = adjustedPoint(0);\n (*plyPoints[i]).location(1) = adjustedPoint(1);\n (*plyPoints[i]).location(2) = adjustedPoint(2);\n }\n}\n\n\n\n\n\n\n/** Based on a percentage of points in the biggest plane, it calculates the threshold for the plane.\n * @param points the list of points positions.\n * @param planeEq the equation for the plane.\n * @param probThreshold the percentage of points required to determine threshold.\n * @return the calculated threshold.\n */\nfloat calcThreshold(std::vector points, Eigen::Vector4f planeEq, float probThreshold){\n std::vector buckets;\n float maxDist = maxDistance(points, planeEq);\n int numJumps = 10000, pointCount = 0, placeHold = 0, reqPoints = std::ceil(points.size()*probThreshold);\n float jumpSize = maxDist/(numJumps-1), dist, threshold = 0;\n \n for(int i = 0; i < numJumps; i++){\n buckets.push_back(0);\n }\n //Counts the number of Points in each region bucket.\n for(int i = 0; i < points.size(); i++){\n dist = distToPlane(points[i],planeEq);\n buckets[std::floor(dist/jumpSize)]++;\n }\n //sums point count in buckets until it goes over the users estimated plane count.\n while(pointCount < reqPoints){\n pointCount += buckets[placeHold];\n placeHold++;\n }\n //sets that point as threshold.\n threshold = (placeHold+1)*jumpSize;\n \n return threshold;\n\n}\n\n\n\n\n/**Determines the number of trials needed to have the accuracy that is requested.\n * @param inlierProb the probability of a point being an inlier.\n * @param acceptedFailProb the accepted rate of failure.\n *@return the number of trials required.\n */\nfloat numChecks(float inlierProb, float acceptedFailProb){\n float numChecks = 0;\n if(inlierProb < 1){\n numChecks = ((std::log(acceptedFailProb))/(std::log(1 - (std::pow(inlierProb,3)))));\n }\n \n return numChecks;\n}\n\n\n/**Determines if the plane is a null plane.\n @param plane the plane equation.x\n @return a statement of if the plane is a null plane.\n */\nbool planeNull(Eigen::Vector4f plane){\n return (abs(plane(0)) == 0 && plane(1) == 0 && plane(2) == 0 && plane(3) == 0);\n}\n\n\n\n\n\n\n\n/**Proforms analysis on the inputed point cloud, to find planes in the point cloud, colouring\n them accordingly. The program requires the user to input some information about the data,\n such as a points limit to when to stop looking for planes, an estimate of the percentage\n of points in the largest plane, and the probability of success.\n*/\nint main (int argc, char *argv[]) {\n int pointIn, count, bestCount, point1In, point2In, point3In, reqPlaneCalcs = 0;\n float posThresh = 0, threshProb = 0.4, threshold = 0, inlierProb = 0.001;\n Eigen::Vector4f bestPlane(0,0,0,0), curPlane;\n Eigen::Vector3f holdPoint;\n Eigen::Vector3i baseColour;\n std::vector points, pointsList, planePoints;\n int trialCount = 0,planeCount = 0;\n bool stillPlanes = true, threshFound = false;\n // Check the commandline arguments.\n if (argc != 6) {\n std::cout << \"Usage: planeFinder \" << std::endl;\n return -1;\n }\n int planeSizeThreshold = atoi(argv[3]);\n float pointPercentBiggestPlane = atof(argv[4]);\n float acceptedFailProb = atof(argv[5]);\n std::vector pointsList2, planePoints2;\n \n reqPlaneCalcs = numChecks(pointPercentBiggestPlane, acceptedFailProb);\n threshold = std::numeric_limits::max();\n std::cout << \"Searching for planes until the next best plane size is less than \" << planeSizeThreshold << std::endl;\n std::cout << \"The estimated percentage of points in the biggest plane is \" << pointPercentBiggestPlane << std::endl;\n std::cout << \"Applying RANSAC with an acceptedFailRate of \" << acceptedFailProb << std::endl; \n\n // Storage for the point cloud.\n SimplePly ply;\n // Read in the data from a PLY file\n std::cout << \"Reading PLY data from \" << argv[1] << std::endl;\n if (!ply.read(argv[1])) {\n std::cout << \"Could not read PLY data from file \" << argv[1] << std::endl;\n return -1;\n }\n\n // Stores copy of points read in.\n for(int i = 0; i < ply.size(); ++i){\n pointsList2.push_back(&ply[i]);\n }\n \n \n std::cout << \"Read \" << ply.size() << \" points\" << std::endl;\n \n // Recolour points - here we are just doing colour based on index\n std::cout << \"Recolouring points\" << std::endl;\n \n //Sets colours\n std::vector colours;\n colours.push_back(Eigen::Vector3i(255,0,0));\n colours.push_back(Eigen::Vector3i(0,255,0));\n colours.push_back(Eigen::Vector3i(0,0,255));\n colours.push_back(Eigen::Vector3i(255,255,0));\n colours.push_back(Eigen::Vector3i(0,255,255));\n colours.push_back(Eigen::Vector3i(255,0,255));\n colours.push_back(Eigen::Vector3i(255,255,255));\n colours.push_back(Eigen::Vector3i(0,0,0));\n \n holdPoint = Eigen::Vector3f(ply[0].location(0),ply[0].location(1),ply[0].location(2));\n \n \n \n //builds a vector containing vectors of the points positions.\n for(int i = 0; i < ply.size(); i++){\n holdPoint = Eigen::Vector3f(ply[i].location(0),ply[i].location(1),ply[i].location(2));\n pointsList.push_back(holdPoint);\n }\n\n \n \n\n //starts looking for planes.\n while(stillPlanes && pointsList.size() > 2){\n //zeros bestPlane.\n for(int j = 0; j < 4; j++){\n bestPlane(j) = 0;\n }\n \n //increase plane Count.\n\n planeCount++;\n //Resets variables.\n bestCount = 0;\n inlierProb = 0.001;\n trialCount = 0;\n \n //finds the threshold based off of users estimate.\n if(!threshFound){\n for(int z = 0; z < 110; z++){\n\tpoint1In = std::rand()%pointsList.size();\n\tpoint2In = std::rand()%pointsList.size();\n\tpoint3In = std::rand()%pointsList.size();\n\tpoints.clear();\n\tpoints.push_back(pointsList[point1In]);\n\tpoints.push_back(pointsList[point2In]);\n\tpoints.push_back(pointsList[point3In]);\n\tcurPlane = calcPlane(points);\n\tif(!planeNull(curPlane)){\n\t posThresh = calcThreshold(pointsList, curPlane, pointPercentBiggestPlane);\n\t if(posThresh < threshold){\n\t threshold = posThresh;\n\t bestPlane = curPlane;\n\t }\n\t}\n }\n //makes sure only one threshold is found.\n threshFound = true;\n }\n\n\n\n //starts looking for planes with the calculated threshold.\n while(trialCount < numChecks(inlierProb, acceptedFailProb)){\n trialCount++;\n std::cout << numChecks(inlierProb, acceptedFailProb) << std::endl;\n //finds three random points and builds a plane.\n point1In = std::rand()%pointsList.size();\n point2In = std::rand()%pointsList.size();\n point3In = std::rand()%pointsList.size();\n points.clear();\n points.push_back(pointsList[point1In]);\n points.push_back(pointsList[point2In]);\n points.push_back(pointsList[point3In]);\n curPlane = calcPlane(points);\n count = 0;\n //makes sure it isn't a null plane.\n if(!planeNull(curPlane)){\n\tfor(int k = 0; k < pointsList.size(); k++){\n\t //counts number of points within threshold.\n\t if(distToPlane(pointsList[k], curPlane) <= threshold){\n\t count++;\n\t }\n\t}\n\t//checks if this is best plane then updates if it is.\n\tif(count > bestCount){\n\t bestCount = count;\n\t bestPlane = curPlane;\n\t inlierProb = ((float)bestCount)/pointsList.size();\n\t \n\t}\n }\n }\n //Cuts out if the plane is too small.\n if(bestCount < planeSizeThreshold){\n stillPlanes = false;\n }\n //Makes sure the unlikely chance of a null best plane occuring doesn't get through.\n else if(!planeNull(bestPlane)){\n //recolours and removes points.\n for(int j = pointsList2.size() - 1; j > -1; j--){\n\tholdPoint(0) = (*pointsList2[j]).location(0);\n\tholdPoint(1) = (*pointsList2[j]).location(1);\n\tholdPoint(2) = (*pointsList2[j]).location(2);\n\t\n\tif(distToPlane(holdPoint, bestPlane) <= threshold){\n\t \n\t (*pointsList2[j]).colour = colours[planeCount%colours.size()];\n\t //planePoints.push_back(pointsList[j]);\n\t pointsList[j] = pointsList[pointsList.size() - 1];\n\t pointsList.pop_back();\n\t //planePoints2.push_back(pointsList2[j]);\n\t pointsList2[j] = pointsList2[pointsList2.size() - 1];\n\t pointsList2.pop_back();\n\t\n\t}\n }\n //would do least squares if it worked properly. No time to work out the error.\n //leastSquares(planePoints, planePoints2);\n //planePoints.clear();\n //planePoints2.clear();\n }\n }\n \n \n // Write the resulting (re-coloured) point cloud to a PLY file.\n std::cout << \"Writing PLY data to \" << argv[2] << std::endl;\n if (!ply.write(argv[2])) {\n std::cout << \"Could not write PLY data to file \" << argv[2] << std::endl;\n return -2;\n }\n return 0;\n}\n\n", "meta": {"hexsha": "5851b7518d101d308ceba8de8b6003e590e24e50", "size": 12652, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "planeFinder.cpp", "max_stars_repo_name": "SimonFinnie/Plane-Detection-in-Point-Clouds", "max_stars_repo_head_hexsha": "fbcc57edf2bddfdd3da407222764b30c9bcb7058", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-12-13T07:45:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T09:14:19.000Z", "max_issues_repo_path": "planeFinder.cpp", "max_issues_repo_name": "SimonFinnie/Plane-Detection-in-Point-Clouds", "max_issues_repo_head_hexsha": "fbcc57edf2bddfdd3da407222764b30c9bcb7058", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-05-21T07:39:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-21T07:39:29.000Z", "max_forks_repo_path": "planeFinder.cpp", "max_forks_repo_name": "SimonFinnie/Plane-Detection-in-Point-Clouds", "max_forks_repo_head_hexsha": "fbcc57edf2bddfdd3da407222764b30c9bcb7058", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2017-12-13T07:45:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T08:40:43.000Z", "avg_line_length": 33.6489361702, "max_line_length": 171, "alphanum_fraction": 0.6651912741, "num_tokens": 3642, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462514578343, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6894446618139808}} {"text": "/* Boost example/transc.cpp\n * how to use an external library (GMP/MPFR in this case) in order to\n * get correct transcendental functions on intervals\n *\n * Copyright 2003 Guillaume Melquiond\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \n//extern \"C\" {\n#include \n#include \n//}\n#include \n\nstruct full_rounding:\n boost::numeric::interval_lib::rounded_arith_opp\n{\nprivate:\n typedef int mpfr_func(mpfr_t, const __mpfr_struct*, mp_rnd_t);\n double invoke_mpfr(double x, mpfr_func f, mp_rnd_t r) {\n mpfr_t xx;\n mpfr_init_set_d(xx, x, GMP_RNDN);\n f(xx, xx, r);\n double res = mpfr_get_d(xx, r);\n mpfr_clear(xx);\n return res;\n }\npublic:\n# define GENR_FUNC(name) \\\n double name##_down(double x) { return invoke_mpfr(x, mpfr_##name, GMP_RNDD); } \\\n double name##_up (double x) { return invoke_mpfr(x, mpfr_##name, GMP_RNDU); }\n GENR_FUNC(exp)\n GENR_FUNC(log)\n GENR_FUNC(sin)\n GENR_FUNC(cos)\n GENR_FUNC(tan)\n GENR_FUNC(asin)\n GENR_FUNC(acos)\n GENR_FUNC(atan)\n GENR_FUNC(sinh)\n GENR_FUNC(cosh)\n GENR_FUNC(tanh)\n GENR_FUNC(asinh)\n GENR_FUNC(acosh)\n GENR_FUNC(atanh)\n};\n\nnamespace dummy {\n using namespace boost;\n using namespace numeric;\n using namespace interval_lib;\n typedef save_state R;\n typedef checking_strict P;\n typedef interval > I;\n};\n\ntypedef dummy::I I;\n\ntemplate\nos_t& operator<<(os_t &os, const I &a) {\n os << '[' << a.lower() << ',' << a.upper() << ']';\n return os;\n}\n\nint main() {\n I x(0.5, 2.5);\n std::cout << \"x = \" << x << std::endl;\n std::cout.precision(16);\n# define GENR_TEST(name) \\\n std::cout << #name \"(x) = \" << name(x) << std::endl\n GENR_TEST(exp);\n GENR_TEST(log);\n GENR_TEST(sin);\n GENR_TEST(cos);\n GENR_TEST(tan);\n GENR_TEST(asin);\n GENR_TEST(acos);\n GENR_TEST(atan);\n GENR_TEST(sinh);\n GENR_TEST(cosh);\n GENR_TEST(tanh);\n GENR_TEST(asinh);\n GENR_TEST(acosh);\n GENR_TEST(atanh);\n return 0;\n}\n", "meta": {"hexsha": "2036f98323a407dd264734b6b930756f8499662f", "size": 2121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "boost/libs/numeric/interval/examples/transc.cpp", "max_stars_repo_name": "randolphwong/mcsema", "max_stars_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/libs/numeric/interval/examples/transc.cpp", "max_issues_repo_name": "randolphwong/mcsema", "max_issues_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/libs/numeric/interval/examples/transc.cpp", "max_forks_repo_name": "randolphwong/mcsema", "max_forks_repo_head_hexsha": "eb5b376736e7f57ff0a61f7e4e5a436bbb874720", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 23.3076923077, "max_line_length": 82, "alphanum_fraction": 0.676096181, "num_tokens": 672, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.6893668200395321}} {"text": "// find_mean_and_sd_normal.cpp\r\n\r\n// Copyright Paul A. Bristow 2007, 2010.\r\n\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Example of finding mean or sd for normal distribution.\r\n\r\n// Note that this file contains Quickbook mark-up as well as code\r\n// and comments, don't change any of the special comment mark-ups!\r\n\r\n//[normal_std\r\n/*`\r\nFirst we need some includes to access the normal distribution,\r\nthe algorithms to find location and scale\r\n(and some std output of course).\r\n*/\r\n\r\n#include // for normal_distribution\r\n using boost::math::normal; // typedef provides default type is double.\r\n#include // for cauchy_distribution\r\n using boost::math::cauchy; // typedef provides default type is double.\r\n#include \r\n using boost::math::find_location;\r\n#include \r\n using boost::math::find_scale;\r\n using boost::math::complement;\r\n using boost::math::policies::policy;\r\n\r\n#include \r\n using std::cout; using std::endl; using std::left; using std::showpoint; using std::noshowpoint;\r\n#include \r\n using std::setw; using std::setprecision;\r\n#include \r\n using std::numeric_limits;\r\n#include \r\n using std::exception;\r\n//] [/normal_std Quickbook]\r\n\r\nint main()\r\n{\r\n cout << \"Find_location (mean) and find_scale (standard deviation) examples.\" << endl;\r\n try\r\n {\r\n\r\n//[normal_find_location_and_scale_eg\r\n\r\n/*`\r\n[h4 Using find_location and find_scale to meet dispensing and measurement specifications]\r\n\r\nConsider an example from K Krishnamoorthy,\r\nHandbook of Statistical Distributions with Applications,\r\nISBN 1-58488-635-8, (2006) p 126, example 10.3.7.\r\n\r\n\"A machine is set to pack 3 kg of ground beef per pack.\r\nOver a long period of time it is found that the average packed was 3 kg\r\nwith a standard deviation of 0.1 kg.\r\nAssume the packing is normally distributed.\"\r\n\r\nWe start by constructing a normal distribution with the given parameters:\r\n*/\r\n\r\ndouble mean = 3.; // kg\r\ndouble standard_deviation = 0.1; // kg\r\nnormal packs(mean, standard_deviation);\r\n/*`We can then find the fraction (or %) of packages that weigh more than 3.1 kg.\r\n*/\r\n\r\ndouble max_weight = 3.1; // kg\r\ncout << \"Percentage of packs > \" << max_weight << \" is \"\r\n<< cdf(complement(packs, max_weight)) * 100. << endl; // P(X > 3.1)\r\n\r\n/*`We might want to ensure that 95% of packs are over a minimum weight specification,\r\nthen we want the value of the mean such that P(X < 2.9) = 0.05.\r\n\r\nUsing the mean of 3 kg, we can estimate\r\nthe fraction of packs that fail to meet the specification of 2.9 kg.\r\n*/\r\n\r\ndouble minimum_weight = 2.9;\r\ncout <<\"Fraction of packs <= \" << minimum_weight << \" with a mean of \" << mean\r\n << \" is \" << cdf(complement(packs, minimum_weight)) << endl;\r\n// fraction of packs <= 2.9 with a mean of 3 is 0.841345\r\n\r\n/*`This is 0.84 - more than the target fraction of 0.95.\r\nIf we want 95% to be over the minimum weight,\r\nwhat should we set the mean weight to be?\r\n\r\nUsing the KK StatCalc program supplied with the book and the method given on page 126 gives 3.06449.\r\n\r\nWe can confirm this by constructing a new distribution which we call 'xpacks'\r\nwith a safety margin mean of 3.06449 thus:\r\n*/\r\ndouble over_mean = 3.06449;\r\nnormal xpacks(over_mean, standard_deviation);\r\ncout << \"Fraction of packs >= \" << minimum_weight\r\n<< \" with a mean of \" << xpacks.mean()\r\n << \" is \" << cdf(complement(xpacks, minimum_weight)) << endl;\r\n// fraction of packs >= 2.9 with a mean of 3.06449 is 0.950005\r\n\r\n/*`Using this Math Toolkit, we can calculate the required mean directly thus:\r\n*/\r\ndouble under_fraction = 0.05; // so 95% are above the minimum weight mean - sd = 2.9\r\ndouble low_limit = standard_deviation;\r\ndouble offset = mean - low_limit - quantile(packs, under_fraction);\r\ndouble nominal_mean = mean + offset;\r\n// mean + (mean - low_limit - quantile(packs, under_fraction));\r\n\r\nnormal nominal_packs(nominal_mean, standard_deviation);\r\ncout << \"Setting the packer to \" << nominal_mean << \" will mean that \"\r\n << \"fraction of packs >= \" << minimum_weight\r\n << \" is \" << cdf(complement(nominal_packs, minimum_weight)) << endl;\r\n// Setting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95\r\n\r\n/*`\r\nThis calculation is generalized as the free function called\r\n[link math_toolkit.dist.dist_ref.dist_algorithms find_location].\r\n\r\nTo use this we will need to\r\n*/\r\n\r\n#include \r\n using boost::math::find_location;\r\n/*`and then use find_location function to find safe_mean,\r\n& construct a new normal distribution called 'goodpacks'.\r\n*/\r\ndouble safe_mean = find_location(minimum_weight, under_fraction, standard_deviation);\r\nnormal good_packs(safe_mean, standard_deviation);\r\n/*`with the same confirmation as before:\r\n*/\r\ncout << \"Setting the packer to \" << nominal_mean << \" will mean that \"\r\n << \"fraction of packs >= \" << minimum_weight\r\n << \" is \" << cdf(complement(good_packs, minimum_weight)) << endl;\r\n// Setting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95\r\n\r\n/*`\r\n[h4 Using Cauchy-Lorentz instead of normal distribution]\r\n\r\nAfter examining the weight distribution of a large number of packs, we might decide that,\r\nafter all, the assumption of a normal distribution is not really justified.\r\nWe might find that the fit is better to a __cauchy_distrib.\r\nThis distribution has wider 'wings', so that whereas most of the values\r\nare closer to the mean than the normal, there are also more values than 'normal'\r\nthat lie further from the mean than the normal.\r\n\r\nThis might happen because a larger than normal lump of meat is either included or excluded.\r\n\r\nWe first create a __cauchy_distrib with the original mean and standard deviation,\r\nand estimate the fraction that lie below our minimum weight specification.\r\n*/\r\n\r\ncauchy cpacks(mean, standard_deviation);\r\ncout << \"Cauchy Setting the packer to \" << mean << \" will mean that \"\r\n << \"fraction of packs >= \" << minimum_weight\r\n << \" is \" << cdf(complement(cpacks, minimum_weight)) << endl;\r\n// Cauchy Setting the packer to 3 will mean that fraction of packs >= 2.9 is 0.75\r\n\r\n/*`Note that far fewer of the packs meet the specification, only 75% instead of 95%.\r\nNow we can repeat the find_location, using the cauchy distribution as template parameter,\r\nin place of the normal used above.\r\n*/\r\n\r\ndouble lc = find_location(minimum_weight, under_fraction, standard_deviation);\r\ncout << \"find_location(minimum_weight, over fraction, standard_deviation); \" << lc << endl;\r\n// find_location(minimum_weight, over fraction, packs.standard_deviation()); 3.53138\r\n/*`Note that the safe_mean setting needs to be much higher, 3.53138 instead of 3.06449,\r\nso we will make rather less profit.\r\n\r\nAnd again confirm that the fraction meeting specification is as expected.\r\n*/\r\ncauchy goodcpacks(lc, standard_deviation);\r\ncout << \"Cauchy Setting the packer to \" << lc << \" will mean that \"\r\n << \"fraction of packs >= \" << minimum_weight\r\n << \" is \" << cdf(complement(goodcpacks, minimum_weight)) << endl;\r\n// Cauchy Setting the packer to 3.53138 will mean that fraction of packs >= 2.9 is 0.95\r\n\r\n/*`Finally we could estimate the effect of a much tighter specification,\r\nthat 99% of packs met the specification.\r\n*/\r\n\r\ncout << \"Cauchy Setting the packer to \"\r\n << find_location(minimum_weight, 0.99, standard_deviation)\r\n << \" will mean that \"\r\n << \"fraction of packs >= \" << minimum_weight\r\n << \" is \" << cdf(complement(goodcpacks, minimum_weight)) << endl;\r\n\r\n/*`Setting the packer to 3.13263 will mean that fraction of packs >= 2.9 is 0.99,\r\nbut will more than double the mean loss from 0.0644 to 0.133 kg per pack.\r\n\r\nOf course, this calculation is not limited to packs of meat, it applies to dispensing anything,\r\nand it also applies to a 'virtual' material like any measurement.\r\n\r\nThe only caveat is that the calculation assumes that the standard deviation (scale) is known with\r\na reasonably low uncertainty, something that is not so easy to ensure in practice.\r\nAnd that the distribution is well defined, __normal_distrib or __cauchy_distrib, or some other.\r\n\r\nIf one is simply dispensing a very large number of packs,\r\nthen it may be feasible to measure the weight of hundreds or thousands of packs.\r\nWith a healthy 'degrees of freedom', the confidence intervals for the standard deviation\r\nare not too wide, typically about + and - 10% for hundreds of observations.\r\n\r\nFor other applications, where it is more difficult or expensive to make many observations,\r\nthe confidence intervals are depressingly wide.\r\n\r\nSee [link math_toolkit.dist.stat_tut.weg.cs_eg.chi_sq_intervals Confidence Intervals on the standard deviation]\r\nfor a worked example\r\n[@../../../example/chi_square_std_dev_test.cpp chi_square_std_dev_test.cpp]\r\nof estimating these intervals.\r\n\r\n\r\n[h4 Changing the scale or standard deviation]\r\n\r\nAlternatively, we could invest in a better (more precise) packer\r\n(or measuring device) with a lower standard deviation, or scale.\r\n\r\nThis might cost more, but would reduce the amount we have to 'give away'\r\nin order to meet the specification.\r\n\r\nTo estimate how much better (how much smaller standard deviation) it would have to be,\r\nwe need to get the 5% quantile to be located at the under_weight limit, 2.9\r\n*/\r\ndouble p = 0.05; // wanted p th quantile.\r\ncout << \"Quantile of \" << p << \" = \" << quantile(packs, p)\r\n << \", mean = \" << packs.mean() << \", sd = \" << packs.standard_deviation() << endl;\r\n/*`\r\nQuantile of 0.05 = 2.83551, mean = 3, sd = 0.1\r\n\r\nWith the current packer (mean = 3, sd = 0.1), the 5% quantile is at 2.8551 kg,\r\na little below our target of 2.9 kg.\r\nSo we know that the standard deviation is going to have to be smaller.\r\n\r\nLet's start by guessing that it (now 0.1) needs to be halved, to a standard deviation of 0.05 kg.\r\n*/\r\nnormal pack05(mean, 0.05);\r\ncout << \"Quantile of \" << p << \" = \" << quantile(pack05, p)\r\n << \", mean = \" << pack05.mean() << \", sd = \" << pack05.standard_deviation() << endl;\r\n// Quantile of 0.05 = 2.91776, mean = 3, sd = 0.05\r\n\r\ncout <<\"Fraction of packs >= \" << minimum_weight << \" with a mean of \" << mean\r\n << \" and standard deviation of \" << pack05.standard_deviation()\r\n << \" is \" << cdf(complement(pack05, minimum_weight)) << endl;\r\n// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.05 is 0.97725\r\n/*`\r\nSo 0.05 was quite a good guess, but we are a little over the 2.9 target,\r\nso the standard deviation could be a tiny bit more. So we could do some\r\nmore guessing to get closer, say by increasing standard deviation to 0.06 kg,\r\nconstructing another new distribution called pack06.\r\n*/\r\nnormal pack06(mean, 0.06);\r\ncout << \"Quantile of \" << p << \" = \" << quantile(pack06, p)\r\n << \", mean = \" << pack06.mean() << \", sd = \" << pack06.standard_deviation() << endl;\r\n// Quantile of 0.05 = 2.90131, mean = 3, sd = 0.06\r\n\r\ncout <<\"Fraction of packs >= \" << minimum_weight << \" with a mean of \" << mean\r\n << \" and standard deviation of \" << pack06.standard_deviation()\r\n << \" is \" << cdf(complement(pack06, minimum_weight)) << endl;\r\n// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.06 is 0.95221\r\n/*`\r\nNow we are getting really close, but to do the job properly,\r\nwe might need to use root finding method, for example the tools provided,\r\nand used elsewhere, in the Math Toolkit, see\r\n[link math_toolkit.toolkit.internals1.roots2 Root Finding Without Derivatives].\r\n\r\nBut in this (normal) distribution case, we can and should be even smarter\r\nand make a direct calculation.\r\n*/\r\n\r\n/*`Our required limit is minimum_weight = 2.9 kg, often called the random variate z.\r\nFor a standard normal distribution, then probability p = N((minimum_weight - mean) / sd).\r\n\r\nWe want to find the standard deviation that would be required to meet this limit,\r\nso that the p th quantile is located at z (minimum_weight).\r\nIn this case, the 0.05 (5%) quantile is at 2.9 kg pack weight, when the mean is 3 kg,\r\nensuring that 0.95 (95%) of packs are above the minimum weight.\r\n\r\nRearranging, we can directly calculate the required standard deviation:\r\n*/\r\nnormal N01; // standard normal distribution with meamn zero and unit standard deviation.\r\np = 0.05;\r\ndouble qp = quantile(N01, p);\r\ndouble sd95 = (minimum_weight - mean) / qp;\r\n\r\ncout << \"For the \"<< p << \"th quantile to be located at \"\r\n << minimum_weight << \", would need a standard deviation of \" << sd95 << endl;\r\n// For the 0.05th quantile to be located at 2.9, would need a standard deviation of 0.0607957\r\n\r\n/*`We can now construct a new (normal) distribution pack95 for the 'better' packer,\r\nand check that our distribution will meet the specification.\r\n*/\r\n\r\nnormal pack95(mean, sd95);\r\ncout <<\"Fraction of packs >= \" << minimum_weight << \" with a mean of \" << mean\r\n << \" and standard deviation of \" << pack95.standard_deviation()\r\n << \" is \" << cdf(complement(pack95, minimum_weight)) << endl;\r\n// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.0607957 is 0.95\r\n\r\n/*`This calculation is generalized in the free function find_scale,\r\nas shown below, giving the same standard deviation.\r\n*/\r\ndouble ss = find_scale(minimum_weight, under_fraction, packs.mean());\r\ncout << \"find_scale(minimum_weight, under_fraction, packs.mean()); \" << ss << endl;\r\n// find_scale(minimum_weight, under_fraction, packs.mean()); 0.0607957\r\n\r\n/*`If we had defined an over_fraction, or percentage that must pass specification\r\n*/\r\ndouble over_fraction = 0.95;\r\n/*`And (wrongly) written\r\n\r\n double sso = find_scale(minimum_weight, over_fraction, packs.mean());\r\n\r\nWith the default policy, we would get a message like\r\n\r\n[pre\r\nMessage from thrown exception was:\r\n Error in function boost::math::find_scale(double, double, double, Policy):\r\n Computed scale (-0.060795683191176959) is <= 0! Was the complement intended?\r\n]\r\n\r\nBut this would return a *negative* standard deviation - obviously impossible.\r\nThe probability should be 1 - over_fraction, not over_fraction, thus:\r\n*/\r\n\r\ndouble ss1o = find_scale(minimum_weight, 1 - over_fraction, packs.mean());\r\ncout << \"find_scale(minimum_weight, under_fraction, packs.mean()); \" << ss1o << endl;\r\n// find_scale(minimum_weight, under_fraction, packs.mean()); 0.0607957\r\n\r\n/*`But notice that using '1 - over_fraction' - will lead to a\r\n[link why_complements loss of accuracy, especially if over_fraction was close to unity.]\r\nIn this (very common) case, we should instead use the __complements,\r\ngiving the most accurate result.\r\n*/\r\n\r\ndouble ssc = find_scale(complement(minimum_weight, over_fraction, packs.mean()));\r\ncout << \"find_scale(complement(minimum_weight, over_fraction, packs.mean())); \" << ssc << endl;\r\n// find_scale(complement(minimum_weight, over_fraction, packs.mean())); 0.0607957\r\n\r\n/*`Note that our guess of 0.06 was close to the accurate value of 0.060795683191176959.\r\n\r\nWe can again confirm our prediction thus:\r\n*/\r\n\r\nnormal pack95c(mean, ssc);\r\ncout <<\"Fraction of packs >= \" << minimum_weight << \" with a mean of \" << mean\r\n << \" and standard deviation of \" << pack95c.standard_deviation()\r\n << \" is \" << cdf(complement(pack95c, minimum_weight)) << endl;\r\n// Fraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.0607957 is 0.95\r\n\r\n/*`Notice that these two deceptively simple questions:\r\n\r\n* Do we over-fill to make sure we meet a minimum specification (or under-fill to avoid an overdose)?\r\n\r\nand/or\r\n\r\n* Do we measure better?\r\n\r\nare actually extremely common.\r\n\r\nThe weight of beef might be replaced by a measurement of more or less anything,\r\nfrom drug tablet content, Apollo landing rocket firing, X-ray treatment doses...\r\n\r\nThe scale can be variation in dispensing or uncertainty in measurement.\r\n*/\r\n//] [/normal_find_location_and_scale_eg Quickbook end]\r\n\r\n }\r\n catch(const exception& e)\r\n { // Always useful to include try & catch blocks because default policies\r\n // are to throw exceptions on arguments that cause errors like underflow, overflow.\r\n // Lacking try & catch blocks, the program will abort without a message below,\r\n // which may give some helpful clues as to the cause of the exception.\r\n cout <<\r\n \"\\n\"\"Message from thrown exception was:\\n \" << e.what() << endl;\r\n }\r\n return 0;\r\n} // int main()\r\n\r\n\r\n/*\r\n\r\nOutput is:\r\n\r\n//[normal_find_location_and_scale_output\r\n\r\nFind_location (mean) and find_scale (standard deviation) examples.\r\nPercentage of packs > 3.1 is 15.8655\r\nFraction of packs <= 2.9 with a mean of 3 is 0.841345\r\nFraction of packs >= 2.9 with a mean of 3.06449 is 0.950005\r\nSetting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95\r\nSetting the packer to 3.06449 will mean that fraction of packs >= 2.9 is 0.95\r\nCauchy Setting the packer to 3 will mean that fraction of packs >= 2.9 is 0.75\r\nfind_location(minimum_weight, over fraction, standard_deviation); 3.53138\r\nCauchy Setting the packer to 3.53138 will mean that fraction of packs >= 2.9 is 0.95\r\nCauchy Setting the packer to -0.282052 will mean that fraction of packs >= 2.9 is 0.95\r\nQuantile of 0.05 = 2.83551, mean = 3, sd = 0.1\r\nQuantile of 0.05 = 2.91776, mean = 3, sd = 0.05\r\nFraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.05 is 0.97725\r\nQuantile of 0.05 = 2.90131, mean = 3, sd = 0.06\r\nFraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.06 is 0.95221\r\nFor the 0.05th quantile to be located at 2.9, would need a standard deviation of 0.0607957\r\nFraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.0607957 is 0.95\r\nfind_scale(minimum_weight, under_fraction, packs.mean()); 0.0607957\r\nfind_scale(minimum_weight, under_fraction, packs.mean()); 0.0607957\r\nfind_scale(complement(minimum_weight, over_fraction, packs.mean())); 0.0607957\r\nFraction of packs >= 2.9 with a mean of 3 and standard deviation of 0.0607957 is 0.95\r\n\r\n//] [/normal_find_location_and_scale_eg_output]\r\n\r\n*/\r\n\r\n\r\n\r\n", "meta": {"hexsha": "0e5e0376c5df591b466fef42522ee9d78fbb42a9", "size": 18314, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/find_mean_and_sd_normal.cpp", "max_stars_repo_name": "jmuskaan72/Boost", "max_stars_repo_head_hexsha": "047e36c01841a8cd6a5c74d4e3034da46e327bc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/math/example/find_mean_and_sd_normal.cpp", "max_issues_repo_name": "xiaoliang2121/Boost", "max_issues_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T08:23:23.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-24T07:48:47.000Z", "max_forks_repo_path": "libs/math/example/find_mean_and_sd_normal.cpp", "max_forks_repo_name": "xiaoliang2121/Boost", "max_forks_repo_head_hexsha": "fc90c3fde129c62565c023f091eddc4a7ed9902b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 44.1301204819, "max_line_length": 112, "alphanum_fraction": 0.7160642132, "num_tokens": 4769, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513814471134, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6892892154310121}} {"text": "#ifndef RSVD_ERROR_ESTIMATORS_HPP_\n#define RSVD_ERROR_ESTIMATORS_HPP_\n\n#include \n\nnamespace Rsvd {\n\n/// \\brief Compute the relative Frobenius error of a matrix approximation.\n///\n/// \\long The formula for the relative error is\n/// \\f[ \\varepsilon = \\frac{ \\| \\tilde{A} - A \\|_{\\mathrm{F}} }{ \\| A \\|_{\\mathrm{F}} }. \\f]\n///\n/// Both matrices can be real or complex.\n///\n/// \\tparam MatrixType Eigen matrix type.\n///\n/// \\param reference Reference matrix \\f$ A \\f$. It is assumed that this matrix has positive\n/// Frobenius norm.\n///\n/// \\param approximation Approximation \\f$ \\tilde{A} \\f$ of the reference matrix.\n///\n/// \\return Relative Frobenius error \\f$ \\varepsilon \\f$ of the approximation (non-negative real).\ntemplate \ntypename Eigen::NumTraits::Real\nrelativeFrobeniusNormError(const MatrixType &reference, const MatrixType &approximation) {\n const auto differenceNorm = (approximation - reference).norm();\n const auto referenceNorm = reference.norm();\n\n assert(referenceNorm > 0);\n\n return differenceNorm / referenceNorm;\n}\n\n} // namespace Rsvd\n\n#endif\n", "meta": {"hexsha": "8659b0fb25f43c685c35c5172dc3a4b2cdf9c714", "size": 1130, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rsvd/ErrorEstimators.hpp", "max_stars_repo_name": "valerii-filev-picsart/rsvd", "max_stars_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/rsvd/ErrorEstimators.hpp", "max_issues_repo_name": "valerii-filev-picsart/rsvd", "max_issues_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/rsvd/ErrorEstimators.hpp", "max_forks_repo_name": "valerii-filev-picsart/rsvd", "max_forks_repo_head_hexsha": "348b10c0930a137ede14a40548ec1e0956420318", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5405405405, "max_line_length": 98, "alphanum_fraction": 0.717699115, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.798186775339273, "lm_q1q2_score": 0.6891477594085732}} {"text": "#include \n#include \n#include \n#include \n \nusing big_int = boost::multiprecision::cpp_int;\n \nbig_int ipow(big_int base, big_int exp) {\n big_int result(1);\n while (exp) {\n if (exp & 1) {\n result *= base;\n }\n exp >>= 1;\n base *= base;\n }\n return result;\n}\n \nbig_int ackermann(unsigned m, unsigned n) {\n static big_int (*ack)(unsigned, big_int) =\n [](unsigned m, big_int n)->big_int {\n switch (m) {\n case 0:\n return n + 1;\n case 1:\n return n + 2;\n case 2:\n return 3 + 2 * n;\n case 3:\n return 5 + 8 * (ipow(big_int(2), n) - 1);\n default:\n return n == 0 ? ack(m - 1, big_int(1)) : ack(m - 1, ack(m, n - 1));\n }\n };\n return ack(m, big_int(n));\n}\n \nint main() {\n for (unsigned m = 0; m < 4; ++m) {\n for (unsigned n = 0; n < 10; ++n) {\n std::cout << \"A(\" << m << \", \" << n << \") = \" << ackermann(m, n) << \"\\n\";\n }\n }\n \n std::cout << \"A(4, 1) = \" << ackermann(4, 1) << \"\\n\";\n \n std::stringstream ss;\n ss << ackermann(4, 2);\n auto text = ss.str();\n std::cout << \"A(4, 2) = (\" << text.length() << \" digits)\\n\"\n << text.substr(0, 80) << \"\\n...\\n\"\n << text.substr(text.length() - 80) << \"\\n\";\n}\n\n", "meta": {"hexsha": "f5f3f6f5a3ea3fa1b4b44d0a97c92c46862c2d4d", "size": 1258, "ext": "cc", "lang": "C++", "max_stars_repo_path": "ackermann/better_main.cc", "max_stars_repo_name": "DomirScire/Ackermann", "max_stars_repo_head_hexsha": "d18aefcaf93a0b300fc9ada408f6f3ce66fa1b24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-19T01:20:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-19T01:20:46.000Z", "max_issues_repo_path": "ackermann/better_main.cc", "max_issues_repo_name": "DomirScire/Ackermann", "max_issues_repo_head_hexsha": "d18aefcaf93a0b300fc9ada408f6f3ce66fa1b24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ackermann/better_main.cc", "max_forks_repo_name": "DomirScire/Ackermann", "max_forks_repo_head_hexsha": "d18aefcaf93a0b300fc9ada408f6f3ce66fa1b24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.4642857143, "max_line_length": 79, "alphanum_fraction": 0.4944356121, "num_tokens": 441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966641739774, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.689099131534952}} {"text": "/* \n * Copyright 2009-2015 The VOTCA Development Team (http://www.votca.org)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n#include \n#include \n\n#include \"mkl.h\"\n#include \"mkl_lapacke.h\"\n\n\nnamespace votca { namespace tools {\n\nusing namespace std;\n\n\nvoid linalg_cholesky_decompose( ub::matrix &A){\n // Cholesky decomposition using MKL\n // input matrix A will be changed\n\n // LAPACK variables\n MKL_INT info;\n MKL_INT n = A.size1();\n char uplo = 'L';\n \n // pointer for LAPACK\n double * pA = const_cast(&A.data().begin()[0]);\n info = LAPACKE_dpotrf( LAPACK_ROW_MAJOR , uplo , n, pA, n );\n if ( info != 0 )\n throw std::runtime_error(\"Matrix not symmetric positive definite\");\n}\n\n\nvoid linalg_cholesky_decompose( ub::matrix &A){\n // Cholesky decomposition using MKL\n // input matrix A will be changed\n\n // LAPACK variables\n MKL_INT info;\n MKL_INT n = A.size1();\n char uplo = 'L';\n \n // pointer for LAPACK\n float * pA = const_cast(&A.data().begin()[0]);\n info = LAPACKE_spotrf( LAPACK_ROW_MAJOR , uplo , n, pA, n );\n if ( info != 0 )\n throw std::runtime_error(\"Matrix not symmetric positive definite\");\n}\n\n\n\n\nvoid linalg_cholesky_solve( ub::vector &x, ub::matrix &A, ub::vector &b ){\n /* calling program should catch the error error code\n * thrown by LAPACKE_dpotrf and take\n * necessary steps\n */\n \n \n // LAPACK variables\n MKL_INT info;\n MKL_INT n = A.size1();\n char uplo = 'L';\n \n // pointer for LAPACK LU factorization of input matrix\n double * pA = const_cast(&A.data().begin()[0]); // input array\n \n // get LU factorization\n info = LAPACKE_dpotrf( LAPACK_ROW_MAJOR , uplo , n, pA, n );\n \n if ( info != 0 )\n throw std::runtime_error(\"Matrix not symmetric positive definite\");\n \n MKL_INT nrhs = 1;\n \n // pointer of LAPACK LU solver\n double * pb = const_cast(&b.data()[0]);\n info = LAPACKE_dpotrs(LAPACK_ROW_MAJOR, uplo, n, nrhs, pA, n, pb, n );\n\n // on output, b contains solution\n x = b;\n}\n\n}}\n", "meta": {"hexsha": "51df6071f7254223e2b12d2e0fef21da5ac41bdb", "size": 2713, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/libtools/linalg/mkl/cholesky.cc", "max_stars_repo_name": "tomspur/votca-tools", "max_stars_repo_head_hexsha": "dc1491002294edbd73baf78195408d172f71def3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/libtools/linalg/mkl/cholesky.cc", "max_issues_repo_name": "tomspur/votca-tools", "max_issues_repo_head_hexsha": "dc1491002294edbd73baf78195408d172f71def3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/libtools/linalg/mkl/cholesky.cc", "max_forks_repo_name": "tomspur/votca-tools", "max_forks_repo_head_hexsha": "dc1491002294edbd73baf78195408d172f71def3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6836734694, "max_line_length": 98, "alphanum_fraction": 0.6509399189, "num_tokens": 741, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767970940975, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6890900626969079}} {"text": "#include \"pch.h\"\n#include \n#include \"ReverseDistortionEstimator.h\"\n#include \"photogrammetry.h\"\n\n\nReverseDistortionEstimator::ReverseDistortionEstimator(const Camera& cam)\n{\n\t//solves for the inverse distortion (like opencv)\n\t//see: https://docs.opencv.org/3.4.6/d9/d0c/group__calib3d.html\n\t\n\tint x_spacing = cam.W / 10;\n\tint y_spacing = cam.H / 10;\n\tvector > grid_points;\n\tvector > grid_points_undistorted;\n\tvector > dist_corrections;\n\tgrid_points.reserve(200);\n\t\n\t//calculating the estimation grid:\n\tfor (int x = 0; x <= cam.W; x += x_spacing)\n\t{\n\t\tfor (int y = 0; y <= cam.H; y += y_spacing)\n\t\t{\n\t\t\tgrid_points.push_back({\n\t\t\t\tstatic_cast(x),\n\t\t\t\tstatic_cast(y) });\n\t\t}\n\t}\n\tgrid_points.shrink_to_fit();\n\n\t//transformation from column/row coordinates to image-centered coordinates\n\tstd::transform(grid_points.begin(), grid_points.end(), grid_points.begin(),\n\t\t[&](std::array& p ){\n\t\treturn std::array{\n\t\t\tp[0] = p[0] - cam.W / 2.0 + 0.5,\n\t\t\tp[1] = cam.H / 2.0 - p[1] - 0.5}; });\n\n\n\t//transformation from image-centered coordinates to fiducial coordiantes\n\tstd::transform(grid_points.begin(), grid_points.end(), grid_points.begin(),\n\t\t[&](std::array& p) {\n\t\treturn std::array{\n\t\t\tp[0] = p[0] - cam.InternalOrientation[1],\n\t\t\tp[1] = p[1] - cam.InternalOrientation[2]}; });\n\n\t\n\tgrid_points_undistorted.resize(grid_points.size());\n\tdist_corrections.resize(grid_points.size());\n\n\t\n\tstd::transform(grid_points.begin(), grid_points.end(), dist_corrections.begin(),\n\t\t[&](std::array& p) {\n\t\treturn std::array{\n\t\t\tfT_xDistCorrection(cam.RadialDistortion, cam.TangentialDistortion, p[0], p[1]),\n\t\t\tfT_yDistCorrection(cam.RadialDistortion, cam.TangentialDistortion, p[0], p[1])}; });\n\t\n\n\tfor (size_t i = 0, S = grid_points.size(); i < S; i++)\n\t{\n\t\tgrid_points_undistorted.at(i)[0] = grid_points.at(i)[0] - dist_corrections.at(i)[0];\n\t\tgrid_points_undistorted.at(i)[1] = grid_points.at(i)[1] - dist_corrections.at(i)[1];\n\t}\n\n\t//solving the reversed distortion using Eieng linear algerbra tools:\n\t//each coordinate generates one equation:\n\tEigen::MatrixXd A(2 * grid_points_undistorted.size(), 5);\n\tEigen::VectorXd L(2 * grid_points_undistorted.size());\n\tEigen::VectorXd X(5);\n\tEigen::VectorXd V(2 * grid_points_undistorted.size());\n\n\tfor (size_t i = 0, S = grid_points_undistorted.size(); i < S; i++)\n\t{\n\t\t//we are estimating in the normalized space so w have to use normalized values\n\t\tdouble x = grid_points_undistorted.at(i)[0] /cam.InternalOrientation[0];\n\t\tdouble y = -grid_points_undistorted.at(i)[1] /cam.InternalOrientation[0];\n\t\tdouble dx = dist_corrections.at(i)[0] / cam.InternalOrientation[0];\n\t\tdouble dy = -dist_corrections.at(i)[1] / cam.InternalOrientation[0];\n\t\tdouble rr = x * x + y * y;\n\n\t\tA(2 * i, 0) = x * rr;\n\t\tA(2 * i, 1) = x * rr*rr;\n\t\tA(2 * i, 2) = x * rr*rr*rr;\n\t\tA(2 * i, 3) = 2 * x * y;\n\t\tA(2 * i, 4) = rr + 2 * x*x;\n\t\tL(2 * i) = dx;\n\n\t\tA(2 * i + 1, 0) = y * rr;\n\t\tA(2 * i + 1, 1) = y * rr*rr;\n\t\tA(2 * i + 1, 2) = y * rr*rr*rr;\n\t\tA(2 * i + 1, 3) = rr + 2 * y * y;\n\t\tA(2 * i + 1, 4) = 2 * x * y;\n\t\tL(2 * i + 1) = dy;\n\t}\n\n\tX = A.colPivHouseholderQr().solve(L);\n\tV = L - A * X;\n\tRMSE = std::sqrt((1.0 /(L.rows()-1)) * V.transpose()*V);\n\n\tfor (int i = 0; i < 5; i++) DistortionYDown.at(i) = X(i);\n\n}\n\n\nReverseDistortionEstimator::~ReverseDistortionEstimator()\n{\n}\n", "meta": {"hexsha": "a4638bcf645eb0ba273a6ae89c111f9464655972", "size": 3437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xtrel/ReverseDistortionEstimator.cpp", "max_stars_repo_name": "kubakolecki/xtrel", "max_stars_repo_head_hexsha": "f8557fb641df175b0b7a5bf7f42fa662e82d7785", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-08T14:41:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T03:38:52.000Z", "max_issues_repo_path": "xtrel/ReverseDistortionEstimator.cpp", "max_issues_repo_name": "kubakolecki/xtrel", "max_issues_repo_head_hexsha": "f8557fb641df175b0b7a5bf7f42fa662e82d7785", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xtrel/ReverseDistortionEstimator.cpp", "max_forks_repo_name": "kubakolecki/xtrel", "max_forks_repo_head_hexsha": "f8557fb641df175b0b7a5bf7f42fa662e82d7785", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.1214953271, "max_line_length": 87, "alphanum_fraction": 0.6488216468, "num_tokens": 1166, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682086, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6888924592939887}} {"text": "#include \"mnist_loader.h\"\n#include \"node.h\"\n\n#include \n#include \n#include \n\n#define EIGEN_MPL2_ONLY\n\n#define INPUT_SIZE 784\n#define HIDDEN_SIZE 50\n#define OUTPUT_SIZE 10\n\nconst double VAR_DIFF = 1.0e-4;\nconst double MOD_RATIO = 1.0e-2;\n\nnamespace {\n\tEigen::VectorXf ReLu(Eigen::VectorXf &val)\n\t{\n\t\tEigen::VectorXf ret(val.rows());\n\n\t\tfor(int i = 0 ; i < val.rows() ; i++)\n\t\t{\n\t\t\tret[i] = fmax(0, val[i]);\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tEigen::VectorXf Softmax(Eigen::VectorXf &val)\n\t{\n\t\tEigen::VectorXf ret(val.rows());\n\n\t\tdouble sum = 0;\n\t\tdouble *exp_array = new double[val.rows()];\n\n\t\tfor(int i = 0 ; i < val.rows() ; i++)\n\t\t{\n\t\t\texp_array[i] = exp(val[i]);\n\t\t\tsum += exp_array[i];\n\t\t}\n\n\t\t// printf(\"softmax sum = %f\\n\", sum);\n\t\tfor(int i = 0 ; i < val.rows() ; i++)\n\t\t{\n\t\t\tret[i] = exp_array[i] / sum;\n\t\t}\n\n\t\tdelete[] exp_array;\n\n\t\treturn ret;\n\t}\n\n\tEigen::VectorXf MakeOnehotVector(int size, int index)\n\t{\n\t\tEigen::VectorXf ret = Eigen::VectorXf::Zero(size);\n\t\tret[index] = 1;\n\t\treturn ret;\n\t}\n\n\tfloat SquareError(Eigen::VectorXf vec1, Eigen::VectorXf vec2)\n\t{\n\t\tassert(vec1.rows() == vec2.rows());\n\t\tassert(vec1.cols() == vec2.cols());\n\t\tassert(vec1.cols() == 1);\n\n\t\tfloat error = 0;\n\t\tfor(int i = 0 ; i < vec1.rows() ; i++)\n\t\t{\n\t\t\tfloat v = vec1[i] - vec2[i];\n\t\t\terror += v * v;\n\t\t}\n\n\t\treturn error;\n\t}\n\n\tint MaxIndex(Eigen::VectorXf vec)\n\t{\n\t\tint max_index = 0;\n\t\tfor(int i = 0 ; i < vec.rows() ; i++)\n\t\t{\n\t\t\tif(vec[max_index] < vec[i])\n\t\t\t{\n\t\t\t\tmax_index = i;\n\t\t\t}\n\t\t}\n\t\treturn max_index;\n\t}\n};\n\nEigen::VectorXf Array2VectorXf(uint8_t *array, int size)\n{\n\tEigen::VectorXf ret(size);\n\n\t// this conversion needs due to different data format\n\tfor(int i = 0 ; i < size ; i++)\n\t{\n\t\tret[i] = array[i];\n\t}\n\n\treturn ret;\n}\n\nEigen::VectorXf Predict(Node &node1, Node &node2, Eigen::VectorXf input)\n{\n\tEigen::VectorXf temp;\n\n\ttemp = node1.Calc(input);\n\ttemp = ReLu(temp);\n\ttemp = node2.Calc(temp);\n\ttemp = Softmax(temp);\n\n\treturn temp;\n}\n\ndouble CalcError(Node &node1, Node &node2, Eigen::VectorXf input, Eigen::VectorXf ans)\n{\n\tEigen::VectorXf output = Predict(node1, node2, input);\n\tdouble error_rate = SquareError(output, ans);\n\n\treturn error_rate;\n}\n\nint main()\n{\n\tstd::vector > train_image_list;\n\tstd::vector train_label_list;\n\tstd::vector > test_image_list;\n\tstd::vector test_label_list;\n\n\tEigen::initParallel();\n\tEigen::setNbThreads(4);\n\n\tprintf(\"[INFO] load image...\\n\");\n\tstd::shared_ptr loader = std::make_shared();\n\tif(loader->LoadImage(\"../train-images-idx3-ubyte\", train_image_list) == false)\n\t{\n\t\tprintf(\"[ERROR] load data error.\\n\");\n\t}\n\n\tif(loader->LoadLabel(\"../train-labels-idx1-ubyte\", train_label_list) == false)\n\t{\n\t\tprintf(\"[ERROR] load data error.\\n\");\n\t}\n\n\tif(loader->LoadImage(\"../t10k-images-idx3-ubyte\", test_image_list) == false)\n\t{\n\t\tprintf(\"[ERROR] load data error.\\n\");\n\t}\n\n\tif(loader->LoadLabel(\"../t10k-labels-idx1-ubyte\", test_label_list) == false)\n\t{\n\t\tprintf(\"[ERROR] load data error.\\n\");\n\t}\n\n\tNode node1(INPUT_SIZE, HIDDEN_SIZE);\n\tif(node1.Load(\"weight_node1\") == false)\n\t{\n\t\tprintf(\"[INFO] node1 weight value initialize with random value.\\n\");\n\t}\n\tNode node2(HIDDEN_SIZE, OUTPUT_SIZE);\n\tif(node2.Load(\"weight_node2\") == false)\n\t{\n\t\tprintf(\"[INFO] node2 weight value initialize with random value.\\n\");\n\t}\n\n\tprintf(\"[INFO] training...\\n\");\n\tsranddev();\n\t// for(int image_index = 0 ; image_index < train_image_list.size() ; image_index++)\n\t// for(int image_index = 0 ; image_index < 100 ; image_index++)\n\tfor(int train_count = 0 ; train_count < 100 ; train_count++)\n\t{\n\t\tint image_index = rand() % train_image_list.size();\n\n//\t\tif(image_index % 100 == 0)\n//\t\t{\n//\t\t\tprintf(\"[INFO] exec %d/%d\\n\", image_index, (int)train_label_list.size());\n//\t\t}\n\n\t\tstd::shared_ptr image = train_image_list[image_index];\n\t\tEigen::VectorXf input = Array2VectorXf(image->image, image->image_size);\n\t\tint ans = train_label_list[image_index];\n\t\tEigen::VectorXf ans_vec = MakeOnehotVector(OUTPUT_SIZE, ans);\n//\t\tprintf(\"image_index = %d, ans = %d\\n\", image_index, ans);\n\n\t\tinput.normalize();\n\n\t\tdouble *node1_mod = new double[node1.GetMaxWeightIndex()];\n\t\tdouble *node2_mod = new double[node2.GetMaxWeightIndex()];\n\n\t\tfor(int i = 0 ; i < node1.GetMaxWeightIndex() ; i++)\n\t\t{\n\t\t\tdouble dyp = 0;\n\t\t\tdouble dyn = 0;\n\n\t\t\tnode1.PushWeightDiff(i, VAR_DIFF);\n\t\t\tdyp = CalcError(node1, node2, input, ans_vec);\n\t\t\tnode1.PopWeightDiff();\n\n\t\t\tnode1.PushWeightDiff(i, -VAR_DIFF);\n\t\t\tdyn = CalcError(node1, node2, input, ans_vec);\n\t\t\tnode1.PopWeightDiff();\n\n\t\t\tnode1_mod[i] = (dyp - dyn) / (2.0 * VAR_DIFF);\n\n//\t\t\tprintf(\"dyp=%f, dyn=%f, mod=%f\\n\", dyp, dyn, node1_mod[i]);\n\t\t}\n\n\t\tfor(int i = 0 ; i < node2.GetMaxWeightIndex() ; i++)\n\t\t{\n\t\t\tdouble dyp = 0;\n\t\t\tdouble dyn = 0;\n\n\t\t\tnode2.PushWeightDiff(i, VAR_DIFF);\n\t\t\tdyp = CalcError(node1, node2, input, ans_vec);\n\t\t\tnode2.PopWeightDiff();\n\n\t\t\tnode2.PushWeightDiff(i, -VAR_DIFF);\n\t\t\tdyn = CalcError(node1, node2, input, ans_vec);\n\t\t\tnode2.PopWeightDiff();\n\n\t\t\tnode2_mod[i] = (dyp - dyn) / (2.0 * VAR_DIFF);\n\n//\t\t\tprintf(\"dyp=%lf, dyn=%lf, mod=%lf\\n\", dyp, dyn, node2_mod[i]);\n\t\t}\n\n\t\tfor(int i = 0 ; i < node1.GetMaxWeightIndex() ; i++)\n\t\t{\n\t\t\tnode1.AddWeight(i, node1_mod[i] * -MOD_RATIO);\n\t\t}\n\n\t\tfor(int i = 0 ; i < node2.GetMaxWeightIndex() ; i++)\n\t\t{\n\t\t\tnode2.AddWeight(i, node2_mod[i] * -MOD_RATIO);\n\t\t}\n\n\t\tdelete[] node1_mod;\n\t\tdelete[] node2_mod;\n\n\t\t//return 1;\n\n//\t\tif(image_index == 10)\n//\t\t{\n//\t\t\t// optimization test\n//\t\t\treturn 1;\n//\t\t}\n\t}\n\n\tnode1.Save(\"weight_node1\");\n\tnode2.Save(\"weight_node2\");\n\n\tprintf(\"[INFO] test...\\n\");\n\tstd::vector result_list;\n\tfor(int image_index = 0 ; image_index < test_image_list.size() ; image_index++)\n\t{\n\t\tstd::shared_ptr image = test_image_list[image_index];\n\t\tEigen::VectorXf input = Array2VectorXf(image->image, image->image_size);\n\n\t\tinput.normalize();\n\t\tEigen::VectorXf output = Predict(node1, node2, input);\n\n\t\tint result = MaxIndex(output);\n\t\tresult_list.push_back(result);\n\n\t}\n\n\tassert(result_list.size() == test_label_list.size());\n\tint success_count = 0;\n\tint fail_count = 0;\n\tfor(int i = 0 ; i < result_list.size() ; i++)\n\t{\n//\t\tprintf(\"result = %d, test = %d,\", result_list[i], test_label_list[i]);\n\t\tif(result_list[i] == test_label_list[i])\n\t\t{\n\t\t\tsuccess_count++;\n\t\t}else\n\t\t{\n\t\t\tfail_count++;\n\t\t}\n\t}\n\tfloat accuracy = success_count / (float)(success_count + fail_count);\n\tstd::cout << \"accuracy = \" << accuracy << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "d31b1b03277cfc79788d0a6426a3d0fb0c05b018", "size": 6577, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c/main.cpp", "max_stars_repo_name": "yasuharu/dlearning", "max_stars_repo_head_hexsha": "856f4b8aad5396c138e365e326600986f8674dfe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c/main.cpp", "max_issues_repo_name": "yasuharu/dlearning", "max_issues_repo_head_hexsha": "856f4b8aad5396c138e365e326600986f8674dfe", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c/main.cpp", "max_forks_repo_name": "yasuharu/dlearning", "max_forks_repo_head_hexsha": "856f4b8aad5396c138e365e326600986f8674dfe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.9965034965, "max_line_length": 86, "alphanum_fraction": 0.6346358522, "num_tokens": 2055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951698485603, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6887970265746812}} {"text": "#include \n#include \n#include \n\nint main(int argc, char **argv)\n{\n // 100x100 Random Matrix\n Eigen::MatrixXd Rand = Eigen::MatrixXd::Random(100, 100);\n Eigen::MatrixXd A = Rand * Rand.transpose();\n Eigen::VectorXd b_ = Eigen::VectorXd::Random(100);\n Eigen::VectorXd x_ = Eigen::VectorXd::Zero(100);\n\n clock_t t_start = clock();\n\n // LU Decomposition\n x_ = A.partialPivLu().solve(b_); // A must be Invertible\n std::cout << \"time of partialPivLu() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n // std::cout << \"x = \" << x_.transpose() << std::endl;\n t_start = clock();\n\n x_ = A.fullPivLu().solve(b_);\n std::cout << \"time of fullPivLu() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n // std::cout << \"x = \" << x_.transpose() << std::endl;\n t_start = clock();\n\n\n // QR Decomposition\n x_ = A.householderQr().solve(b_);\n std::cout << \"time of householderQr() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n // std::cout << \"x = \" << x_.transpose() << std::endl;\n t_start = clock();\n\n x_ = A.colPivHouseholderQr().solve(b_);\n std::cout << \"time of colPivHouseholderQr() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n // std::cout << \"x = \" << x_.transpose() << std::endl;\n t_start = clock();\n\n x_ = A.fullPivHouseholderQr().solve(b_);\n std::cout << \"time of fullPivHouseholderQr() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n // std::cout << \"x = \" << x_.transpose() << std::endl;\n t_start = clock();\n\n\n // Cholesky Decomposition\n x_ = A.llt().solve(b_); // A must be Positive Definite\n std::cout << \"time of llt() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n // std::cout << \"x = \" << x_.transpose() << std::endl;\n t_start = clock();\n\n x_ = A.ldlt().solve(b_); // A must be Positive or Negative Semidefinite\n std::cout << \"time of ldlt() is \" << 1000 * (clock() - t_start) / (double) CLOCKS_PER_SEC << \"ms\" << std::endl;\n // std::cout << \"x = \" << x_.transpose() << std::endl;\n t_start = clock();\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "014e19efa93b70e7980fac0640e8a22809268c1a", "size": 2211, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PA2/code/src/useSolvers.cpp", "max_stars_repo_name": "SS47816/VSLAM", "max_stars_repo_head_hexsha": "eb7da5d96baca547973eb94361f57dc0a04d1b36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PA2/code/src/useSolvers.cpp", "max_issues_repo_name": "SS47816/VSLAM", "max_issues_repo_head_hexsha": "eb7da5d96baca547973eb94361f57dc0a04d1b36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PA2/code/src/useSolvers.cpp", "max_forks_repo_name": "SS47816/VSLAM", "max_forks_repo_head_hexsha": "eb7da5d96baca547973eb94361f57dc0a04d1b36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7894736842, "max_line_length": 129, "alphanum_fraction": 0.5929443691, "num_tokens": 742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.688545545376078}} {"text": "//\n// Dynamics of a single pendulum.\n// State space is 2-d [\\theta, \\dot\\theta]: angle, angular velocity\n// If \\theta=\\pi is straight up, \\theta=0 is straight down\n// \n\n# pragma once\n\n#include \n\n#include \n\nnamespace simulators\n{\nnamespace pendulum\n{\n\ntemplate\nusing Vector = simulators::Vector;\n\nenum State\n{\n THETA = 0,\n THETADOT,\n STATE_DIM\n};\n\nenum Control \n{\n TORQUE = 0,\n CONTROL_DIM\n};\n\n// Useful for holding the parameters of the pendulum, including integration timestep.\nclass Pendulum\n{\npublic:\n Pendulum(const double dt, const double damping_coeff, const double length);\n // Discrete time dynamics.\n Vector operator()(const Vector& x, const Vector& u);\nprivate:\n double dt_;\n double damping_coeff_;\n double length_;\n\n};\n\n\n// Returns a function that can return x_{t+1} = f(x_t, u_t) for a chosen dt. \n// Underlying uses RK4 integration.\nilqr::DynamicsFunc make_discrete_dynamics_func(const double dt, const double length, const double damping_coeff);\n\n// Defines pendulum dynamics as xdot = f(x,u).\n//Eigen::VectorXd continuous_dynamics(const Eigen::VectorXd& state, const Eigen::VectorXd& control, \n// const double length, const double damping_coeff);\n\nVector continuous_dynamics(const Vector& x, const Vector& u, \n const double length, const double damping_coeff);\n} // namespace pendulum\n} // namespace simulators\n", "meta": {"hexsha": "e0a689ab1a94c40477d3974b23047898ee8860cb", "size": 1569, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/experiments/simulators/pendulum.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/experiments/simulators/pendulum.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/experiments/simulators/pendulum.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 25.7213114754, "max_line_length": 113, "alphanum_fraction": 0.6998087954, "num_tokens": 370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6884012309124793}} {"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License .\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__SO3_HPP_\n#define SMOOTH__SO3_HPP_\n\n#include \n#include \n\n#include \"internal/lie_group_base.hpp\"\n#include \"internal/macro.hpp\"\n#include \"internal/so3.hpp\"\n#include \"lie_group.hpp\"\n#include \"map.hpp\"\n\nnamespace smooth {\n\n// \\cond\ntemplate\nclass SO2;\n// \\endcond\n\n/**\n * @brief Base class for SO3 Lie group types\n *\n * Internally represented as a member of \\f$ \\mathbb{S}^3 \\f$ (unit quaternions).\n *\n * Memory layout\n * -------------\n *\n * - Group: \\f$ \\mathbf{x} = [q_x, q_y, q_z, q_w] \\f$ (same as Eigen quaternion).\n * - Tangent: \\f$ \\mathbf{a} = [\\omega_x, \\omega_y, \\omega_z] \\f$\n *\n * Constraints\n * -----------\n *\n * - Group: \\f$ q_x^2 + q_y^2 + q_z^2 + q_w^2 = 1, q_w >= 0 \\f$\n * - Tangent: \\f$ -\\pi < \\omega_x, \\omega_y, \\omega_z \\leq \\pi \\f$\n *\n * Lie group matrix form\n * ---------------------\n *\n * 3x3 rotation matrix\n *\n * Lie algebra matrix form\n * -----------------------\n *\n * \\f[\n * \\mathbf{a}^\\wedge =\n * \\begin{bmatrix}\n * 0 & -\\omega_z & \\omega_y \\\\\n * \\omega_z & 0 & -\\omega_x \\\\\n * -\\omega_y & \\omega_x & 0 \\\\\n * \\end{bmatrix} \\in \\mathbb{R}^{3 \\times 3}\n * \\f]\n */\ntemplate\nclass SO3Base : public LieGroupBase<_Derived>\n{\n using Base = LieGroupBase<_Derived>;\n\nprotected:\n SO3Base() = default;\n\npublic:\n SMOOTH_INHERIT_TYPEDEFS;\n\n /**\n * @brief Access quaterion.\n */\n Eigen::Map> quat() requires is_mutable\n {\n return Eigen::Map>(static_cast<_Derived &>(*this).data());\n }\n\n /**\n * @brief Access const quaterion.\n */\n Eigen::Map> quat() const\n {\n return Eigen::Map>(static_cast(*this).data());\n }\n\n /**\n * @brief Return euler angles.\n *\n * @param i1, i2, i3 euler angle axis convention (\\f$0=x, 1=y, 2=z\\f$).\n * Default values correspond to ZYX rotation.\n *\n * Returned angles a1, a2, a3 are s.t. rotation is described by\n * \\f$ Rot_{i_1}(a_1) * Rot_{i_2}(a_2) * Rot_{i_3}(a_3). \\f$\n * where \\f$ Rot_i(a) \\f$ rotates an angle \\f$a\\f$ around the \\f$i\\f$:th axis.\n */\n Eigen::Vector3\n eulerAngles(Eigen::Index i1 = 2, Eigen::Index i2 = 1, Eigen::Index i3 = 0) const\n {\n return quat().toRotationMatrix().eulerAngles(i1, i2, i3);\n }\n\n /**\n * @brief Rotation action on 3D vector.\n */\n template\n Eigen::Vector3 operator*(const Eigen::MatrixBase & v) const\n {\n return quat() * v;\n }\n\n /**\n * @brief Project to SO2.\n *\n * This keeps the yaw/z axis component of the rotation.\n *\n * @note SO2 header must be included.\n */\n SO2 project_so2() const\n {\n using std::atan2;\n\n const auto q = quat();\n Scalar yaw = atan2(\n Scalar(2) * (q.w() * q.z() + q.x() * q.y()),\n Scalar(1) - Scalar(2) * (q.y() * q.y() + q.z() * q.z()));\n return SO2(yaw);\n }\n};\n\n// STORAGE TYPE TRAITS\n\n// \\cond\ntemplate\nclass SO3;\n// \\endcond\n\n// \\cond\ntemplate\nstruct liebase_info>\n{\n static constexpr bool is_mutable = true;\n\n using Impl = SO3Impl<_Scalar>;\n using Scalar = _Scalar;\n\n template\n using PlainObject = SO3;\n};\n// \\endcond\n\n/**\n * @brief Storage implementation of SO3 Lie group.\n *\n * @see SO3Base for group API.\n */\ntemplate\nclass SO3 : public SO3Base>\n{\n using Base = SO3Base>;\n\n SMOOTH_GROUP_API(SO3);\n\npublic:\n /**\n * @brief Construct from quaternion.\n *\n * @param quat Eigen quaternion.\n *\n * @note Input is normalized inside constructor.\n */\n template\n SO3(const Eigen::QuaternionBase & quat) : coeffs_(quat.normalized().coeffs())\n {\n if (coeffs_(3) < 0) { coeffs_ *= Scalar(-1); }\n }\n\n /**\n * @brief SO3 representing rotation around the x axis\n * @param angle angle of rotation [rad]\n */\n static SO3 rot_x(const Scalar & angle)\n {\n using std::cos, std::sin;\n\n SO3 ret;\n ret.coeffs() << sin(angle / 2), Scalar(0), Scalar(0), cos(angle / 2);\n if (ret.coeffs()(3) < 0) { ret.coeffs() *= Scalar(-1); }\n return ret;\n }\n\n /**\n * @brief SO3 representing rotation around the y axis\n * @param angle angle of rotation [rad]\n */\n static SO3 rot_y(const Scalar & angle)\n {\n using std::cos, std::sin;\n\n SO3 ret;\n ret.coeffs() << Scalar(0), sin(angle / 2), Scalar(0), cos(angle / 2);\n if (ret.coeffs()(3) < 0) { ret.coeffs() *= Scalar(-1); }\n return ret;\n }\n\n /**\n * @brief SO3 representing rotation around the z axis\n * @param angle angle of rotation [rad]\n */\n static SO3 rot_z(const Scalar & angle)\n {\n using std::cos, std::sin;\n\n SO3 ret;\n ret.coeffs() << Scalar(0), Scalar(0), sin(angle / 2), cos(angle / 2);\n if (ret.coeffs()(3) < 0) { ret.coeffs() *= Scalar(-1); }\n return ret;\n }\n};\n\n// \\cond\ntemplate\nstruct liebase_info>> : public liebase_info>\n{};\n// \\endcond\n\n/**\n * @brief Memory mapping of SO3 Lie group.\n *\n * @see SO3Base for group API.\n */\ntemplate\nclass Map> : public SO3Base>>\n{\n using Base = SO3Base>>;\n\n SMOOTH_MAP_API();\n};\n\n// \\cond\ntemplate\nstruct liebase_info>> : public liebase_info>\n{\n static constexpr bool is_mutable = false;\n};\n// \\endcond\n\n/**\n * @brief Const memory mapping of SO3 Lie group.\n *\n * @see SO3Base for group API.\n */\ntemplate\nclass Map> : public SO3Base>>\n{\n using Base = SO3Base>>;\n\n SMOOTH_CONST_MAP_API();\n};\n\nusing SO3f = SO3; ///< SO3 with float scalar representation\nusing SO3d = SO3; ///< SO3 with double scalar representation\n\n} // namespace smooth\n\n#endif // SMOOTH__SO3_HPP_\n", "meta": {"hexsha": "073c8e9783a81d56dba1bc15ae47dd866775be2c", "size": 7214, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/so3.hpp", "max_stars_repo_name": "tgurriet/smooth", "max_stars_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/smooth/so3.hpp", "max_issues_repo_name": "tgurriet/smooth", "max_issues_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smooth/so3.hpp", "max_forks_repo_name": "tgurriet/smooth", "max_forks_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.2237762238, "max_line_length": 100, "alphanum_fraction": 0.6443027447, "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631476836816, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6884012285660999}} {"text": "#pragma once\n#include \n\nnamespace mdk {\n using VRef = Eigen::Vector3d const&;\n\n inline double angle(VRef v1, VRef v2, VRef v3) {\n auto u1 = v2 - v1, u2 = v2 - v3;\n return acos(u1.dot(u2) / (u1.norm() * u2.norm()));\n }\n\n inline double dihedral(VRef v1, VRef v2, VRef v3, VRef v4) {\n auto u1 = v2 - v1, u2 = v3 - v2, u3 = v4 - v3;\n auto d1 = u1.cross(u2), d2 = u2.cross(u3);\n\n if (d1.isZero() || d2.isZero()) return 0.0;\n double phi = acos(d1.dot(d2) / (d1.norm() * d2.norm()));\n if (d1.dot(u3) < 0.) phi = -phi;\n return phi;\n }\n\n double asphericity(Vectors const& v) {\n Vector mean = v.vectorwise().mean();\n\n Eigen::Matrix3d mit;\n double crg;\n for (size_t i = 0; i < v.size(); ++i) {\n Vector diff = v.col(i) - mean;\n crg += diff.squaredNorm();\n\n Vector sq_diff = diff.array() * diff.array();\n mit(0,0) += sq_diff(1) + sq_diff(2);\n mit(1,1) += sq_diff(2) + sq_diff(0);\n mit(2,2) += sq_diff(0) + sq_diff(1);\n mit(0,1) -= diff(0) * diff(1);\n mit(1,2) -= diff(1) * diff(2);\n mit(0,2) -= diff(0) * diff(2);\n }\n mit(1,0) = mit(0,1);\n mit(2,1) = mit(1,2);\n mit(2,0) = mit(0,2);\n crg = sqrt(crg / v.size());\n\n auto eigenvaluesC = mit.eigenvalues();\n double eigenvalues[3] = {\n sqrt(eigenvaluesC(0).real() / v.size()),\n sqrt(eigenvaluesC(1).real() / v.size()),\n sqrt(eigenvaluesC(2).real() / v.size())\n };\n\n std::sort(eigenvalues, eigenvalues + 3);\n return eigenvalues[1] - 0.5 * (eigenvalues[0] + eigenvalues[2]);\n }\n}\n", "meta": {"hexsha": "17c8dbe19268ad864652c5a3721d5946ed8a0b80", "size": 1730, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mdk/src/utils/Math.hpp", "max_stars_repo_name": "if-pan-zpp/mdk", "max_stars_repo_head_hexsha": "a66575ae2160b3d8408fe4dceb971706f650bd05", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "mdk/src/utils/Math.hpp", "max_issues_repo_name": "if-pan-zpp/mdk", "max_issues_repo_head_hexsha": "a66575ae2160b3d8408fe4dceb971706f650bd05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mdk/src/utils/Math.hpp", "max_forks_repo_name": "if-pan-zpp/mdk", "max_forks_repo_head_hexsha": "a66575ae2160b3d8408fe4dceb971706f650bd05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-19T09:24:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-19T09:24:34.000Z", "avg_line_length": 31.4545454545, "max_line_length": 72, "alphanum_fraction": 0.4855491329, "num_tokens": 589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628703, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6883992963676202}} {"text": "/*\nCopyright 2012-2018 Tamas Bolner\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n#include \n#include \n#include \"SimplexSolver.h\"\n#include \"exception.h\"\n\nusing namespace Eigen;\n\n/**\n * Constructor\n * \n * @param int mode This can be one of these: SIMPLEX_MINIMIZE, SIMPLEX_MAXIMIZE\n * @param const VectorXd &objectiveFunction The coefficients of the objective function.\n * @param const MatrixXd &constraints Full matrix for the constraints. Contains also the righthand-side values.\n * @returns SimplexSolver\n */\nSimplexSolver::SimplexSolver(int mode, const VectorXd &objectiveFunction, const MatrixXd &constraints) {\n int64_t constantColumn, temp;\n this->foundSolution = false;\n this->optimum = 0;\n this->numberOfVariables = objectiveFunction.rows();\n \n /*\n Validate input parameters\n */\n if (mode != SIMPLEX_MINIMIZE && mode != SIMPLEX_MAXIMIZE) {\n throw FException(\"SimplexSolver: invalid value for the 'mode' parameter.\");\n }\n\n if (objectiveFunction.rows() < 1) {\n throw FException(\"SimplexSolver: The coefficient vector of the objective function must contain at least one row.\");\n }\n\n if (constraints.rows() < 1) {\n throw FException(\"SimplexSolver: The constraint matrix must contain at least one row.\");\n }\n \n if (constraints.cols() != objectiveFunction.rows() + 1) {\n throw FException(\"SimplexSolver: The constraint matrix has %d columns, but should have %d, because the coefficient vector of the objective function has %d rows.\",\n constraints.cols(), objectiveFunction.rows() + 1, objectiveFunction.rows());\n }\n \n for (int i = 0; i < this->numberOfVariables; i++) {\n if (objectiveFunction(i) == 0) {\n throw FException(\"SimplexSolver: One of the coefficients of the objective function is zero.\");\n }\n }\n\n temp = constraints.cols() - 1;\n for (int i = 0; i < constraints.rows(); i++) {\n if (constraints(i, temp) < 0) {\n throw FException(\"SimplexSolver: All righthand-side coefficients of the constraint matrix must be non-negative.\");\n }\n }\n \n /*\n Build tableau\n */\n if (mode == SIMPLEX_MAXIMIZE) {\n // Maximize\n this->tableau.resize(constraints.rows() + 1, this->numberOfVariables + constraints.rows() + 1);\n\n this->tableau << -objectiveFunction.transpose(), MatrixXd::Zero(1, constraints.rows() + 1),\n constraints.leftCols(this->numberOfVariables), MatrixXd::Identity(constraints.rows(), constraints.rows()), constraints.rightCols(1);\n } else {\n // Minimize: construct the Dual problem\n this->tableau.resize(this->numberOfVariables + 1, this->numberOfVariables + constraints.rows() + 1);\n\n this->tableau << -constraints.rightCols(1).transpose(), MatrixXd::Zero(1, this->numberOfVariables + 1),\n constraints.leftCols(this->numberOfVariables).transpose(), MatrixXd::Identity(this->numberOfVariables, this->numberOfVariables), objectiveFunction;\n }\n \n /*\n Simplex algorithm\n */\n if (mode == SIMPLEX_MAXIMIZE) {\n // Maximize original problem\n if (!this->simplexAlgorithm(this->numberOfVariables)) {\n return; // No solution\n }\n } else {\n // Maximize the dual of the minimization problem\n if (!this->simplexAlgorithm(constraints.rows())) {\n return; // No solution\n }\n }\n \n /*\n Fetch solution\n */\n constantColumn = this->tableau.cols() - 1;\n this->solution.resize(this->numberOfVariables);\n\n if (mode == SIMPLEX_MAXIMIZE) {\n // Maximize\n for (int i = 0; i < this->numberOfVariables; i++) {\n temp = this->getPivotRow(i);\n \n if (temp > 0) {\n // Basic variable\n this->solution(i) = this->tableau(temp, constantColumn);\n } else {\n // Non-basic variable\n this->solution(i) = 0;\n }\n }\n this->foundSolution = true;\n this->optimum = this->tableau(0, constantColumn);\n } else {\n // Minimize\n for (int i = 0; i < this->numberOfVariables; i++) {\n this->solution(i) = this->tableau(0, constraints.rows() + i);\n }\n this->foundSolution = true;\n this->optimum = this->tableau(0, constantColumn);\n }\n}\n\n/**\n * Returns true if a solution has been found.\n * Return false otherwise.\n *\n * @returns boolean\n */\nbool SimplexSolver::hasSolution() {\n return this->foundSolution;\n}\n\n/**\n * Returns the maximum/minimum value of\n * the objective function.\n * \n * @returns double\n */\ndouble SimplexSolver::getOptimum() {\n return this->optimum;\n}\n\n/**\n * Returns a vector with the variable\n * values for the solution.\n *\n * return VectorXd\n */\nVectorXd SimplexSolver::getSolution() {\n return this->solution;\n}\n\n/**\n * Searches for the pivot row in the given column, by calculating the ratios.\n * Tries to find smallest non-negative ratio.\n * Returns -1 if all possible pivots are 0 or if the ratios are negative.\n * Deals with cases like this: 0/negative < 0/positive\n * \n * @param int64_t column\n * @returns int64_t Returns the number of the pivot row, or -1 if found none.\n */\nint64_t SimplexSolver::findPivot_min(int64_t column) {\n int64_t minIndex = -1;\n int64_t constantColumn = this->tableau.cols() - 1;\n double minRatio = 0;\n double minConstant = 0; // For the \"0/negative < 0/positive\" difference the constants have to be tracked also.\n double ratio;\n int64_t rowNum = this->tableau.rows();\n \n for (int i = 1; i < rowNum; i++) {\n if (this->tableau(i, column) == 0) {\n continue;\n }\n\n ratio = this->tableau(i, constantColumn) / this->tableau(i, column);\n if (ratio < 0) {\n //The ratio must be non-negative\n continue;\n }\n\n if (minIndex == -1) {\n // First pivot candidate\n minIndex = i;\n minRatio = ratio;\n minConstant = this->tableau(i, constantColumn);\n } else {\n if (ratio == 0 && ratio == minRatio) {\n // 0/negative < 0/positive\n if (this->tableau(i, constantColumn) < minConstant) {\n minIndex = i;\n minRatio = ratio;\n minConstant = this->tableau(i, constantColumn);\n }\n } else if (ratio < minRatio) {\n minIndex = i;\n minRatio = ratio;\n minConstant = this->tableau(i, constantColumn);\n }\n }\n }\n\n return minIndex;\n}\n\n/**\n * Iterates through the this->tableau matrix to solve the problem.\n * \n * @param int64_t variableNum The number of variables (dimensions). (different for the minimization problem)\n * @returns bool Returns true if a solution has been found. Returns false otherwise.\n */\nbool SimplexSolver::simplexAlgorithm(int64_t variableNum) {\n MatrixXd::Index pivotColumn;\n int64_t pivotRow;\n \n while (true) {\n /*\n Find pivot column, check for halt condition\n */\n this->tableau.row(0).leftCols(variableNum).minCoeff(&pivotColumn);\n if (this->tableau(0, pivotColumn) >= 0) {\n //Found no negative coefficient\n break;\n }\n \n /*\n Find pivot row\n */\n pivotRow = this->findPivot_min(pivotColumn);\n if (pivotRow == -1) {\n //no solution\n return false;\n }\n \n /*\n Do pivot operation\n */\n this->tableau.row(pivotRow) /= this->tableau(pivotRow, pivotColumn);\n this->tableau(pivotRow, pivotColumn) = 1; // For possible precision issues\n for (int i = 0; i < this->tableau.rows(); i++) {\n if (i == pivotRow) continue;\n \n this->tableau.row(i) -= this->tableau.row(pivotRow) * this->tableau(i, pivotColumn);\n this->tableau(i, pivotColumn) = 0; // For possible precision issues\n }\n }\n\n return true;\n}\n\n/**\n * If the given column has only one coefficient with value 1 (except in topmost row), and all other\n * coefficients are zero, then returns the row of the non-zero value.\n * Otherwise return -1.\n * This method is used in the final step of maximization, when we read\n * the solution from the tableau.\n * \n * @param int64_t column\n * @returns int64_t\n */\nint64_t SimplexSolver::getPivotRow(int64_t column) {\n int64_t one_row = -1;\n\n for (int i = 1; i < this->tableau.rows(); i++) {\n if (this->tableau(i, column) == 1) {\n if (one_row >= 0) {\n return -1;\n } else {\n one_row = i;\n continue;\n }\n } else if (this->tableau(i, column) != 0) {\n return -1;\n }\n }\n\n return one_row;\n}\n", "meta": {"hexsha": "f480c026a61616c94615a6aa89e1ed4b963177dd", "size": 9453, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "algorithm/src/SimplexSolver.cpp", "max_stars_repo_name": "besha94/master-thesis", "max_stars_repo_head_hexsha": "d6836f232b97cb26d754dfa0661ad29fc8033096", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2017-09-09T14:29:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T01:38:20.000Z", "max_issues_repo_path": "algorithm/src/SimplexSolver.cpp", "max_issues_repo_name": "besha94/master-thesis", "max_issues_repo_head_hexsha": "d6836f232b97cb26d754dfa0661ad29fc8033096", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-27T09:57:25.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-27T13:32:56.000Z", "max_forks_repo_path": "algorithm/src/SimplexSolver.cpp", "max_forks_repo_name": "besha94/master-thesis", "max_forks_repo_head_hexsha": "d6836f232b97cb26d754dfa0661ad29fc8033096", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2018-02-17T07:05:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T08:36:06.000Z", "avg_line_length": 32.7093425606, "max_line_length": 178, "alphanum_fraction": 0.5981169999, "num_tokens": 2255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110425624792, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6883385591833583}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n\r\n// #include \r\n// #include \"matplotlibcpp.h\"\r\n\r\n// namespace plt = matplotlibcpp;\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n\r\n\r\nvoid ucitajTacke(vector> &tacke, int duzina) {\r\n\tpair tacka;\r\n\tfor (int i = 0; i < duzina; i++) {\r\n\t\tcin >> tacka.first >> tacka.second;\r\n\t\ttacke.push_back(tacka);\r\n\t}\r\n}\r\n\r\n\r\nMatrixXf kreirajMatricuIx3(vector> &tacke) {\r\n\tMatrixXf Mat(tacke.size(), 3);\r\n\r\n\tint i = 0;\r\n\twhile (i < tacke.size()) {\r\n\t\tMat(i, 0) = tacke[i].first;\r\n\t\tMat(i, 1) = tacke[i].second;\r\n\t\tMat(i, 2) = 1;\r\n\t\ti++;\r\n\t}\r\n\t/*\r\n\t\t| t[0][p1] t[0][p2] 1 |\r\n\t\t| t[1][p1] t[1][p2] 1 |\r\n\t\t| t[2][p1] t[3][p2] 1 | \r\n\t\t| t[4][p1] t[4][p2] 1 |\r\n\t\t| ........\t\t\t |\r\n\t*/\r\n\treturn Mat;\r\n}\r\n\r\n\r\n// Svaka tacka i njena slika iz vektora pravi ovu matricu 2 x 9\r\n// Za broj tacaka n, pravi matricu 2n x 9\r\nMatrixXf kreirajMatricu2nx9(vector> &pocetne, vector> &projektovane) {\r\n\t\r\n\tMatrixXf matrix2nx9(2 * pocetne.size(), 9);\r\n\t\r\n\tauto i = pocetne.begin();\r\n\tauto j = projektovane.begin();\r\n\tint k = 0;\r\n\t\r\n\twhile (i < pocetne.end()) {\r\n\t\tmatrix2nx9(k, 0) = 0;\r\n\t\tmatrix2nx9(k, 1) = 0;\r\n\t\tmatrix2nx9(k, 2) = 0;\r\n\t\tmatrix2nx9(k, 3) = -i->first;\r\n\t\tmatrix2nx9(k, 4) = -i->second;\r\n\t\tmatrix2nx9(k, 5) = -1;\r\n\t\tmatrix2nx9(k, 6) = j->second * i->first;\r\n\t\tmatrix2nx9(k, 7) = j->second * i->second;\r\n\t\tmatrix2nx9(k, 8) = j->second;\r\n\r\n\t\tmatrix2nx9(k + 1, 0) = i->first;\r\n\t\tmatrix2nx9(k + 1, 1) = i->second;\r\n\t\tmatrix2nx9(k + 1, 2) = 1;\r\n\t\tmatrix2nx9(k + 1, 3) = 0;\r\n\t\tmatrix2nx9(k + 1, 4) = 0;\r\n\t\tmatrix2nx9(k + 1, 5) = 0;\r\n\t\tmatrix2nx9(k + 1, 6) = -(j->first * i->first);\r\n\t\tmatrix2nx9(k + 1, 7) = -(j->first * i->second);\r\n\t\tmatrix2nx9(k + 1, 8) = -(j->first);\r\n\t\r\n\t\ti++; \r\n\t\tj++; \r\n\t\tk += 2;\r\n\t\t/// | 0\t 0 0 -b[0] -b[1] -1 (p[1]*b[0]) (p[1]*b[1]) p[1]\t|\t\tb - par pocetnih koordinata tacaka\r\n\t\t///\t| p[0] p[1] 1 0 0 0 -(p[0]*b[0]) -(p[0]*b[1]) -p[0]\t|\t\tp - par projektovanih koordinata tacaka\r\n\t\t///\t|\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t\t.\t|\r\n\t\t/// |\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t\t.\t|\r\n\t\t/// |\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t.\t\t.\t|\r\n\t}\r\n\r\n\treturn matrix2nx9;\r\n}\r\n\r\nMatrixXf resiP(MatrixXf Mat, Vector3f vec, int k) {\r\n\tVector3f stepen = ((Mat.transpose()).inverse()) * vec;\r\n\r\n\tint m = stepen.size();\r\n\tint n = k;\r\n\tMatrixXf P(n, m);\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tfor (int j = 0; j < m; j++) {\r\n\t\t\tP(i, j) = stepen(i) * Mat(i, j);\r\n\t\t}\r\n\t}\r\n\treturn P.transpose();\r\n}\r\n\r\n\r\nMatrixXf naivniAlgoritam(vector> pocetne, vector> projektovane) {\r\n\r\n\tfloat x, y;\r\n\r\n\tx = pocetne.back().first;\r\n\ty = pocetne.back().second;\r\n\tVector3f v(x, y, 1);\r\n\r\n\tx = projektovane.back().first;\r\n\ty = projektovane.back().second;\r\n\tVector3f vp(x, y, 1);\r\n\r\n\tpocetne.pop_back();\r\n\tprojektovane.pop_back();\r\n\r\n\tMatrixXf M = kreirajMatricuIx3(pocetne);\r\n\tMatrixXf Mp = kreirajMatricuIx3(projektovane);\r\n\r\n\tMatrixXf P1 = resiP(M, v, pocetne.size());\r\n\tMatrixXf P2 = resiP(Mp, vp, projektovane.size());\r\n\r\n\r\n\treturn P2 * P1.inverse();\r\n}\r\n\r\n\r\nMatrixXf DLTAlgoritam(vector> pocetne, vector> projektovane) {\r\n\r\n\tint br_tacaka = pocetne.size();\r\n\r\n\tMatrixXf matrix2nx9 = kreirajMatricu2nx9(pocetne, projektovane);\r\n\t// SVD razbija matricu na proizvode 3 matrice\r\n\tJacobiSVD Svd(matrix2nx9, ComputeFullV);\r\n\t\r\n\tMatrixXf Mat(2 * br_tacaka, 9);\r\n\tMatrixXf matrica_poslednje_kolone(3, 3);\r\n\tMat = Svd.matrixV();\t// Uzimamo 3. matricu V iz A = USV*\r\n\r\n\tint br_kolona = Mat.cols();\r\n\t// Uzimamo poslednju kolonu iz dekompozicije\r\n\tfor (int i = 0; i < 3; i++) {\r\n\t\tfor (int j = 0; j < 3; j++) {\r\n\t\t\tmatrica_poslednje_kolone(i, j) = Mat(i * 3 + j, br_kolona - 1);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\treturn matrica_poslednje_kolone;\r\n}\r\n\r\nfloat izrSrednjeRastojanje(vector> tacke, pair tezite) {\r\n\r\n\tfloat prosecno_rastojanje = 0;\r\n\tint n = tacke.size();\r\n\tfor (auto i = tacke.begin(); i < tacke.end(); i++) {\r\n\t\tfloat medju_rastojanje = sqrt(pow(i->first - tezite.first, 2) + pow(i->second - tezite.second, 2));\t// sqrt((x2-x1)^2 + (y2-y1)^2)\r\n\t\tprosecno_rastojanje += medju_rastojanje;\r\n\t}\r\n\r\n\treturn prosecno_rastojanje / n;\r\n}\r\n\r\nVector3f izrCentroidu(vector> tacke) {\r\n\r\n\tfloat tx = 0;\r\n\tfloat ty = 0;\r\n\tint n = tacke.size();\r\n\r\n\t// Sabiramo tezine koordinata\r\n\tfor (auto i = tacke.begin(); i < tacke.end(); i++) {\r\n\t\ttx += i->first;\r\n\t\tty += i->second;\r\n\t}\r\n\r\n\t// centroida = (tx/n, ty/n, 1)\r\n\t// homogene\r\n\tVector3f centroida;\r\n\tcentroida << tx / n, ty / n, 1;\r\n\r\n\t/*\r\n\t// Test: teziste\r\n\tcout << \"Teziste je : \" << centroida;\r\n\tcout << endl;\r\n\t*/\r\n\r\n\treturn centroida;\r\n}\r\n\r\nMatrixXf izrMatricuNormalizacije(vector> tacke) {\r\n\t/*\r\n\t1. Izracunati teziste sistema tacaka\r\n\t2. Translirati teziste u koordinatni pocetak (matrica T)\r\n\t3. Skalirati tacke tako da prosecna udaljenost tacke od koordinatnog pocetka bude sqrt(2) (matrica homotetije S)\r\n\t4. Matrica normalizacije je jednaka S * T\r\n\t*/\r\n\tVector3f vteziste = izrCentroidu(tacke);\r\n\tpair t(vteziste(0), vteziste(1));\r\n\r\n\t// Matrica T: Translira teziste ovog skupa tacaka u O(0,0)\r\n\tMatrixXf T(3, 3);\r\n\tT << 1, 0, -vteziste(0),\r\n\t\t 0, 1, -vteziste(1),\r\n\t\t 0, 0,\t 1;\r\n\t// cout << T << endl;\r\n\tfloat srednje_rastojanje = izrSrednjeRastojanje(tacke, t);\r\n\tfloat k_skaliranja = sqrt(2) / srednje_rastojanje;\r\n\t// Matrica S: Skalira, tako da prosecno rastojanje tacaka od koordinatnog pocetka bude jednak sqrt(2)\r\n\tMatrixXf S(3, 3);\r\n\tS << k_skaliranja,\t\t0,\t\t\t0,\r\n\t\t\t0,\t\t\tk_skaliranja,\t0,\r\n\t\t\t0,\t\t\t\t0,\t\t\t1;\r\n\t// cout << S << endl;\r\n\t// Prvo transliramo pa skaliramo\r\n\treturn S * T;\r\n}\r\n\r\nMatrixXf nDLTAlgoritam(vector> pocetne, vector> projektovane) {\r\n\t/*\r\n\t1. Normalizuj tacke i slike:\tnx[i] = T * x[i], npx[i] = Tp * px[i]\r\n\t2. Uradi DLT na:\t\t\t\tnx[i] <-> npx[i]\r\n\t3. Denormalizuj resenje:\t\tH = Tp_inv * nH * T\r\n\t*/\r\n\t\r\n\tMatrixXf T = izrMatricuNormalizacije(pocetne);\r\n\tMatrixXf s_tacka = (T * kreirajMatricuIx3(pocetne).transpose()).transpose();\t// 3x3 * nx3.transp\r\n\t//\tcout << T << endl << endl << s_tacka << endl << endl;\r\n\r\n\tMatrixXf Tp = izrMatricuNormalizacije(projektovane);\r\n\tMatrixXf p_tacka = (Tp * kreirajMatricuIx3(projektovane).transpose()).transpose();\t// 3x3 * nx3.transp\r\n\t//\tcout << Tp << endl << endl << p_tacka << endl << endl;\r\n\r\n\r\n\tint n = pocetne.size();\r\n\tvector> s;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\ts.push_back(pair(s_tacka(i, 0), s_tacka(i, 1)));\r\n\t\t//\tcout << s_tacka(i, 0) << \" \" << s_tacka(i, 1) << endl;\r\n\t}\r\n\t\r\n\tvector> p;\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tp.push_back(pair(p_tacka(i, 0), p_tacka(i, 1)));\r\n\t\t//\tcout << p_tacka(i, 0) << \" \" << p_tacka(i, 1) << endl;\r\n\t}\r\n\r\n\t/*\r\n\t////\t---- Plot ----\r\n\tfor (int i = 0; i < n; i++) {\r\n\t\tplt::plot(s_tacka(i,0), s_tacka(i, 1), 'go');\r\n\t\tplt::plot(p_tacka(i, 0), p_tacka(i, 1), 'g+');\r\n\t}\r\n\t*/\r\n\r\n\tMatrixXf H = DLTAlgoritam(s, p);\r\n\treturn Tp.inverse() * H * T;\r\n}\r\n\r\nint main() {\r\n\tint opcija;\r\n\tcout << \"Izaberite opciju: \" << endl << \"1. Rucni unos koordinata\" << endl << \"2. Izabir koordinata pomocu misa\" << endl << \"::: \";\r\n\tcin >> opcija;\r\n\tif (opcija == 1) {\t\t\t\t// Rucni unos koordinata\r\n\t\t// Unos tacaka\r\n\t\tint br_tacaka;\r\n\t\tcout << \"Unesite broj korespodencija: \";\r\n\t\tcin >> br_tacaka;\r\n\t\tif (br_tacaka < 0) {\r\n\t\t\tcout << \"greska: Neispravan unos! (ocekivan broj veci od 0)\" << endl;\r\n\t\t\treturn -1;\r\n\t\t\r\n\t\t}\r\n\r\n\t\tvector> pocetne_tacke;\r\n\t\tvector> projektovane_tacke;\r\n\r\n\t\tcout << \"Ucitajte ulazne tacke kao parove x, y: \" << endl;\r\n\t\tucitajTacke(pocetne_tacke, br_tacaka);\r\n\t\tcout << \"Ucitajte izlazne tacke kao parove x, y: \" << endl;\r\n\t\tucitajTacke(projektovane_tacke, br_tacaka);\r\n\t\tcout << endl;\r\n\t\tif (br_tacaka == 4) {\r\n\t\t\tcout << \"--- Naivni algoritam: ---\" << endl;\r\n\t\t\tcout << naivniAlgoritam(pocetne_tacke, projektovane_tacke) << endl;\r\n\t\t\t\r\n\t\t\t/*\r\n\t\t\t////\t---- Plot ----\r\n\t\t\tfor (int i = 0; i < br_tacaka; i++) {\r\n\t\t\t\tplt::plot(pocetne_tacke[i].first, pocetne_tacke[i].second, 'ro');\r\n\t\t\t\tplt::plot(projektovane_tacke[i].first, projektovane_tacke[i].second, 'r+');\r\n\t\t\t}\r\n\t\t\t*/\r\n\r\n\t\t}\r\n\r\n\t\tcout << \"--- DLT algoritam: ---\" << endl;\r\n\t\tcout << DLTAlgoritam(pocetne_tacke, projektovane_tacke) << endl;\r\n\r\n\t\tcout << \"---Normalizovani DLT algoritam: ---\" << endl;\r\n\t\tcout << nDLTAlgoritam(pocetne_tacke, projektovane_tacke);\r\n\r\n\t\t//\tERROR: Error\tC1083\tCannot open include file : 'Python.h' : No such file or directory\r\n\t\t//\tVS ne cita Python header iako je ubacen u Additional Include Libraries, kao i postaveljen kao header u src dir\r\n\r\n\t\t/*\r\n\t\t////\t---- Plot ----\r\n\t\tplt::figure_size(1200, 780);\r\n\t\tplt::show();\r\n\t\t*/\r\n\r\n\t}\r\n\telse if (opcija == 2) {\t\t\t// Izabir koordinata pomocu misa\r\n\t\t\r\n\t\tcout << \"Nije zavrseno!\";\r\n\t\treturn 0;\r\n\t\t\r\n\t}\r\n\telse {\t\t\t\t\t\t\t// Greska\r\n\t\tcout << \"greska: Izabrana je nepostojeca opcija!\";\r\n\t\treturn -1;\r\n\t}\r\n\r\n\r\n\treturn 0;\r\n}", "meta": {"hexsha": "559331d43cb97c1754b1d42fc86cfbf9d0f65180", "size": 9054, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "02. Calculating projections and Removing distortion/removing_distortion.cpp", "max_stars_repo_name": "lkora/MATF-PPGR", "max_stars_repo_head_hexsha": "a92a7d617bc0b588e0b7492447eeeca7185a1e98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-06T19:54:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-28T18:41:25.000Z", "max_issues_repo_path": "02. Calculating projections and Removing distortion/removing_distortion.cpp", "max_issues_repo_name": "lkora/MATF-PPGR", "max_issues_repo_head_hexsha": "a92a7d617bc0b588e0b7492447eeeca7185a1e98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "02. Calculating projections and Removing distortion/removing_distortion.cpp", "max_forks_repo_name": "lkora/MATF-PPGR", "max_forks_repo_head_hexsha": "a92a7d617bc0b588e0b7492447eeeca7185a1e98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6036585366, "max_line_length": 134, "alphanum_fraction": 0.5863706649, "num_tokens": 3565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637469145053, "lm_q2_score": 0.8006920020959543, "lm_q1q2_score": 0.688325886646285}} {"text": "// Copyright John Maddock 2007.\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0. (See accompanying file\r\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n// Note that this file contains quickbook mark-up as well as code\r\n// and comments, don't change any of the special comment mark-ups!\r\n\r\n//[policy_eg_10\r\n\r\n/*`\r\n\r\nTo understand how the rounding policies for \r\nthe discrete distributions can be used, we'll\r\nuse the 50-sample binomial distribution with a \r\nsuccess fraction of 0.5 once again, and calculate\r\nall the possible quantiles at 0.05 and 0.95.\r\n\r\nBegin by including the needed headers:\r\n\r\n*/\r\n\r\n#include \r\n#include \r\n\r\n/*`\r\n\r\nNext we'll bring the needed declarations into scope, and\r\ndefine distribution types for all the available rounding policies:\r\n\r\n*/\r\n\r\nusing namespace boost::math::policies;\r\nusing namespace boost::math;\r\n\r\ntypedef binomial_distribution<\r\n double, \r\n policy > > \r\n binom_round_outwards;\r\n\r\ntypedef binomial_distribution<\r\n double, \r\n policy > > \r\n binom_round_inwards;\r\n\r\ntypedef binomial_distribution<\r\n double, \r\n policy > > \r\n binom_round_down;\r\n\r\ntypedef binomial_distribution<\r\n double, \r\n policy > > \r\n binom_round_up;\r\n\r\ntypedef binomial_distribution<\r\n double, \r\n policy > > \r\n binom_round_nearest;\r\n\r\ntypedef binomial_distribution<\r\n double, \r\n policy > > \r\n binom_real_quantile;\r\n\r\n/*`\r\n\r\nNow let's set to work calling those quantiles:\r\n\r\n*/\r\n\r\nint main()\r\n{\r\n std::cout << \r\n \"Testing rounding policies for a 50 sample binomial distribution,\\n\"\r\n \"with a success fraction of 0.5.\\n\\n\"\r\n \"Lower quantiles are calculated at p = 0.05\\n\\n\"\r\n \"Upper quantiles at p = 0.95.\\n\\n\";\r\n\r\n std::cout << std::setw(25) << std::right\r\n << \"Policy\"<< std::setw(18) << std::right \r\n << \"Lower Quantile\" << std::setw(18) << std::right \r\n << \"Upper Quantile\" << std::endl;\r\n \r\n // Test integer_round_outwards:\r\n std::cout << std::setw(25) << std::right\r\n << \"integer_round_outwards\"\r\n << std::setw(18) << std::right\r\n << quantile(binom_round_outwards(50, 0.5), 0.05)\r\n << std::setw(18) << std::right\r\n << quantile(binom_round_outwards(50, 0.5), 0.95) \r\n << std::endl;\r\n \r\n // Test integer_round_inwards:\r\n std::cout << std::setw(25) << std::right\r\n << \"integer_round_inwards\"\r\n << std::setw(18) << std::right\r\n << quantile(binom_round_inwards(50, 0.5), 0.05)\r\n << std::setw(18) << std::right\r\n << quantile(binom_round_inwards(50, 0.5), 0.95) \r\n << std::endl;\r\n \r\n // Test integer_round_down:\r\n std::cout << std::setw(25) << std::right\r\n << \"integer_round_down\"\r\n << std::setw(18) << std::right\r\n << quantile(binom_round_down(50, 0.5), 0.05)\r\n << std::setw(18) << std::right\r\n << quantile(binom_round_down(50, 0.5), 0.95) \r\n << std::endl;\r\n \r\n // Test integer_round_up:\r\n std::cout << std::setw(25) << std::right\r\n << \"integer_round_up\"\r\n << std::setw(18) << std::right\r\n << quantile(binom_round_up(50, 0.5), 0.05)\r\n << std::setw(18) << std::right\r\n << quantile(binom_round_up(50, 0.5), 0.95) \r\n << std::endl;\r\n \r\n // Test integer_round_nearest:\r\n std::cout << std::setw(25) << std::right\r\n << \"integer_round_nearest\"\r\n << std::setw(18) << std::right\r\n << quantile(binom_round_nearest(50, 0.5), 0.05)\r\n << std::setw(18) << std::right\r\n << quantile(binom_round_nearest(50, 0.5), 0.95) \r\n << std::endl;\r\n \r\n // Test real:\r\n std::cout << std::setw(25) << std::right\r\n << \"real\"\r\n << std::setw(18) << std::right\r\n << quantile(binom_real_quantile(50, 0.5), 0.05)\r\n << std::setw(18) << std::right\r\n << quantile(binom_real_quantile(50, 0.5), 0.95) \r\n << std::endl;\r\n}\r\n\r\n/*`\r\n\r\nWhich produces the program output:\r\n\r\n[pre\r\nTesting rounding policies for a 50 sample binomial distribution,\r\nwith a success fraction of 0.5.\r\n\r\nLower quantiles are calculated at p = 0.05\r\n\r\nUpper quantiles at p = 0.95.\r\n\r\nTesting rounding policies for a 50 sample binomial distribution,\r\nwith a success fraction of 0.5.\r\n\r\nLower quantiles are calculated at p = 0.05\r\n\r\nUpper quantiles at p = 0.95.\r\n\r\n Policy Lower Quantile Upper Quantile\r\n integer_round_outwards 18 31\r\n integer_round_inwards 19 30\r\n integer_round_down 18 30\r\n integer_round_up 19 31\r\n integer_round_nearest 19 30\r\n real 18.701 30.299\r\n]\r\n\r\n*/\r\n\r\n//] ends quickbook import\r\n\r\n", "meta": {"hexsha": "e1970cf2bcf9860ccc6b1d28f5f43c46b9320d8e", "size": 5157, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/example/policy_eg_10.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-07-12T13:04:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-30T23:23:46.000Z", "max_issues_repo_path": "libs/math/example/policy_eg_10.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/math/example/policy_eg_10.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2015-12-23T01:51:57.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-25T04:58:32.000Z", "avg_line_length": 29.9825581395, "max_line_length": 75, "alphanum_fraction": 0.5896839248, "num_tokens": 1408, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6882335456325815}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nvoid main() {\n\t{\n\t\tMatrixXf M1(3, 3); // column-major storage\n\t\tM1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n\t\tcout << \"M1: \\n\" << M1 << endl;\n\t\tMap v1(M1.data(), M1.size());\n\t\tcout << \"v1: \\n\" << v1 << endl;\n\n\t\tMatrix M2(M1);\n\t\tcout << \"M2: \\n\" << M2 << endl;\n\t\tMap v2(M2.data(), M2.size());\n\t\tcout << \"v2: \\n\" << v2 << endl;\n\t}\n\t{\n\t\tMatrixXf M1(2, 6);\n\t\tM1 << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12;\n\t\tcout << \"M1: \\n\" << M1 << endl;\n\t\tMap v1(M1.data(), M1.size());\n\t\tcout << \"v1: \\n\" << v1 << endl;\n\t\tMap M2(M1.data(), 6, 2);\n\t\tMap v2(M2.data(), M2.size());\n\t\tcout << \"M2: \\n\" << M2 << endl;\n\t\tcout << \"v2: \\n\" << v2 << endl;\n\t}\n\t{\n\t\t// Slicing\n\t\tRowVectorXf v = RowVectorXf::LinSpaced(20, 0, 19);\n\t\tcout << \"Input: \\n\" << v << endl;\n\t\tMap> v2(v.data(), v.size() / 2);\n\t\tcout << \"Even: \\n\" << v2 << endl;\n\t}\n\t{\n\t\tMatrixXf M1 = MatrixXf::Random(3, 8);\n\t\tcout << \"Column major input: \\n\" << M1 << endl;\n\t\tMap> M2(M1.data(), M1.rows(), \n\t\t\t\t\t\t\t\t\t\t (M1.cols() + 2) / 3, \n\t\t\t\t\t\t\t\t\t\t OuterStride<>(M1.outerStride() * 3));\n\t\tcout << \"1 column over 3: \\n\" << M2 << endl;\n\n\t\ttypedef Matrix RowMajorMatrixXf;\n\t\tRowMajorMatrixXf M3(M1);\n\t\tcout << \"Row major input:\" << endl << M3 << \"\\n\";\n\t\tMap > M4(M3.data(), M3.rows(), (M3.cols() + 2) / 3,\n\t\t\tStride(M3.outerStride(), 3));\n\t\tcout << \"1 column over 3:\" << endl << M4 << \"\\n\";\n\t}\n\tsystem(\"pause\");\n}", "meta": {"hexsha": "18f5694265c8a9edb1f346c22b3edc32af8990fc", "size": 1657, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eigen/eigen/reshape_slicing/reshape_slicing.cpp", "max_stars_repo_name": "quanhua92/learning-notes", "max_stars_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/eigen/eigen/reshape_slicing/reshape_slicing.cpp", "max_issues_repo_name": "quanhua92/learning-notes", "max_issues_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/eigen/eigen/reshape_slicing/reshape_slicing.cpp", "max_forks_repo_name": "quanhua92/learning-notes", "max_forks_repo_head_hexsha": "a9c50d3955c51bb58f4b012757c550b76c5309ef", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6851851852, "max_line_length": 93, "alphanum_fraction": 0.5383222692, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696748, "lm_q2_score": 0.8705972751232809, "lm_q1q2_score": 0.6882335413361578}} {"text": "//\n// Polynomials.cpp\n// kcalg\n//\n// Created by knightc on 2019/7/15.\n// Copyright © 2019 knightc. All rights reserved.\n//\n\n#include \n#include \n\n#include \"opentsb/math.h\"\n\n#include //单 x 的整数系数的多项式因式分解\n#include //单 x 的 整数系数函数/多项式\n#include //单 x 的 模 p 的整数系数函数/多项式\n#include //单 x 的 模 p 的整数系数多项式因式分解\n#include \n#include \n#include \n#include \n\nusing namespace NTL;\nusing namespace std;\n\n\nZZ y_polynomials(const ZZX &f,const ZZ xPoint) {\n \n ZZ m;\n m= f.rep[0];\n \n for (long i=1 ; i < f.rep.length(); i++) {\n if (!IsZero(f.rep[i])){\n m+=power(xPoint, i) * f.rep[i];\n }\n }\n\n\n return m;\n}\n\n\nvoid test_polynomials_main() {\n \n ZZX f;\n \n //f= a0+a1*x +a2*x^2 + a3 * x^3 +... + an * x^n\n ifstream fin(\"/Users/kc/git/alg-test/kcalg/kcalg/poly.txt\");\n fin >> f;\n // cin >> f;//xcode的输入会自动补齐,但是键盘输入需要手动输入\"【 \"与 \" 】\"\n \n Vec< Pair > factors;//pair--系数、指数的对;vec_pair_ZZX_long\n ZZ c;\n \n factor(c, factors, f);//多项式的因式分解\n \n // cout << c << \"\\n\" << factors << \"\\n\";\n \n \n //特定多项式输出:分圆多项式\n vec_ZZX phi(INIT_SIZE, 5);\n for (long i = 1; i <= 5; i++) {\n ZZX t;\n t = 1;\n \n for (long j = 1; j <= i-1; j++)\n if (i % j == 0)\n t *= phi(j);\n \n phi(i) = (ZZX(INIT_MONO, i) - 1)/t;\n \n // cout << phi(i) << \"\\n\";\n }\n \n\n //多项式赋值示例\n ZZX t1;\n ZZ t11;\n SetCoeff(t1, 4, 1); //SetCoeff的优点:自动判断长度是否变化,即保证领项系数非0\n //SetCoeff(t1, 2560, 128); //尝试一下,大数\n t1.rep[2] = 2; //ZZX.rep的缺点:改变系数的同时不判断长度是否变化\n SetCoeff(t1, 0, -1);\n SetCoeff(t1, 5, 0); //领项系数设为 0 时,自动去掉\n // t1[4]=2; //也可以直接定义系数值\n \n cout << t1 << \"\\n\";\n ZZ t12;\n t12=12345678901234567890;//long 最大只能 20 位,不能直接转换。但是 ZZ 类型可以无穷大\n t11=y_polynomials(t1, t12);\n cout << t11 << endl;//t12=2 时,正确值为 23\n \n ZZX t2;\n t2.rep.SetLength(6); //如果没有SetCoeff,使用ZZX.rep之前必须先用该句初始化长度\n t2.rep[4] = 1;\n t2.rep[0] = -1;\n// cout << t2 << \"\\n\"; //注:此时领项系数是0,即第 6 项的系数为 0\n \n t2.normalize(); //作用:重新调整长度,以保证领项系数非0\n // cout << t2 << \"\\n\";\n \n //下面两种从多项式中取系数的值的方法等价\n if (t1.rep[4] == 1 and coeff(t1, 4) == 1 ){\n // cout << \"多项式取值正确\" << \"\\n\";\n }\n // cout << GCD(t1, t2) << endl;\n \n //mod p polynomials\n ZZ p(65537);\n ZZ_p::init(p);\n \n ZZ_pX f_px;\n //cin >> f_px;\n SetCoeff(f_px, 4, 2);\n f_px.rep[3]=35;\n SetCoeff(f_px,5,1);//领项系数必须为 1:leadcoeff=1\n \n \n vec_pair_ZZ_pX_long factors_px;\n CanZass(factors_px, f_px); // calls \"Cantor/Zassenhaus\" algorithm\n // cout << factors_px << \"\\n\" << f_px << \"\\n\";\n \n \n // mod gf2e polynomials\n GF2X P;\n SetCoeff(P, 8, 1);\n SetCoeff(P, 4, 1);\n SetCoeff(P, 3, 1);\n SetCoeff(P, 1, 1);\n SetCoeff(P, 0, 1);\n GF2E::init(P);\n \n GF2EX f_gf2ex;\n SetCoeff(f_gf2ex, 0, 65537);\n // f_gf2ex.rep[2]= 23;\n \n vec_pair_GF2EX_long factors_gf2ex;\n // CanZass(factors_gf2ex, f_gf2ex);\n // cout << factors_gf2ex << \"\\n\" << f_gf2ex << \"\\n\";\n \n}\n\n\n\n\n", "meta": {"hexsha": "6f94377d2329fb19b76ecb295d69379c57bd136c", "size": 3184, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kcalg/math/Polynomials.cpp", "max_stars_repo_name": "kn1ghtc/kctsb", "max_stars_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-16T00:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T00:10:51.000Z", "max_issues_repo_path": "kcalg/math/Polynomials.cpp", "max_issues_repo_name": "kn1ghtc/kctsb", "max_issues_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kcalg/math/Polynomials.cpp", "max_forks_repo_name": "kn1ghtc/kctsb", "max_forks_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9586206897, "max_line_length": 70, "alphanum_fraction": 0.5288944724, "num_tokens": 1402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505453836382, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6881230228824331}} {"text": "#include \n#include \n#include \n#include \"../../include/Optimization/LineSearch.h\"\n#include \"../../include/Optimization/NewtonDescent.h\"\n#include \"../../include/timer.h\"\n// #include \"SuiteSparse_config.h\"\n\nvoid OptSolver::newtonSolver(std::function*, bool)> objFunc, std::function findMaxStep, Eigen::VectorXd& x0, int numIter, double gradTol, double xTol, double fTol, bool disPlayInfo, std::function getNormFunc, std::string* savingFolder, std::function postProcess)\n{\n\tconst int DIM = x0.rows();\n Eigen::VectorXd randomVec = x0;\n randomVec.setRandom();\n x0 += 1e-6 * randomVec;\n\tEigen::VectorXd grad = Eigen::VectorXd::Zero(DIM);\n\tEigen::SparseMatrix hessian;\n\n\tEigen::VectorXd neggrad, delta_x;\n\tdouble maxStepSize = 1.0;\n\tdouble reg = 1e-8;\n\n\tbool isProj = true;\n Timer totalTimer;\n double totalAssemblingTime = 0;\n double totalSolvingTime = 0;\n double totalLineSearchTime = 0;\n\n totalTimer.start();\n\tstd::ofstream optInfo;\n\tif (savingFolder)\n\t{\n\t\toptInfo = std::ofstream((*savingFolder) + \"_optInfo.txt\");\n\t\toptInfo << \"Newton solver with termination criterion: \" << std::endl;\n\t\tstd::cout << \"gradient tol: \" << gradTol << \", function update tol: \" << fTol << \", variable update tol: \" << xTol << \", maximum iteration: \" << numIter << std::endl << std::endl;\n\t}\n\tint i = 0;\n\tfor (; i < numIter; i++)\n\t{\n\t\tif(disPlayInfo)\n\t\t\tstd::cout << \"\\niter: \" << i << std::endl;\n\t\tif(savingFolder)\n\t\t\toptInfo << \"\\niter: \" << i << std::endl;\n Timer localTimer;\n localTimer.start();\n\t\tdouble f = objFunc(x0, &grad, &hessian, isProj);\n localTimer.stop();\n double localAssTime = localTimer.elapsed() * 1e-3;\n totalAssemblingTime += localAssTime;\n\n localTimer.start();\n\t\tEigen::SparseMatrix H = hessian;\n\t\tEigen::SparseMatrix I(DIM, DIM);\n\t\tI.setIdentity();\n\t\tstd::cout << \"num of nonzeros: \" << H.nonZeros() << \", rows: \" << H.rows() << \", cols: \" << H.cols() << std::endl;\n\t\tEigen::CholmodSupernodalLLT> solver(H);\n\n\t\t// Eigen::CholmodSimplicialLLT > solver(H);\n\n\n\t\twhile (solver.info() != Eigen::Success)\n\t\t{\n\t\t\tif (disPlayInfo)\n\t\t\t{\n\t\t\t\tif (isProj)\n\t\t\t\t\tstd::cout << \"some small perturb is needed to remove round-off error, current reg = \" << reg << std::endl;\n\t\t\t\telse\n\t\t\t\t\tstd::cout << \"Matrix is not positive definite, current reg = \" << reg << std::endl;\n\t\t\t}\n\t\t\t\t\n\t\t\tH = hessian + reg * I;\n\t\t\tsolver.compute(H);\n\t\t\treg = std::max(2 * reg, 1e-16);\n\n if(reg > 1e4)\n {\n std::cout << \"reg is too large, use SPD hessian instead.\" << std::endl;\n reg = 1e-6;\n isProj = true;\n f = objFunc(x0, &grad, &hessian, isProj);\n }\n\t\t}\n\n\t\tneggrad = -grad;\n\t\tdelta_x = solver.solve(neggrad);\n\n localTimer.stop();\n double localSolvingTime = localTimer.elapsed() * 1e-3;\n totalSolvingTime += localSolvingTime;\n\n\n\t\tmaxStepSize = findMaxStep(x0, delta_x);\n\n localTimer.start();\n\t\tdouble rate = LineSearch::backtrackingArmijo(x0, grad, delta_x, objFunc, maxStepSize);\n localTimer.stop();\n double localLinesearchTime = localTimer.elapsed() * 1e-3;\n totalLineSearchTime += localLinesearchTime;\n\n\n\t\tif (!isProj)\n\t\t{\n\t\t\treg *= 0.5;\n\t\t\treg = std::max(reg, 1e-16);\n\t\t}\n\t\t\n\t\tx0 = x0 + rate * delta_x;\n\n\t\tdouble fnew = objFunc(x0, &grad, NULL, isProj);\n\t\tif (disPlayInfo)\n\t\t{\n\t\t\tstd::cout << \"line search rate : \" << rate << \", actual hessian : \" << !isProj << \", reg = \" << reg << std::endl;\n\t\t\tstd::cout << \"f_old: \" << f << \", f_new: \" << fnew << \", grad norm: \" << grad.norm() << \", delta x: \" << rate * delta_x.norm() << \", delta_f: \" << f - fnew << std::endl;\n\t\t\tif (getNormFunc)\n\t\t\t{\n\t\t\t\tdouble gradz, gradw;\n\t\t\t\tgetNormFunc(grad, gradz, gradw);\n\n\t\t\t\tdouble updatez, updatew;\n\t\t\t\tgetNormFunc(rate * delta_x, updatez, updatew);\n\t\t\t\tstd::cout << \"z grad: \" << gradz << \", w grad: \" << gradw << \", z change: \" << updatez << \", w change: \" << updatew << std::endl;\n\t\t\t}\n std::cout << \"timing info (in total seconds): \" << std::endl;\n std::cout << \"assembling took: \" << totalAssemblingTime << \", LLT solver took: \" << totalSolvingTime << \", line search took: \" << totalLineSearchTime << std::endl;\n\t\t}\n\n if(postProcess)\n {\n postProcess(x0);\n if (disPlayInfo)\n {\n double tmpfnew = objFunc(x0, &grad, NULL, isProj);\n std::cout << \"after post process, f_new: \" << tmpfnew << \", grad norm: \" << grad.norm() << std::endl;\n }\n\n }\n\n\t\tif (savingFolder)\n\t\t{\n\t\t\toptInfo << \"line search rate : \" << rate << \", actual hessian : \" << !isProj << \", reg = \" << reg << std::endl;\n\t\t\toptInfo << \"f_old: \" << f << \", f_new: \" << fnew << \", grad norm: \" << grad.norm() << \", delta x: \" << rate * delta_x.norm() << \", delta_f: \" << f - fnew << std::endl;\n\t\t\tif (getNormFunc)\n\t\t\t{\n\t\t\t\tdouble gradz, gradw;\n\t\t\t\tgetNormFunc(grad, gradz, gradw);\n\n\t\t\t\tdouble updatez, updatew;\n\t\t\t\tgetNormFunc(rate * delta_x, updatez, updatew);\n\t\t\t\toptInfo << \"z grad: \" << gradz << \", w grad: \" << gradw << \", z change: \" << updatez << \", w change: \" << updatew << std::endl;\n\t\t\t}\n\t\t\toptInfo << \"timing info (in total seconds): \" << std::endl;\n\t\t\toptInfo << \"assembling took: \" << totalAssemblingTime << \", LLT solver took: \" << totalSolvingTime << \", line search took: \" << totalLineSearchTime << std::endl;\n\n\t\t\tif (i % 100 == 0)\n\t\t\t{\n\t\t\t\tstd::string fileName = (*savingFolder) + \"intermediate.txt\";\n\t\t\t\tstd::ofstream ofs(fileName);\n\t\t\t\tif (ofs)\n\t\t\t\t{\n\t\t\t\t\tofs << std::setprecision(std::numeric_limits::digits10 + 1) << x0 << std::endl;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif ((f - fnew) / f < 1e-5 || rate * delta_x.norm() < 1e-5 || grad.norm() < 1e-4 || std::abs(f) < 1e-4)\n\t\t{\n\t\t\tisProj = false;\n\t\t\t// double f = objFunc(x0, &grad, &hessian, isProj);\n\t\t\t// H = hessian;\n\t\t\t// solver.compute(hessian);\n\t\t\t// double tmpReg = 1e-8;\n\t\t\t// while (solver.info() != Eigen::Success)\n\t\t\t// {\t\n\t\t\t// \thessian = H + tmpReg * I;\n\t\t\t// \tsolver.compute(hessian);\n\t\t\t// \ttmpReg = std::max(2 * tmpReg, 1e-16);\n\t\t\t// }\n\t\t\t// if(tmpReg > 1e-5)\n\t\t\t// {\n\t\t\t// \tstd::cout << \"hessian is far away from PD, stick with PD hessian.\" << std::endl;\n\t\t\t// \tisProj = true;\n\t\t\t// }\n\n\t\t}\n\t\t\t\n\n\t\tif (rate < 1e-8)\n\t\t{\n\t\t\tstd::cout << \"terminate with small line search rate (<1e-8): L2-norm = \" << grad.norm() << std::endl;\n\t\t\tbreak;\n\t\t}\n\n\t\tif (grad.norm() < gradTol)\n\t\t{\n\t\t\tstd::cout << \"terminate with gradient L2-norm = \" << grad.norm() << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\t\t\n\t\tif (rate * delta_x.norm() < xTol)\n\t\t{\n\t\t\tstd::cout << \"terminate with small variable change, gradient L2-norm = \" << grad.norm() << std::endl;\n\t\t\tbreak;\n\t\t}\n\t\t\t\n\t\tif (f - fnew < fTol)\n\t\t{ \n\t\t\tstd::cout << \"terminate with small energy change, gradient L2-norm = \" << grad.norm() << std::endl;\n\t\t\tbreak;\n\t\t}\n\t}\n\tif (i >= numIter)\n\t\tstd::cout << \"terminate with reaching the maximum iteration, with gradient L2-norm = \" << grad.norm() << std::endl;\n\n double f = objFunc(x0, &grad, &hessian, false);\n Eigen::SparseMatrix I(DIM, DIM), H = hessian;\n I.setIdentity();\n Eigen::CholmodSupernodalLLT> solver(H);\n\n reg = 1e-10;\n while (solver.info() != Eigen::Success)\n {\n if (disPlayInfo)\n {\n if (isProj)\n std::cout << \"some small perturb is needed to remove round-off error, current reg = \" << reg << std::endl;\n else\n std::cout << \"Matrix is not positive definite, current reg = \" << reg << std::endl;\n }\n\n H = hessian + reg * I;\n solver.compute(H);\n reg = std::max(2 * reg, 1e-16);\n }\n std::cout << \"end up with energy: \" << f << \", gradient: \" << grad.norm() << std::endl;\n std::cout << \"mininal evalues of hessian is between: \" << reg / 2 << \", \" << reg << std::endl;\n\n totalTimer.stop();\n if(disPlayInfo)\n {\n std::cout << \"total time costed (s): \" << totalTimer.elapsed() * 1e-3 << \", within that, assembling took: \" << totalAssemblingTime << \", LLT solver took: \" << totalSolvingTime << \", line search took: \" << totalLineSearchTime << std::endl;\n }\n\n\tif (savingFolder)\n\t{\n\t\toptInfo << \"total time costed (s): \" << totalTimer.elapsed() * 1e-3 << \", within that, assembling took: \" << totalAssemblingTime << \", LLT solver took: \" << totalSolvingTime << \", line search took: \" << totalLineSearchTime << std::endl;\n\n\t\tstd::string fileName = (*savingFolder) + \"final_res.txt\";\n\t\tstd::ofstream ofs(fileName);\n\t\tif (ofs)\n\t\t{\n\t\t\tofs << std::setprecision(std::numeric_limits::digits10 + 1) << x0 << std::endl;\n\t\t}\n\n\n\t}\n\t\t\n}\n\n\n", "meta": {"hexsha": "c9b4eaaace0f39b1e532014bd6b75e712234e14d", "size": 9136, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Optimization/NewtonDescent.cpp", "max_stars_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_stars_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Optimization/NewtonDescent.cpp", "max_issues_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_issues_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Optimization/NewtonDescent.cpp", "max_forks_repo_name": "csyzzkdcz/PhaseInterpolation_polyscope", "max_forks_repo_head_hexsha": "4833a569f9eca1c222f7cdfd8e4aae3f03d8ad0b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2741312741, "max_line_length": 467, "alphanum_fraction": 0.5829684764, "num_tokens": 2756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6881230150608545}} {"text": "#include \"PolyMesh/IOManager.h\"\n#include \n#define pi 3.1415926\n\nusing namespace acamcad;\nusing namespace polymesh;\nusing namespace Eigen;\n\nvoid BarycentricCoordinates(PolyMesh* mesh)\n{\n\tint v_n = mesh->numVertices();\n\tstd::vector inner_id(v_n);\n\tint iter;\n\tint boundary_num, inner_num;\n\n\tstd::vector u(mesh->numVertices());\n\tstd::vector v(mesh->numVertices());\n\n\titer = 0;\n\tfor (VertexIter v_it = mesh->vertices_begin(); v_it != mesh->vertices_end(); ++v_it)\n\t{\n\t\tif (!mesh->isBoundary(*v_it))\n\t\t{\n\t\t\tinner_id[(*v_it)->index()] = iter;\n\t\t\titer++;\n\t\t}\n\t}\n\tinner_num = iter;\n\tboundary_num = v_n - iter;\n\n\tMHalfedge* first_heh;\n\tfor (HalfEdgeIter he_it = mesh->halfedge_begin(); he_it != mesh->halfedge_end(); ++he_it)\n\t{\n\t\tif (mesh->isBoundary(*he_it))\n\t\t{\n\t\t\tfirst_heh = *he_it;\n\t\t\tbreak;\n\t\t}\n\t}\n\tMHalfedge* iter_heh = first_heh->next();\n\titer = 0;\n\twhile (iter_heh != first_heh)\n\t{\n\t\tMVert* from_v = iter_heh->fromVertex();\n\t\tu[from_v->index()] = cos(double(2 * pi *iter / boundary_num));\n\t\tv[from_v->index()] = sin(double(2 * pi *iter / boundary_num));\n\t\titer_heh = iter_heh->next();\n\t\titer++;\n\t}\n\tu[first_heh->fromVertex()->index()] = cos(double(2 * pi *iter / boundary_num));\n\tv[first_heh->fromVertex()->index()] = sin(double(2 * pi *iter / boundary_num));\n\n\tSparseMatrix weight(v_n, v_n);\n\tstd::vector> triplet;\n\n\tfor (FaceIter f_it = mesh->polyfaces_begin(); f_it != mesh->polyfaces_end(); ++f_it)\n\t{\n\t\tMHalfedge* heh = (*f_it)->halfEdge();\n\t\tMVert* v0 = heh->fromVertex();\n\t\tMVert* v1 = heh->toVertex();\n\t\tMHalfedge* next_heh = heh->next();\n\t\tMVert* v2 = next_heh->toVertex();\n\n\t\tdouble l2 = (v0->position() - v1->position()).norm();\n\t\tdouble l1 = (v0->position() - v2->position()).norm();\n\t\tdouble l0 = (v1->position() - v2->position()).norm();\n\n\t\tdouble angle = acos(dot(v2->position() - v0->position(), v1->position() - v0->position())/(l1*l2));\n\t\ttriplet.push_back(Triplet(v0->index(), v1->index(), tan(angle*0.5) / l2));\n\t\ttriplet.push_back(Triplet(v0->index(), v2->index(), tan(angle*0.5) / l1));\n\n\t\tangle = acos(dot(v0->position() - v1->position(), v2->position() - v1->position())/(l2*l0));\n\t\ttriplet.push_back(Triplet(v1->index(), v0->index(), tan(angle*0.5) / l2));\n\t\ttriplet.push_back(Triplet(v1->index(), v2->index(), tan(angle*0.5) / l0));\n\n\t\tangle = acos(dot(v0->position() - v2->position(), v1->position() - v2->position())/(l0*l1));\n\t\ttriplet.push_back(Triplet(v2->index(), v0->index(), tan(angle*0.5) / l1));\n\t\ttriplet.push_back(Triplet(v2->index(), v1->index(), tan(angle*0.5) / l0));\n\t}\n\tweight.setFromTriplets(triplet.begin(), triplet.end());\n\n\tSparseMatrix inner(inner_num, inner_num);\n\tVectorXd ub(inner_num), vb(inner_num);\n\n\ttriplet.clear();\n\tfor (VertexIter v_it = mesh->vertices_begin(); v_it != mesh->vertices_end(); ++v_it)\n\t{\n\t\tif (!mesh->isBoundary(*v_it))\n\t\t{\n\t\t\tdouble tempu = 0;\n\t\t\tdouble tempv = 0;\n\t\t\tfor (VertexVertexIter vv_it = mesh->vv_iter(*v_it); vv_it.isValid(); ++vv_it)\n\t\t\t{\n\t\t\t\tif (mesh->isBoundary(*vv_it))\n\t\t\t\t{\n\t\t\t\t\ttempu += u[(*vv_it)->index()] * weight.coeff((*v_it)->index(), (*vv_it)->index());\n\t\t\t\t\ttempv += v[(*vv_it)->index()] * weight.coeff((*v_it)->index(), (*vv_it)->index());\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttriplet.push_back(Triplet(inner_id[(*v_it)->index()], inner_id[(*vv_it)->index()], -weight.coeff((*v_it)->index(), (*vv_it)->index())));\n\t\t\t\t}\n\t\t\t\ttriplet.push_back(Triplet(inner_id[(*v_it)->index()], inner_id[(*v_it)->index()], weight.coeff((*v_it)->index(), (*vv_it)->index())));\n\t\t\t}\n\t\t\tub[inner_id[(*v_it)->index()]] = tempu;\n\t\t\tvb[inner_id[(*v_it)->index()]] = tempv;\n\t\t}\n\t}\n\tinner.setFromTriplets(triplet.begin(), triplet.end());\n\tSparseLU> solver;\n\tsolver.analyzePattern(inner);\n\tsolver.factorize(inner);\n\tVectorXd result_u = solver.solve(ub);\n\tVectorXd result_v = solver.solve(vb);\n\n\tfor (VertexIter v_it = mesh->vertices_begin(); v_it != mesh->vertices_end(); ++v_it)\n\t{\n\t\tif (!mesh->isBoundary(*v_it))\n\t\t{\n\t\t\t(*v_it)->setPosition(result_u[inner_id[(*v_it)->index()]], result_v[inner_id[(*v_it)->index()]], 0);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t(*v_it)->setPosition(u[(*v_it)->index()], v[(*v_it)->index()], 0);\n\t\t}\n\t}\n}\n\n\nint main(int argc, const char **argv)\n{\n\tif (argc != 2)\n\t{\n\t\tstd::cout << \"========== Hw7 Usage ==========\\n\";\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"blablabla.exe\ttest.obj\\n\";\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"=================================================\\n\";\n return 0;\n\t}\n\tstd::string mesh_path = argv[1];\n\tPolyMesh* mesh = new PolyMesh();\n\tloadMesh(mesh_path, mesh);\n\tBarycentricCoordinates(mesh);\n\twriteMesh(\"result_\" + mesh_path, mesh);\n return 0;\n}", "meta": {"hexsha": "ebff0af19973c613082bf4ed4ba3e45bfea83bc7", "size": 4716, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/src/hw7/main.cpp", "max_stars_repo_name": "fusheng-ji/Digital_Geometry_Processing", "max_stars_repo_head_hexsha": "98645268cc00e8830b0e1ce592d10e55320b3011", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-03-08T02:40:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T08:09:20.000Z", "max_issues_repo_path": "code/src/hw7/main.cpp", "max_issues_repo_name": "fusheng-ji/Digital_Geometry_Processing", "max_issues_repo_head_hexsha": "98645268cc00e8830b0e1ce592d10e55320b3011", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/src/hw7/main.cpp", "max_forks_repo_name": "fusheng-ji/Digital_Geometry_Processing", "max_forks_repo_head_hexsha": "98645268cc00e8830b0e1ce592d10e55320b3011", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0816326531, "max_line_length": 149, "alphanum_fraction": 0.6212892282, "num_tokens": 1518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308110294983, "lm_q2_score": 0.7371581510799253, "lm_q1q2_score": 0.6880861308195402}} {"text": "using namespace std;\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\n\nclass RNN\n{\n private: \n struct loss_result\n {\n /* Structure for recording the result of the loss method */\n double loss;\n MatrixXd dWxh;\n MatrixXd dWhh;\n MatrixXd dWhy;\n MatrixXd dbh;\n MatrixXd dby;\n MatrixXd hs; \n }; \n\n vector data; //vector that holds the corpus\n map char_id; //map holds corpus unique char and their id\n map id_char; //map id to unique char\n\n int hiddens; //hidden layers number\n int sequence_length; //sequence length\n int data_size; //length of corpus\n int vocab_size; //vocabulary size for the network\n\n MatrixXd W_XH; //Weights from Input to Hiddens\n MatrixXd W_HH; //Weights from Hidden to Hidden\n MatrixXd W_HY; //Weights from Hidden to Output\n MatrixXd BH; //Bias of Hiddens\n MatrixXd BY; //Bias of Outputs\n\n double check (const double min, const double max, double &target)\n {\n /* Sub-method to use for Clip Method */\n if (target > max)\n {\n return max;\n }\n else if (target < min)\n {\n return min;\n }\n return target;\n }\n\n void clip(const double min, const double max, MatrixXd &target)\n {\n /* Clip elements' value inside the Matrix to leave them remain in between min and max */\n for (int r = 0; r < target.rows(); r ++)\n {\n for (auto item = target.row(r).data(); item < target.row(r).data() + target.size(); item += target.outerStride()) \n {\n *item = check(min, max, *item);\n } \n }\n }\n\n const vector ravel(MatrixXd &target)\n {\n /* Generate a 1 by M Vector; Keep all values of target in 1D vector */\n vector p;\n \n for (int r = 0; r < target.rows(); r ++)\n {\n for (auto item = target.row(r).data(); item < target.row(r).data() + target.size(); item += target.outerStride())\n {\n p.push_back(*item);\n }\n }\n\n return p;\n }\n\n const int choice (vector &p)\n {\n /* Random Choice Method*/\n random_device rng; //set rng\n mt19937 gen(rng()); //use another generator to generate upon rng\n boost::random::discrete_distribution<> dist (p.begin(), p.end()); //apply discrete distrib upon probabilities vector\n\n int randomNumber = dist(gen); //set random ID & return\n return randomNumber;\n }\n\n loss_result* loss(const vector &inputs, const vector &targets, const MatrixXd &hprev)\n {\n /* Inputs and Targets are list of IDs \n Hprev holds a matrix of initial Hidden States x 1\n Return Loss Result Structure\n */\n\n map xs, hs, ys, ps; //map that holds iteration -> Matrix correspond to Inputs, Hiddens, Outputs, Probs\n MatrixXd original (hprev); //Make a copy of hprev\n hs[-1] = original; //Set -1 as original; this is for the 1st iteration; hs[i - 1]\n double loss = 0.0; //Initialize loss\n\n //Forward Propagation\n for (int i = 0; i < inputs.size(); i ++)\n {\n xs[i] = MatrixXd::Zero(vocab_size, 1); //Initalizes first X\n xs[i].row(inputs[i]).array() = 1; //encode X in 1 of K representation \n \n //Apply Activation Function; Tanh(X * Weights of X->H + Weights of Hidden * Hidden States + Bias Hidden)\n hs[i] = ((W_XH * xs[i]) + (W_HH * hs[i - 1]) + BH).unaryExpr(&tanh);\n \n //Set Outputs; Weights of Y * Hidden States + Bias Y\n ys[i] = (W_HY * hs[i]) + BY;\n \n //Set Exp(current Y)\n MatrixXd ys_exp = ys[i].unaryExpr(&exp);\n\n //Set Probabilities of the next Y\n ps[i] = ys_exp / ys_exp.sum();\n\n //Set new loss \n loss += -log(ps[i].coeff(targets[i], 0));\n }\n\n //Gradients\n MatrixXd dWxh = MatrixXd::Zero(W_XH.rows(), W_XH.cols());\n MatrixXd dWhy = MatrixXd::Zero(W_HY.rows(), W_HY.cols());\n MatrixXd dWhh = MatrixXd::Zero(W_HH.rows(), W_HH.cols());\n MatrixXd dbh = MatrixXd::Zero(BH.rows(), BH.cols());\n MatrixXd dby = MatrixXd::Zero(BY.rows(), BY.cols());\n MatrixXd dh_next = MatrixXd::Zero(hs[0].rows(), hs[0].cols());\n \n //Backpropagation: Computing Gradient \n for (int i = inputs.size() - 1; i >= 0; i --)\n { \n //copy current probabilities\n MatrixXd dy(ps[i]); \n //back prop into y \n dy.row(targets[i]) = dy.row(targets[i]).array() - 1.0; \n \n //grab gradients of weights and biases of y\n dWhy += (dy * hs[i].transpose());\n dby.noalias() += dy;\n\n //back prop into h\n MatrixXd dh = ((W_HY.transpose() * dy) + dh_next);\n //back prop into tanh nonlinear\n MatrixXd dhraw = ((1 - (hs[i].array() * hs[i].array())).array() * dh.array()); \n\n //set gradients\n dbh.noalias() += dhraw;\n dWxh += (dhraw * xs[i].transpose());\n dWhh += (dhraw * hs[i - 1].transpose());\n dh_next = (W_HH.transpose() * dhraw);\n }\n \n /* Clip values in matrices to prevent gradient explosion */\n clip(-10, 10, dWxh);\n clip(-10, 10, dWhh);\n clip(-10, 10, dWhy);\n clip(-10, 10, dbh);\n clip(-10, 10, dby);\n \n /* Allocate necessary items into newly created Structure */\n loss_result* item = new loss_result();\n item->loss = loss; item->dbh = dbh; item->dby = dby;\n item->dWhh = dWhh; item->dWhy = dWhy; item->dWxh = dWxh;\n item->hs = hs[inputs.size() - 1];\n\n return item;\n }\n\n const vector sample(const MatrixXd &h_prev, const int &seedID, const int &m)\n {\n /* Generate a Sample of Char ID for Text Generation */\n MatrixXd x = MatrixXd::Zero(vocab_size, 1); //generate a new bias called x\n x.row(seedID).array() = 1.0; //set the entry at seedID equals to 1\n vector samples; //new samples of char IDs\n\n for (int i = 0; i < m; i ++)\n { \n MatrixXd h = (W_XH * x) + (W_HH * h_prev) + BH; //current Hypothesis\n h = h.unaryExpr(&tanh); //apply tanh\n\n MatrixXd y = W_HY * h + BY; //Produce Y\n MatrixXd exp_y = y.unaryExpr(&exp); //Apply Exp\n\n MatrixXd p = exp_y / exp_y.sum(); //Create Probabilities \n vector probabilities = ravel(p); //Produce 1 by M vector\n\n int ix = choice(probabilities); //Select a choice based on probabilities\n\n x = MatrixXd::Zero(vocab_size, 1); //Reset X or Inputs\n\n x.row(ix).array() = 1.0; //Set all elements in row SeedID equals to 1.0 again\n samples.push_back(ix); //Push ID onto samples vector\n }\n\n return samples;\n }\n \n const vector getID(const int min, const int max)\n {\n // Get a list of characters based on the range of p and sequence length \n vector item;\n \n for (int c = min; c < max; c ++)\n {\n item.push_back(char_id[data[c]]);\n }\n \n return item;\n }\n\n const string genText(const vector samples)\n {\n /* Generate Text With Parallelism Enabled */\n string output = \"\";\n\n #pragma omp declare reduction (merge : string : omp_out.insert(omp_out.end(), omp_in.begin(), omp_in.end()))\n #pragma omp parallel for reduction (merge : output)\n for (int i = 0; i < samples.size(); i++)\n {\n #pragma omp critical\n output += id_char[samples[i]];\n }\n\n return output;\n }\n\n public: \n RNN(const int &hidden_size, const int &seq_length)\n {\n hiddens = hidden_size;\n sequence_length = seq_length;\n } \n\n void load(const string filename)\n {\n /* Load File and Enumerate through each character in the text file; get unique char and assign their ID */\n ifstream file(filename); // grab file\n string line; // a string for holding current line\n int count = 0; // count variable\n vector corpus;\n\n /* Grab all lines in the text file */\n while(getline(file, line))\n {\n corpus.push_back(line);\n }\n\n file.close(); // close the file\n\n //set next line into the map and allocate the same ID into both map; then increment the ID\n char_id[\"\\n\"] = count; id_char[count] = \"\\n\"; count ++; \n char_id[\" \"] = count; id_char[count] = \" \"; count ++;\n\n //Loop through the corpus\n //Find Unique characters and allocate it with a unique ID\n //Also, append each character in the line onto the data vector for RNN's feeding\n for (auto &line: corpus)\n {\n int line_size = line.size();\n if (line_size > 0)\n {\n int c = 0;\n istringstream word(line);\n for (string current; word >> current;)\n {\n data.push_back(current);\n if (c < line_size)\n {\n data.push_back(\" \");\n }\n\n if (char_id.find(current) == char_id.end())\n {\n char_id[current] = count;\n id_char[count] = current;\n count ++;\n }\n c ++;\n }\n\n data.push_back(\"\\n\");\n }\n else\n {\n data.push_back(\"\\n\");\n }\n }\n\n data_size = data.size(); //set data size\n vocab_size = char_id.size(); //set vocab size\n \n /* Set Weights and Biases */\n W_XH = MatrixXd::Random(hiddens, vocab_size) * 0.01;\n W_HH = MatrixXd::Random(hiddens, hiddens) * 0.01;\n W_HY = MatrixXd::Random(vocab_size, hiddens) * 0.01;\n BH = MatrixXd::Zero(hiddens, 1);\n BY = MatrixXd::Zero(vocab_size, 1);\n\n cout << \"Create Topology: Done!\" << endl;\n }\n\n const void learn()\n {\n /* Learn Method */\n\n //Initalizes memory variables for Adam Gradient Descent aka AdaGrad\n MatrixXd mWXH = MatrixXd::Zero(W_XH.rows(), W_XH.cols());\n MatrixXd mWHH = MatrixXd::Zero(W_HH.rows(), W_HH.cols());\n MatrixXd mWHY = MatrixXd::Zero(W_HY.rows(), W_HY.cols());\n MatrixXd mBH = MatrixXd::Zero(BH.rows(), BH.cols());\n MatrixXd mBY = MatrixXd::Zero(BY.rows(), BY.cols());\n\n int n = 0; //iteration\n int p = 0; //incrementer for input & target\n\n double smooth_loss = -log(1.0/ double(vocab_size)) * double(sequence_length); \n double learning_rate = 1 * exp(-1);\n \n MatrixXd h_prev; //saving previous hiddens\n\n while (true)\n {\n if ( ((p + sequence_length + 1) >= data_size) or (n == 0))\n {\n h_prev = MatrixXd::Zero(hiddens, 1); //Initalizes or Reset the memory of RNN\n p = 0; //Set sequence incrementer back to 0\n }\n\n /* Grab Inputs and Targets */\n vector inputs = getID(p, p + sequence_length); \n vector targets = getID(p + 1, p + sequence_length + 1);\n\n // Grab Loss Function's Outputs\n loss_result* item = loss(inputs, targets, h_prev);\n\n // Set new loss\n smooth_loss = smooth_loss * 0.999 + item->loss * 0.001;\n\n if ((n % 100 == 0) && (n != 0))\n {\n /* Generate Text and Display Current Loss */\n auto samples = sample(h_prev, inputs[0], 200);\n auto text = genText(samples);\n\n cout << \"\\n\" << text << endl;\n cout << \"\\n\";\n cout << \"Iteration #: \" << n << \" Loss: \" << smooth_loss << endl;\n }\n \n if ((n % 1000000 == 0) && (n != 0))\n {\n // decreases learning rate as number of iteration increases\n if (learning_rate >= 0.0000001)\n {\n learning_rate = learning_rate / (1.0 + (exp(-n/(n + 1))));\n }\n else\n {\n //restart\n learning_rate = 0.1;\n }\n \n }\n\n /* Update Weight using AdaGrad*/\n mWXH.noalias() += MatrixXd(item->dWxh.array() * item->dWxh.array());\n W_XH += MatrixXd(-learning_rate * item->dWxh.array() / sqrt(mWXH.array() + 1e-8));\n\n mWHH.noalias() += MatrixXd(item->dWhh.array() * item->dWhh.array());\n W_HH += MatrixXd(-learning_rate * item->dWhh.array() / sqrt(mWHH.array() + 1e-8));\n \n mWHY.noalias() += MatrixXd(item->dWhy.array() * item->dWhy.array());\n W_HY += MatrixXd(-learning_rate * item->dWhy.array() / sqrt(mWHY.array() + 1e-8));\n\n /* Update Biases*/\n mBH.noalias() += MatrixXd(item->dbh.array() * item->dbh.array());\n BH += MatrixXd(-learning_rate * item->dbh.array() / sqrt(mBH.array() + 1e-8));\n\n mBY.noalias() += MatrixXd(item->dby.array() * item->dby.array());\n BY += MatrixXd(-learning_rate * item->dby.array() / sqrt(mBY.array() + 1e-8));\n\n delete(item); //free the loss result structure\n \n p += sequence_length; //update current sequence length\n n ++; //increment current iteration\n }\n }\n};\n\nint main(int argc, char* argv[])\n{\n if (argc != 4)\n {\n cout << \"Arguments: Corpus File, hidden size, sequence length\" << endl;\n return 0;\n }\n //grab arguments and convert char to int for hidden size and sequence length\n string filename = argv[1]; int hidden_size = atoi(argv[2]); int seq_length = atoi(argv[3]);\n\n Eigen::initParallel();\n RNN rnn = RNN(hidden_size, seq_length);\n rnn.load(filename);\n rnn.learn();\n}\n", "meta": {"hexsha": "32b835a943291a31306a0b64065a7847deaa3cc7", "size": 17121, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RNN.cpp", "max_stars_repo_name": "Lemon-cmd/Recurrent-Neural-Network", "max_stars_repo_head_hexsha": "87e055fbb972ed3c351c418737c34ec38e9d3339", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RNN.cpp", "max_issues_repo_name": "Lemon-cmd/Recurrent-Neural-Network", "max_issues_repo_head_hexsha": "87e055fbb972ed3c351c418737c34ec38e9d3339", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RNN.cpp", "max_forks_repo_name": "Lemon-cmd/Recurrent-Neural-Network", "max_forks_repo_head_hexsha": "87e055fbb972ed3c351c418737c34ec38e9d3339", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9593301435, "max_line_length": 135, "alphanum_fraction": 0.4455931312, "num_tokens": 3707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6880170218995671}} {"text": "#include \"Triangle.h\"\n#include \"Ray.h\"\n#include \n\nbool Triangle::intersect(\n const Ray & ray, const double min_t, double & t, Eigen::Vector3d & n) const\n{\n ////////////////////////////////////////////////////////////////////////////\n // Replace with your code here\n double beta = 0;\n double gamma = 0;\n double t_prime = 0;\n\n // corners: a = corners[0], b = corners[1], c = corners[2]\n // Calculate dummy variables for Cramer's rule calculation (from textbook)\n double a = std::get<0>(corners)(0) - std::get<1>(corners)(0);\n double d = std::get<0>(corners)(0) - std::get<2>(corners)(0);\n double g = ray.direction(0);\n\n double b = std::get<0>(corners)(1) - std::get<1>(corners)(1);\n double e = std::get<0>(corners)(1) - std::get<2>(corners)(1);\n double h = ray.direction(1);\n\n double c = std::get<0>(corners)(2) - std::get<1>(corners)(2);\n double f = std::get<0>(corners)(2) - std::get<2>(corners)(2);\n double i = ray.direction(2);\n\n double j = std::get<0>(corners)(0) - ray.origin(0);\n double k = std::get<0>(corners)(1) - ray.origin(1);\n double l = std::get<0>(corners)(2) - ray.origin(2);\n\n // intermediate dummy variables for calculating beta, gamma, and t\n double ei_minus_hf = (e * i) - (h * f);\n double gf_minus_di = (g * f) - (d * i);\n double dh_minus_eg = (d * h) - (e * g);\n double ak_minus_jb = (a * k) - (j * b);\n double jc_minus_al = (j * c) - (a * l);\n double bl_minus_kc = (b * l) - (k * c);\n\n double M = (a * ei_minus_hf) + (b * gf_minus_di) + (c * dh_minus_eg);\n t_prime = -(((f * ak_minus_jb) + (e * jc_minus_al) + (d * bl_minus_kc)) / M);\n\n if (t_prime < min_t)\n {\n return false;\n }\n\n gamma = ((i * ak_minus_jb) + (h * jc_minus_al) + (g * bl_minus_kc)) / M;\n if (gamma < 0 || gamma > 1)\n {\n return false;\n }\n\n beta = ((j * ei_minus_hf) + (k * gf_minus_di) + (l * dh_minus_eg)) / M;\n if (beta < 0 || beta > (1 - gamma))\n {\n return false;\n }\n\n if (t_prime < t)\n {\n t = t_prime;\n // given two vectors u and v, the cross product (u X v) = n (normal vector)\n // u = b - a, v = c - a\n Eigen::Vector3d u = std::get<1>(corners) - std::get<0>(corners);\n Eigen::Vector3d v = std::get<2>(corners) - std::get<0>(corners);\n n = u.cross(v);\n n.normalize();\n\n return true;\n }\n else\n {\n return false;\n }\n ////////////////////////////////////////////////////////////////////////////\n}\n\n\n", "meta": {"hexsha": "70c0b2f5a55ec9382dc49b1ab66190f30bac58c4", "size": 2386, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Triangle.cpp", "max_stars_repo_name": "jackys-95/computer-graphics-final-image-competition", "max_stars_repo_head_hexsha": "65e7c041530f319d10faba177ef03963aad16e56", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Triangle.cpp", "max_issues_repo_name": "jackys-95/computer-graphics-final-image-competition", "max_issues_repo_head_hexsha": "65e7c041530f319d10faba177ef03963aad16e56", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Triangle.cpp", "max_forks_repo_name": "jackys-95/computer-graphics-final-image-competition", "max_forks_repo_head_hexsha": "65e7c041530f319d10faba177ef03963aad16e56", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.825, "max_line_length": 79, "alphanum_fraction": 0.537300922, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009480320036, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6880170115799661}} {"text": "// This file is part of Eigen, a lightweight C++ template library\r\n// for linear algebra.\r\n//\r\n// Copyright (C) 2014 Jianwei Cui \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 \r\n#include \r\n#include \r\n\r\nusing Eigen::Tensor;\r\n\r\ntemplate \r\nstatic void test_1D_fft_ifft_invariant(int sequence_length) {\r\n Tensor tensor(sequence_length);\r\n tensor.setRandom();\r\n\r\n array fft;\r\n fft[0] = 0;\r\n\r\n Tensor, 1, DataLayout> tensor_after_fft;\r\n Tensor, 1, DataLayout> tensor_after_fft_ifft;\r\n\r\n tensor_after_fft = tensor.template fft(fft);\r\n tensor_after_fft_ifft = tensor_after_fft.template fft(fft);\r\n\r\n VERIFY_IS_EQUAL(tensor_after_fft.dimension(0), sequence_length);\r\n VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(0), sequence_length);\r\n\r\n for (int i = 0; i < sequence_length; ++i) {\r\n VERIFY_IS_APPROX(static_cast(tensor(i)), static_cast(std::real(tensor_after_fft_ifft(i))));\r\n }\r\n}\r\n\r\ntemplate \r\nstatic void test_2D_fft_ifft_invariant(int dim0, int dim1) {\r\n Tensor tensor(dim0, dim1);\r\n tensor.setRandom();\r\n\r\n array fft;\r\n fft[0] = 0;\r\n fft[1] = 1;\r\n\r\n Tensor, 2, DataLayout> tensor_after_fft;\r\n Tensor, 2, DataLayout> tensor_after_fft_ifft;\r\n\r\n tensor_after_fft = tensor.template fft(fft);\r\n tensor_after_fft_ifft = tensor_after_fft.template fft(fft);\r\n\r\n VERIFY_IS_EQUAL(tensor_after_fft.dimension(0), dim0);\r\n VERIFY_IS_EQUAL(tensor_after_fft.dimension(1), dim1);\r\n VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(0), dim0);\r\n VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(1), dim1);\r\n\r\n for (int i = 0; i < dim0; ++i) {\r\n for (int j = 0; j < dim1; ++j) {\r\n //std::cout << \"[\" << i << \"][\" << j << \"]\" << \" Original data: \" << tensor(i,j) << \" Transformed data:\" << tensor_after_fft_ifft(i,j) << std::endl;\r\n VERIFY_IS_APPROX(static_cast(tensor(i,j)), static_cast(std::real(tensor_after_fft_ifft(i,j))));\r\n }\r\n }\r\n}\r\n\r\ntemplate \r\nstatic void test_3D_fft_ifft_invariant(int dim0, int dim1, int dim2) {\r\n Tensor tensor(dim0, dim1, dim2);\r\n tensor.setRandom();\r\n\r\n array fft;\r\n fft[0] = 0;\r\n fft[1] = 1;\r\n fft[2] = 2;\r\n\r\n Tensor, 3, DataLayout> tensor_after_fft;\r\n Tensor, 3, DataLayout> tensor_after_fft_ifft;\r\n\r\n tensor_after_fft = tensor.template fft(fft);\r\n tensor_after_fft_ifft = tensor_after_fft.template fft(fft);\r\n\r\n VERIFY_IS_EQUAL(tensor_after_fft.dimension(0), dim0);\r\n VERIFY_IS_EQUAL(tensor_after_fft.dimension(1), dim1);\r\n VERIFY_IS_EQUAL(tensor_after_fft.dimension(2), dim2);\r\n VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(0), dim0);\r\n VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(1), dim1);\r\n VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(2), dim2);\r\n\r\n for (int i = 0; i < dim0; ++i) {\r\n for (int j = 0; j < dim1; ++j) {\r\n for (int k = 0; k < dim2; ++k) {\r\n VERIFY_IS_APPROX(static_cast(tensor(i,j,k)), static_cast(std::real(tensor_after_fft_ifft(i,j,k))));\r\n }\r\n }\r\n }\r\n}\r\n\r\ntemplate \r\nstatic void test_sub_fft_ifft_invariant(int dim0, int dim1, int dim2, int dim3) {\r\n Tensor tensor(dim0, dim1, dim2, dim3);\r\n tensor.setRandom();\r\n\r\n array fft;\r\n fft[0] = 2;\r\n fft[1] = 0;\r\n\r\n Tensor, 4, DataLayout> tensor_after_fft;\r\n Tensor tensor_after_fft_ifft;\r\n\r\n tensor_after_fft = tensor.template fft(fft);\r\n tensor_after_fft_ifft = tensor_after_fft.template fft(fft);\r\n\r\n VERIFY_IS_EQUAL(tensor_after_fft.dimension(0), dim0);\r\n VERIFY_IS_EQUAL(tensor_after_fft.dimension(1), dim1);\r\n VERIFY_IS_EQUAL(tensor_after_fft.dimension(2), dim2);\r\n VERIFY_IS_EQUAL(tensor_after_fft.dimension(3), dim3);\r\n VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(0), dim0);\r\n VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(1), dim1);\r\n VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(2), dim2);\r\n VERIFY_IS_EQUAL(tensor_after_fft_ifft.dimension(3), dim3);\r\n\r\n for (int i = 0; i < dim0; ++i) {\r\n for (int j = 0; j < dim1; ++j) {\r\n for (int k = 0; k < dim2; ++k) {\r\n for (int l = 0; l < dim3; ++l) {\r\n VERIFY_IS_APPROX(static_cast(tensor(i,j,k,l)), static_cast(tensor_after_fft_ifft(i,j,k,l)));\r\n }\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid test_cxx11_tensor_ifft() {\r\n CALL_SUBTEST(test_1D_fft_ifft_invariant(4));\r\n CALL_SUBTEST(test_1D_fft_ifft_invariant(16));\r\n CALL_SUBTEST(test_1D_fft_ifft_invariant(32));\r\n CALL_SUBTEST(test_1D_fft_ifft_invariant(1024*1024));\r\n\r\n CALL_SUBTEST(test_2D_fft_ifft_invariant(4,4));\r\n CALL_SUBTEST(test_2D_fft_ifft_invariant(8,16));\r\n CALL_SUBTEST(test_2D_fft_ifft_invariant(16,32));\r\n CALL_SUBTEST(test_2D_fft_ifft_invariant(1024,1024));\r\n\r\n CALL_SUBTEST(test_3D_fft_ifft_invariant(4,4,4));\r\n CALL_SUBTEST(test_3D_fft_ifft_invariant(8,16,32));\r\n CALL_SUBTEST(test_3D_fft_ifft_invariant(16,4,8));\r\n CALL_SUBTEST(test_3D_fft_ifft_invariant(256,256,256));\r\n\r\n CALL_SUBTEST(test_sub_fft_ifft_invariant(4,4,4,4));\r\n CALL_SUBTEST(test_sub_fft_ifft_invariant(8,16,32,64));\r\n CALL_SUBTEST(test_sub_fft_ifft_invariant(16,4,8,12));\r\n CALL_SUBTEST(test_sub_fft_ifft_invariant(64,64,64,64));\r\n}\r\n", "meta": {"hexsha": "76e67afe26d443f82a257d7b864a050211582a85", "size": 6088, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/eigen-eigen-323c052e1731/unsupported/test/cxx11_tensor_ifft.cpp", "max_stars_repo_name": "k4rth33k/dnnc-operators", "max_stars_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2019-08-16T14:35:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-11T23:59:22.000Z", "max_issues_repo_path": "packages/eigen-eigen-323c052e1731/unsupported/test/cxx11_tensor_ifft.cpp", "max_issues_repo_name": "k4rth33k/dnnc-operators", "max_issues_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-08-12T04:38:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-04T16:32:13.000Z", "max_forks_repo_path": "packages/eigen-eigen-323c052e1731/unsupported/test/cxx11_tensor_ifft.cpp", "max_forks_repo_name": "k4rth33k/dnnc-operators", "max_forks_repo_head_hexsha": "a7fe3f1240c12b3438558def71fbfcd4520446c3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-08-15T13:29:00.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-09T17:08:04.000Z", "avg_line_length": 39.2774193548, "max_line_length": 157, "alphanum_fraction": 0.7094283837, "num_tokens": 1795, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797172476384, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6878632293042737}} {"text": "/*\nA class to represent an extension field \n*/\n\n#ifndef EXTENSION_FIELD\n#define EXTENSION_FIELD\n\n#include \n#include \n#include \n#include \n\n#include \"polynomial.hpp\"\n\nusing namespace std;\n\n// extension field element (EFE)\ntemplate class EFE:\n\tboost::field_operators< EFE,\n\tboost::equality_comparable< EFE\n\t> >\n{\npublic: \n\t//! an element of the extension field is a polynomial with coefficients in the prime field PFE\n\tpolynomial el;\n\t//! the degree of the extension\n\tstatic unsigned m; \n\t//! primitive polynomial defining the extension field\n\tstatic polynomial prim_poly;\n\t//! constructors\n\tEFE(vector& v): el(polynomial(v)) {};\n\tEFE(polynomial& el_): el(el_) {};\n\tEFE(unsigned x){ // set the coeff with exponent zero to x\n\t\tvector tmpv(m, PFE(0) );\n\t\ttmpv[0] = PFE(x);\n\t\tel = polynomial(tmpv);\n\t}\n\tEFE(){};\n\n\tEFE& operator += (const EFE& x){\n\t\tel += x.el;\n\t\treturn *this;\n\t}\n\t\n\tEFE& operator -= (const EFE& x){\n\t\tel -= x.el;\n\t\treturn *this;\n\t}\n\n\tEFE& operator *= (const EFE& x){\n\t\t// multiply\n\t\tpolynomial ptmp = el*x.el;\n\t\t// modulo the primitive polynomial\n\t\n\t\tint exp;\n\t\twhile( (exp = ptmp.degree() - prim_poly.degree()) >= 0 ){\n\t\t\t// difference in exponents\n\t\t\t//unsigned exp = ptmp.degree() - prim_poly.degree();\n\t\t\t// primitive polynomial; to be muliplied..\t\n\t\t\tpolynomial primtmp = prim_poly;\n\t\t\tPFE co_mo = ptmp.poly[ptmp.degree()]; \n\t\t\tco_mo /= prim_poly.poly[prim_poly.degree()];\n\t\t\tprimtmp.multiply_monomial( co_mo , exp );\n\t\t\tptmp -= primtmp;\n\t\t}\n\n\t\tptmp.poly.resize(ptmp.degree()+1);\n\t\tel = ptmp;\n\t\treturn *this;\n\t}\n\n\tEFE& operator /= (const EFE& x){\n\t\t*this = (x.inverse() * (*this)); \n\t\treturn *this;\n\t}\n\t\n\t//! compute the multiplicative inverse via the extended Euclidean algorithm \n\tEFE inverse() const {\n\t\t\n\t\tpolynomial rem1 = prim_poly;\n\t\tpolynomial rem2 = el;\n\t\tpolynomial aux1 = polynomial(0);\n\t\tpolynomial aux2 = polynomial(1);\n\n\n\t\twhile(! rem2.iszero() ){\n\t\t\t// res.first = quotient(rem1/rem2)\n\t\t\t// res.second = remainder(rem1/rem2)\n\t\t\t\n\t\t\tpair, polynomial > res = divide(rem1,rem2);\n\n\t\t\tpolynomial aux_new = polynomial(0) - res.first*aux2 + aux1;\n\n\t\t\t// prepare for the next step\n\t\t\trem1 = rem2;\n\t\t\trem2 = res.second;\n\t\t\taux1 = aux2;\n\t\t\taux2 = aux_new;\n\t\t\t\n\t\t}\n\t\n\t\taux1.multiply_monomial(pow(rem1.poly[0],-1), 0);\n\n\t\treturn aux1;\n\t}\n\n\n\t\n\tunsigned order() const {\n\t\t// multiplicative neutral element = 1\n\t\t//PFE one = PFE(1);\n\t\tvector vecone = vector(1,PFE(1));\n\t\tEFE one = EFE(vecone); \n\t\tEFE tmp = *this; //EFE(el);\t\t\n\t\tunsigned ord = 1;\n\t\twhile(!(tmp == one)){\n\t\t\tord++;\n\t\t\ttmp *= *this;\n\t\t\t//cout << tmp << endl;\n\t\t}\n\t\treturn ord;\n\t}\n\t/*\n\t// not a good solution\n\tvector tovec() const {\n\t\tvector vec(m,0);\n\t\tfor(unsigned i=0;i tovec() const {\n\t\tif(el.poly.size()!=m){\n\t\t\tvector tmp(m,PFE(0));\n\t\t\tfor(unsigned i=0;i veczero = vector(1,PFE(0));\n\t\tEFE zero = EFE(veczero);\n\t\treturn (zero == *this);\n\t}\n\t\n\tbool isempty() const {\n\t\treturn (el.poly.size() == 0);\n\t}\n\n\tbool operator ==(const EFE& x) const {\n\t\t\n\t\tfor(unsigned i = 0; i < min(el.poly.size(),x.el.poly.size()); ++i)\n\t\t\tif(!(x.el.poly[i] == el.poly[i]) ) return false;\n\t\t\n\t\t// need to verify if the coefficients of the larger vector that are necessarily zero in the smaller vector are also zero in the larger vector \n\t\tif(el.poly.size() > x.el.poly.size()){\n\t\t\tfor(unsigned i = x.el.poly.size() ; i\n ostream &operator<<(ostream &stream, const EFE x)\n {\n\t \tstream << x.el;\n \treturn stream; // must return stream\n\t};\n\ntemplate\n \tEFE pow(const EFE& a, int exp){\n\t\t\n\t\tif(a.iszero()) return a;\n\t\tif(exp == 0) {\n\t\t\tvector vecone = vector(1,PFE(1));\n\t\t\treturn EFE(vecone); \n\t\t}\n\t\t\n\t\tEFE tmp;\n\t\t\n\t\tif(exp < 0){\n\t\t\tEFE am = a.inverse(); \n\t\t\ttmp = am;\n\t\t\tfor(unsigned i =1; i < abs(exp); ++i) tmp *= am;\n\t\t} else { // exp > 0\n\t\t\ttmp = a;\n\t\t\tfor(unsigned i =1; i < abs(exp); ++i) tmp *= a;\n\t\t}\n\n\t\treturn tmp;\n\t};\n\n\n\n#endif\n", "meta": {"hexsha": "ed0da9b432b11173b30aff4980b0a810ecadd8fe", "size": 4584, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/EFE.hpp", "max_stars_repo_name": "libingzheren/dna_rs_coding", "max_stars_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2019-12-01T11:55:24.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-18T01:57:11.000Z", "max_issues_repo_path": "include/EFE.hpp", "max_issues_repo_name": "libingzheren/dna_rs_coding", "max_issues_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-01-26T09:13:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-26T15:19:01.000Z", "max_forks_repo_path": "include/EFE.hpp", "max_forks_repo_name": "libingzheren/dna_rs_coding", "max_forks_repo_head_hexsha": "70ba95627e72a0e90a38d51a6c8f18ede46255e4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2019-12-05T06:14:13.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-25T09:10:36.000Z", "avg_line_length": 22.2524271845, "max_line_length": 144, "alphanum_fraction": 0.6112565445, "num_tokens": 1462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118213, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6878632188176235}} {"text": "#include \n#include \n\n#include \n\nint main() {\n // We are going to calculate the eigenvalues of M\n Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 10);\n Eigen::MatrixXd M = A + A.transpose();\n\n // Construct matrix operation object using the wrapper class DenseSymMatProd\n Spectra::DenseSymMatProd op(M);\n\n // Construct eigen solver object, requesting the largest three eigenvalues\n#ifdef SPECTRA_LESS_1_0_0\n Spectra::SymEigsSolver< double, Spectra::LARGEST_ALGE, Spectra::DenseSymMatProd > eigs(&op, 3, 6);\n#else\n Spectra::SymEigsSolver> eigs(op, 3, 6);\n#endif\n\n // Initialize and compute\n eigs.init();\n#ifdef SPECTRA_LESS_1_0_0\n int nconv = eigs.compute();\n#else\n int nconv = eigs.compute(Spectra::SortRule::LargestAlge);\n#endif\n\n // Retrieve results\n Eigen::VectorXd evalues;\n#ifdef SPECTRA_LESS_1_0_0\n if (eigs.info() == Spectra::SUCCESSFUL) {\n#else\n if (eigs.info() == Spectra::CompInfo::Successful) {\n#endif\n evalues = eigs.eigenvalues();\n }\n\n std::cout << \"Eigenvalues found:\\n\" << evalues << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "3da7ef12504b7aee33400f24d597b0f7eb4bdcf2", "size": 1182, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "recipes/spectra/all/test_package/test_package.cpp", "max_stars_repo_name": "rockandsalt/conan-center-index", "max_stars_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 562.0, "max_stars_repo_stars_event_min_datetime": "2019-09-04T12:23:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:41:43.000Z", "max_issues_repo_path": "recipes/spectra/all/test_package/test_package.cpp", "max_issues_repo_name": "rockandsalt/conan-center-index", "max_issues_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9799.0, "max_issues_repo_issues_event_min_datetime": "2019-09-04T12:02:11.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T23:55:45.000Z", "max_forks_repo_path": "recipes/spectra/all/test_package/test_package.cpp", "max_forks_repo_name": "rockandsalt/conan-center-index", "max_forks_repo_head_hexsha": "d739adcec3e4dd4c250eff559ceb738e420673dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1126.0, "max_forks_repo_forks_event_min_datetime": "2019-09-04T11:57:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T16:43:38.000Z", "avg_line_length": 27.488372093, "max_line_length": 110, "alphanum_fraction": 0.6878172589, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6875560943357715}} {"text": "#include \n#include \n#include \n\n//accumulators\n#include \n#include \n#include \n#include \n#include \n\nnamespace rct_optimizations\n{\n\nEigen::Quaterniond computeQuaternionMean(const std::vector& quaterns)\n{\n /* Mean quaternion is found using method described by Markley et al: Quaternion Averaging\n * https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/20070017872.pdf\n *\n * M = sum(w_i * q_i * q_i^T) Eq. 12\n * q_bar = argmax(q^T * M * q) Eq. 13\n *\n * \"The solution of this maximization problem is well known. The average quaternion is\n * the eigenvector of M corresponding to the maximum eigenvalue.\"\n *\n * In the above equations, w_i is the weight of the ith quaternion.\n * In this case, all quaternions are equally weighted (i.e. w_i = 1)\n */\n\n Eigen::Matrix4d M = Eigen::Matrix4d::Zero();\n\n for(const Eigen::Quaterniond& q : quaterns)\n {\n M += q.coeffs() * q.coeffs().transpose();\n }\n\n // Calculate the SVD of the M matrix\n Eigen::JacobiSVD svd(M, Eigen::ComputeFullU);\n\n // The eigenvectors are represented by the columns of the U matrix; the eigenvector corresponding to the largest eigenvalue is in row 0\n Eigen::Quaterniond q;\n q.coeffs() << svd.matrixU().col(0);\n\n assert(std::isnan(q.w()) == false &&\n std::isnan(q.x()) == false &&\n std::isnan(q.y()) == false &&\n std::isnan(q.z()) == false);\n\n return q;\n};\n\nQuaternionStats computeQuaternionStats(const std::vector &quaternions)\n{\n QuaternionStats q_stats;\n q_stats.mean = computeQuaternionMean(quaternions);\n\n double q_var = 0.0;\n for (const Eigen::Quaterniond &q : quaternions)\n {\n q_var += std::pow(q_stats.mean.angularDistance(q), 2.0);\n }\n q_var /= static_cast(quaternions.size() - 1);\n q_stats.stdev = std::sqrt(q_var);\n\n return q_stats;\n}\n\nPnPNoiseStat qualifyNoise2D(const std::vector& params)\n{\n PnPNoiseStat output;\n std::size_t count = params.size();\n\n std::vector solution_transforms;\n solution_transforms.reserve(count);\n\n std::vector translations;\n translations.reserve(count);\n\n std::vector orientations;\n orientations.reserve(count);\n\n namespace ba = boost::accumulators;\n ba::accumulator_set> x_acc;\n ba::accumulator_set> y_acc;\n ba::accumulator_set> z_acc;\n\n for (auto& prob : params)\n {\n rct_optimizations::PnPResult result;\n\n result = rct_optimizations::optimize(prob);\n\n if (result.converged)\n {\n //we will save the full result here for debugging purposes\n solution_transforms.push_back(result.camera_to_target);\n translations.push_back(solution_transforms.back().translation());\n\n x_acc(result.camera_to_target.translation()(0));\n y_acc(result.camera_to_target.translation()(1));\n z_acc(result.camera_to_target.translation()(2));\n\n orientations.push_back(Eigen::Quaterniond(result.camera_to_target.rotation()));\n }\n }\n\n output.p_stat.mean << ba::mean(x_acc), ba::mean(y_acc), ba::mean(z_acc);\n output.p_stat.stdev << std::sqrt(ba::variance(x_acc)), std::sqrt(ba::variance(y_acc)), std::sqrt(ba::variance(z_acc));\n output.q_stat = computeQuaternionStats(orientations);\n\n return output;\n}\n\nPnPNoiseStat qualifyNoise3D(const std::vector& params)\n{\n PnPNoiseStat output;\n std::size_t count = params.size();\n\n std::vector solution_transforms;\n solution_transforms.reserve(count);\n\n std::vector translations;\n translations.reserve(count);\n\n std::vector orientations;\n orientations.reserve(count);\n\n namespace ba = boost::accumulators;\n ba::accumulator_set> x_acc;\n ba::accumulator_set> y_acc;\n ba::accumulator_set> z_acc;\n\n for (auto& prob : params)\n {\n rct_optimizations::PnPResult result;\n\n result = rct_optimizations::optimize(prob);\n\n if (result.converged)\n {\n //we will save the full result here for debugging purposes\n solution_transforms.push_back(result.camera_to_target);\n translations.push_back(solution_transforms.back().translation());\n\n x_acc(result.camera_to_target.translation()(0));\n y_acc(result.camera_to_target.translation()(1));\n z_acc(result.camera_to_target.translation()(2));\n\n orientations.push_back(Eigen::Quaterniond(result.camera_to_target.rotation()));\n }\n }\n\n output.p_stat.mean << ba::mean(x_acc), ba::mean(y_acc), ba::mean(z_acc);\n output.p_stat.stdev << std::sqrt(ba::variance(x_acc)), std::sqrt(ba::variance(y_acc)), std::sqrt(ba::variance(z_acc));\n output.q_stat = computeQuaternionStats(orientations);\n\n return output;\n}\n\n}//rct_optimizations\n", "meta": {"hexsha": "46b576c98843288445fb185649816cfeacac6b29", "size": 5229, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rct_optimizations/src/rct_optimizations/validation/noise_qualification.cpp", "max_stars_repo_name": "m-limbird/robot_cal_tools", "max_stars_repo_head_hexsha": "c3ee0c26895af50219afc450e7e6f866b7b86cbe", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 110.0, "max_stars_repo_stars_event_min_datetime": "2018-07-01T07:59:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T04:27:44.000Z", "max_issues_repo_path": "rct_optimizations/src/rct_optimizations/validation/noise_qualification.cpp", "max_issues_repo_name": "m-limbird/robot_cal_tools", "max_issues_repo_head_hexsha": "c3ee0c26895af50219afc450e7e6f866b7b86cbe", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 65.0, "max_issues_repo_issues_event_min_datetime": "2018-07-02T02:29:36.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T19:11:41.000Z", "max_forks_repo_path": "rct_optimizations/src/rct_optimizations/validation/noise_qualification.cpp", "max_forks_repo_name": "m-limbird/robot_cal_tools", "max_forks_repo_head_hexsha": "c3ee0c26895af50219afc450e7e6f866b7b86cbe", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2018-07-01T01:43:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:14:47.000Z", "avg_line_length": 32.4782608696, "max_line_length": 137, "alphanum_fraction": 0.7116083381, "num_tokens": 1391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6875398646818064}} {"text": "#pragma once\n\n#include \n#include \n#include \n#include \n\n/*!\n * \\defgroup typedefs Typedefs\n */\n\nnamespace utils\n{\n inline double pow2(const double a);\n inline arma::vec pow2(const arma::vec& a);\n inline double pow3(const double a);\n inline double pow4(const double a);\n inline double pow5(const double a);\n inline double pow6(const double a);\n\n inline arma::vec cubeRoot(const arma::vec& input);\n\n inline arma::vec centerDifference(const arma::vec& input);\n\n inline arma::vec centerDifference(const arma::subview_col& input);\n\n inline arma::vec centerSum(const arma::vec& input);\n\n inline arma::vec centerSum(const arma::subview_col& input);\n\n inline arma::vec centerAverage(const arma::vec& input);\n\n inline arma::vec centerAverage(const arma::subview_col& input);\n\n inline arma::vec weightedAverage(const arma::vec& weightA, const arma::vec& weightB, const arma::vec& A, const arma::vec& B);\n\n inline double weightedAverage(const double weightA, const double weightB, const double A, const double B);\n\n inline bool isRelativeDifferenceWithinTolerance(\n const double oldValue,\n const double newValue,\n const double tolerance);\n\n inline bool areRelativeDifferencesWithinTolerance(\n const arma::vec& oldValues,\n const arma::vec& newValues,\n const double tolerance);\n\n inline double convertBurialToStandardDefinition(\n const double burial,\n const double innerDiameter,\n const arma::rowvec& width);\n\n inline double convertBurialToStandardDefinition(\n const double burial,\n const double innerDiameter,\n const arma::subview_row& width);\n\n inline arma::vec convertBurialToStandardDefinition(\n const arma::vec& burial,\n const arma::vec& innerDiameter,\n const arma::colvec& width);\n\n inline arma::vec convertBurialToStandardDefinition(\n const arma::vec& burial,\n const arma::vec& innerDiameter,\n const arma::mat& width);\n\n inline arma::vec smooth(const arma::vec& x, const double smoothness);\n\n inline arma::vec smoothTransition(const arma::vec& firstPart, const arma::vec& lastPart, double smoothness = 1.0, const double timeStep = 60);\n\n inline arma::vec createSmoothTransient(\n const double initialValue,\n const double finalValue,\n const arma::uword n,\n const double smoothness,\n const arma::uword dt);\n\n inline arma::vec findLogSpacedConcentricShellWidths(\n const double innerRadius,\n const double outerRadius,\n const arma::uword nShells);\n\n inline arma::cube loadCubeFromFile(const std::string& filename, const arma::file_type& fileType = arma::csv_ascii);\n inline arma::mat loadMatFromFile(const std::string& filename, const arma::file_type& fileType = arma::csv_ascii);\n inline arma::vec loadVecFromFile(const std::string& filename, const arma::file_type& fileType = arma::csv_ascii);\n}\n\ninline double utils::pow2(const double a)\n{\n return a*a;\n}\n\ninline arma::vec utils::pow2(const arma::vec& a)\n{\n return a%a;\n}\n\ninline double utils::pow3(const double a)\n{\n return a*a*a;\n}\n\ninline double utils::pow4(const double a)\n{\n return a*a*a*a;\n}\n\ninline double utils::pow5(const double a)\n{\n return a*a*a*a*a;\n}\n\ninline double utils::pow6(const double a)\n{\n return a*a*a*a*a*a;\n}\n\ninline arma::vec utils::cubeRoot(const arma::vec& input)\n{\n arma::vec cubed = arma::zeros(input.n_elem);\n for (arma::uword i = 0; i < input.n_elem; i++)\n {\n cubed(i) = std::cbrt(input(i));\n }\n return cubed;\n}\n\narma::vec utils::centerDifference(const arma::vec& input)\n{\n return input(arma::span(1, input.n_elem - 1)) - input(arma::span(0, input.n_elem - 2));\n}\n\narma::vec utils::centerDifference(const arma::subview_col& input)\n{\n return input.rows(1, input.n_elem - 1) - input.rows(0, input.n_elem - 2);\n}\n\narma::vec utils::centerSum(const arma::vec& input)\n{\n return input(arma::span(1, input.n_elem - 1)) + input(arma::span(0, input.n_elem - 2));\n}\n\narma::vec utils::centerSum(const arma::subview_col& input)\n{\n return input.rows(1, input.n_elem - 1) + input.rows(0, input.n_elem - 2);\n}\n\narma::vec utils::centerAverage(const arma::vec& input)\n{\n return centerSum(input)/2.0;\n}\n\narma::vec utils::centerAverage(const arma::subview_col& input)\n{\n return centerSum(input)/2.0;\n}\n\ndouble utils::weightedAverage(const double weightA, const double weightB, const double A, const double B)\n{\n if (std::round(weightA + weightB) == 0)\n {\n throw std::invalid_argument(\"utils::weightedAverage(): both weights are zero\");\n }\n\n return (A*weightA + B*weightB)/(weightA + weightB);\n}\n\narma::vec utils::weightedAverage(const arma::vec& weightA, const arma::vec& weightB, const arma::vec& A, const arma::vec& B)\n{\n if (!arma::all((weightA + weightB) != 0))\n {\n throw std::invalid_argument(\"utils::weightedAverage(): both weights are zero\");\n }\n\n return (A % weightA + B % weightB)/(weightA + weightB);\n}\n\nbool utils::isRelativeDifferenceWithinTolerance(\n const double oldValue,\n const double newValue,\n const double tolerance)\n{\n double relativeDifference;\n if (oldValue != 0)\n {\n relativeDifference = std::abs(newValue - oldValue)/std::abs(oldValue);\n }\n else if (newValue != 0)\n {\n relativeDifference = std::abs(newValue - oldValue)/std::abs(newValue);\n }\n else\n {\n // both values zero, difference also zero\n return true;\n }\n return relativeDifference < tolerance;\n}\n\nbool utils::areRelativeDifferencesWithinTolerance(\n const arma::vec& oldValues,\n const arma::vec& newValues,\n const double tolerance)\n{\n for (arma::uword i = 0; i < oldValues.n_elem; i++)\n {\n double relativeDifference;\n if (oldValues(i) != 0)\n {\n relativeDifference = std::abs(newValues(i) - oldValues(i))/std::abs(oldValues(i));\n }\n else if (newValues(i) != 0)\n {\n relativeDifference = std::abs(newValues(i) - oldValues(i))/std::abs(newValues(i));\n }\n else\n {\n // both values zero, difference also zero\n continue;\n }\n\n if (relativeDifference > tolerance)\n {\n return false;\n }\n }\n\n return true;\n}\n\ndouble utils::convertBurialToStandardDefinition(\n const double burial,\n const double innerDiameter,\n const arma::rowvec& width)\n{\n return burial + innerDiameter/2.0 + arma::sum(width);\n}\n\ndouble utils::convertBurialToStandardDefinition(\n const double burial,\n const double innerDiameter,\n const arma::subview_row& width)\n{\n return burial + innerDiameter/2.0 + arma::sum(width);\n}\n\narma::vec utils::convertBurialToStandardDefinition(\n const arma::vec& burial,\n const arma::vec& innerDiameter,\n const arma::colvec& width)\n{\n return burial + innerDiameter/2.0 + arma::sum(width);\n}\n\narma::vec utils::convertBurialToStandardDefinition(\n const arma::vec& burial,\n const arma::vec& innerDiameter,\n const arma::mat& width)\n{\n // burial depth is defined as \"from top of soil to center of pipe\" in our code,\n // but given as distance from top of pipe to top of soil in thesis and in SIM\n // this means that we have to add half a diameter + the width of all layers to convert\n arma::vec convertedBurial = arma::zeros(burial.n_elem);\n for (arma::uword i = 0; i < burial.n_elem; i++)\n {\n convertedBurial(i) = convertBurialToStandardDefinition(burial(i), innerDiameter(i), width.row(i));\n }\n\n return convertedBurial;\n}\n\narma::vec utils::smooth(const arma::vec& x, const double smoothness)\n{\n return 0.5 + 0.5*tanh((x - 0.5)/smoothness); // use x - 0.5 to get transition point to be between x = 0 and x = 1.0\n}\n\narma::vec utils::smoothTransition(\n const arma::vec& firstPart,\n const arma::vec& lastPart,\n double smoothness,\n const double timeStep)\n{\n // smooths transition from firstPart to lastPart by using a tanh function\n // idea from here: http://www.j-raedler.de/2010/10/smooth-transition-between-functions-with-tanh/\n\n // the smoothing is time-independent (or time-depending, depending on how you look at it),\n // meaning that changing the time step but using the same smoothness should result in the same smoothed curve,\n // if you also scale the x-axis correctly (meaning: use time on the x-axis, not number of time steps)\n\n // a smoothness of 1.0 will give a transition that uses approx. 10 minutes\n // a smoothness of 5.0 will use around 30 minutes\n\n arma::uword m = firstPart.n_elem;\n arma::uword n = lastPart.n_elem;\n\n // non-dimensionalizing smoothness\n // default time step of 60 gives no scaling\n smoothness *= 60.0/timeStep; // 60 is standard timestep\n\n arma::vec f = arma::join_cols(\n firstPart,\n arma::zeros(n) + firstPart(m-1) // repeat last element of firstPart\n );\n arma::vec g = arma::join_cols(\n arma::zeros(m) + lastPart(0), // repeat first element of lastPart\n lastPart\n );\n\n arma::vec x = arma::linspace(-int(m)+1, n, m+n); // !!! cast to int before subtracting, since m is unsigned int!!!\n arma::vec s = smooth(x, smoothness);\n\n arma::vec h = (1-s) % f + s % g;\n\n return h;\n}\n\narma::vec utils::createSmoothTransient(\n const double initialValue,\n const double finalValue,\n const arma::uword n,\n const double smoothness,\n const arma::uword dt)\n{\n // transient will be centered in interval [0, n]\n if (n % 2 != 0)\n {\n std::cout << \"n (\" << n << \") should be divisible by 2!\" << std::endl;\n }\n arma::vec a = arma::zeros(n/2) + initialValue;\n arma::vec b = arma::zeros(n/2) + finalValue;\n return smoothTransition(a, b, smoothness, dt);\n}\n\narma::vec utils::findLogSpacedConcentricShellWidths(\n const double innerRadius,\n const double outerRadius,\n const arma::uword nShells)\n{\n arma::vec logSpacedLayerRadii = arma::logspace(log10(innerRadius), log10(outerRadius), nShells+1);\n arma::vec logSpacedLayerWidths = arma::zeros(nShells);\n for (arma::uword i = 0; i < nShells; i++)\n {\n logSpacedLayerWidths(i) = logSpacedLayerRadii(i+1) - logSpacedLayerRadii(i);\n }\n\n return logSpacedLayerWidths;\n}\n\narma::cube utils::loadCubeFromFile(const std::string& filename, const arma::file_type& fileType)\n{\n arma::cube c;\n if (!c.load(filename, fileType))\n {\n throw std::runtime_error(\"Couldn't load file \\\"\" + filename + \"\\\"\");\n }\n\n return c;\n}\n\narma::mat utils::loadMatFromFile(const std::string& filename, const arma::file_type& fileType)\n{\n arma::mat m;\n if (!m.load(filename, fileType))\n {\n throw std::runtime_error(\"Couldn't load file \\\"\" + filename + \"\\\"\");\n }\n\n return m;\n}\n\narma::vec utils::loadVecFromFile(const std::string& filename, const arma::file_type& fileType)\n{\n arma::vec v;\n if (!v.load(filename, fileType))\n {\n throw std::runtime_error(\"Couldn't load file \\\"\" + filename + \"\\\"\");\n }\n\n return v;\n}\n", "meta": {"hexsha": "dbbfbc3790538fc7c8bd621cee02103bc11f736e", "size": 11633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utilities/utilities.hpp", "max_stars_repo_name": "kewin1983/transient-pipeline-flow", "max_stars_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-26T03:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T03:30:07.000Z", "max_issues_repo_path": "src/utilities/utilities.hpp", "max_issues_repo_name": "kewin1983/transient-pipeline-flow", "max_issues_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utilities/utilities.hpp", "max_forks_repo_name": "kewin1983/transient-pipeline-flow", "max_forks_repo_head_hexsha": "4ffe0b61d3d40d9bcb82a3743b2c2e403521835d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3733681462, "max_line_length": 146, "alphanum_fraction": 0.6436860655, "num_tokens": 2981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511322604133, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6873971989817607}} {"text": "#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace boost::math;\n\ninline double calcindex(double beta, const double a, const double nn)\n{\n double p = double(a)/double(nn);\n const double b = nn - a;\n const double r = ((double)a/(double)nn);\n const double rup = ((double)a+1.0)/((double)nn+1.0);\n const double rdn = ((double)a)/((double)nn+1.0);\n \n for(int k = 0; k < 10; ++k)\n {\n if(p > 1 || p < r || p != p) \n {\n cerr << \"Warning! returning approximation for a = \" << a << \" and b = \" << b << endl;\n return r;\n }\n const double safe = p/(1-beta);\n\n const double lhs = r*(1-ibeta(a+1,b,p));\n const double expmax = lhs + p*ibeta((double)a,b,p); \n //cout << expmax << \". lhs = \" << lhs << \". rhs = \" << p*ibeta((double)a,b,p) << endl;\n const double risky = r+ beta/(1-beta)*expmax;\n\n const double orig = risky - safe;\n const double deriv = beta/(1-beta)*ibeta(a,b,p) - 1/(1-beta);\n p -= orig/deriv;\n }\n return p;\n}\n\nvoid computeIndices(const int n, const double beta, vector >& indices)\n{\n for(int nn = n-1; nn >= 2; --nn)\n {\n for(int a = 1; a <= nn-1; ++a)\n {\n double p = calcindex(beta, a, nn);\n indices[a-1][nn-a-1] = p;\n }\n }\n}\n\nint main(int argc, const char** args)\n{\n if(argc != 3)\n {\n cerr << \"need 2 arguments [n] [beta]\" << endl;\n exit(1);\n }\n int n;\n string strnum = args[1];\n stringstream ss(strnum);\n ss >> n;\n\n double beta;\n string betastr = args[2];\n stringstream ssbeta(betastr);\n ssbeta >> beta;\n \n //cout << calcindex(beta,292,292+1170) << endl;\n //cout << \"finding indices for size limit [\" << n << \"] and step size [\" << step << \"]\" << endl; \n vector > indices(n-1, vector(n-1, 0));\n computeIndices(n, beta, indices);\n\n for(int i = 0; i < n-1; ++i)\n {\n for(int j=0; j < n-2; ++j)\n {\n cout << indices[i][j] << \", \"; \n }\n cout << indices[i][n-2] << endl;\n }\n}\n\n", "meta": {"hexsha": "a8e60a00d030a761e89cc2706734878c5350908d", "size": 2044, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/ibetas.cpp", "max_stars_repo_name": "gutin/FastGittins", "max_stars_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T12:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T16:14:34.000Z", "max_issues_repo_path": "cpp/ibetas.cpp", "max_issues_repo_name": "gutin/FastGittins", "max_issues_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/ibetas.cpp", "max_forks_repo_name": "gutin/FastGittins", "max_forks_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T02:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T02:40:39.000Z", "avg_line_length": 24.6265060241, "max_line_length": 99, "alphanum_fraction": 0.5557729941, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6873655788156859}} {"text": "#include \"patMixtureNormal.h\"\n#include \"patErrMiscError.h\"\n#include // for normal_distribution\n#include \"patDisplay.h\"\n#include \"patError.h\"\n#include \n#include \nusing boost::math::normal;\n\npatMixtureNormal::patMixtureNormal(int& components, \n\tvector& w, \n\tvector& mu,\n\tvector& sigma, \n\tpatError *& err):\n\tm_components(components),m_w(w),m_mu(mu),m_sigma(sigma){\n\n\tbool flag = false;\t\t\n\tdouble total_w=0.0;\n\n\tif(m_mu.size()==m_components && m_sigma.size()==m_components && m_w.size()==m_components){\n\t\tfor(vector::const_iterator iter = m_w.begin();iter!=m_w.end();++iter){\n\t\t\ttotal_w+=*iter;\n\t\t}\n\n\t\tif (total_w< 1.0000001 && total_w > 0.999999){\n\t\t\tflag= true;\n\t\t}\n\t}\n\n\tif(flag !=true){\n\t\tstringstream str;\n\t\tstr << \"Wrong distribution\" <describe());\n\t}\n}\n\ndouble patMixtureNormal::pdf(const double& value) const{\n\n\tdouble proba = 0.0;\n\tfor (int i = 0; i < m_components;++i) {\n\n\tboost::math::normal s(m_mu[i],m_sigma[i]);\n\t\tproba += m_w[i]\n\t\t\t\t* boost::math::pdf(s,value ) ;\n\t}\n\treturn proba;\n}\n", "meta": {"hexsha": "dc3c09fd77191a152f9267873d82e444334dc0ab", "size": 1149, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Math/patMixtureNormal.cc", "max_stars_repo_name": "godosou/smaroute", "max_stars_repo_head_hexsha": "e2ccc9492dff54c8ef5c74d5309d2b06758ba342", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-02-23T16:02:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-26T17:58:53.000Z", "max_issues_repo_path": "src/Math/patMixtureNormal.cc", "max_issues_repo_name": "godosou/smaroute", "max_issues_repo_head_hexsha": "e2ccc9492dff54c8ef5c74d5309d2b06758ba342", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math/patMixtureNormal.cc", "max_forks_repo_name": "godosou/smaroute", "max_forks_repo_head_hexsha": "e2ccc9492dff54c8ef5c74d5309d2b06758ba342", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-02-23T16:05:59.000Z", "max_forks_repo_forks_event_max_datetime": "2017-05-04T16:13:16.000Z", "avg_line_length": 23.4489795918, "max_line_length": 92, "alphanum_fraction": 0.6736292428, "num_tokens": 334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850093037732, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6873451080738194}} {"text": "/**\r\n * @file FEMesh.hpp\r\n * @brief The finite element mesh for a line.\r\n * @author Francois Roy\r\n * @date 01/06/2020\r\n */\r\n#ifndef FEMESH_H\r\n#define FEMESH_H\r\n\r\n#include \r\n#include \r\n#include \r\n#include \"spdlog/spdlog.h\"\r\n#include \"utils/Utils.hpp\"\r\n\r\nnamespace numerical {\r\n\r\nnamespace fem {\r\n\r\n/**\r\n* Holds data structures for a uniform mesh on a line in space, plus a \r\n* uniform mesh in time.\r\n* \r\n* The finite element mesh has n elements and an associated polynomial of \r\n* degree d.\r\n*\r\n* @param lengths A 2-lists of min and max coordinates in the spatial direction.\r\n* @param t0 The initial time in time mesh.\r\n* @param tend The final time in time mesh.\r\n* @param nt Number of cells in time mesh.\r\n* @param n Number of cells in the spatial direction.\r\n* @param d The polynomial degree, default = 1.\r\n*/\r\ntemplate \r\nclass FEMesh { // TODO inherit form common/Mesh\r\ntypedef Eigen::Matrix Vec;\r\nprivate:\r\n\tconst std::vector m_lengths;\r\n\tconst T m_t0, m_tend;\r\n const int m_nt, m_nx, m_d;\r\n\tT m_dt, m_dx;\r\n\tVec m_x;\r\n\tVec m_t;\r\npublic:\r\n\tFEMesh(const std::vector& lengths, T t0, T tend, int nx, int nt, \r\n int d=1) \r\n\t : m_lengths(lengths),\r\n\t m_t0(t0),\r\n m_tend(tend),\r\n m_nx(nx),\r\n m_nt(nt),\r\n m_d(d)\r\n\t{\r\n \tif(m_lengths.size() != 2){\r\n \t\tthrow std::invalid_argument(\"length is not a 2-list.\");\r\n \t}\r\n \tm_dx = (m_lengths[1] - m_lengths[0])/ T(m_nx);\r\n if(m_dx <= 0){\r\n throw std::invalid_argument(\"not a valid interval.\");\r\n }\r\n m_dt = m_tend / T(m_nt);\r\n m_x = Vec::LinSpaced(m_nx + 1, m_lengths[0], m_lengths[1]);\r\n m_t = Vec::LinSpaced(m_nt + 1, m_t0, m_tend);\r\n\t}\r\n /**\r\n * Local vertex to global vertex mapping (cells).\r\n */\r\n std::vector> cells(){\r\n std::vector> out;\r\n for(int i=0; i> dof_map(){\r\n std::vector> out;\r\n std::vector m;\r\n if(m_d == 0){\r\n for(int i; i left(){\r\n return {0};\r\n }\r\n /**\r\n * The indices of the nodes on the right boundary.\r\n *\r\n * @return The indices of the nodes on the right boundary, \r\n */\r\n std::vector right(){\r\n std::vector out = left();\r\n for(int& i : out){\r\n i += m_nx;\r\n }\r\n \treturn out;\r\n }\r\n /**\r\n * @return the time list.\r\n */\r\n Vec t() {\r\n return m_t;\r\n }\r\n\t/**\r\n\t* @return the list of coordinates.\r\n\t*/\r\n\tVec vertices() {\r\n\t\treturn m_x;\r\n\t}\r\n};\r\n\r\n} // namespace fem\r\n\r\n} // namespace numerical\r\n\r\n#endif // MESH_H\r\n", "meta": {"hexsha": "eb40c1d9701f749f71e610fac66d2bd836c92886", "size": 3550, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "numerical/fem/FEMesh.hpp", "max_stars_repo_name": "frRoy/Numerical", "max_stars_repo_head_hexsha": "97e2167cf794eceaeba395bb1958fee72d8cbecf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "numerical/fem/FEMesh.hpp", "max_issues_repo_name": "frRoy/Numerical", "max_issues_repo_head_hexsha": "97e2167cf794eceaeba395bb1958fee72d8cbecf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "numerical/fem/FEMesh.hpp", "max_forks_repo_name": "frRoy/Numerical", "max_forks_repo_head_hexsha": "97e2167cf794eceaeba395bb1958fee72d8cbecf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3150684932, "max_line_length": 80, "alphanum_fraction": 0.5216901408, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.810478926981208, "lm_q2_score": 0.8479677622198946, "lm_q1q2_score": 0.6872600020386364}} {"text": "#include \"../misc_math.h\"\n#include \"../string_utils.h\"\n#include \n#include \n#include \n\n\n\nusing namespace std;\nnamespace coela {\nnamespace misc_math {\n\n\n\ndouble linearly_interpolate(double x1, double y1, double x2, double y2, double x_between)\n{\n// cerr<<\"Inputs: \"<= x_between);\n\n //Flat line case, pick arbitrary mid point.\n if (x1==x2) { return (y1+y2)/2.0; }\n\n double grad = (y2 - y1) / (x2 - x1);\n return y1 + grad*(x_between-x1);\n}\n\ndouble dimensionless_airy_function(double x, double ratio)\n{\n //ratio = ratio of DIAMETERS ( or equiv, ratio of radii.) (not area)\n double j = 2.0 * (boost::math::cyl_bessel_j(1, x) - ratio*boost::math::cyl_bessel_j(1,\n ratio*x)) / (x*(1.0 - ratio*ratio)) ; // 2[ J(x)/x - f*f*J(fx)/fx ] / (1-f*f)\n return j*j;\n}\n\ndouble airy_function(double angle, double wavelength, double aperture_diameter,\n double obscuration_diameter)\n{\n double f = obscuration_diameter / aperture_diameter; //fractional obscuration\n double x = M_PI * aperture_diameter * (angle) /\n wavelength; //rescaled distance from centre\n// double x = M_PI * aperture_diameter * sin(angle) / wavelength; //better for large angles? But irrelevant here\n //avoid divide by 0 - return the value \"in the limit\" as x-->0:\n if (x==0) { x=1e-9; }\n //simple case: I = ( 2 J1[x] / x )^2\n// double j = 2.0 * ( boost::math::cyl_bessel_j(1, x) - f*boost::math::cyl_bessel_j(1, f*x) ) / (x*(1.0 - f*f ) ); // 2( J(x) - fJ(fx) ) / x(1-f*f)\n// return j*j;\n return dimensionless_airy_function(x, f);\n}\n\ndouble airy_fwhm_in_rads(double wavelength, double aperture_diameter,\n double obscuration_diameter)\n{\n //Monotonic between peak and first minima- use bisection and linear interpolation NB first minima not at 1.22 if obscuration !=0, but will do for a first approximation\n double lower_limit(0.0), upper_limit(1.22*wavelength/aperture_diameter), eps(1e-5),\n delta(1.0);\n double hwhm_angle(upper_limit/2.0);\n while (fabs(delta)>eps) {\n delta = airy_function(hwhm_angle, wavelength, aperture_diameter,\n obscuration_diameter) -0.5;\n if (delta >0) {\n //too close to origin\n lower_limit = hwhm_angle;\n } else { upper_limit = hwhm_angle; }\n hwhm_angle = (upper_limit + lower_limit) /2.0;\n }\n return hwhm_angle*2.0;\n}\n\ndouble gaussian_1d_function(double radius, double peak_value, double sigma)\n{\n if (sigma!=0) { return peak_value*exp(-1.0*radius*radius/(2.0*sigma*sigma)); }\n else if (radius<1e-7) { return peak_value; }\n return 0;\n}\n\ndouble moffat_function(double radius, double sigma, double beta)\n{\n assert(sigma!=0);\n double scale_length = radius/sigma;\n return pow((1+scale_length*scale_length), -1.0*beta);\n}\n\ndouble moffat_fwhm(double sigma, double beta)\n{\n return 2.0*sigma* sqrt(pow(2.0, 1.0/beta) - 1);\n}\n\ndouble moffat_sigma(double fwhm, double beta)\n{\n double radius_of_half_maximum=fwhm/2.0;\n return radius_of_half_maximum / sqrt((pow(2.0, 1.0/beta) - 1.0));\n}\n\nunsigned long integer_factorial(int n)\n{\n assert(n<20);\n if (n==0) { return 1ul; }\n return n*integer_factorial(n-1);\n}\n\n\n///Sidesteps the integer limits, but as such is not exact. Used for calculating PDFs for an EMCCD (which are already approximations anyway).\ndouble approx_factorial_double(double number)\n{\n if (number <= 1.0) { return 1.0; }\n return number * approx_factorial_double(number - 1.0);\n}\n\ndouble integer_power(double x, int n)\n{\n if (n==0) { return 1.0; }\n if (n<0) { return 1.0/integer_power(x,-1*n); }\n\n double result=x;\n while (n!=1) {\n result*=x;\n n--;\n }\n return result;\n}\n\npair fit_1d_parabola_to_find_local_maxima(double x0,\n double y_xm1, double y_x0, double y_xp1)\n{\n //nb should have been fed a local maximum, so:\n// using string_utils::ftoa;\n// if (!(y_x0 > y_xm1 && y_x0 > y_xp1))\n// throw std::runtime_error(\"Fit parabola: Not a local max: \"+ftoa(y_x0) +\" less than \"+ftoa(y_xm1)+\"or\"+ftoa(y_xp1));\n// ;\n assert(y_x0 >= y_xm1 && y_x0 >= y_xp1);\n pair xmax_ymax;\n//See Lisa Poyneer 2003, \"scene-based SHWFS\" for a nicely formatted version... but it's just very simple math.\n double b = -0.5*(y_xm1 - y_xp1);\n double two_a =(y_xm1 + y_xp1 -2*y_x0);\n //c = y_x0\n\n// xmax_ymax.first= x0 + ( 0.5*(y_xm1 - y_xp1) )/(y_xm1 + y_xp1 -2*y_x0);\n xmax_ymax.first= x0 - b/two_a;\n xmax_ymax.second=y_x0 - b*b/(2*two_a);\n\n return xmax_ymax;\n}\n\ndouble bilinear_interpolate(double x, double y,\n double x0, double y0,\n double x1, double y1,\n double f_x0_y0, double f_x1_y0, double f_x0_y1, double f_x1_y1)\n{\n double x_frac(x-x0 / (x1-x0)), y_frac(y-y0 / (y1-y0));\n\n return f_x0_y0 *(1 - x_frac)*(1 - y_frac)\n + f_x1_y0 *(x_frac)*(1 - y_frac)\n + f_x0_y1 *(1-x_frac)*(y_frac)\n + f_x1_y1 *(x_frac)*(y_frac) ;\n}\n\n}\n}\n", "meta": {"hexsha": "f67d282e81275c0ec70500318d4bc37510f6cf6f", "size": 5472, "ext": "cc", "lang": "C++", "max_stars_repo_path": "coela_utility/src/implementation/misc_math.cc", "max_stars_repo_name": "timstaley/coelacanth", "max_stars_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T03:08:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-22T03:08:45.000Z", "max_issues_repo_path": "coela_utility/src/implementation/misc_math.cc", "max_issues_repo_name": "timstaley/coelacanth", "max_issues_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coela_utility/src/implementation/misc_math.cc", "max_forks_repo_name": "timstaley/coelacanth", "max_forks_repo_head_hexsha": "d8adc49bac5dac54fdce600ea0260c526ce361af", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3658536585, "max_line_length": 171, "alphanum_fraction": 0.6120248538, "num_tokens": 1713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045907347107, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.687213934337948}} {"text": "//\n// Created by jennings on 2018/10/26.\n//\n\n#ifndef CSCI5570_LOGITSTIC_REGRESSION_HPP\n#define CSCI5570_LOGITSTIC_REGRESSION_HPP\n\n#include \"base/magic.hpp\"\n#include \n#include \n#include \n#include \"lib/svm_sample.hpp\"\n\nusing namespace Eigen;\nusing namespace csci5570;\nusing DataStore = std::vector;\n\ntemplate \nclass LogisticRegression {\npublic:\n LogisticRegression(DataStore* data_store, float learning_rate=0.001)\n : data_store_(data_store), learning_rate_(learning_rate) {\n // initialize theta\n for(auto& row : (*data_store_)) {\n for(auto& col : row.x_) {\n theta_[col.first] = 0.0;\n grad_[col.first] = 0.0;\n }\n }\n }\n\n double predict(lib::SVMSample sample) {\n double z = 0;\n for(auto& col : sample.x_) {\n Key key = col.first;\n auto x = col.second;\n z += x * theta_[key];\n }\n return 1.0 / (1 + std::exp(-z));\n }\n\n double get_loss() {\n double loss = 0;\n for (auto& row : (*data_store_)) {\n int y = row.y_ <= 0 ? 0 : 1;\n double pred = predict(row);\n loss += (-1 * y * std::log(pred) - (1 - y) * std::log(1 - pred));\n }\n return loss/data_store_->size();\n }\n\n void compute_gradient(std::vector& grad) {\n for(auto& g : grad_) {\n g.second = 0.0;\n }\n for (auto& row : (*data_store_)) {\n // NOTICE that row.y_ maybe +1/-1\n auto y = row.y_ <= 0 ? 0 : 1;\n auto z = 0;\n for(auto& col : row.x_) {\n Key key = col.first;\n auto x = col.second;\n z += x * theta_[key];\n }\n auto g = 1 / (1 + std::exp(-z));\n for(auto& col : row.x_) {\n Key key = col.first;\n auto x = col.second;\n grad_[key] += -learning_rate_ * x * (g - y);\n }\n }\n for(auto& g : grad_) {\n grad.push_back(g.second / data_store_->size());\n }\n// Matrix Z = (*X_) * theta_;\n// Matrix G = Z.unaryExpr([](T z){\n// return 1 / (1 + std::exp(-z));\n// });\n// grad = -learning_rate_ * X_->transpose() * (G - (*Y_));\n }\n\n void update_theta(const std::vector& keys, const std::vector& vals) {\n uint32_t size = keys.size();\n for(uint32_t i = 0; i < size; i++) {\n if (theta_.find(keys[i]) == theta_.end()) {continue;}\n theta_[keys[i]] = vals[i];\n }\n }\n\n float test_acc() {\n float correct = 0;\n uint32_t total = 0;\n for (auto& row : (*data_store_)) {\n // NOTICE that row.y_ maybe +1/-1\n auto y = row.y_ <= 0 ? 0 : 1;\n auto z = 0;\n for(auto& col : row.x_) {\n Key key = col.first;\n auto x = col.second;\n z += x * theta_[key];\n }\n auto g = 1 / (1 + std::exp(-z));\n auto y_pred = g <= 0.5 ? 0 : 1;\n if (y_pred == y) {correct++;}\n total++;\n }\n if (total == 0) {\n return -1;\n }\n return correct / total;\n }\n\n void get_keys(std::vector& keys) {\n for(auto& kv : theta_) {\n keys.push_back(kv.first);\n }\n }\n\nprivate:\n DataStore* data_store_;\n std::map theta_;\n std::map grad_;\n float learning_rate_;\n};\n\n\n#endif //CSCI5570_LOGITSTIC_REGRESSION_HPP\n", "meta": {"hexsha": "5d1e3f93990ea8ca21aeeefcd6f458c8fac35121", "size": 3142, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "app/logitstic_regression.hpp", "max_stars_repo_name": "samjjx/csci5570", "max_stars_repo_head_hexsha": "b051a1500cfd537ec1044279f553bd89fd3fc1ae", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-03T00:44:21.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-03T00:44:21.000Z", "max_issues_repo_path": "app/logitstic_regression.hpp", "max_issues_repo_name": "samjjx/csci5570", "max_issues_repo_head_hexsha": "b051a1500cfd537ec1044279f553bd89fd3fc1ae", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app/logitstic_regression.hpp", "max_forks_repo_name": "samjjx/csci5570", "max_forks_repo_head_hexsha": "b051a1500cfd537ec1044279f553bd89fd3fc1ae", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-11-14T16:09:03.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-20T09:46:39.000Z", "avg_line_length": 24.546875, "max_line_length": 79, "alphanum_fraction": 0.5432845321, "num_tokens": 980, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6872139274147401}} {"text": "#include \"EpipolarConsistency.h\"\n\n#include \n\nnamespace EpipolarConsistency\n{\n\tusing Geometry::Pi;\n\n\t/// 2DO Should use SVD from Geometry module to reduce compile time.\n\tGeometry::RP3Point estimateIsoCenter(const std::vector &Ps)\n\t{\n\t\tint n=(int)Ps.size();\n\t\tEigen::Matrix3d A=Eigen::Vector3d(n,n,n).asDiagonal();\n\t\tEigen::Vector3d b(0,0,0);\n\t\t// Distance as norm of a point projected to plane orthogonal to view direction through the origin.\n\t\tfor (int i=0;i(0,0);\n\t\t\t// View direction\n\t\t\tEigen::Vector3d V=P.block<1,3>(2,0).normalized();\n\t\t\t// O=id-v*v^T is projection in direction v.\n\t\t\tA-=V*V.transpose();\n\t\t\t// For points x on the principal ray it holds that O*x=O*C\n\t\t\tb+=C-V*(V.transpose()*C);\n\t\t}\n\t\t// Solve by SVD\n\t\tEigen::JacobiSVD svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\t\tGeometry::RP3Point O(0,0,0,1);\n\t\tO.block<3,1>(0,0)=svd.solve(b);\n\t\treturn O;\n\t}\n\n\tdouble estimateObjectRadius(const ProjectionMatrix& P, int n_u, int n_v)\n\t{\n\t\tusing namespace Geometry;\n\t\tusing namespace std;\n\t\t// Get the focal lengths in pixels.\n\t\tauto alphas=getCameraFocalLengthPx(P);\n\t\t// Compute field of view (use maximum of u and v).\n\t\tdouble fov =max(abs(atan(0.5*n_u/alphas.first)), abs(atan(0.5*n_v/alphas.second)));\n\t\t// The source to iso-center distance.\n\t\tdouble sid =getCameraCenter(P).head(3).norm();\n\t\t// Return approximate radius of an circumscribed sphere.\n\t\treturn sin(fov)*sid;\n\t}\n\n\tstd::pair estimateAngularRange(const RP3Line& B, double object_radius_mm)\n\t{\n\t\t// Distance of baseline to origin\n\t\tdouble baseline_dist=Geometry::pluecker_distance_to_origin(B);\n\t\t// If the baseline intersects the object, ECC is not well-defined. We return a half circle anyway.\n\t\tif (baseline_dist<=object_radius_mm)\n\t\t\treturn std::make_pair(-0.5*Pi,0.5*Pi);\n\t\t// Else, find angle of plane which touches the sphere\n\t\tdouble kappa_max=std::abs(std::asin(object_radius_mm/baseline_dist));\n\t\treturn std::make_pair(-kappa_max,kappa_max);\n\t}\n\n\tdouble estimateAngularStep(const ProjectionMatrix& P0, const ProjectionMatrix& P1, int n_u, int n_v)\n\t{\n\t\tusing namespace Geometry;\n\t\tdouble radius_mm=std::max(estimateObjectRadius(P0,n_u,n_v),estimateObjectRadius(P1,n_u,n_v));\n\t\tauto baseline=join_pluecker(getCameraCenter(P0),getCameraCenter(P1));\n\t\tauto range_kappa=estimateAngularRange(baseline,radius_mm);\n\t\treturn 2.0*(range_kappa.second-range_kappa.first)/std::sqrt(n_u*n_u+n_v*n_v);\n\t}\n\n\tMetric& Metric::setObjectRadius(double radius_mm)\n\t{\n\t\tobject_radius_mm=radius_mm;\n\t\treturn *this;\n\t}\n\n\tdouble Metric::getObjectRadius() const\n\t{\n\t\tif (object_radius_mm>0)\n\t\t\treturn object_radius_mm;\n\t\tif (getProjectionMatrices().empty())\n\t\t\treturn 0;\n\t\tauto P=getProjectionMatrices().front();\n\t\treturn estimateObjectRadius(P,n_u,n_v);\n\t}\n\n\tMetric& Metric::setEpipolarPlaneStep(double dkappa_rad) {\n\t\tdkappa=dkappa_rad;\n\t\treturn *this;\n\t}\n\n\tMetric& Metric::setProjectionMatrices(const std::vector& _Ps)\n\t{\n\t\tPs=_Ps;\n\t\treturn *this;\n\t}\n\n\tconst std::vector&Metric:: getProjectionMatrices() const\n\t{\n\t\treturn Ps;\n\t}\n\n\tMetric::Metric() : object_radius_mm(0), dkappa(0), n_u(0), n_v(0) {}\n\n\tMetric::~Metric() {}\n\n} // namespace EpipolarConsistency\n", "meta": {"hexsha": "7b5299abdb736956b8d0cbdfd0933e7eaecf99d5", "size": 3368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/LibEpipolarConsistency/EpipolarConsistency.cpp", "max_stars_repo_name": "mareikethies/EpipolarConsistency", "max_stars_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-21T16:33:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T03:03:00.000Z", "max_issues_repo_path": "code/LibEpipolarConsistency/EpipolarConsistency.cpp", "max_issues_repo_name": "mareikethies/EpipolarConsistency", "max_issues_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-06-14T07:48:55.000Z", "max_issues_repo_issues_event_max_datetime": "2018-06-14T07:48:55.000Z", "max_forks_repo_path": "code/LibEpipolarConsistency/EpipolarConsistency.cpp", "max_forks_repo_name": "mareikethies/EpipolarConsistency", "max_forks_repo_head_hexsha": "63d7ca2fd705911a6c93ca4247486fc66a9d31c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-05-15T21:38:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-06T07:20:47.000Z", "avg_line_length": 31.476635514, "max_line_length": 101, "alphanum_fraction": 0.7211995249, "num_tokens": 1006, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.687184390196371}} {"text": "/*--\r\n Open3DMotion \r\n Copyright (c) 2004-2012.\r\n All rights reserved.\r\n See LICENSE.txt for more information.\r\n--*/\r\n\r\n#include \r\n#include \r\n#include \"Open3DMotion/Maths/LinearSolve3.h\"\r\n\r\n#ifndef OPEN3DMOTION_LINEAR_ALGEBRA_EIGEN\r\nextern \"C\"\r\n{\r\n#include \r\n#include \r\n}\r\n#else\r\n#include \r\n#endif\r\n\r\nnamespace Open3DMotion\r\n{\r\n\r\n\t// Linear alegebra helper function: calls LAPACK routine\r\n\t// Solves linear least squares in 3D\r\n\tbool LinearSolve3(float* x, const float* A, const float* b, int numrows, float* rms /*=NULL*/, float rcond /*=0.001*/)\r\n\t{\t\r\n#ifndef OPEN3DMOTION_LINEAR_ALGEBRA_EIGEN\r\n\r\n\t\tint i, j;\r\n\r\n\t\t// transpose as required for lapack\r\n\t\tfloat* AT = new float[3*numrows];\r\n\t\tfor (i = 0; i < 3; i++)\r\n\t\t\tfor (j = 0; j < numrows; j++)\r\n\t\t\t\tAT[i*numrows+j] = A[3*j + i];\r\n\r\n\t\t// copy input vector\r\n\t\tfloat* y = new float[numrows];\r\n\t\tfor (i = 0; i < numrows; i++)\r\n\t\t\ty[i] = b[i];\r\n\r\n\t\t// params required for lapack\r\n\t\tlong mrows = numrows;\r\n\t\tlong ncols = 3;\r\n\t\tlong nrhs = 1;\r\n\t\tlong lda = numrows;\r\n\t\tlong ldb = numrows;\r\n\t\tlong jpvt[3] = { 0, 0, 0 };\r\n\t\tlong rank = 0;\r\n\t\tlong info = 0;\r\n\r\n\t\t// call lapack function to query work size\r\n\t\tlong lwork_query = -1;\r\n\t\tfloat opt_work_size = 1.0f;\r\n\t\tsgelsy_(&mrows, &ncols, &nrhs, AT, &lda, y, &ldb, jpvt, &rcond, &rank, &opt_work_size, &lwork_query, &info);\r\n\r\n\t\t// return if any probs with params\r\n\t\tif (info != 0)\r\n\t\t\treturn false;\r\n\r\n\t\t// get opt work size and call for real\r\n\t\tlong lwork_opt = (long)opt_work_size;\r\n\t\tfloat* work = new float[lwork_opt];\r\n\t\tsgelsy_(&mrows, &ncols, &nrhs, AT, &lda, y, &ldb, jpvt, &rcond, &rank, work, &lwork_opt, &info);\r\n\r\n\t\t// copy result\r\n\t\tfor (i = 0; i < 3; i++)\r\n\t\t\tx[i] = y[i];\r\n\r\n\t\t// done with temp data\r\n\t\tdelete [] work;\r\n\t\tdelete [] AT;\r\n\t\tdelete [] y;\r\n\r\n\t\t// must have params ok (info = 0) and full rank (3)\r\n\t\tif (info != 0 || rank != 3)\r\n\t\t\treturn false;\r\n\r\n\t\t// if requested, compute RMS\r\n\t\tif (rms)\r\n\t\t{\r\n\t\t\tfloat sumsq(0.0f);\r\n\t\t\tfor (i = 0; i < numrows; i++)\r\n\t\t\t{\r\n\t\t\t\tfloat ax(0.0f);\r\n\t\t\t\tfor (j = 0; j < 3; j++)\r\n\t\t\t\t\tax += A[3*i+j] * x[j];\r\n\t\t\t\tfloat diff = ax - b[i];\r\n\t\t\t\tsumsq += diff*diff;\r\n\t\t\t}\r\n\t\t\t*rms = sqrt(sumsq / numrows);\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\r\n#else\r\n\r\n\t\t// Map to Eigen objects\r\n\t\tEigen::Map< const Eigen::Matrix > C(A, numrows, 3);\r\n Eigen::Map< const Eigen::Matrix > d(b, numrows, 1);\r\n Eigen::Map< Eigen::Matrix > y(x, 3, 1);\r\n\r\n\t\t// compute CTC ( = ATA )\r\n\t\tEigen::MatrixXf CT = C.transpose();\r\n\t\tEigen::Matrix3f CTC = CT * C;\r\n\r\n\t\t// perform check on reciprocal condition number\tto mimic LAPACK behaviour\r\n\t\tEigen::Vector3f e = Eigen::EigenSolver (CTC).eigenvalues().real();\r\n\t\tfloat CTC_rcond = e.minCoeff() / e.maxCoeff();\r\n\t\tif (CTC_rcond < rcond)\r\n\t\t\treturn false;\t\t\r\n\r\n\t\t// compute CTd = ATb\r\n\t\tEigen::Vector3f CTd = CT * d;\r\n\r\n\t\t// solve\r\n\t\ty = CTC.ldlt().solve(CTd);\r\n\r\n\t\t// compute rms error if requested\r\n\t\tif (rms)\r\n\t\t\t*rms = sqrt((C*y - d).squaredNorm() / numrows);\r\n\r\n\t\treturn true;\r\n\r\n#endif\r\n\t}\r\n\r\n}\r\n", "meta": {"hexsha": "52b1755fe8bd023b3f758d50df594d9f175136e3", "size": 3128, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Utilities/Open3DMotion/src/Open3DMotion/Maths/LinearSolve3.cpp", "max_stars_repo_name": "mitkof6/BTKCore", "max_stars_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_stars_repo_licenses": ["Barr", "Unlicense"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2015-04-21T20:40:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T03:35:03.000Z", "max_issues_repo_path": "Utilities/Open3DMotion/src/Open3DMotion/Maths/LinearSolve3.cpp", "max_issues_repo_name": "mitkof6/BTKCore", "max_issues_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_issues_repo_licenses": ["Barr", "Unlicense"], "max_issues_count": 17.0, "max_issues_repo_issues_event_min_datetime": "2015-06-23T20:51:57.000Z", "max_issues_repo_issues_event_max_datetime": "2020-08-17T17:08:57.000Z", "max_forks_repo_path": "Utilities/Open3DMotion/src/Open3DMotion/Maths/LinearSolve3.cpp", "max_forks_repo_name": "mitkof6/BTKCore", "max_forks_repo_head_hexsha": "d4c03aa9e354be16265d0efe0815c09b35abc642", "max_forks_repo_licenses": ["Barr", "Unlicense"], "max_forks_count": 56.0, "max_forks_repo_forks_event_min_datetime": "2015-05-11T11:04:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-15T20:37:04.000Z", "avg_line_length": 23.8778625954, "max_line_length": 120, "alphanum_fraction": 0.5875959079, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6871678187617931}} {"text": "/*\n * Copyright (C) 2021 Open Source Robotics Foundation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n*/\n\n#ifndef IGNITION_MATH_EIGEN3_UTIL_HH_\n#define IGNITION_MATH_EIGEN3_UTIL_HH_\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ignition\n{\n namespace math\n {\n namespace eigen3\n {\n /// \\brief Get covariance matrix from a set of 3d vertices\n /// https://github.com/isl-org/Open3D/blob/76c2baf9debd460900f056a9b51e9a80de9c0e64/cpp/open3d/utility/Eigen.cpp#L305\n /// \\param[in] _vertices a vector of 3d vertices\n /// \\return Covariance matrix\n inline Eigen::Matrix3d covarianceMatrix(\n const std::vector &_vertices)\n {\n if (_vertices.empty())\n return Eigen::Matrix3d::Identity();\n\n Eigen::Matrix cumulants;\n cumulants.setZero();\n for (const auto &vertex : _vertices)\n {\n const Eigen::Vector3d &point = math::eigen3::convert(vertex);\n cumulants(0) += point(0);\n cumulants(1) += point(1);\n cumulants(2) += point(2);\n cumulants(3) += point(0) * point(0);\n cumulants(4) += point(0) * point(1);\n cumulants(5) += point(0) * point(2);\n cumulants(6) += point(1) * point(1);\n cumulants(7) += point(1) * point(2);\n cumulants(8) += point(2) * point(2);\n }\n\n Eigen::Matrix3d covariance;\n\n cumulants /= static_cast(_vertices.size());\n\n covariance(0, 0) = cumulants(3) - cumulants(0) * cumulants(0);\n covariance(1, 1) = cumulants(6) - cumulants(1) * cumulants(1);\n covariance(2, 2) = cumulants(8) - cumulants(2) * cumulants(2);\n covariance(0, 1) = cumulants(4) - cumulants(0) * cumulants(1);\n covariance(1, 0) = covariance(0, 1);\n covariance(0, 2) = cumulants(5) - cumulants(0) * cumulants(2);\n covariance(2, 0) = covariance(0, 2);\n covariance(1, 2) = cumulants(7) - cumulants(1) * cumulants(2);\n covariance(2, 1) = covariance(1, 2);\n return covariance;\n }\n\n /// \\brief Get the oriented 3d bounding box of a set of 3d\n /// vertices using PCA\n /// http://codextechnicanum.blogspot.com/2015/04/find-minimum-oriented-bounding-box-of.html\n /// \\param[in] _vertices a vector of 3d vertices\n /// \\return Oriented 3D box\n inline ignition::math::OrientedBoxd verticesToOrientedBox(\n const std::vector &_vertices)\n {\n math::OrientedBoxd box;\n\n // Return an empty box if there are no vertices\n if (_vertices.empty())\n return box;\n\n math::Vector3d mean;\n for (const auto &point : _vertices)\n mean += point;\n mean /= static_cast(_vertices.size());\n\n Eigen::Vector3d centroid = math::eigen3::convert(mean);\n Eigen::Matrix3d covariance = covarianceMatrix(_vertices);\n\n // Eigen Vectors\n Eigen::SelfAdjointEigenSolver\n eigenSolver(covariance, Eigen::ComputeEigenvectors);\n Eigen::Matrix3d eigenVectorsPCA = eigenSolver.eigenvectors();\n\n // This line is necessary for proper orientation in some cases.\n // The numbers come out the same without it, but the signs are\n // different and the box doesn't get correctly oriented in some cases.\n eigenVectorsPCA.col(2) =\n eigenVectorsPCA.col(0).cross(eigenVectorsPCA.col(1));\n\n // Transform the original cloud to the origin where the principal\n // components correspond to the axes.\n Eigen::Matrix4d projectionTransform(Eigen::Matrix4d::Identity());\n projectionTransform.block<3, 3>(0, 0) = eigenVectorsPCA.transpose();\n projectionTransform.block<3, 1>(0, 3) =\n -1.0f * (projectionTransform.block<3, 3>(0, 0) * centroid);\n\n Eigen::Vector3d minPoint(INF_I32, INF_I32, INF_I32);\n Eigen::Vector3d maxPoint(-INF_I32, -INF_I32, -INF_I32);\n\n // Get the minimum and maximum points of the transformed cloud.\n for (const auto &point : _vertices)\n {\n Eigen::Vector4d pt(0, 0, 0, 1);\n pt.head<3>() = math::eigen3::convert(point);\n Eigen::Vector4d tfPoint = projectionTransform * pt;\n minPoint = minPoint.cwiseMin(tfPoint.head<3>());\n maxPoint = maxPoint.cwiseMax(tfPoint.head<3>());\n }\n\n const Eigen::Vector3d meanDiagonal = 0.5f * (maxPoint + minPoint);\n\n // quaternion is calculated using the eigenvectors (which determines\n // how the final box gets rotated), and the transform to put the box\n // in correct location is calculated\n const Eigen::Quaterniond bboxQuaternion(eigenVectorsPCA);\n const Eigen::Vector3d bboxTransform =\n eigenVectorsPCA * meanDiagonal + centroid;\n\n math::Vector3d size(\n maxPoint.x() - minPoint.x(),\n maxPoint.y() - minPoint.y(),\n maxPoint.z() - minPoint.z()\n );\n math::Pose3d pose;\n pose.Rot() = math::eigen3::convert(bboxQuaternion);\n pose.Pos() = math::eigen3::convert(bboxTransform);\n\n box.Size(size);\n box.Pose(pose);\n return box;\n }\n }\n }\n}\n\n#endif\n", "meta": {"hexsha": "25f740bd8948117430292137561dbfd3eb9ece4c", "size": 6031, "ext": "hh", "lang": "C++", "max_stars_repo_path": "eigen3/include/ignition/math/eigen3/Util.hh", "max_stars_repo_name": "srmainwaring/ign-math", "max_stars_repo_head_hexsha": "ff55578b52b9c42daaea666c3c1205551b07afbb", "max_stars_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_stars_count": 43.0, "max_stars_repo_stars_event_min_datetime": "2019-08-21T20:50:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T11:48:25.000Z", "max_issues_repo_path": "eigen3/include/ignition/math/eigen3/Util.hh", "max_issues_repo_name": "srmainwaring/ign-math", "max_issues_repo_head_hexsha": "ff55578b52b9c42daaea666c3c1205551b07afbb", "max_issues_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_issues_count": 277.0, "max_issues_repo_issues_event_min_datetime": "2020-04-16T23:38:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:11:58.000Z", "max_forks_repo_path": "eigen3/include/ignition/math/eigen3/Util.hh", "max_forks_repo_name": "srmainwaring/ign-math", "max_forks_repo_head_hexsha": "ff55578b52b9c42daaea666c3c1205551b07afbb", "max_forks_repo_licenses": ["ECL-2.0", "Apache-2.0"], "max_forks_count": 48.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T21:15:43.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T19:29:04.000Z", "avg_line_length": 37.2283950617, "max_line_length": 123, "alphanum_fraction": 0.6330625104, "num_tokens": 1632, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6871678049234973}} {"text": "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n \nstruct ardsqexpKernel{\n ardsqexpKernel():\n length_scales(1,1),\n length_scales_2(1,1),\n train(1,std::vector(1,0)),\n sigma_f(1.0),\n sigma_f_2(1.0),\n K(train.size(),0)\n {\n }\n\n ardsqexpKernel(std::vector> train, std::vector theta):\n train(train),\n sigma_f(theta[theta.size()-1]),\n sigma_f_2(sigma_f*sigma_f),\n K(train.size(),0)\n {\n length_scales = std::vector(theta.begin(),theta.end()-1);\n length_scales_2 = std::vector(length_scales.size(),0);\n for (size_t i = 0; i < length_scales.size(); i++){\n length_scales_2[i] = length_scales[i]*length_scales[i];\n } \n }\n\n std::vector operator()(const std::vector& New){ \n for (auto i = 0; i < train.size(); i++){\n double ard_sum = 0;\n for(auto j = 0; j < train[0].size(); j++) {\n double diff = train[i][j]-New[j];\n ard_sum += diff*diff/(length_scales_2[j]);\n }\n K[i] = sigma_f_2*exp(-0.5*ard_sum);\n }\n return K;\n }\n\n std::vector> train;\n std::vector length_scales;\n std::vector length_scales_2;\n double sigma_f;\n double sigma_f_2;\n std::vector K;\n};\n", "meta": {"hexsha": "e64b0c8f9356af92f30f8871d7214ecfc622aa9f", "size": 1454, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Mahi/FesExo/Kernels.hpp", "max_stars_repo_name": "mahilab/FES_Exo", "max_stars_repo_head_hexsha": "46b5f911048993eadaceaf51d50a8a0d2d523507", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Mahi/FesExo/Kernels.hpp", "max_issues_repo_name": "mahilab/FES_Exo", "max_issues_repo_head_hexsha": "46b5f911048993eadaceaf51d50a8a0d2d523507", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Mahi/FesExo/Kernels.hpp", "max_forks_repo_name": "mahilab/FES_Exo", "max_forks_repo_head_hexsha": "46b5f911048993eadaceaf51d50a8a0d2d523507", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.9615384615, "max_line_length": 86, "alphanum_fraction": 0.5694635488, "num_tokens": 418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426831, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6871396809394892}} {"text": "//\n// kc_rsa.cpp\n// kcalg\n//\n// Created by knightc on 2019/7/22.\n// Copyright © 2019 knightc. All rights reserved.\n//\n\n#include \"opentsb/kc_sec.h\"\n#include \"opentsb/kc_common.h\"\n#include \"rsaUtil.hpp\"\n\n#include \"opentsb/test.h\"\n\n#include \n#include \n\n#include \n\n\nint rsa_getKey(ZZ pubKey[],ZZ privKey[]) {\n \n ZZ p,q,n ,f_n;\n ZZ pubkey_e,privKey_d;\n \n pubkey_e= 65537;\n \n RandomPrime(p, 1024);\n RandomPrime(q, 1024);\n // NextPrime(q, p );\n// p= 37;\n// q= 23;\n// if (GCD(p , q )==1) {\n// cout << \"p and q is prime \" << endl;\n// }\n \n \n n= p * q;\n oula(p, q, f_n);\n \n if (GCD(pubkey_e, f_n )== 1) {\n cout << \" pubkey_e is true \\n\" << endl;\n }\n \n privKey_d = InvMod(pubkey_e, f_n);\n \n pubKey[0]=pubkey_e;\n pubKey[1]=n;\n \n \n privKey[0] = privKey_d;\n privKey[1] =p;\n privKey[2] = q ;\n \n cout <<\"公钥 e = \"<< pubkey_e <<\"\\n\"\n << \"共模 n = \" << n << \"\\n\"\n << \"欧拉 n = \" << f_n << \"\\n\"\n <<\"私钥 d = \" <\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n// #include \"g2o/core/auto_differentiation.h\"\n// #include \"g2o/core/base_unary_edge.h\"\n// #include \"g2o/core/base_vertex.h\"\n// #include \"g2o/core/optimization_algorithm_factory.h\"\n// #include \"g2o/core/sparse_optimizer.h\"\n// #include \"g2o/stuff/command_args.h\"\n// #include \"g2o/stuff/sampler.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"matplotlibcpp.h\"\n\nG2O_USE_OPTIMIZATION_LIBRARY(dense);\n\n\nusing namespace std;\nusing namespace Eigen;\nnamespace plt = matplotlibcpp;\n\n\ntemplate \nT g(TT x, T a, T b, T c)\n{\n return ceres::exp(a * x * x + b * x + c);\n}\n\n\n\n\nclass CurveFittingVertex: public g2o::BaseVertex<3, Eigen::Vector3d> {\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n virtual void setToOriginImpl() override {\n _estimate << 0.0, 0.0, 0.0;\n }\n virtual void oplusImpl(const double* update) override {\n _estimate += Eigen::Vector3d(update);\n }\n\n virtual bool read(std::istream&) {}\n virtual bool write(std::ostream&) const {}\n};\n\nclass CurveFittingEdge: public g2o::BaseUnaryEdge<1, double, CurveFittingVertex> {\n public: \n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n CurveFittingEdge(double x): _x(x) {}\n\n // Without auto-diff\n virtual void computeError() override {\n const CurveFittingVertex* v = static_cast(_vertices[0]);\n const Eigen::Vector3d abc = v->estimate();\n _error(0, 0) = _measurement - g(_x, abc[0], abc[1], abc[2]);\n }\n\n // Analytical jacobian\n virtual void linearizeOplus() override {\n const CurveFittingVertex *v = static_cast(_vertices[0]);\n const Eigen::Vector3d abc = v->estimate();\n double y = g(_x, abc[0], abc[1], abc[2]);\n _jacobianOplusXi[0] = -_x * _x * y;\n _jacobianOplusXi[1] = -_x * y;\n _jacobianOplusXi[2] = -y;\n }\n\n\n\n // with auto-diff\n // template \n // bool operator() (const T* abc, T *error) const {\n // error[0] = measurement() - g(_x, abc[0], abc[1], abc[2]);\n // return true;\n // }\n\n virtual bool read(istream&) {}\n virtual bool write(ostream&) const {}\n\n private:\n double _x;\n\n\n // G2O_MAKE_AUTO_AD_FUNCTIONS // use autodiff\n}; \n\n\nint main(int argc, char **argv) {\n std::cout << \"Gauss-Newton \\n\";\n\n double aa = 1.0, bb = 2.0, cc = 1.0;\n double a = 2.0, b = -1.0, c = 5.5;\n\n double obs_sigma = 1.0;\n std::default_random_engine generator;\n std::normal_distribution obs_noise_distrib(0.0, obs_sigma);\n\n\n int N = 100;\n std::vector x_data(N), y_data(N);\n for (int i = 0; i < N; ++i)\n {\n x_data[i] = static_cast(i) / 100.0;\n y_data[i] = g(x_data[i], aa, bb, cc) + obs_noise_distrib(generator);\n\n }\n\n\n typedef g2o::BlockSolver> BlockSolverType;\n typedef g2o::LinearSolverDense LinearSolverType;\n\n // auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n // g2o::make_unique(g2o::make_unique())\n // );\n\n g2o::SparseOptimizer optimizer;\n // optimizer.setAlgorithm(solver);\n g2o::OptimizationAlgorithmProperty solverProperty;\n optimizer.setAlgorithm(g2o::OptimizationAlgorithmFactory::instance()->construct(\"lm_dense\", solverProperty));\n optimizer.setVerbose(true);\n\n\n // Create vertex\n CurveFittingVertex *v = new CurveFittingVertex();\n v->setEstimate(Eigen::Vector3d(a, b, c));\n v->setId(0);\n optimizer.addVertex(v);\n\n // Add edges\n for (int i = 0; i < N; ++i)\n {\n CurveFittingEdge * edge = new CurveFittingEdge(x_data[i]);\n edge->setId(i);\n edge->setVertex(0, v);\n edge->setMeasurement(y_data[i]);\n edge->setInformation(Eigen::Matrix::Identity() / (obs_sigma * obs_sigma));\n optimizer.addEdge(edge);\n }\n\n\n chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n\n optimizer.initializeOptimization();\n optimizer.optimize(10);\n\n chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n chrono::duration time_used = chrono::duration_cast>(t2 - t1);\n cout << \"solve time cost = \" << time_used.count() << \" seconds. \" << endl;\n \n \n a = v->estimate()[0];\n b = v->estimate()[1];\n c = v->estimate()[2];\n\n std::cout << \"final = \" << a << \" \" << b << \" \" << c << \"\\n\";\n\n\n\n vector final_y_data(N);\n for (int i = 0; i < N; ++i)\n {\n final_y_data[i] = g(x_data[i], a, b, c);\n }\n\n plt::scatter(x_data, y_data);\n std::map parameters;\n parameters[\"c\"] = \"red\";\n plt::scatter(x_data, final_y_data, 1.0, parameters);\n plt::show(); \n\n\n return 0;\n}\n", "meta": {"hexsha": "6128e8a94e1b7962d873b8e15d76dcad8ef34ba1", "size": 5020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch6/curve_fitting_g2o.cpp", "max_stars_repo_name": "zinsmatt/slambook2", "max_stars_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch6/curve_fitting_g2o.cpp", "max_issues_repo_name": "zinsmatt/slambook2", "max_issues_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch6/curve_fitting_g2o.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9892473118, "max_line_length": 111, "alphanum_fraction": 0.6651394422, "num_tokens": 1527, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6870962337313626}} {"text": "/* Copyright (c) 2010-2015, Delft University of Technology\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are\n * permitted provided that the following conditions are met:\n * - Redistributions of source code must retain the above copyright notice, this list of\n * conditions and the following disclaimer.\n * - Redistributions in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and/or other materials\n * provided with the distribution.\n * - Neither the name of the Delft University of Technology nor the names of its contributors\n * may be used to endorse or promote products derived from this software without specific\n * prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS\n * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Changelog\n * YYMMDD Author Comment\n * 100903 K. Kumar File created.\n * 100916 L. Abdulkadir File checked.\n * 100929 K. Kumar Checked code by D. Dirkx added.\n * 101110 K. Kumar Added raiseToExponentPower() function.\n * 102410 D. Dirkx Minor comment changes as code check.\n * 101213 K. Kumar Bugfix raiseToIntegerExponent(); renamed raiseToIntegerPower().\n * Added computeAbsoluteValue() functions.\n * 110202 K. Kumar Added overload for State* for computeLinearInterpolation().\n * 110111 J. Melman Added computeModulo() function.\n * 110411 K. Kumar Added convertCartesianToSpherical() function.\n * 110606 J. Melman Removed possible singularity from\n * convertCartesianToSpherical.\n * 110707 K. Kumar Added computeSampleMean(), computeSampleVariance() functions.\n * 110905 S. Billemont Reorganized includes.\n * Moved (con/de)structors and getter/setters to header.\n * 120127 D. Dirkx First version branched from basic mathematics in Tudat Core.\n * 120127 K. Kumar Minor comment edits.\n * 120118 D. Gondelach Added new convertCylindricalToCartesian functions.\n * 120214 K. Kumar Branched from old Tudat trunk for new coordinate conversions.\n * 120217 K. Kumar Updated computeModuloForSignedValues() to computeModulo()\n * from Tudat Core.\n * 120926 E. Dekens Added spherical gradient to Cartesian conversion.\n * 131022 T. Roegiers Added conversion from spherical state to Cartesian state.\n * Added conversion from Cartesian state to spherical state.\n * 140114 E. Brandon Reorganized includes.\n * Minor changes during code check.\n *\n * References\n * Press W.H., et al. Numerical Recipes in C++: The Art of Scientific Computing. Cambridge\n * University Press, February 2002.\n * Torok, J.S. Analytical Mechanics: with an Introduction to Dynamical Systems, John Wiley and\n * Sons, Inc., 2000.\n * Vallado, D.A. Fundamentals of Astrodynamics and Applications. Microcosm Press, 2001.\n *\n * Notes\n *\n */\n\n#include \n#include \n#include \n\n#include \n\n#include \"Tudat/Mathematics/BasicMathematics/basicMathematicsFunctions.h\"\n#include \"Tudat/Mathematics/BasicMathematics/mathematicalConstants.h\"\n#include \"Tudat/Mathematics/BasicMathematics/coordinateConversions.h\"\n\nnamespace tudat\n{\n\nnamespace coordinate_conversions\n{\n\n\n//! Convert spherical (radius_, zenith, azimuth) to Cartesian (x,y,z) coordinates.\nEigen::Vector3d convertSphericalToCartesian( const Eigen::Vector3d& sphericalCoordinates )\n{\n // Create local variables.\n double radius_ = sphericalCoordinates( 0 );\n double zenithAngle_ = sphericalCoordinates( 1 );\n double azimuthAngle_ = sphericalCoordinates( 2 );\n\n // Declaring sine which has multiple usages to save computation time.\n double sineOfZenithAngle_ = std::sin( sphericalCoordinates( 1 ) );\n\n // Create output Vector3d.\n Eigen::Vector3d convertedCartesianCoordinates_ = Eigen::Vector3d::Zero( 3 );\n\n // Perform transformation.\n convertedCartesianCoordinates_( 0 ) = radius_ * std::cos( azimuthAngle_ ) * sineOfZenithAngle_;\n convertedCartesianCoordinates_( 1 ) = radius_ * std::sin( azimuthAngle_ ) * sineOfZenithAngle_;\n convertedCartesianCoordinates_( 2 ) = radius_ * std::cos( zenithAngle_ );\n\n return convertedCartesianCoordinates_;\n}\n\n//! Convert Cartesian (x,y,z) to spherical (radius, zenith, azimuth) coordinates.\nEigen::Vector3d convertCartesianToSpherical( const Eigen::Vector3d& cartesianCoordinates )\n{\n // Create output Vector3d.\n Eigen::Vector3d convertedSphericalCoordinates_ = Eigen::Vector3d::Zero( 3 );\n\n // Compute transformation of Cartesian coordinates to spherical coordinates.\n convertedSphericalCoordinates_( 0 ) = cartesianCoordinates.norm( );\n\n // Check if coordinates are at origin.\n if ( convertedSphericalCoordinates_( 0 ) < std::numeric_limits< double >::epsilon( ) )\n {\n convertedSphericalCoordinates_( 1 ) = 0.0;\n convertedSphericalCoordinates_( 2 ) = 0.0;\n }\n // Else compute coordinates using trigonometric relationships.\n else\n {\n convertedSphericalCoordinates_( 1 ) = std::acos( cartesianCoordinates( 2 )\n / convertedSphericalCoordinates_( 0 ) );\n convertedSphericalCoordinates_( 2 ) = std::atan2( cartesianCoordinates( 1 ),\n cartesianCoordinates( 0 ) );\n }\n\n return convertedSphericalCoordinates_;\n}\n\n\n//! Convert cylindrical to Cartesian coordinates.\nEigen::Vector3d convertCylindricalToCartesian( const double radius,\n const double azimuthAngle, const double z )\n{\n // Create Cartesian coordinates vector.\n Eigen::Vector3d cartesianCoordinates;\n\n // If radius < 0, then give warning.\n if ( radius < 0.0 )\n {\n std::cerr << \"Warning: cylindrical radial coordinate is negative!\\n\"\n << \"This could give incorrect results!\\n\";\n }\n\n // Compute and set Cartesian coordinates.\n cartesianCoordinates << radius * std::cos( azimuthAngle ), // x-coordinate\n radius * std::sin( azimuthAngle ), // y-coordinate\n z; // z-coordinate\n\n return cartesianCoordinates;\n}\n\n//! Convert cylindrical to cartesian coordinates.\nEigen::Vector3d convertCylindricalToCartesian( const Eigen::Vector3d& cylindricalCoordinates )\n{\n // Create Cartesian coordinates vector.\n Eigen::Vector3d cartesianCoordinates;\n\n // If radius < 0, then give warning.\n if ( cylindricalCoordinates( 0 ) < 0.0 )\n {\n std::cerr << \"Warning: cylindrical radial coordinate is negative! \"\n << \"This could give incorrect results!\\n\";\n }\n\n // Compute and set Cartesian coordinates.\n cartesianCoordinates\n << cylindricalCoordinates( 0 )\n * std::cos( cylindricalCoordinates( 1 ) ), // x-coordinate\n cylindricalCoordinates( 0 )\n * std::sin( cylindricalCoordinates( 1 ) ), // y-coordinate\n cylindricalCoordinates( 2 ); // z-coordinate\n\n return cartesianCoordinates;\n}\n\n//! Convert cylindrical to Cartesian state.\nbasic_mathematics::Vector6d convertCylindricalToCartesianState(\n const basic_mathematics::Vector6d& cylindricalState )\n{\n // Create Cartesian state vector, initialized with zero entries.\n basic_mathematics::Vector6d cartesianState = basic_mathematics::Vector6d::Zero( );\n\n // Get azimuth angle, theta.\n double azimuthAngle = cylindricalState( 1 );\n\n // Compute and set Cartesian coordinates.\n cartesianState.head( 3 ) = convertCylindricalToCartesian(\n Eigen::Vector3d( cylindricalState.head( 3 ) ) );\n\n // If r = 0 AND Vtheta > 0, then give warning and assume Vtheta=0.\n if ( std::fabs(cylindricalState( 0 )) <= std::numeric_limits< double >::epsilon( )\n && std::fabs(cylindricalState( 4 )) > std::numeric_limits< double >::epsilon( ) )\n {\n std::cerr << \"Warning: cylindrical velocity Vtheta (r*thetadot) does not equal zero while \"\n << \"the radius (r) is zero! Vtheta is taken equal to zero!\\n\";\n\n // Compute and set Cartesian velocities.\n cartesianState.tail( 3 )\n << cylindricalState( 3 ) * std::cos( azimuthAngle ), // xdot\n cylindricalState( 3 ) * std::sin( azimuthAngle ), // ydot\n cylindricalState( 5 ); // zdot\n }\n\n else\n {\n // Compute and set Cartesian velocities.\n cartesianState.tail( 3 )\n << cylindricalState( 3 ) * std::cos( azimuthAngle )\n - cylindricalState( 4 ) * std::sin( azimuthAngle ), // xdot\n cylindricalState( 3 ) * std::sin( azimuthAngle )\n + cylindricalState( 4 ) * std::cos( azimuthAngle ), // ydot\n cylindricalState( 5 ); // zdot\n }\n\n return cartesianState;\n}\n\n//! Convert Cartesian to cylindrical coordinates.\nEigen::Vector3d convertCartesianToCylindrical( const Eigen::Vector3d& cartesianCoordinates )\n{\n // Create cylindrical coordinates vector.\n Eigen::Vector3d cylindricalCoordinates;\n\n // Declare new variable, the azimuth angle.\n double azimuthAngle;\n\n // Compute azimuth angle, theta.\n /* If x = 0, then azimuthAngle = pi/2 (y>0) or 3*pi/2 (y<0) or 0 (y=0),\n else azimuthAngle = arctan(y/x).\n */\n using mathematical_constants::PI;\n if ( std::fabs(cartesianCoordinates( 0 ) ) <= std::numeric_limits< double >::epsilon( ) )\n {\n azimuthAngle = basic_mathematics::computeModulo(\n static_cast< double >( boost::math::sign( cartesianCoordinates( 1 ) ) )\n * 0.5 * PI, 2.0 * PI );\n }\n\n else\n {\n azimuthAngle = basic_mathematics::computeModulo(\n std::atan2( cartesianCoordinates( 1 ),\n cartesianCoordinates( 0 ) ), 2.0 * PI );\n }\n\n // Compute and set cylindrical coordinates.\n cylindricalCoordinates <<\n std::sqrt( pow( cartesianCoordinates( 0 ), 2 )\n + pow( cartesianCoordinates( 1 ), 2 ) ), // Radius\n azimuthAngle, // Azimuth angle, theta\n cartesianCoordinates( 2 ); // z-coordinate\n\n return cylindricalCoordinates;\n}\n\n//! Convert Cartesian to cylindrical state.\nbasic_mathematics::Vector6d convertCartesianToCylindricalState(\n const basic_mathematics::Vector6d& cartesianState )\n{\n // Create cylindrical state vector, initialized with zero entries.\n basic_mathematics::Vector6d cylindricalState = basic_mathematics::Vector6d::Zero( );\n\n // Compute and set cylindrical coordinates.\n cylindricalState.head( 3 ) = convertCartesianToCylindrical(\n Eigen::Vector3d( cartesianState.head( 3 ) ) );\n\n // Compute and set cylindrical velocities.\n /* If radius = 0, then Vr = sqrt(xdot^2+ydot^2) and Vtheta = 0,\n else Vr = (x*xdot+y*ydot)/radius and Vtheta = (x*ydot-y*xdot)/radius.\n */\n if ( cylindricalState( 0 ) <= std::numeric_limits< double >::epsilon( ) )\n {\n cylindricalState.tail( 3 ) <<\n std::sqrt( pow( cartesianState( 3 ), 2 ) + pow( cartesianState( 4 ), 2 ) ), // Vr\n 0.0, // Vtheta\n cartesianState( 5 ); // Vz\n }\n\n else\n {\n cylindricalState.tail( 3 ) <<\n ( cartesianState( 0 ) * cartesianState( 3 )\n + cartesianState( 1 ) * cartesianState( 4 ) ) / cylindricalState( 0 ), // Vr\n ( cartesianState( 0 ) * cartesianState( 4 )\n - cartesianState( 1 ) * cartesianState( 3 ) ) / cylindricalState( 0 ), // Vtheta\n cartesianState( 5 ); // Vz\n }\n\n return cylindricalState;\n}\n\n//! Convert spherical to Cartesian gradient.\nEigen::Vector3d convertSphericalToCartesianGradient( const Eigen::Vector3d& sphericalGradient,\n const Eigen::Vector3d& cartesianCoordinates )\n{\n // Compute radius.\n const double radius = std::sqrt( cartesianCoordinates( 0 ) * cartesianCoordinates( 0 )\n + cartesianCoordinates( 1 ) * cartesianCoordinates( 1 )\n + cartesianCoordinates( 2 ) * cartesianCoordinates( 2 ) );\n\n // Compute square of distance within xy-plane.\n const double xyDistanceSquared = cartesianCoordinates( 0 ) * cartesianCoordinates( 0 )\n + cartesianCoordinates( 1 ) * cartesianCoordinates( 1 );\n\n // Compute distance within xy-plane.\n const double xyDistance = std::sqrt( xyDistanceSquared );\n\n // Compute transformation matrix.\n const Eigen::Matrix3d transformationMatrix = (\n Eigen::Matrix3d( 3, 3 ) <<\n cartesianCoordinates( 0 ) / radius,\n - cartesianCoordinates( 0 ) * cartesianCoordinates( 2 )\n / ( radius * radius * xyDistance ),\n - cartesianCoordinates( 1 ) / xyDistanceSquared,\n cartesianCoordinates( 1 ) / radius,\n - cartesianCoordinates( 1 ) * cartesianCoordinates( 2 )\n / ( radius * radius * xyDistance ),\n + cartesianCoordinates( 0 ) / xyDistanceSquared,\n cartesianCoordinates( 2 ) / radius,\n xyDistance / ( radius * radius ),\n 0.0\n ).finished( );\n\n // Return Cartesian gradient.\n return transformationMatrix * sphericalGradient;\n}\n\n//! Convert spherical to Cartesian state.\nbasic_mathematics::Vector6d convertSphericalToCartesianState(\n const basic_mathematics::Vector6d& sphericalState )\n{\n // Create Cartesian state vector, initialized with zero entries.\n basic_mathematics::Vector6d convertedCartesianState = basic_mathematics::Vector6d::Zero( );\n\n // Create local variables.\n const double radius = sphericalState( 0 );\n const double azimuthAngle = sphericalState( 1 );\n const double elevationAngle = sphericalState( 2 );\n\n // Precompute sine/cosine of angles, which has multiple usages, to save computation time.\n const double cosineOfElevationAngle = std::cos( elevationAngle );\n const double sineOfElevationAngle = std::sin( elevationAngle );\n const double cosineOfAzimuthAngle = std::cos( azimuthAngle );\n const double sineOfAzimuthAngle = std::sin( azimuthAngle );\n\n // Set up transformation matrix for spherical to cylindrical conversion.\n Eigen::Matrix3d transformationMatrixSphericalToCylindrical = Eigen::Matrix3d::Zero( );\n transformationMatrixSphericalToCylindrical( 0, 0 ) = cosineOfElevationAngle;\n transformationMatrixSphericalToCylindrical( 0, 2 ) = -sineOfElevationAngle;\n transformationMatrixSphericalToCylindrical( 1, 1 ) = 1.0;\n transformationMatrixSphericalToCylindrical( 2, 0 ) = sineOfElevationAngle;\n transformationMatrixSphericalToCylindrical( 2, 2 ) = cosineOfElevationAngle;\n\n // Set up transformation matrix for cylindrical to Cartesian conversion.\n Eigen::Matrix3d transformationMatrixCylindricalToCartesian = Eigen::Matrix3d::Zero( );\n transformationMatrixCylindricalToCartesian( 0, 0 ) = cosineOfAzimuthAngle;\n transformationMatrixCylindricalToCartesian( 0, 1 ) = -sineOfAzimuthAngle;\n transformationMatrixCylindricalToCartesian( 1, 0 ) = sineOfAzimuthAngle;\n transformationMatrixCylindricalToCartesian( 1, 1 ) = cosineOfAzimuthAngle;\n transformationMatrixCylindricalToCartesian( 2, 2 ) = 1.0;\n\n // Compute transformation matrix for spherical to Cartesian conversion.\n const Eigen::Matrix3d transformationMatrixSphericalToCartesian\n = transformationMatrixCylindricalToCartesian\n * transformationMatrixSphericalToCylindrical;\n\n // Perform transformation of position coordinates.\n convertedCartesianState( 0 ) = radius * cosineOfAzimuthAngle * cosineOfElevationAngle;\n convertedCartesianState( 1 ) = radius * sineOfAzimuthAngle * cosineOfElevationAngle;\n convertedCartesianState( 2 ) = radius * sineOfElevationAngle;\n\n // Perform transformation of velocity vector.\n convertedCartesianState.segment( 3, 3 ) =\n transformationMatrixSphericalToCartesian * sphericalState.segment( 3, 3 );\n\n // Return Cartesian state vector.\n return convertedCartesianState;\n}\n\n//! Convert Cartesian to spherical state.\nbasic_mathematics::Vector6d convertCartesianToSphericalState(\n const basic_mathematics::Vector6d& cartesianState )\n{\n // Create spherical state vector, initialized with zero entries.\n basic_mathematics::Vector6d convertedSphericalState = basic_mathematics::Vector6d::Zero( );\n\n // Compute radius.\n convertedSphericalState( 0 ) = cartesianState.segment( 0, 3 ).norm( );\n\n // Check if radius is nonzero.\n /*\n * If r > 0, the elevation and azimuth angles are computed using trigonometric relationships.\n * If r = 0, the coordinates are at the origin, the elevation and azimuth angles equal to zero.\n * Since the state vector was initialized with zeroes, this is already the case.\n */\n if ( convertedSphericalState( 0 ) > std::numeric_limits< double >::epsilon( ) )\n {\n // Compute elevation and azimuth angles using trigonometric relationships.\n // Azimuth angle.\n convertedSphericalState( 1 ) = std::atan2( cartesianState( 1 ), cartesianState( 0 ) );\n // Elevation angle.\n convertedSphericalState( 2 ) = std::asin( cartesianState( 2 )\n / convertedSphericalState( 0 ) );\n }\n\n // Precompute sine/cosine of angles, which has multiple usages, to save computation time.\n const double cosineOfElevationAngle = std::cos( convertedSphericalState( 2 ) );\n const double sineOfElevationAngle = std::sin( convertedSphericalState( 2 ) );\n const double cosineOfAzimuthAngle = std::cos( convertedSphericalState( 1 ) );\n const double sineOfAzimuthAngle = std::sin( convertedSphericalState( 1 ) );\n\n // Set up transformation matrix for cylindrical to spherical conversion.\n Eigen::Matrix3d transformationMatrixCylindricalToSpherical = Eigen::Matrix3d::Zero( );\n transformationMatrixCylindricalToSpherical( 0, 0 ) = cosineOfElevationAngle;\n transformationMatrixCylindricalToSpherical( 0, 2 ) = sineOfElevationAngle;\n transformationMatrixCylindricalToSpherical( 1, 1 ) = 1.0;\n transformationMatrixCylindricalToSpherical( 2, 0 ) = -sineOfElevationAngle;\n transformationMatrixCylindricalToSpherical( 2, 2 ) = cosineOfElevationAngle;\n\n // Set up transformation matrix for Cartesian to cylindrical conversion.\n Eigen::Matrix3d transformationMatrixCartesianToCylindrical = Eigen::Matrix3d::Zero( );\n transformationMatrixCartesianToCylindrical( 0, 0 ) = cosineOfAzimuthAngle;\n transformationMatrixCartesianToCylindrical( 0, 1 ) = sineOfAzimuthAngle;\n transformationMatrixCartesianToCylindrical( 1, 0 ) = -sineOfAzimuthAngle;\n transformationMatrixCartesianToCylindrical( 1, 1 ) = cosineOfAzimuthAngle;\n transformationMatrixCartesianToCylindrical( 2, 2 ) = 1.0;\n\n // Compute transformation matrix for Cartesian to spherical conversion.\n const Eigen::Matrix3d transformationMatrixCartesianToSpherical\n = transformationMatrixCylindricalToSpherical\n * transformationMatrixCartesianToCylindrical;\n\n // Perform transformation of velocity vector.\n convertedSphericalState.segment( 3, 3 )\n = transformationMatrixCartesianToSpherical * cartesianState.segment( 3, 3 );\n\n // Return spherical state vector.\n return convertedSphericalState;\n}\n\n} // namespace coordinate_conversions\n\n} // namespace tudat\n", "meta": {"hexsha": "4e56e6b3f1e89f21166332a8f4a6b6f920bc877d", "size": 21171, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tudat/Mathematics/BasicMathematics/coordinateConversions.cpp", "max_stars_repo_name": "JPelamatti/ThesisTUDAT", "max_stars_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tudat/Mathematics/BasicMathematics/coordinateConversions.cpp", "max_issues_repo_name": "JPelamatti/ThesisTUDAT", "max_issues_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tudat/Mathematics/BasicMathematics/coordinateConversions.cpp", "max_forks_repo_name": "JPelamatti/ThesisTUDAT", "max_forks_repo_head_hexsha": "b94ce35fb7c8fa44ae83238e296a979dfa3adfe8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-30T03:42:22.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-30T03:42:22.000Z", "avg_line_length": 47.4686098655, "max_line_length": 99, "alphanum_fraction": 0.6569363752, "num_tokens": 4808, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245787544825, "lm_q2_score": 0.8244619220634456, "lm_q1q2_score": 0.6870443839026318}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nusing namespace cv;\n// define VecVec2d and VecVec3d\ntypedef vector> VecVector2d;\ntypedef vector> VecVector3d;\n\n// Functions Get the matching points\nvoid find_feature_matches(const Mat &img_1, const Mat &img_2,std::vector &keypoints_1,\n std::vector &keypoints_2,std::vector &matches);\n\n// Functions to Change the pixel points into camera normalization points\nPoint2d pixel2cam(const Point2d &p, const Mat &K);\n\n// Bundle Adjustment By Gauss-Newton\nvoid bundleAdjustmentGaussNewton(\n const VecVector3d &points_3d, \n const VecVector2d &points_2d,\n const Mat &K, \n Sophus::SE3d &pose // need to be optimazied\n);\n\n// Bundle Adjustment By G2O\nvoid bundleAdjustmentG2O(\n const VecVector3d &points_3d, \n const VecVector2d &points_2d,\n const Mat &K,\n Sophus::SE3d &pose\n);\n\nint main(int argc, char const *argv[]){\n if(argc!=5){\n cout<<\"Usage (bash): pose_estimation3d2d.cpp \"< keypoints_1, keypoints_2;\nvector matches;\nfind_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\ncout << \"Totally found \" << matches.size() << \" matches\" << endl;\n\n// Build 3d -2d reflections\n\n// depth image is 16-bit unchar mono-channel picture\nMat rgbd_image01 = imread(argv[3], CV_LOAD_IMAGE_UNCHANGED);\nMat camera_K = (Mat_(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1); \nvector pts_3d;\nvector pts_2d;\nfor(DMatch m :matches){\n // reference : Mat.ptr(int a)[int b] : means the pixel in row a, col b.\n // get the keypoint's deep\nushort d = rgbd_image01.ptr(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)]; \nif(d==0) continue; \nfloat normalized_d = d /1000.0;\nPoint2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt,camera_K);\npts_3d.push_back(Point3f(p1.x*normalized_d,p1.y*normalized_d,normalized_d)); // keypint one's 3d , 相机坐标\npts_2d.push_back(keypoints_2[m.trainIdx].pt); // keypoint2 :only 2d\n}\n\n// Solve PNP using OpenCV\nMat r, t; // r is rotation vector , t is translation vector\nsolvePnP(pts_3d,pts_2d,camera_K,Mat(),r,t, false, cv::SOLVEPNP_EPNP);\nMat inliners;\nbool result = solvePnPRansac(pts_3d,pts_2d,camera_K,Mat(),r,t,false,100,4.0,0.99,inliners);\ncout< &keypoints_1,\n std::vector &keypoints_2,\n std::vector &matches) {\n //-- 初始化\n Mat descriptors_1, descriptors_2;\n // used in OpenCV3\n Ptr detector = ORB::create();\n Ptr descriptor = ORB::create();\n // use this if you are in OpenCV2\n // Ptr detector = FeatureDetector::create ( \"ORB\" );\n // Ptr descriptor = DescriptorExtractor::create ( \"ORB\" );\n Ptr matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n //-- 第一步:检测 Oriented FAST 角点位置\n detector->detect(img_1, keypoints_1);\n detector->detect(img_2, keypoints_2);\n\n //-- 第二步:根据角点位置计算 BRIEF 描述子\n descriptor->compute(img_1, keypoints_1, descriptors_1);\n descriptor->compute(img_2, keypoints_2, descriptors_2);\n\n //-- 第三步:对两幅图像中的BRIEF描述子进行匹配,使用 Hamming 距离\n vector match;\n //BFMatcher matcher ( NORM_HAMMING );\n matcher->match(descriptors_1, descriptors_2, match);\n\n //-- 第四步:匹配点对筛选\n double min_dist = 10000, max_dist = 0;\n\n //找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离\n for (int i = 0; i < descriptors_1.rows; i++) {\n double dist = match[i].distance;\n if (dist < min_dist) min_dist = dist;\n if (dist > max_dist) max_dist = dist;\n }\n //当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.但有时候最小距离会非常小,设置一个经验值30作为下限.\n for (int i = 0; i < descriptors_1.rows; i++) {\n if (match[i].distance <= max(2 * min_dist, 30.0)) {\n matches.push_back(match[i]);\n }\n }\n}\n\nPoint2d pixel2cam(const Point2d &p, const Mat &K) {\n return Point2d\n (\n (p.x - K.at(0, 2)) / K.at(0, 0),\n (p.y - K.at(1, 2)) / K.at(1, 1)\n );\n}\n\n\nvoid bundleAdjustmentGaussNewton(\n const VecVector3d &points_3d,\n const VecVector2d &points_2d,\n const Mat &K,\n Sophus::SE3d &pose) {\n typedef Eigen::Matrix Vector6d; // because Se(3) is a 6 dim vector, First 3 P is translation, Second 3 Fi is rotatiom\n const int iterations = 10;\n double cost = 0, lastCost = 0;\n /// camera model//\n // X' = f(X/Z) Y'= f(Y/Z)\n // u = aX' +cx v= bY' + cy\n \n // Camera inner parameter\n // [ fx, 0 , cx ]\n // K = [ 0, fx, cy ]\n // [ 0, 0, 1 ]\n double fx = K.at(0, 0);\n double fy = K.at(1, 1);\n double cx = K.at(0, 2);\n double cy = K.at(1, 2);\n\n for (int iter = 0; iter < iterations; iter++) {\n Eigen::Matrix H = Eigen::Matrix::Zero(); //这里之所以是 6 x 6 是因为J(x)TJ(X) = H, J(X)是2 x 6 \n Vector6d b = Vector6d::Zero(); // b = J(x)Tf(x), J(x)T是 6 x 2, f(x)是 x,y 2个维度的误差,所以是2 x 1.\n cost = 0;\n // compute cost\n for (int i = 0; i < points_3d.size(); i++) {\n Eigen::Vector3d pc = pose * points_3d[i];\n double inv_z = 1.0 / pc[2]; // 1/Z'\n double inv_z2 = inv_z * inv_z; // 1/Z^2\n Eigen::Vector2d proj(fx * pc[0] / pc[2] + cx, fy * pc[1] / pc[2] + cy);\n\n Eigen::Vector2d e = points_2d[i] - proj; // 重投影误差\n\n cost += e.squaredNorm();\n Eigen::Matrix 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点累加\n b += -J.transpose() * e;\n }\n\n Vector6d dx;\n dx = H.ldlt().solve(b); // 更新 se3\n\n if (isnan(dx[0])) {\n cout << \"result is nan!\" << endl;\n break;\n }\n\n if (iter > 0 && cost >= lastCost) {\n // cost increase, update is not good\n cout << \"cost: \" << cost << \", last cost: \" << lastCost << endl;\n break;\n }\n\n // update your estimation // 更新SE(3)\n pose = Sophus::SE3d::exp(dx) * pose; \n lastCost = cost;\n\n cout << \"iteration \" << iter << \" cost=\" << std::setprecision(12) << cost << endl;\n if (dx.norm() < 1e-6) { // 当需要更新的左乘se(3)足够小。\n // converge\n break;\n }\n }\n cout << \"pose by g-n: \\n\" << pose.matrix() << endl;\n\n}\n\n// 定义 Vertex 和 Edge\n\nclass VertexPose : public g2o::BaseVertex<6, Sophus::SE3d>{\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW; // Eigen 内部处理动态分配变量的对齐问题\n // setToOriginImpl()用来重置优化变量, 这里初始化一个空 的 SE3\n // 这里使用虚函数的原因是由C++11新特性,重写了父类的虚函数\n virtual void setToOriginImpl() override {\n _estimate = Sophus::SE3d(); \n }\n /// left multiplication on SE3, setToOriginImpl()用来Upfate优化变量,这里使用左乘来更新\n virtual void oplusImpl(const double *update) override {\n Eigen::Matrix update_eigen;\n update_eigen << update[0], update[1], update[2], update[3], update[4], update[5];\n _estimate = Sophus::SE3d::exp(update_eigen) * _estimate;\n }\n virtual bool read(istream &in) override {}\n\n virtual bool write(ostream &out) const override {}\n};\n\n/// 定义边, 也就是重新投影误差, 我们知道重投影误差为2位, 类型是vector2d, 优化对象的类型是一个VertexPose\nclass EdgeProjection : public g2o::BaseUnaryEdge<2, Eigen::Vector2d, VertexPose> {\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n // 构造函数\n EdgeProjection(const Eigen::Vector3d &pos, const Eigen::Matrix3d &K) : _pos3d(pos), _K(K) {}\n// 计算重新投影误差\n virtual void computeError() override {\n const VertexPose *v = static_cast (_vertices[0]);\n Sophus::SE3d T = v->estimate(); // 获得顶点的观测value\n Eigen::Vector3d pos_pixel = _K * (T * _pos3d); // // K TP = s[u,v]\n pos_pixel /= pos_pixel[2]; // 齐次到非齐次\n _error = _measurement - pos_pixel.head<2>(); //_measurement:存储观测值\n }\n // 更新操作, 定义Jaco矩阵即可,这里使用就是G-N法\n virtual void linearizeOplus() override {\n const VertexPose *v = static_cast (_vertices[0]);\n Sophus::SE3d T = v->estimate();\n Eigen::Vector3d pos_cam = T * _pos3d; \n double fx = _K(0, 0);\n double fy = _K(1, 1);\n double cx = _K(0, 2);\n double cy = _K(1, 2);\n double X = pos_cam[0];\n double Y = pos_cam[1];\n double Z = pos_cam[2];\n double Z2 = Z * Z;\n _jacobianOplusXi\n << -fx / Z, 0, fx * X / Z2, fx * X * Y / Z2, -fx - fx * X * X / Z2, fx * Y / Z,\n 0, -fy / Z, fy * Y / (Z * Z), fy + fy * Y * Y / Z2, -fy * X * Y / Z2, -fy * X / Z;\n };\n\n virtual bool read(istream &in) override {}\n\n virtual bool write(ostream &out) const override {}\n\nprivate:\n Eigen::Vector3d _pos3d;\n Eigen::Matrix3d _K;\n};\n\nvoid bundleAdjustmentG2O(\n const VecVector3d &points_3d, \n const VecVector2d &points_2d,\n const Mat &K,\n Sophus::SE3d &pose\n){\n // 构建图优化,先设定g2o\n // pose is 6 , 3 for rotation, 3 for translation. landmark is 3 : X,Y,Z,观测点的维度\n typedef g2o::BlockSolver> BlockSolverType; // pose is 6, landmark is 3\n typedef g2o::LinearSolverDense LinearSolverType; // 线性求解器, 去优化Pose Matrix\n // 梯度下降方法,可以从GN, LM, DogLeg 中选, 接受一个BlockSolverType,用Linear\n auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n g2o::make_unique(g2o::make_unique()));\n\n g2o::SparseOptimizer optimizer; // 图模型\n optimizer.setAlgorithm(solver); // 设置求解器\n optimizer.setVerbose(true); // 打开调试输出\n\n // 下面开始往图里面添加 Vertex 和 Edge\n // vertex, 只有一个R,t\n VertexPose *vertex_pose = new VertexPose(); // camera vertex_pose\n vertex_pose->setId(0);\n vertex_pose->setEstimate(Sophus::SE3d());\n optimizer.addVertex(vertex_pose);\n\n // Camera K\n Eigen::Matrix3d K_eigen;\n K_eigen <<\n K.at(0, 0), K.at(0, 1), K.at(0, 2),\n K.at(1, 0), K.at(1, 1), K.at(1, 2),\n K.at(2, 0), K.at(2, 1), K.at(2, 2);\n\n // edges\n int index = 1;\n for (size_t i = 0; i < points_2d.size(); ++i) {\n auto p2d = points_2d[i];\n auto p3d = points_3d[i];\n EdgeProjection *edge = new EdgeProjection(p3d, K_eigen);\n edge->setId(index);\n edge->setVertex(0, vertex_pose); // 对应成员函数_vertex\n edge->setMeasurement(p2d); // 对应成员函数_mesurement\n edge->setInformation(Eigen::Matrix2d::Identity()); // 图中的Q就是信息矩阵,为了表示我们对误差各分量重视程度的不一样。\n // 一般情况下,我们都设置这个矩阵为单位矩阵,表示我们对所有的误差分量的重视程度都一样。\n optimizer.addEdge(edge);\n index++;\n }\n optimizer.setVerbose(true);\n optimizer.initializeOptimization();\n optimizer.optimize(10);\n cout << \"pose estimated by g2o =\\n\" << vertex_pose->estimate().matrix() << endl;\n pose = vertex_pose->estimate();\n}", "meta": {"hexsha": "70c85929dc6c6c1d1ed363a763647d8a5f430177", "size": 12406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "vision_slam/VO/pose_estimation/pose_estimation_3d2d.cpp", "max_stars_repo_name": "kant/VO", "max_stars_repo_head_hexsha": "2acf9cb88eb2ec43adc272b57fd140bcace53e97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-20T04:52:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-20T04:52:45.000Z", "max_issues_repo_path": "vision_slam/VO/pose_estimation/pose_estimation_3d2d.cpp", "max_issues_repo_name": "kant/VO", "max_issues_repo_head_hexsha": "2acf9cb88eb2ec43adc272b57fd140bcace53e97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "vision_slam/VO/pose_estimation/pose_estimation_3d2d.cpp", "max_forks_repo_name": "kant/VO", "max_forks_repo_head_hexsha": "2acf9cb88eb2ec43adc272b57fd140bcace53e97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-05T23:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-05T23:30:49.000Z", "avg_line_length": 34.7507002801, "max_line_length": 134, "alphanum_fraction": 0.6474286635, "num_tokens": 4565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.68703709162585}} {"text": "#ifndef SEGWAY_SIM_COMMON_H\n#define SEGWAY_SIM_COMMON_H\n\n#include \"segway_sim/CyberTimer.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic const uint32_t STATE_LENGTH = 7;\nstatic const uint32_t INPUT_LENGTH = 2;\nstatic const uint32_t CMD_LENGTH = 2;\n\ninline void quat2eulZYX(const Eigen::Quaterniond &q,\n Eigen::Vector3d &eul)\n{\n\tdouble eul_tmp = 2.0 * (q.y() * q.y());\n\teul(0) = atan2(2.0 * q.w() * q.x() + 2.0 * q.y() * q.z(), (1.0 - 2.0 * (q.x() * q.x())) - eul_tmp);\n\t\n\tdouble sinp = +2.0 * (q.w() * q.y() - q.z() * q.x());\n\tif (abs(sinp) >= 1)\n\t\teul(1) = copysign(M_PI / 2, sinp); // use 90 degrees if out of range\n\telse\n\t\teul(1) = asin(sinp);\n\n\teul(2) = atan2(2.0 * q.w() * q.z() + 2.0 * q.x() * q.y(), (1.0 - eul_tmp) - 2.0 * (q.z() * q.z()));\n}\n\ninline void quat2rotm(const Eigen::Quaterniond &q,\n Eigen::Matrix3d &rotm)\n{\n\trotm(0,0) = 1-2*q.y()*q.y()-2*q.z()*q.z();\n\trotm(0,1) = 2*q.x()*q.y()-2*q.z()*q.w();\n\trotm(0,2) = 2*q.x()*q.z()+2*q.y()*q.w();\n\trotm(1,0) = 2*q.x()*q.y()+2*q.z()*q.w();\n\trotm(1,1) = 1-2*q.x()*q.x()-2*q.z()*q.z();\n\trotm(1,2) = 2*q.y()*q.z()-2*q.x()*q.w();\n\trotm(2,0) = 2*q.x()*q.z()-2*q.y()*q.w();\n\trotm(2,1) = 2*q.y()*q.z()+2*q.x()*q.w();\n\trotm(2,2) = 1-2*q.x()*q.x()-2*q.y()*q.y();\n}\n\ninline void eul2quatZYX(const Eigen::Vector3d &eul,\n Eigen::Quaterniond &q)\n{\n\tdouble cy = cos(eul(2) * 0.5);\n\tdouble sy = sin(eul(2) * 0.5);\n\tdouble cp = cos(eul(1) * 0.5);\n\tdouble sp = sin(eul(1) * 0.5);\n\tdouble cr = cos(eul(0) * 0.5);\n\tdouble sr = sin(eul(0) * 0.5);\n\n\tq.w() = cy * cp * cr + sy * sp * sr;\n\tq.x() = cy * cp * sr - sy * sp * cr;\n\tq.y() = sy * cp * sr + cy * sp * cr;\n\tq.z() = sy * cp * cr - cy * sp * sr;\n}\n\ninline void removeYaw(Eigen::Quaterniond &q)\n{\n\tEigen::Vector3d eul;\n\tquat2eulZYX(q,eul);\n\teul(2) = 0;\n\teul2quatZYX(eul,q);\n}\n\ninline Eigen::Matrix3d rotx(double angle)\n{\n\tEigen::Matrix3d rotm;\n\trotm(0,0) = 1; rotm(0,1) = 0; rotm(0,2) = 0;\n\trotm(1,0) = 0; rotm(1,1) = cos(angle); rotm(1,2) = -sin(angle);\n\trotm(2,0) = 0; rotm(2,1) = sin(angle); rotm(2,2) = cos(angle);\n\treturn rotm;\n}\n\ninline Eigen::Matrix3d roty(double angle)\n{\n\tEigen::Matrix3d rotm;\n\trotm(0,0) = cos(angle); rotm(0,1) = 0; rotm(0,2) = sin(angle);\n\trotm(1,0) = 0; rotm(1,1) = 1; rotm(1,2) = 0;\n\trotm(2,0) = -sin(angle); rotm(2,1) = 0; rotm(2,2) = cos(angle);\n\treturn rotm;\n}\n\ninline Eigen::Matrix3d rotz(double angle)\n{\n\tEigen::Matrix3d rotm;\n\trotm(0,0) = cos(angle); rotm(0,1) = -sin(angle); rotm(0,2) = 0;\n\trotm(1,0) = sin(angle); rotm(1,1) = cos(angle); rotm(1,2) = 0;\n\trotm(2,0) = 0; rotm(2,1) = 0; rotm(2,2) = 1;\n\treturn rotm;\n}\n\ninline double deg2rad(double angle)\n{\n\treturn angle*M_PI/180.0;\n}\n\ninline double rad2deg(double angle)\n{\n\treturn angle*180.0/M_PI;\n}\n\ninline double saturate(double in, double min, double max)\n{\n\tdouble out;\n\tif(min>max)\n\t{\n\t\tdouble tmp = max;\n\t\tmax = min;\n\t\tmin = tmp;\n\t}\n\n\tif(in>max)\n\t\tout = max;\n\telse if(inmax)\n\t{\n\t\tdouble tmp = max;\n\t\tmax = min;\n\t\tmin = tmp;\n\t}\n\n\tif(in>max)\n\t\tin = max;\n\telse if(inmax)\n\t{\n\t\tdouble tmp = max;\n\t\tmax = min;\n\t\tmin = tmp;\n\t}\n\n\tfor(uint32_t i = 0; imax)\n\t\t\tin[i] = max;\n\t\telse if(in[i]\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate\nvoid printMat(const T& mat, int size){\n for (int i = 0; i < size; i++){\n for (int j = 0; j < size - 1; j++){\n std::cout << mat(i, j) << \", \";\n }\n std::cout << mat(i, size - 1) << std::endl;\n }\n}\n\nvoid hMatrixSolver(\n const std::vector& matches,\n const std::vector& pts1,\n const std::vector& pts2,\n Eigen::Matrix3d& H\n) {\n int size = matches.size();\n Eigen::Matrix3Xd P(3, size);\n Eigen::Matrix3Xd Q(3, size);\n P.setZero();\n Q.setZero();\n #pragma omp parallel for num_threads(8)\n for (size_t i = 0; i < matches.size(); i++) {\n const cv::Point2f& _p1 = pts1[matches[i].queryIdx].pt;\n const cv::Point2f& _p2 = pts2[matches[i].trainIdx].pt;\n P.block<3, 1>(0, i) = Eigen::Vector3d(_p1.x, _p1.y, 1);\n Q.block<3, 1>(0, i) = Eigen::Vector3d(_p2.x, _p2.y, 1);\n }\n Eigen::Matrix3d PPT = P * P.transpose();\n Eigen::Matrix3d inv = (PPT).ldlt().solve(Eigen::Matrix3d::Identity()); // LDLT分解求逆矩阵 (PP^T)\n Eigen::Matrix3d res = PPT * inv;\n H = Q * P.transpose() * inv;\n}\n\nvoid featureExtract(\n const cv::Mat& src1,\n const cv::Mat& src2,\n cv::Mat& dst,\n Eigen::Matrix3d& H\n){\n std::vector matches;\n std::vector pts1, pts2;\n #define POINT_NUM 64\n cv::Mat dscp1, dscp2;\n #pragma omp parallel sections\n {\n #pragma omp section\n {\n cv::Ptr det1 = cv::ORB::create(POINT_NUM);\n cv::Ptr des1 = cv::ORB::create(POINT_NUM);\n det1->detectAndCompute(src1, cv::noArray(), pts1, dscp1);\n }\n #pragma omp section\n {\n cv::Ptr det2 = cv::ORB::create(POINT_NUM);\n cv::Ptr des2 = cv::ORB::create(POINT_NUM);\n det2->detectAndCompute(src2, cv::noArray(), pts2, dscp2);\n }\n }\n std::cout << \"Parallel ORB descriptors found.\\n\";\n cv::Ptr match = cv::DescriptorMatcher::create(cv::DescriptorMatcher::BRUTEFORCE_HAMMINGLUT);\n match->match(dscp1, dscp2, matches);\n std::cout << \"ORB descriptors matched.\\n\";\n std::vector crn1, crn2;\n for (const cv::DMatch& mt: matches){\n crn1.push_back(pts1[mt.queryIdx].pt);\n crn2.push_back(pts2[mt.trainIdx].pt);\n }\n cv::Mat mask;\n \n cv::Mat cvH = cv::findHomography(crn1, crn2, mask, cv::RANSAC, 16);\n printf(\"Homography found. mask is %d, %d, %d, %d\\n\", mask.cols, mask.rows, mask.type(), CV_8UC1);\n printf(\"The original match num is %lu.\\n\", matches.size());\n std::vector truth;\n for (size_t i = 0; i < matches.size(); i++){\n if (mask.at(i) == 1){\n truth.push_back(matches[i]);\n }\n }\n cv::drawMatches(src1, pts1, src2, pts2, truth, dst);\n hMatrixSolver(truth, pts1, pts2, H);\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n printf(\"%lf, \", cvH.at(i, j));\n }\n printf(\"\\n\");\n }\n}\n\n\n/// 可视化\nvoid alignmentVisualize(const cv::Mat& src, cv::Mat&dst, Eigen::Matrix3d H) {\n dst.create(src.rows, src.cols, CV_8UC3);\n #pragma for num_threads(8);\n for (int i = 0; i < src.rows; i++) {\n for (int j = 0; j < src.cols; j++) {\n Eigen::Vector3d now(j, i, 1.0);\n Eigen::Vector3d trans = H * now;\n int px = trans[0], py = trans[1];\n if (px >= 0 && px < dst.cols && py >= 0 && py < dst.rows) {\n dst.at(py, px) = src.at(i, j);\n } \n }\n }\n}\n\nint main() {\n cv::Mat src1 = cv::imread(\"../data/ImageA.jpg\");\n cv::Mat src2 = cv::imread(\"../data/ImageB.jpg\");\n cv::Mat gray1, gray2;\n cv::cvtColor(src1, gray1, cv::COLOR_BGR2GRAY);\n cv::cvtColor(src2, gray2, cv::COLOR_BGR2GRAY);\n cv::equalizeHist(gray1, gray1);\n cv::equalizeHist(gray2, gray2);\n cv::Mat aligned;\n cv::Mat feats;\n\n Eigen::Matrix3d H;\n\n featureExtract(gray1, gray2, feats, H);\n std::cout << \"H matrix is:\\n\";\n printMat(H, 3);\n cv::imwrite(\"../data/features.jpg\", feats);\n\n alignmentVisualize(src1, aligned, H);\n cv::imwrite(\"../data/result.jpg\", aligned);\n return 0;\n}", "meta": {"hexsha": "af1ae2bba3d655b1ffc8051dacdaef4a760f682a", "size": 4620, "ext": "cc", "lang": "C++", "max_stars_repo_path": "second/align.cc", "max_stars_repo_name": "Enigmatisms/DIP", "max_stars_repo_head_hexsha": "f8dcbfc60bcb7be3d79d52e23c689e214f79630b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-28T09:03:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-28T09:03:39.000Z", "max_issues_repo_path": "second/align.cc", "max_issues_repo_name": "Enigmatisms/DIP", "max_issues_repo_head_hexsha": "f8dcbfc60bcb7be3d79d52e23c689e214f79630b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "second/align.cc", "max_forks_repo_name": "Enigmatisms/DIP", "max_forks_repo_head_hexsha": "f8dcbfc60bcb7be3d79d52e23c689e214f79630b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3076923077, "max_line_length": 119, "alphanum_fraction": 0.5681818182, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070133672955, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6869024410469349}} {"text": "/**\n * Kalman Filter \n * Skeleton code for teaching \n * A3M33MKR\n * Czech Technical University \n * Faculty of Electrical Engineering\n * Intelligent and Mobile Robotics group\n *\n * Authors: Zdeněk Kasl, Karel Košnar kosnar@labe.felk.cvut.cz\n *\n * this code is inspired by tutorial on Kalman Filter by Greg Czerniak \n *\n * Licence: MIT (see LICENSE file)\n **/\n/*TODO set up the convarience matrices better and re-measure the noice constants (process noise/measurenment noice)*/\n\n#include\n#include\n#include\n#include\n#include\n#include \n\n#include \"gui/gui.h\"\n#include \"systemSimulator/system.h\"\n\nusing namespace imr;\nusing namespace gui;\nusing namespace Eigen;\nusing namespace std;\n\n#define PRINT(name) Print(#name, (name))\n\nvoid Print(const char *name, Matrix4f m);\n\nPoint KalmanFilter(Point measuredPosition);\n\nIOFormat CleanFmt(4, 0, \", \", \"\\n\", \"[\", \"]\");\n\nMatrix4f A, B, Sigma, R, Q, E, C;\n//Matrix2f Q;\n//Matrix C;\nVector4f mu, u;\nfloat dt = 0.1;\n\n//noice constants\ndouble q = 100;\ndouble r = 0.1;\n\n//step constant\nint step = 10;\n\nvoid initMatrices() {\n A << 1, 0, dt, 0,\n 0, 1, 0, dt,\n 0, 0, 1, 0,\n 0, 0, 0, 1;\n\n B << 0, 0, 0, 0,\n 0, -0.5 * dt * dt, 0, 0,\n 0, 0, 0, 0,\n 0, 0, 0, -dt;\n\n u << 9.8, 9.8, 9.8, 9.8;\n\n mu << -300, 100, 0, 0;\n\n Sigma << 0.1, 0, 0, 0,\n 0, 0.1, 0, 0,\n 0, 0, 0.1, 0,\n 0, 0, 0, 0.1;\n\n// /Noice consts.\n//-------------------------------------------------------------------\n C << 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1;\n\n Q << q, 0, 0, 0,\n 0, q, 0, 0,\n 0, 0, q, 0,\n 0, 0, 0, q;\n\n R << r, 0, 0, 0,\n 0, r, 0, 0,\n 0, 0, r, 0,\n 0, 0, 0, r;\n//-------------------------------------------------------------------\n E << 1, 0, 0, 0,\n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1;\n}\n\n\nvoid help(char **argv) {\n std::cout << \"\\nUsage of the program \" << argv[0] + 2 << std::endl\n << \"Parameter [-h or -H] displays this message.\" << std::endl\n << \" Parametr [-n or -N] number of simulation steps.\"\n << std::endl;\n}\n\nint main(int argc, char **argv) {\n int nSteps = 1000;\n char *dataFile;\n\n // Parse all console parameters\n for (int i = 0; i < argc; i++) {\n if (argv[i][0] == '-') {\n switch (argv[i][1]) {\n //> HELP\n case 'H' :\n case 'h' :\n help(argv);\n break;\n case 'N':\n case 'n':\n assert(i + 1 < argc);\n assert(atoi(argv[i + 1]) > 1);\n step = atoi(argv[i + 1]);\n break;\n default :\n std::cout << \"Parameter \\033[1;31m\" << argv[i] << \"\\033[0m is not valid!\\n\"\n << \"Use parameter -h or -H for help.\" << std::endl;\n break;\n }\n }\n }\n // All parameters parsed\n\n Gui gui;\n System system;\n\n //> comment line below in order to let the program\n //> continue right away\n gui.startInteractor();\n\n initMatrices();\n\n Point measurement;\n Point truth;\n Point kfPosition;\n\n\n for (int i = 1; i < nSteps; i++) {\n system.makeStep();\n truth = system.getTruthPosition();\n measurement = system.getMeasurement();\n kfPosition = KalmanFilter(measurement);\n gui.setPoints(truth, measurement, kfPosition);\n\n //> comment line below in order to let the program\n //> continue right away\n //if (i % step == 0) gui.startInteractor();\n\n }\n gui.startInteractor();\n return EXIT_SUCCESS;\n}\n\n\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n// implement Kalman Filter here\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\nPoint KalmanFilter(const Point measuredPosition) {\n Point ret;\n Vector4f mu_actual, z, y;\n Matrix4f Sigma_actual, K, S, S_inv;\n\n z << measuredPosition.x,\n measuredPosition.y,\n 0,\n 0;\n\n PRINT(A);\n PRINT(C);\n //-------------------------------------------------------------------------------\n mu_actual = A * mu + B * u;\n\n //Error estimation\n //-------------------------------------------------------------------------------\n Sigma_actual = A * Sigma * A.transpose() + R;\n PRINT(Sigma_actual);\n\n //K gain\n //-------------------------------------------------------------------------------\n S = C * Sigma_actual * C.transpose() + Q;\n PRINT(S);\n\n K = Sigma_actual * C.transpose() * S.inverse();\n PRINT(K);\n\n //improvement\n //-------------------------------------------------------------------------------\n y = z - C * mu_actual;\n mu = mu_actual + K * y;\n Sigma = (E - K * C) * Sigma_actual;\n PRINT(Sigma);\n\n ret.x = mu(0);\n ret.y = mu(1);\n\n //Simulation of system\n //ret.x = mu_actual(0);\n //ret.y = mu_actual(1);\n //mu = mu_actual;\n\n cout << \"X: \" << ret.x << \" Y: \" << ret.y <<\n \" Vx: \" << mu(2) << \" Vy: \" << mu(3) << endl;\n cout << \"-------------------------------------------------------------------\" << endl;\n\n return ret;\n}\n\nvoid Print(const char *name, Matrix4f m){\n cout << name << \": \" << endl;\n cout << m.format(CleanFmt) << endl;\n cout << \"-------------------------------------------------------------------\" << endl;\n}\n\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\n\n", "meta": {"hexsha": "8c561f41e28422cf1a62ac1e3d875f0b9ed8fcf8", "size": 5868, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kf_main.cpp", "max_stars_repo_name": "ondrejKunte/Kalman", "max_stars_repo_head_hexsha": "997f3c4979cd303fd654e81cb1db4d35f2391c2c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kf_main.cpp", "max_issues_repo_name": "ondrejKunte/Kalman", "max_issues_repo_head_hexsha": "997f3c4979cd303fd654e81cb1db4d35f2391c2c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kf_main.cpp", "max_forks_repo_name": "ondrejKunte/Kalman", "max_forks_repo_head_hexsha": "997f3c4979cd303fd654e81cb1db4d35f2391c2c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6244541485, "max_line_length": 117, "alphanum_fraction": 0.4074642127, "num_tokens": 1612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311355, "lm_q2_score": 0.7905303186696748, "lm_q1q2_score": 0.686833913658352}} {"text": "// Software License for MTL\r\n//\r\n// Copyright (c) 2007 The Trustees of Indiana University.\r\n// 2008 Dresden University of Technology and the Trustees of Indiana University.\r\n// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\r\n// All rights reserved.\r\n// Authors: Shikhar Vashistha\r\n//\r\n// This file is part of the Matrix Template Library\r\n//\r\n// See also license.mtl.txt in the distribution.\r\n\r\n#include \r\n#include \r\n#include \r\n\r\n\r\nusing namespace std;\r\n\r\n\r\ndouble f(double) { /* cout << \"double\\n\"; */ return 1.0; }\r\ncomplex f(complex)\r\n{\r\n //cout << \"complex\\n\"; \r\n return complex(1.0, -1.0);\r\n}\r\n\r\n\r\nint main(int, char**)\r\n{\r\n using namespace mtl; using mtl::io::tout;\r\n unsigned size = 4, row = size + 1, col = size;\r\n\r\n double tol(0.00001);\r\n dense_vector vec(size), vec1(size);\r\n dense2D A(row, col), Q(row, row), R(row, col), A_test(row, col),\r\n A_t(col, row), Q_t(col, col), R_t(col, row), A_t_test(col, row);\r\n dense2D > dz(row, col), Qz(row, row), Rz(row, col);\r\n dense2D > dc(size, size);\r\n compressed2D Ac(size, size), Qc(size, size), Rc(size, size), A_testc(size, size);\r\n A = 0;\r\n\r\n A[0][0] = 1; A[0][1] = 1; A[0][2] = 1;\r\n A[1][0] = 3; A[1][1] = -1; A[1][2] = -2;\r\n A[2][0] = 1; A[2][1] = 7; A[2][2] = 1;\r\n A[3][3] = -10; A[4][0] = 4; A[4][2] = 3;\r\n tout << \"A=\\n\" << A << \"\\n\";\r\n laplacian_setup(Ac, 2, 2);\r\n\r\n\r\n tout << \"START-----dense2d---------row > col\\n\";\r\n\r\n dense2D A1(A[iall][iall]), A2(A);\r\n boost::tie(Q, R) = lq(A1);\r\n tout << \"R=\\n\" << R << \"\\n\";\r\n tout << \"Q=\\n\" << Q << \"\\n\";\r\n A_test = Q * R - A2;\r\n tout << \"Q*R=\\n\" << Q * R << \"\\n\";\r\n\r\n tout << \"one_norm(Rest A)=\" << one_norm(A_test) << \"\\n\";\r\n MTL_THROW_IF(one_norm(A_test) > tol, mtl::logic_error(\"wrong LQ decomposition of matrix A\"));\r\n\r\n\r\n tout << \"START------dense2d-------row < col\\n\";\r\n\r\n A_t = trans(A);\r\n boost::tie(Q_t, R_t) = lq(A_t);\r\n tout << \"R_t=\\n\" << R_t << \"\\n\";\r\n tout << \"Q_t=\\n\" << Q_t << \"\\n\";\r\n A_t_test = Q_t * R_t - A_t;\r\n tout << \"Q_t*R_t=\\n\" << Q_t * R_t << \"\\n\";\r\n\r\n tout << \"one_norm(Rest A')=\" << one_norm(A_t_test) << \"\\n\";\r\n MTL_THROW_IF(one_norm(A_t_test) > tol, mtl::logic_error(\"wrong LQ decomposition of matrix trans(A)\"));\r\n\r\n tout << \"START-------compressed2d-------row > col\\n\";\r\n#if 1\r\n boost::tie(Qc, Rc) = lq(Ac);\r\n tout << \"R=\\n\" << Rc << \"\\n\";\r\n tout << \"Q=\\n\" << Qc << \"\\n\";\r\n A_testc = Qc * Rc - Ac;\r\n tout << \"Q*R=\\n\" << Qc * Rc << \"\\n\";\r\n tout << \"A=\\n\" << Ac << \"\\n\";\r\n\r\n tout << \"one_norm(Rest A)=\" << one_norm(A_testc) << \"\\n\";\r\n MTL_THROW_IF(one_norm(A_testc) > tol, mtl::logic_error(\"wrong LQ decomposition of matrix A\"));\r\n#endif\r\n\r\n#if 0\r\n dz[0][0] = complex(1.0, 0.0);\r\n dz[0][1] = complex(1.0, 0.0);\r\n dz[0][2] = complex(1, 0);\r\n dz[1][0] = complex(1, 0);\r\n dz[1][1] = complex(-1, 0);\r\n dz[1][2] = complex(-2, 0);\r\n dz[2][0] = complex(1, 0);\r\n dz[2][1] = complex(-2, 0);\r\n dz[2][2] = complex(1, 0);\r\n dz[3][3] = complex(-10, 0);\r\n tout << \"MAtrix complex=\\n\" << dz << \"\\n\";\r\n\r\n tout << \"START-----complex---------\" << dz[0][0] << \"\\n\";\r\n //AxB==BxA(For square matrix) LQ==QR(Transpose(A)\r\n boost::tie(Qz, Rz) = lq(dz);\r\n // Rz= lq_zerl(dz).second;\r\n // tout<<\"MAtrix R=\"<< Rz <<\"\\n\";\r\n // tout<<\"MAtrix Q=\"<< Qz <<\"\\n\";\r\n // tout<<\"MAtrix A=Q*R--outside\"<< Qz*Rz <<\"\\n\";\r\n#endif\r\n /*\r\n Normal equations\r\n A^T A x = A^T b\r\n \r\n These equations are called the normal equations of the least squares problem\r\n \r\n Coefficient matrix A^TA is the Gram matrix of A\r\n\r\n Equivalent to del f(x) = 0 where f(x) = ||Ax-b||^2\r\n\r\n All solutions of the least squares problem satisfy the normal equations.\r\n\r\n\r\n if A has linearly independent columns, then:\r\n\r\n A^T is non-singular\r\n \r\n Normal equations have unique solution xcap=(A^T A)^-1 A^T b\r\n */\r\n //Rewriting least squares solution using QR/LQ factorization A = QR, QR==LQ(transpose(A)).\r\n // x = R^-1 Q^T x b\r\n /* 1. compute QR factorization A = QR(2mn^2 flops if A is m × n)\r\n 2. matrix - vector product d = Q^T b(2mn flops)\r\n 3. solve Rx = d by back substitution(n^2 flops)\r\n complexity: 2mn^2 flops\r\n */\r\n /*\r\n Example\r\n\r\n | 3 -6| |-1 |\r\n A=| 4 -8|, b=| 7 |\r\n\t | 0 1| | 2 |\r\n \r\n 1. QR/LQ factorization A = QR/LQ with\r\n\r\n |3/5 0| \r\n \tQ=|4/5 0|, R=|5 -10|\r\n \t | 0 1| |0\t 1 |\r\n\r\n 2. calculate d=Q^Tb = (5,2)\r\n\r\n 3. solve Rx=d\r\n \t\t\r\n \t|5 -10| |x1| = |5|\r\n\t|0 1 | |x2| |2|\r\n\r\n\tsolution is x1=5, x2=2\t\r\n \r\n */\r\n //Problem with regular method occurs when forming Gram matrix A^T A as it is unstable\r\n //QR factorization method is more stable because it avoids forming A^T A\r\n dense2D x(A[iall][iall]),d(A[iall][iall]),b(A[iall][iall]);\r\n hessian_setup(x, 3.0); hessian_setup(d, 1.0);\r\n hessian_setup(b, 3.0);\r\n b[0][0] = -1, b[1][0] = 7, b[2][0] = 2;\r\n boost::tie(Q, R) = lq(A);\r\n mult(Q,b,d);\r\n d = trans(Q) * b;\r\n //d = trans(Q) * b;\r\n //lq decomposition is performed here so R==L here \r\n x = inv(R) * d;\r\n tout << \"Solution to least square's problem is:\" << x;\r\n return 0;\r\n}\r\n", "meta": {"hexsha": "96c3fe58e4c58e61ac3d94449377fa8d121223bf", "size": 5670, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/lq_test.cpp", "max_stars_repo_name": "shikharvashistha/mtl4", "max_stars_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/lq_test.cpp", "max_issues_repo_name": "shikharvashistha/mtl4", "max_issues_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/lq_test.cpp", "max_forks_repo_name": "shikharvashistha/mtl4", "max_forks_repo_head_hexsha": "09d8523d59baf5fdec29f3509a63babc2763af4a", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 32.5862068966, "max_line_length": 126, "alphanum_fraction": 0.5091710758, "num_tokens": 1970, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.8080672181749421, "lm_q1q2_score": 0.6868338495844546}} {"text": "//\n// Created by Sabar Nimmagadda on 4/25/20.\n//\n#include \"Linear Algebra/computations.h\"\n#include \n\n#include \n#include \n#include \n\n\nusing Eigen::MatrixXd;\nusing std::string;\n\n\n MatrixXd Computations::ComputeL(MatrixXd m) {\n typedef Eigen::Matrix L_Matrix;\n Eigen::FullPivLU lu(m);\n //Since the L matrix is a square matrix with the rowsize of the original matrix.\n L_Matrix l = L_Matrix::Identity();\n l.block<3,3>(0,0).triangularView() = lu.matrixLU();\n return l;\n }\n MatrixXd Computations::ComputeU(MatrixXd m) {\n typedef Eigen::Matrix U_Matrix;\n Eigen::FullPivLU lu(m);\n //Since the U matrix has the exact dimensions of the original matrix.\n U_Matrix u = lu.matrixLU().triangularView();\n return u;\n }\n MatrixXd Computations::ComputePermutationMatrix(MatrixXd m) {\n typedef Eigen::Matrix P_Matrix;\n Eigen::FullPivLU lu(m);\n P_Matrix p = lu.matrixLU();\n return p;\n }\n MatrixXd Computations::ComputeInverse(const MatrixXd& m) {\n return m.inverse();\n }\n\n MatrixXd Computations::ComputeRREF(const MatrixXd& m) {\n if (m.rows() >= 1 && m.cols() >= 1) {\n int lead = 0;\n MatrixXd out = m;\n while (lead < m.rows()) {\n float divisor, multiplier;\n for (int r = 0; r < m.rows(); r++) {\n if (out(lead, lead) != 0) {\n divisor = out(lead, lead); //What divides a cell to make its value = 1.\n multiplier = out(r, lead)/ out(lead, lead); //What is multiplied to a cell, so that when it is subtracted the value becomes 0.\n } else {\n divisor = 1;\n multiplier = 1;\n }\n for(int c = 0; c < m.cols(); c++) {\n if (lead == r) {\n out(r,c) /= divisor;//This makes the pivots = 1.\n } else {\n out(r,c) -= out(lead, c) * multiplier; //Making everything that is not a pivot = 0;\n }\n }\n }\n lead++;\n }\n return out;\n }\n }\n\n MatrixXd Computations::ComputeMultiply(MatrixXd matrix1, MatrixXd matrix2) {\n if (matrix1.cols() == matrix2.rows()) {\n return matrix1*matrix2;\n }\n }\n\n MatrixXd Computations::ComputeR(const MatrixXd& matrix) {\n Eigen::HouseholderQR qr(matrix.rows(), matrix.cols());\n qr.compute(matrix);\n MatrixXd R = qr.matrixQR().triangularView();\n return R;\n }\n\n MatrixXd Computations::ComputeQ(const MatrixXd& matrix) {\n Eigen::HouseholderQR qr(matrix.rows(), matrix.cols());\n qr.compute(matrix);\n MatrixXd Q = qr.householderQ();\n return Q;\n }\n\n double Computations::ComputeDotProduct(MatrixXd matrix1, MatrixXd matrix2, int dim) {\n double product = 0;\n for (int i = 0; i < dim; i++) {\n for (int j = 0; j < dim; j++) {\n product += matrix1(i, j) * matrix2(i, j);\n }\n }\n return product;\n }\n\n VectorXcd Computations::ComputeEigenValues(const MatrixXd& matrix) {\n VectorXcd ret = matrix.eigenvalues();\n return ret;\n }\n\n MatrixXcd Computations::ComputeEigenVectors(const MatrixXd& matrix) {\n Eigen::EigenSolver es(matrix);\n return es.eigenvectors();\n }\n\n int Computations::ComputeDeterminant(const MatrixXd& matrix) {\n return matrix.determinant();\n }\n MatrixXd Computations::ComputeColSpace(MatrixXd matrix) {\n if (matrix.size() >= 1) {\n Eigen::ColPivHouseholderQR qr(matrix);\n MatrixXd new_mat;\n if (qr.rank() != 0) {\n for (auto i : qr.colsPermutation().indices()) {\n new_mat.col(i) = matrix.col(i);\n }\n return new_mat;\n }\n return new_mat;\n }\n }\n\n MatrixXd Computations::ComputeRowSpace(MatrixXd matrix) {\n MatrixXd transp = matrix.transpose();\n Eigen::ColPivHouseholderQR qr(transp);\n MatrixXd new_mat;\n for (auto i : qr.colsPermutation().indices()) {\n new_mat.col(i) = transp.col(i);\n }\n return new_mat;\n }\n\n\n\n", "meta": {"hexsha": "9121938685a2f029015f4d792c0722af5009e608", "size": 4379, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/computations.cpp", "max_stars_repo_name": "CS126SP20/Matrix-Machine-LinAlgComputer-SabarNimmagadda", "max_stars_repo_head_hexsha": "928af6c373363eabc7edadf63f3e3a7220d864f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/computations.cpp", "max_issues_repo_name": "CS126SP20/Matrix-Machine-LinAlgComputer-SabarNimmagadda", "max_issues_repo_head_hexsha": "928af6c373363eabc7edadf63f3e3a7220d864f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/computations.cpp", "max_forks_repo_name": "CS126SP20/Matrix-Machine-LinAlgComputer-SabarNimmagadda", "max_forks_repo_head_hexsha": "928af6c373363eabc7edadf63f3e3a7220d864f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.731884058, "max_line_length": 148, "alphanum_fraction": 0.5670244348, "num_tokens": 1112, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787563, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6867926360291264}} {"text": "// =============================================================================\n// MetaProg Chapter III Solution 1\n// Author : Xin Liu\n// =============================================================================\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace mpl = boost::mpl;\n\n////////////////////////////////////////////////////////////////////////////////\nnamespace dimension_analysis\n{\n using mass = mpl::vector_c;\n using length = mpl::vector_c;\n using time = mpl::vector_c;\n using charge = mpl::vector_c;\n using temperature = mpl::vector_c;\n using intensity = mpl::vector_c;\n using amount_of_substance = mpl::vector_c;\n\n using velocity = mpl::vector_c; // l/t\n using acceleration = mpl::vector_c; // l/(t^2)\n using momentum = mpl::vector_c; // ml/t\n using force = mpl::vector_c; // ml/(t^2)\n\n using scalar = mpl::vector_c;\n\n\n template\n class quantity\n {\n public:\n explicit quantity(T x)\n : m_value(x)\n { }\n\n template \n quantity(quantity const& q)\n : m_value(q.value())\n {\n static_assert(mpl::equal::type::value, \"OtherDimensions should be same as Dimensions.\");\n }\n\n public:\n T value() const\n {\n return m_value;\n }\n\n private:\n T m_value;\n };\n\n template \n quantity\n operator+ (const quantity& lhs, const quantity& rhs)\n {\n //static_assert(mpl::equal(), \"D1 and D2 dimensions should be same.\");\n return quantity(lhs.value() + rhs.value());\n }\n\n template \n quantity\n operator- (const quantity& lhs, const quantity& rhs)\n {\n //static_assert(mpl::equal(), \"D1 and D2 dimensions should be same.\");\n return quantity(lhs.value() - rhs.value());\n }\n\n using mpl::placeholders::_;\n\n template \n struct multiply_dimensions\n : mpl::transform >\n { };\n\n template \n quantity::type>\n operator* (const quantity& lhs, const quantity& rhs)\n {\n return quantity::type>(lhs.value() * rhs.value());\n }\n\n template \n struct divide_dimensions\n : mpl::transform>\n { };\n\n template \n quantity::type>\n operator/ (const quantity& lhs, const quantity& rhs)\n {\n return quantity::type>(lhs.value() / rhs.value());\n }\n} // namespace dimension_analysis\n\n\nint main()\n{\n using namespace dimension_analysis;\n\n quantity l{ 1.0f };\n quantity m{ 2.0f };\n\n // expected compile error\n // m = l;\n\n quantity len1{ 1.0f };\n quantity len2{ 2.0f };\n\n len1 = len1 + len2;\n\n // expected compile error\n //len1 = len2 + quantity{ 3.7f };\n\n quantity m1{ 5.0f };\n quantity m3{ 10.0f };\n quantity a1{ 9.8f };\n\n quantity f1 = m1 * a1;\n\n quantity m2 = f1 / a1;\n float rounding_error = std::abs((m2 - m1).value());\n std::cout << \"error: \" << rounding_error << \"\\n\";\n\n f1 = f1 + (quantity)(m3 * a1);\n float rounding_error2 = std::abs((m2 - m1).value());\n std::cout << \"error2: \" << rounding_error2 << \"\\n\";\n bool res = rounding_error2 <= std::numeric_limits::min(); \n if(res) return 0;\n else return -1;\n}\n", "meta": {"hexsha": "d40ed7f138200c440ad8e4af3e24b6ff937e128e", "size": 4668, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ChapterIII/Solution1/main.cpp", "max_stars_repo_name": "Trigolds/MetaCppNN", "max_stars_repo_head_hexsha": "01544451dc0b9480ab7a481f24fd1adc15273230", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ChapterIII/Solution1/main.cpp", "max_issues_repo_name": "Trigolds/MetaCppNN", "max_issues_repo_head_hexsha": "01544451dc0b9480ab7a481f24fd1adc15273230", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ChapterIII/Solution1/main.cpp", "max_forks_repo_name": "Trigolds/MetaCppNN", "max_forks_repo_head_hexsha": "01544451dc0b9480ab7a481f24fd1adc15273230", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6433566434, "max_line_length": 129, "alphanum_fraction": 0.5379177378, "num_tokens": 1350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6867917367463804}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n// this header only for ch8\n#ifndef STATISTICS_HPP\n#define STATISTICS_HPP\nusing namespace std;\n\ndouble genZValue(double alpha) {\n boost::math::normal Ndistribution(0, 1);\n auto Z = boost::math::quantile(complement(Ndistribution, alpha / 2));\n return Z;\n}\n\ndouble genTValue(int degree, double upperTailArea) {\n boost::math::students_t Tdistribution(degree);\n auto T = boost::math::quantile(complement(Tdistribution, upperTailArea));\n return T;\n}\n\ndouble genMean(vector& _dataSet) {\n double sum = 0;\n for (auto i : _dataSet)\n sum += i;\n return sum / _dataSet.size();\n}\n\ndouble genSampleStandardDeviation(vector& _dataSet, double sampleMean, double size) {\n double sxx = 0;\n for (auto i : _dataSet)\n sxx += (i - sampleMean) * (i - sampleMean);\n return sqrt(1 / (size - 1) * sxx);\n}\n\ndouble errorRadius(vector& _dataSet, int degree, int sampleSize, double upperTailArea) {\n double mean = genMean(_dataSet);\n double ssd = genSampleStandardDeviation(_dataSet, mean, sampleSize);\n return ssd / sqrt(sampleSize) * genTValue(degree, upperTailArea);\n}\n\ndouble errorRadius(vector& _dataSet, double upperTailArea = 0.025) {\n /*\n * giving data set and the upper tail area of Student-T distribution\n * return the error radius\n * for too lazy to only input data set\n */\n int sampleSize = _dataSet.size();\n return errorRadius(_dataSet, sampleSize - 1, sampleSize, upperTailArea);\n}\n\ndouble errorRadius(double knownSigma, double alpha, int sampleSize) {\n /*\n * @knownSigma: the population sigma, which over sqrt(n)\n * giving alpha return the error radius for known Sigma of Z distribution\n * return the error radius\n */\n return knownSigma / sqrt(sampleSize) * genZValue(alpha);\n}\n\npair genConfidenceInterval(double theta, double errorRadius) {\n /*\n * @theta: the sample variable\n * @errorRadius: a radius of error, which might greater than 1,\n * means the standardDeviation times (z or t) over sqrt(n)\n */\n return make_pair(theta - errorRadius, theta + errorRadius);\n}\n\ntemplate \nostream& operator<<(ostream& os, const pair& v) {\n os << \"[\" << v.first << \", \" << v.second << \"]\";\n return os;\n}\n\nnamespace needingSampleSize {\nint p(double alpha, double p = 0.5, double marginError = 0.95) {\n /*\n * @p: the p bar of sample proportions, which might be iid Ber(P) (Bernoulli distribution)\n * @marginError: the margin error of confidence interval\n */\n double q = 1 - p, z = genZValue(alpha);\n auto sampleSize = p * q * z * z / marginError / marginError;\n return ceil(sampleSize);\n}\n\nint x_bar(double alpha, double knownTheta, double marginError) {\n /*\n * @knownTheta: the sigma which is the population standard deviation\n * @marginError: the margin error of confidence interval\n */\n double z = genZValue(alpha);\n auto sampleSize = z * z * knownTheta * knownTheta / marginError / marginError;\n return ceil(sampleSize);\n}\n} // namespace needingSampleSize\n\ntemplate \nstring readSingleLineCSV(vector& _dataSet, string fileName) {\n /* will return the file's title\n * read only single line csv file\n * @_dataSet: a container you want to storge at\n * @fileName: fileName\n */\n ifstream inFile(fileName, ios::in);\n if (inFile.fail()) {\n cerr << \"Open file failed\" << endl;\n return \"\";\n }\n string title;\n T rawdata;\n getline(inFile, title);\n while (inFile >> rawdata)\n _dataSet.push_back(rawdata);\n inFile.close();\n return title;\n}\n\ntemplate \nstring readSingleLineCSV(map& proportionDataSet, string fileName) {\n /* \n * only for reading proportion Data\n * will return the file's title\n * read only single line csv file\n * @proportionDataSet: a container you want to storge at\n * @fileName: fileName\n */\n ifstream inFile(fileName, ios::in);\n if (inFile.fail()) {\n cerr << \"Open file failed\" << endl;\n return \"\";\n }\n string title;\n T rawData;\n getline(inFile, title);\n while (getline(inFile, rawData)) {\n auto isInMap = proportionDataSet.find(rawData);\n if (isInMap != proportionDataSet.end())\n proportionDataSet.at(isInMap->first)++;\n else\n proportionDataSet.insert(pair(rawData, 1));\n }\n inFile.close();\n return title;\n}\n\n#endif\n", "meta": {"hexsha": "1b76e8d7dc0e3070c324a4b91d762661d92e455a", "size": 4671, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ch8/statistics.hpp", "max_stars_repo_name": "25077667/statistics_BM_NSYSU", "max_stars_repo_head_hexsha": "2c6c462727d9bf4bcff5844e785fd165a82c5a2d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch8/statistics.hpp", "max_issues_repo_name": "25077667/statistics_BM_NSYSU", "max_issues_repo_head_hexsha": "2c6c462727d9bf4bcff5844e785fd165a82c5a2d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch8/statistics.hpp", "max_forks_repo_name": "25077667/statistics_BM_NSYSU", "max_forks_repo_head_hexsha": "2c6c462727d9bf4bcff5844e785fd165a82c5a2d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7302631579, "max_line_length": 96, "alphanum_fraction": 0.6636694498, "num_tokens": 1180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6867917255923042}} {"text": "#include \n#include \n#include \n#include \n\n#include \"specgram.h\"\n\nstd::vector window_hanning(int size) {\n std::vector window;\n float scale = 2 * M_PI / (size - 1);\n for (int n = 0; n < size; n++)\n window.push_back(0.5 * (1 - cos(scale * n)));\n return window;\n}\n\nstd::pair specgram_shape(int n, int NFFT,\n int noverlap) {\n int stride = NFFT - noverlap;\n int time_steps = (n - noverlap) / stride;\n int n_freqs = NFFT / 2 + 1;\n return std::make_pair(n_freqs, time_steps);\n}\n\nvoid log_cspecgram(const int16_t* const in, int n,\n int NFFT, int Fs,\n int noverlap, float* out,\n float epsilon /* default=1e-7 */) {\n cspecgram(in, n, NFFT, Fs, noverlap, out);\n auto spec_shape = specgram_shape(n, NFFT, noverlap);\n int size = spec_shape.first * spec_shape.second;\n for (int i = 0; i < size; i++)\n out[i] = log(out[i] + epsilon);\n}\n\nvoid cspecgram(const int16_t* const in, int n,\n int NFFT, int Fs,\n int noverlap, float* out) {\n\n int stride = NFFT - noverlap;\n int n_freqs;\n int time_steps;\n std::tie(n_freqs, time_steps) = specgram_shape(n, NFFT, noverlap);\n\n std::vector window(window_hanning(NFFT));\n\n float *x = new float[NFFT * time_steps];\n\n float* in_f = new float[n];\n for (int i = 0; i < n; i++)\n in_f[i] = static_cast(in[i]);\n\n for (int i = 0; i < time_steps; i++) {\n for (int j = 0; j < NFFT; j++) {\n x[i * NFFT + j] = window[j] * in_f[i * stride + j];\n }\n }\n\n // Do an fft for each NFFT seg of x\n fftwf_complex* res = (fftwf_complex*) fftwf_malloc(\n sizeof(fftwf_complex) * n_freqs * time_steps);\n\n fftwf_plan plan = fftwf_plan_many_dft_r2c(1, &NFFT,\n time_steps, x, NULL, 1, NFFT,\n res, NULL, 1, n_freqs,\n FFTW_ESTIMATE | FFTW_DESTROY_INPUT);\n fftwf_execute(plan);\n fftwf_destroy_plan(plan);\n\n for (int i = 0; i < time_steps; i++) {\n int s = i * n_freqs;\n for (int j = 0; j < n_freqs; j++) {\n out[s + j] = res[s + j][0] * res[s + j][0] + \n res[s + j][1] * res[s + j][1];\n }\n }\n\n // Cleanup temporaries\n fftwf_free(res);\n delete[] x;\n delete[] in_f;\n\n // Scale output in the same style as matplotlib\n float scale = 0;\n for (float w : window)\n scale += w * w;\n scale *= Fs;\n for (int i = 0; i < time_steps; i++) {\n int s = i * n_freqs;\n out[s] /= scale;\n for (int j = 1; j < n_freqs - 1; j++) {\n out[s + j] *= (2.0 / scale);\n }\n if (NFFT % 2 == 0) {\n out[s + n_freqs - 1] /= scale;\n } else {\n out[s + n_freqs - 1] *= (2.0 / scale);\n }\n }\n}\n\n#ifdef PYTHON\n#include \n#include \n#include \n#include \n\nnamespace py = boost::python;\nnamespace np = boost::python::numeric;\n\nvoid specgram(np::array input, int NFFT, int Fs,\n int noverlap, np::array output) {\n \n py::object i_shape = input.attr(\"shape\");\n py::object o_shape = output.attr(\"shape\");\n\n if (len(i_shape) != 1 || len(o_shape) != 2)\n throw std::invalid_argument(\"Bad input or ouput shape\");\n unsigned int n = py::extract(i_shape[0]);\n \n int16_t* in_dat = static_cast(PyArray_DATA(input.ptr()));\n float* out_dat = static_cast(PyArray_DATA(output.ptr()));\n cspecgram(in_dat, n, NFFT, Fs, noverlap, out_dat);\n}\n\nBOOST_PYTHON_MODULE(cspecgram) {\n np::array::set_module_and_type(\"numpy\", \"ndarray\");\n py::def(\"specgram\", &specgram);\n}\n#endif\n", "meta": {"hexsha": "9ccd3ea1811bf1668f9d9a840e1588445602dcfa", "size": 3867, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "utils/specgram.cpp", "max_stars_repo_name": "gaoyiyeah/KWS-CTC", "max_stars_repo_head_hexsha": "28fdc2062281996d6408e41a9b49febf3334d730", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 340.0, "max_stars_repo_stars_event_min_datetime": "2017-12-15T22:41:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T14:51:05.000Z", "max_issues_repo_path": "utils/specgram.cpp", "max_issues_repo_name": "gaoyiyeah/KWS-CTC", "max_issues_repo_head_hexsha": "28fdc2062281996d6408e41a9b49febf3334d730", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2018-03-08T07:52:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T23:26:52.000Z", "max_forks_repo_path": "utils/specgram.cpp", "max_forks_repo_name": "gaoyiyeah/KWS-CTC", "max_forks_repo_head_hexsha": "28fdc2062281996d6408e41a9b49febf3334d730", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 82.0, "max_forks_repo_forks_event_min_datetime": "2017-12-21T01:05:04.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-29T09:27:23.000Z", "avg_line_length": 29.7461538462, "max_line_length": 74, "alphanum_fraction": 0.5435738298, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.686768148817579}} {"text": "//\n// Created by Vlad Argunov on 19/10/2021.\n//\n\n#include \"Regression.h\"\n\n#include \n#include \n#include \n\n\nRegression::Regression(std::string type) {\n type_regression = type;\n}\n\n\nvoid Regression::set_data(Eigen::MatrixXd x_values_, Eigen::VectorXd y_values_) {\n x_values = x_values_;\n y_values = y_values_;\n}\n\nvoid Regression::add_constant() {\n Eigen::MatrixXd x_values_with_constant;\n x_values_with_constant.resize(x_values.rows(), x_values.cols() + 1);\n x_values_with_constant.rightCols(x_values.cols()) = x_values;\n\n x_values_with_constant.col(0) = Eigen::VectorXd::Ones(x_values.rows());\n x_values = x_values_with_constant;\n\n}\n\nvoid Regression::print_data() {\n std::cout << \"Data Matrix:\\n\";\n std::cout << x_values << \"\\n\";\n}\n\nvoid Regression::print_responses() {\n std::cout << \"Responses vector:\\n\";\n std::cout << y_values << \"\\n\";\n}\n\nvoid Regression::solve() {\n if (type_regression == \"Linear\"){\n Eigen::MatrixXd computation_matrix;\n computation_matrix.resize(x_values.rows(), x_values.rows());\n computation_matrix = (x_values.transpose() * x_values).inverse();\n parameters = computation_matrix * x_values.transpose() * y_values;\n }\n}\n\nvoid Regression::print_parameters() {\n std::cout << \"Parameters vector:\\n\";\n std::cout << parameters << \"\\n\";\n}\n", "meta": {"hexsha": "f1aa8b152a8104c33fc2161686b9e445a4b59391", "size": 1360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Regression.cpp", "max_stars_repo_name": "vladargunov/QuantKit", "max_stars_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Regression.cpp", "max_issues_repo_name": "vladargunov/QuantKit", "max_issues_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Regression.cpp", "max_forks_repo_name": "vladargunov/QuantKit", "max_forks_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7272727273, "max_line_length": 81, "alphanum_fraction": 0.6742647059, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9433475730993028, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6867338785686556}} {"text": "#pragma once\n#ifndef MANIFOLDMATH_H\n#define MANIFOLDMATH_H\n\n#include \n#include \n\n#include \n\n#include \n\nnamespace Engine\n{\n // Basically all math inside this namespace assumes that the given\n // vectorfields contain unit vectors. They are therefore interpreted\n // as living in a manifold which is the direct product space of N\n // spheres.\n // The only exception are functions which interpret the vectorfield\n // as a single 3N-dimensional vector.\n // TODO: cleanly separate these two cases!\n namespace Manifoldmath\n {\n // Get the norm of a vectorfield (interpreted as a 3N-vector)\n scalar norm(const vectorfield & vf);\n // Normalize a vectorfield (interpreted as a 3N-vector)\n void normalize(vectorfield & vf);\n\n\n // Project v1 to be parallel to v2\n // Note: this assumes normalized vectorfields\n void project_parallel(vectorfield & vf1, const vectorfield & vf2);\n // Project v1 to be orthogonal to v2\n // Note: this assumes normalized vectorfields\n void project_orthogonal(vectorfield & vf1, const vectorfield & vf2);\n // Invert v1's component parallel to v2\n // Note: this assumes normalized vectorfields\n void invert_parallel(vectorfield & vf1, const vectorfield & vf2);\n // Invert v1's component orthogonal to v2\n // Note: this assumes normalized vectorfields\n void invert_orthogonal(vectorfield & vf1, const vectorfield & vf2);\n // Project vf1's vectors into the tangent plane of vf2\n // Note: vf2 must have normalized vectors\n void project_tangential(vectorfield & vf1, const vectorfield & vf2);\n\n\n // The tangential projector is a matrix which projects any vector into the tangent\n // space of a vectorfield, considered to live on the direct product of N unit\n // spheres. It is a 3N x 3N matrix.\n MatrixX tangential_projector(const vectorfield & image);\n\n // Calculate a matrix of orthonormal basis vectors that span the tangent space to\n // a vectorfield, considered to live on the direct product of N unit spheres.\n // The basis vectors will be the spherical unit vectors, except at the poles.\n // The basis will be a 3Nx2N matrix.\n void tangent_basis_spherical(const vectorfield & vf, MatrixX & basis);\n\n // Calculate a matrix of orthonormal basis vectors that span the tangent space to\n // a vectorfield, considered to live on the direct product of N unit spheres.\n // The basis vectors will be generated from cross products with euclidean basis\n // vectors. The basis will be a 3Nx2N matrix.\n void tangent_basis_cross(const vectorfield & vf, MatrixX & basis);\n\n // Calculate a matrix of orthonormal basis vectors that span the tangent space to\n // a vectorfield, considered to live on the direct product of N unit spheres.\n // The basis vectors will form righthanded sets with the vectors of vf.\n // The basis will be a 3Nx2N matrix.\n void tangent_basis_righthanded(const vectorfield & vf, MatrixX & basis);\n\n // Calculate a matrix of orthonormal basis vectors that span the tangent space to\n // a vectorfield, considered to live on the direct product of N unit spheres.\n // The basis vectors will be calculated from orthonormalizations with respect\n // to a random vector. The basis will be a 3Nx2N matrix.\n // void tangent_basis_random(const vectorfield & vf, MatrixX & basis);\n\n\n // This is the derivatives of the coordinate transformation from (unit-)spherical to cartesian\n // i.e. d_cartesian/d_spherical\n void spherical_to_cartesian_jacobian(const vectorfield & vf, MatrixX & jacobian);\n\n // This is the second derivatives of the coordinate transformation from (unit-)spherical to cartesian\n // i.e. d^2_cartesian/d^2_spherical\n void spherical_to_cartesian_hessian(const vectorfield & vf, MatrixX & gamma_x, MatrixX & gamma_y, MatrixX & gamma_z);\n \n //\n void spherical_to_cartesian_coordinate_basis(const vectorfield & vf, MatrixX & basis);\n\n //\n void spherical_coordinate_christoffel_symbols(const vectorfield & vf, MatrixX & gamma_theta, MatrixX & gamma_phi);\n\n\n // Calculate Hessian for a vectorfield constrained to unit length, at any extremum (i.e. where vectors || gradient)\n void hessian_bordered(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & tangent_basis, MatrixX & hessian_out);\n // Calculate tangential derivatives and correction terms according to the projector approach\n void hessian_projected(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & tangent_basis, MatrixX & hessian_out);\n // Calculate tangential derivatives and correction terms according to the projector and Weingarten map approach\n void hessian_weingarten(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & tangent_basis, MatrixX & hessian_out);\n // Calculate spherical derivatives using coordinate transformations via jacobians\n void hessian_spherical(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & hessian_out);\n // Calculate spherical derivates and correction terms using jacobians and christoffel symbols\n void hessian_covariant(const vectorfield & image, const vectorfield & gradient, const MatrixX & hessian, MatrixX & hessian_out);\n\n // Geodesic distance between two vectorfields\n scalar dist_geodesic(const vectorfield & v1, const vectorfield & v2);\n\n // Calculate the \"tangent\" vectorfields pointing between a set of configurations\n void Tangents(std::vector> configurations, const std::vector & energies, std::vector & tangents);\n }\n}\n\n#endif", "meta": {"hexsha": "6ea03f950afe8f034df9b88d038c95e39a7af625", "size": 6156, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "core/include/engine/Manifoldmath.hpp", "max_stars_repo_name": "ddkn/spirit", "max_stars_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 46.0, "max_stars_repo_stars_event_min_datetime": "2020-08-24T22:40:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T06:54:54.000Z", "max_issues_repo_path": "core/include/engine/Manifoldmath.hpp", "max_issues_repo_name": "ddkn/spirit", "max_issues_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "core/include/engine/Manifoldmath.hpp", "max_forks_repo_name": "ddkn/spirit", "max_forks_repo_head_hexsha": "8e51bcdd78ee05d433d000c7e389fe1e6c3716bc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-09-05T13:24:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-06T07:46:47.000Z", "avg_line_length": 55.9636363636, "max_line_length": 162, "alphanum_fraction": 0.6985055231, "num_tokens": 1353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6866351941701577}} {"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n// 2008 Dresden University of Technology and the Trustees of Indiana University.\n// 2010 SimuNova UG, www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also tools/license/license.mtl.txt in the distribution.\n\n// Author: Marc Hartung\n\n#ifndef MTL_MATRIX_QR_GIVENS_INCLUDE\n#define MTL_MATRIX_QR_GIVENS_INCLUDE\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\nnamespace mtl { namespace matrix {\n\n\n/// General Given's transformator\n/**\n * Input-matrix A will be splitted in A = Q*R. Q and R are accessible from getQ() and getR().\n * \\sa givens\n */ \ntemplate \nclass qr_givens_solver {\n \n typedef typename Collection::value_type value_type;\n typedef typename Collection::size_type size_type;\n\npublic:\n \n /** \\brief Constructor needs a sqare-matrix as input\n * \\param MTL-Matrix type\n * \n */\n \n qr_givens_solver(const Matrix& IN) : R(IN), G(2,2), Q(num_cols(IN), num_rows(IN)) {\n\tvalue_type one = math::one(c);\n\tQ = one;\n\teps = 1.0e-8;\n }\n \n /** \\brief Returns Q as the input-matrix-type \n * \n * \\return Matrix Q\n */\n \n Matrix& getQ() {\n\treturn Q;\n }\n \n /** \\brief Returns R as the input-matrix-type \n * \n * \\return Matrix R\n */ \n Matrix& getR() {\n\treturn R;\n }\n \n /** \\brief Sets the distance to zero\n * \n * \\param value_type tolerance to zero\n */ \n void setTolerance(value_type tol) {\n\teps = tol;\n }\n \n /** \\brief Starts QR decompostion\n */\t\n void calc() \n {\n\tvalue_type zero= math::zero(c);\n\tMatrix RIter(2, num_rows(R)), Iter(2, num_rows(R));\n\tfor(size_type i= 0; i < R.num_cols() - 1; i++) {\n\t irange r(i, num_cols(R));\n \t for(size_type j= num_rows(R)-1;j>i;j--) {\n\t\tif (std::abs(R[j][i]) > eps) {\n\t\t set_rotation(R[i][i], R[j][i]);\n\t\t Iter[0][r] = R[i][r];\n\t\t Iter[1][r] = R[j][r];\n\t\t RIter[iall][r] = G*Iter[iall][r];\n\t\t R[i][r] = RIter[0][r];\n\t\t R[j][r] = RIter[1][r];\n\t\t Iter[0][iall] = Q[i][iall];\n\t\t Iter[1][iall] = Q[j][iall];\n\t\t RIter = G*Iter;\n\t\t Q[i][iall] = RIter[0][iall];\n\t\t Q[j][iall] = RIter[1][iall];\n\t\t}\n\t\tR[j][i] = zero;\n\t }\n\t \n\t}\n\t\n\tfor(size_type i= 0; i < num_cols(R) - 1; i++) \n\t R[i+1][i] = zero;\n\t\n }\n \n private:\n \n Matrix R, G, Q;\n value_type c, s, eps;\n \n template \n inline T square(T x) const { return x * x; }\n\n /// Coefficients for Given's rotation \n void set_rotation(value_type a, value_type b)\n {\n\tusing std::abs;\n\tusing mtl::conj;\n\t\n\tvalue_type zero= math::zero(a), one= math::one(b), t;\n\t\n\tif ( b == zero ) {\n\t c= one; s= zero;\n\t} else if ( abs(b) > abs(a) ) {\n\t t = a / abs(b);\n\t s = one/ sqrt(one + square(abs(t)));\n\t c = s * t;\n\t s *= (b/abs(b));\n\t} else {\n\t t = b / abs(a);\n\t c = one / sqrt(one + square(abs(t)));\n\t s = c * t;\n\t c = (a/abs(a))*c;\n\t}\n\t\n\tG= conj(c), conj(s),\n\t -s, c;\n }\n \n};\n\n/// QR-Factorization of matrix A(m x n) based on Givens' rotation\ntemplate \nstd::pair\ninline qr_givens(const Matrix& A)\n{\n qr_givens_solver solver(A);\n solver.calc();\n return std::make_pair(solver.getQ(), solver.getR());\n}\n\n}} // namespace mtl::matrix\n\n#endif // MTL_MATRIX_QR_GIVENS_INCLUDE\n", "meta": {"hexsha": "0e242a1e2a9226d490f92afe7a31ded086e22d36", "size": 3699, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/mtl4/boost/numeric/mtl/operation/qr_givens.hpp", "max_stars_repo_name": "spraetor/amdis2", "max_stars_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-04T16:44:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-03T07:26:27.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/mtl/operation/qr_givens.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/mtl4/boost/numeric/mtl/operation/qr_givens.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.11875, "max_line_length": 94, "alphanum_fraction": 0.5796161125, "num_tokens": 1141, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450965, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6865539943066427}} {"text": "#ifndef InitCondLV_CC_\n#define InitCondLV_CC_\n/**\n * @file initcondlv.cc\n * @brief NPDE homework InitCondLV code\n * @author lfilippo, tille, jgacon, dcasati\n * @copyright Developed at ETH Zurich\n */\n\n#include \n#include \n#include \n\n#include \"../../../lecturecodes/Ode45/ode45.h\"\n\nnamespace InitCondLV {\n\n/* Compute the maps Phi(t,y0) and W(t,y0) at final time T.\n * Use initial data given by u0 and v0. */\n/* SAM_LISTING_BEGIN_1 */\nstd::pair PhiAndW(double u0, double v0,\n double T) {\n // Save the values of Phi and W at time T in PaW.first and PaW.second resp.\n std::pair PaW;\n\n#if SOLUTION\n auto f = [](const Eigen::VectorXd& w) {\n Eigen::VectorXd temp(6);\n temp(0) = (2. - w(1)) * w(0);\n temp(1) = (w(0) - 1.) * w(1);\n temp(2) = (2. - w(1)) * w(2) - w(0) * w(3);\n temp(3) = w(1) * w(2) + (w(0) - 1.) * w(3);\n temp(4) = (2. - w(1)) * w(4) - w(0) * w(5);\n temp(5) = w(1) * w(4) + (w(0) - 1.) * w(5);\n return temp;\n };\n\n Eigen::VectorXd w0(6);\n w0 << u0, v0, 1., 0, 0, 1.;\n\n // Construct ode solver with r.h.s\n Ode45 O(f);\n // Set options\n O.options.rtol = 1e-14;\n O.options.atol = 1e-12;\n // Solve ODE\n auto sol = O.solve(w0, T);\n // Extract needed component\n Eigen::VectorXd wT = sol.back().first;\n\n PaW.first << wT(0), wT(1);\n PaW.second << wT(2), wT(4), wT(3), wT(5);\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return PaW;\n}\n/* SAM_LISTING_END_1 */\n\n} // namespace InitCondLV\n\n#endif // #define InitCondLV_CC_\n", "meta": {"hexsha": "634f2187afa4e09784102e986ea825095fe97203", "size": 1670, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/InitCondLV/mastersolution/initcondlv.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/InitCondLV/mastersolution/initcondlv.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/InitCondLV/mastersolution/initcondlv.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 25.6923076923, "max_line_length": 77, "alphanum_fraction": 0.5604790419, "num_tokens": 600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256472515683, "lm_q2_score": 0.8152324803738429, "lm_q1q2_score": 0.6862836104512117}} {"text": "#include \n#include \n#include \nnamespace mp = boost::multiprecision;\n\ntypedef mp::mpf_float_1000 MPFloat;\n\nstruct MPConstant {\n const char *name {};\n const char *expr {};\n MPFloat value;\n};\n\nint main() {\n const MPFloat one(1);\n const MPFloat two(2);\n const MPFloat ten(10);\n const MPFloat e = mp::exp(one);\n const MPFloat ln2 = mp::log(two);\n const MPFloat ln10 = mp::log(ten);\n const MPFloat pi = 4 * mp::atan(one);\n const MPFloat sqrtpi = mp::sqrt(pi);\n const MPFloat sqrt2 = mp::sqrt(two);\n\n const MPConstant constants[] = {\n {\"E\", \"e\", e},\n {\"LOG2E\", \"log2(e)\", mp::log2(e)},\n {\"LOG10E\", \"log10(e)\", mp::log10(e)},\n {\"LN2\", \"log(2)\", mp::log(two)},\n {\"LN10\", \"log(10)\", mp::log(ten)},\n {\"PI\", \"pi\", pi},\n {\"2PI\", \"2*pi\", 2 * pi},\n {\"4PI\", \"4*pi\", 4 * pi},\n {\"PI_2\", \"pi/2\", pi / 2},\n {\"PI_4\", \"pi/4\", pi / 4},\n {\"1_PI\", \"1/pi\", 1 / pi},\n {\"2_PI\", \"2/pi\", 2 / pi},\n {\"4_PI\", \"4/pi\", 4 / pi},\n {\"1_SQRTPI\", \"1/sqrt(pi)\", 1 / sqrtpi},\n {\"2_SQRTPI\", \"2/sqrt(pi)\", 2 / sqrtpi},\n {\"SQRT2\", \"sqrt(2)\", sqrt2},\n {\"1_SQRT2\", \"1/sqrt(2)\", 1 / sqrt2},\n };\n\n for (const MPConstant &c: constants) {\n std::cout << \"#define \" <<\n boost::format(\"K_%s%|15t|::coreutil::math_constant(%s)%|85t|// %s\\n\")\n % c.name % (c.value.str(36) + 'L') % c.expr;\n }\n\n return 0;\n}\n", "meta": {"hexsha": "e39a4b3fa52a89658fbd5070a5e23430cf58c5d8", "size": 1394, "ext": "cc", "lang": "C++", "max_stars_repo_path": "tools/generate_math_constants.cc", "max_stars_repo_name": "jpcima/coreutil", "max_stars_repo_head_hexsha": "8ec6acec90738919116e71e3a7ea5fe012793ad4", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/generate_math_constants.cc", "max_issues_repo_name": "jpcima/coreutil", "max_issues_repo_head_hexsha": "8ec6acec90738919116e71e3a7ea5fe012793ad4", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/generate_math_constants.cc", "max_forks_repo_name": "jpcima/coreutil", "max_forks_repo_head_hexsha": "8ec6acec90738919116e71e3a7ea5fe012793ad4", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3018867925, "max_line_length": 77, "alphanum_fraction": 0.5337159254, "num_tokens": 520, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6861811606392413}} {"text": "#include \"project/LinearRegression.hpp\"\n#include \n\nLinearRegression::LinearRegression(arma::mat &x,\n arma::vec &y){\n\n X = x;\n Y = y;\n}\n\nvoid LinearRegression::fit(bool fit_inter = true){\n fit_intercept = fit_inter;\n if(fit_intercept){\n coef = arma::solve(\n arma::join_rows(arma::ones(X.n_rows, 1), X),\n Y);\n } else {\n coef = arma::solve(X, Y);\n }\n}\n\narma::colvec LinearRegression::predict(arma::mat &X_pred){\n if(fit_intercept) { \n return arma::join_rows(\n arma::ones(X_pred.n_rows, 1),\n X_pred)*coef;\n }\n else{\n return X_pred*coef;\n }\n}\n", "meta": {"hexsha": "a0e1f95eebde460fce1e476b7d590b819c405502", "size": 708, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LinearRegression.cpp", "max_stars_repo_name": "haruspex-machine/ts-forecast-cpp", "max_stars_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-09T06:27:15.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T06:27:15.000Z", "max_issues_repo_path": "src/LinearRegression.cpp", "max_issues_repo_name": "bklimowski/ts-forecast-cpp", "max_issues_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LinearRegression.cpp", "max_forks_repo_name": "bklimowski/ts-forecast-cpp", "max_forks_repo_head_hexsha": "a4087fc479a422d945d79144cac408552a7ec83c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.125, "max_line_length": 60, "alphanum_fraction": 0.5254237288, "num_tokens": 180, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873763, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6861811587344232}} {"text": "//\n// Copyright © 2017 Arm Ltd. All rights reserved.\n// SPDX-License-Identifier: MIT\n//\n\n#include \"ResizeBilinear.hpp\"\n\n#include \"TensorBufferArrayView.hpp\"\n\n#include \n\n#include \n#include \n\nusing namespace armnnUtils;\n\nnamespace armnn\n{\n\nnamespace\n{\n\ninline float Lerp(float a, float b, float w)\n{\n return w * b + (1.f - w) * a;\n}\n\n}\n\nvoid ResizeBilinear(const float* in,\n const TensorInfo& inputInfo,\n float* out,\n const TensorInfo& outputInfo,\n DataLayoutIndexed dataLayout)\n{\n // We follow the definition of TensorFlow and AndroidNN: the top-left corner of a texel in the output\n // image is projected into the input image to figure out the interpolants and weights. Note that this\n // will yield different results than if projecting the centre of output texels.\n\n const unsigned int batchSize = inputInfo.GetShape()[0];\n const unsigned int channelCount = inputInfo.GetShape()[dataLayout.GetChannelsIndex()];\n\n const unsigned int inputHeight = inputInfo.GetShape()[dataLayout.GetHeightIndex()];\n const unsigned int inputWidth = inputInfo.GetShape()[dataLayout.GetWidthIndex()];\n const unsigned int outputHeight = outputInfo.GetShape()[dataLayout.GetHeightIndex()];\n const unsigned int outputWidth = outputInfo.GetShape()[dataLayout.GetWidthIndex()];\n\n // How much to scale pixel coordinates in the output image, to get the corresponding pixel coordinates\n // in the input image.\n const float scaleY = boost::numeric_cast(inputHeight) / boost::numeric_cast(outputHeight);\n const float scaleX = boost::numeric_cast(inputWidth) / boost::numeric_cast(outputWidth);\n\n TensorBufferArrayView input(inputInfo.GetShape(), in, dataLayout);\n TensorBufferArrayView output(outputInfo.GetShape(), out, dataLayout);\n\n for (unsigned int n = 0; n < batchSize; ++n)\n {\n for (unsigned int c = 0; c < channelCount; ++c)\n {\n for (unsigned int y = 0; y < outputHeight; ++y)\n {\n // Corresponding real-valued height coordinate in input image.\n const float iy = boost::numeric_cast(y) * scaleY;\n\n // Discrete height coordinate of top-left texel (in the 2x2 texel area used for interpolation).\n const float fiy = floorf(iy);\n const unsigned int y0 = boost::numeric_cast(fiy);\n\n // Interpolation weight (range [0,1]).\n const float yw = iy - fiy;\n\n for (unsigned int x = 0; x < outputWidth; ++x)\n {\n // Real-valued and discrete width coordinates in input image.\n const float ix = boost::numeric_cast(x) * scaleX;\n const float fix = floorf(ix);\n const unsigned int x0 = boost::numeric_cast(fix);\n\n // Interpolation weight (range [0,1]).\n const float xw = ix - fix;\n\n // Discrete width/height coordinates of texels below and to the right of (x0, y0).\n const unsigned int x1 = std::min(x0 + 1, inputWidth - 1u);\n const unsigned int y1 = std::min(y0 + 1, inputHeight - 1u);\n\n // Interpolation\n const float ly0 = Lerp(input.Get(n, c, y0, x0), input.Get(n, c, y0, x1), xw); // lerp along row y0.\n const float ly1 = Lerp(input.Get(n, c, y1, x0), input.Get(n, c, y1, x1), xw); // lerp along row y1.\n const float l = Lerp(ly0, ly1, yw);\n\n output.Get(n, c, y, x) = l;\n }\n }\n }\n }\n}\n\n} //namespace armnn\n", "meta": {"hexsha": "2d1087c9a0736da92fb0fbe8c1af804c99625c72", "size": 3831, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/backends/reference/workloads/ResizeBilinear.cpp", "max_stars_repo_name": "jnorwood/armnn", "max_stars_repo_head_hexsha": "774f6f1d7c862fc2b8e1783abef9a0bccdaf9d0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-06-26T23:00:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-26T23:00:46.000Z", "max_issues_repo_path": "src/backends/reference/workloads/ResizeBilinear.cpp", "max_issues_repo_name": "jnorwood/armnn", "max_issues_repo_head_hexsha": "774f6f1d7c862fc2b8e1783abef9a0bccdaf9d0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/backends/reference/workloads/ResizeBilinear.cpp", "max_forks_repo_name": "jnorwood/armnn", "max_forks_repo_head_hexsha": "774f6f1d7c862fc2b8e1783abef9a0bccdaf9d0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.696969697, "max_line_length": 119, "alphanum_fraction": 0.6034977813, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6859954287894193}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nPlotView *createPlotView(const std::string& title, const std::string& xLabel, const std::string yLabel, const PRectF& viewRange, const double Width=1200, const double Height=800);\n\ntypedef std::vector Data;\ntypedef std::unique_ptr FuncPtr;\ntypedef std::weak_ptr ParamPtr;\n\nclass PlanetOrbit\n{\nprivate:\n Genfun::RKIntegrator integrator;\n\npublic:\n Genfun::Parameter* GM;\n Genfun::Parameter* e;\n Genfun::Parameter* a;\n Genfun::Parameter* theta0;\n Genfun::Parameter* inclination;\n Genfun::Parameter* orientation;\n FuncPtr X;\n FuncPtr Y;\n\n PlanetOrbit()\n {\n Genfun::Variable theta;\n Genfun::Sin qSin;\n Genfun::Cos qCos;\n Genfun::Sqrt qSqrt;\n\n GM = integrator.createControlParameter(\"GM\", 0.0002959, 0);\n e = integrator.createControlParameter(\"eccentricity\", 0, 0, 1);\n a = integrator.createControlParameter(\"semimajor axis\", 1);\n theta0 = integrator.createControlParameter(\"Theta0\", 0, -2*M_PI, 2*M_PI);\n orientation = new Genfun::Parameter(\"Orientation\", 0, -2*M_PI, 2*M_PI);\n inclination = new Genfun::Parameter(\"Inclination\", 0, 0, M_PI);\n\n Genfun::GENFUNCTION r = (*a) * (1 - (*e)*(*e)) / (1 + (*e) * qCos(theta - (*theta0)));\n Genfun::GENFUNCTION DTheta = qSqrt((*GM) * (*a) * (1 - (*e)*(*e))) / (r*r);\n\n integrator.addDiffEquation(&DTheta);\n\n Genfun::GENFUNCTION Theta = *integrator.getFunction(theta);\n Genfun::GENFUNCTION Radius = (*a) * (1 - (*e) * (*e)) / (1 + (*e) * qCos(Theta - (*theta0)));\n\n X = FuncPtr((Radius * qCos(Theta - (*theta0) + (*orientation))).clone());\n Y = FuncPtr((Radius * qSin(Theta - (*theta0) + (*orientation))).clone());\n }\n\n ~PlanetOrbit()\n {\n delete orientation;\n }\n};\n\nconst double MAX_ANGLE = 3 * M_PI;\n\ndouble Time2Radian(const double hour, const double minute, const double second)\n{\n const double Hour2Radian = 2 * M_PI / 24;\n const double Minute2Radian = Hour2Radian / 60;\n const double Second2Radian = Minute2Radian/ 60;\n double angle = Hour2Radian*std::abs(hour) + Minute2Radian*std::abs(minute) + Second2Radian*std::abs(second);\n return std::signbit(hour) ? -angle : angle;\n}\n\ndouble Degree2Radian(const double degree, const double minute, const double second)\n{\n const double Degree2Radian = 2 * M_PI / 360;\n const double Minute2Radian = Degree2Radian / 60;\n const double Second2Radian = Minute2Radian / 60;\n double angle = Degree2Radian*std::abs(degree) + Minute2Radian*std::abs(minute) + Second2Radian*std::abs(second);\n return std::signbit(degree) ? -angle : angle;\n}\n\nvoid readData(const std::string& file, Data& TIME, Data& RA, Data& DEC)\n{\n std::ifstream inFile(file);\n std::string day, time;\n\n for (size_t i = 1; inFile >> day >> time; i++)\n {\n TIME.push_back(i);\n\n double hour, minute, second;\n inFile >> hour >> minute >> second;\n RA.push_back(Time2Radian(hour, minute, second));\n inFile >> hour >> minute >> second;\n DEC.push_back(Degree2Radian(hour, minute, second));\n } \n}\n\nData refineData(const Data& rawData, const double lowerBound, const double upperBound);\nHist1D binData(const Data& data);\nTable tableData(const Data& data);\n\nconst std::string dataFileName = \"Mars01.dat\";\nconst bool verbose = true;\n\nint main(int argc, char **argv)\n{\n QApplication app(argc, argv);\n MultipleViewWindow window;\n\n QToolBar *toolBar = window.addToolBar(\"Tools\");\n QAction *quitAction = toolBar->addAction(\"Quit (q)\");\n quitAction->setShortcut(QKeySequence(\"q\"));\n\tQObject::connect(quitAction, SIGNAL(triggered()), &app, SLOT(quit()));\n\n PlanetOrbit Earth;\n Earth.e->setValue(0.8);\n Earth.theta0->setValue(M_PI/3);\n Earth.orientation->setValue(-M_PI/3);\n PlotOrbit earthOrbit(*(Earth.X), *(Earth.Y), 0, 360);\n PlotView *earthView = createPlotView(\"Earth\", \"X\", \"Y\", PRectF(-2, 2, -2, 2), 800, 800);\n earthView->add(&earthOrbit);\n window.add(earthView, \"Earth\");\n\n Data TIME, RA, DEC;\n readData(dataFileName, TIME, RA, DEC);\n\n std::cout << \"RA @ 0: \" << RA[0] << std::endl;\n std::cout << \"DEC @ 0: \" << DEC[0] << std::endl;\n\n PlotView *RAView = createPlotView(\"Right Ascension\", \"Days\", \"\", PRectF(-10, 760, -0.5, 2*M_PI + 0.5));\n window.add(RAView, \"RA\");\n\n PlotProfile RAProfile;\n for (size_t i = 0; i < TIME.size(); i++)\n {\n RAProfile.addPoint(TIME[i],RA[i]);\n }\n {\n PlotProfile::Properties prop;\n prop.pen.setWidth(1);\n RAProfile.setProperties(prop);\n }\n RAView->add(&RAProfile);\n\n\n PlotView *DECView = createPlotView(\"Declination\", \"Days\", \"\", PRectF(-10, 760, -1, 1));\n window.add(DECView, \"DEC\");\n\n PlotProfile DECProfile;\n for (size_t i = 0; i < TIME.size(); i++)\n {\n DECProfile.addPoint(TIME[i], DEC[i]);\n }\n {\n PlotProfile::Properties prop;\n prop.pen.setWidth(1);\n DECProfile.setProperties(prop);\n }\n DECView->add(&DECProfile);\n \n\n\twindow.show();\n\tapp.exec();\n\n return 0;\n}\n\n\nPlotView *createPlotView(const std::string& title, const std::string& xLabel, const std::string yLabel, const PRectF& viewRange, const double Width, const double Height)\n{\n PlotView *view_ptr = new PlotView(viewRange);\n view_ptr->setFixedWidth(Width);\n view_ptr->setFixedHeight(Height);\n\n PlotStream titleStream(view_ptr->titleTextEdit());\n titleStream << PlotStream::Clear()\n << PlotStream::Center()\n << PlotStream::Family(\"Sans Serif\")\n << PlotStream::Size(24)\n << title\n << PlotStream::EndP();\n\n PlotStream xLabelStream(view_ptr->xLabelTextEdit());\n xLabelStream << PlotStream::Clear()\n << PlotStream::Center()\n << PlotStream::Family(\"Sans Serif\")\n << PlotStream::Size(24)\n << xLabel\n << PlotStream::EndP();\n\n PlotStream yLabelStream(view_ptr->yLabelTextEdit());\n yLabelStream << PlotStream::Clear()\n << PlotStream::Center()\n << PlotStream::Family(\"Sans Serif\")\n << PlotStream::Size(24)\n << yLabel\n << PlotStream::EndP();\n \n return view_ptr;\n}", "meta": {"hexsha": "30878b19a7641708e81ebb2fa6591bdd294fd28c", "size": 7404, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Assignments/Assignments_12/EX7/main.cpp", "max_stars_repo_name": "CaoSY/PittCompMethods", "max_stars_repo_head_hexsha": "853c36676df140eecd249bd9905eb9fa704f1585", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assignments/Assignments_12/EX7/main.cpp", "max_issues_repo_name": "CaoSY/PittCompMethods", "max_issues_repo_head_hexsha": "853c36676df140eecd249bd9905eb9fa704f1585", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assignments/Assignments_12/EX7/main.cpp", "max_forks_repo_name": "CaoSY/PittCompMethods", "max_forks_repo_head_hexsha": "853c36676df140eecd249bd9905eb9fa704f1585", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4736842105, "max_line_length": 180, "alphanum_fraction": 0.6442463533, "num_tokens": 2048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6859731728870447}} {"text": "// Implementing the class that is defined in the header file: PerpetualAmericanOption.hpp\r\n//\r\n// (c) Sudhansh Dua\r\n\r\n\r\n#include \"PerpetualAmericanOption.hpp\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n\r\ndouble PerpetualAmericanOption::CallPrice() const\r\n{\r\n\treturn ::PerpetualCall(S, K, r, sig, b);\r\n}\r\n\r\ndouble PerpetualAmericanOption::PutPrice() const\r\n{\r\n\treturn ::PerpetualPut(S, K, r, sig, b);\r\n}\r\n\r\nvoid PerpetualAmericanOption::init()\t\t// Initialising all the default values\r\n{\r\n\t//\tDefault values\r\n\tr = 0.03;\r\n\tsig = 0.2;\r\n\tK = 105;\r\n\tS = 100;\t\t\t\t//\tDefault stock price \r\n\tb = r;\t\t\t\t\t//\tBlack - Scholes(1973) stock option model : b = r\r\n\r\n\ttype = \"C\";\t\t\t\t//\tCall option as the default\r\n}\r\n\r\nvoid PerpetualAmericanOption::copy(const PerpetualAmericanOption& option)\r\n{\r\n\tr = option.r;\r\n\tsig = option.sig;\r\n\tK = option.K;\r\n\tb = option.b;\r\n\ttype = option.type;\r\n\tS = option.S;\r\n}\r\n\r\n\r\n//\tConstructors and destructor\r\n//\tDefault Constructor\r\nPerpetualAmericanOption::PerpetualAmericanOption() : Option()\r\n{\r\n\tinit();\r\n}\r\n\r\n//\tCopy constructor\r\nPerpetualAmericanOption::PerpetualAmericanOption(const PerpetualAmericanOption& option) : Option(option)\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nPerpetualAmericanOption::PerpetualAmericanOption(const double& S1, const double& K1, const double& r1,\r\n\tconst double& sig1, const double& b1, const string type1) : Option(), S(S1), K(K1), r(r1), sig(sig1), b(b1), type(type1) {}\r\n\r\n//\tDestructor\r\nPerpetualAmericanOption::~PerpetualAmericanOption() {}\r\n\r\n\r\n//\tAssignment Operator\r\nPerpetualAmericanOption& PerpetualAmericanOption::operator = (const PerpetualAmericanOption& option)\r\n{\r\n\tif (this == &option)\r\n\t{\r\n\t\treturn *this;\t\t//\tSelf-assignment check!\r\n\t}\r\n\tOption::operator = (option);\r\n\tcopy(option);\r\n\treturn *this;\r\n}\r\n\r\n\r\n// Functions that calculate the option price\r\ndouble PerpetualAmericanOption::Price() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallPrice();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutPrice();\r\n\t}\r\n}\r\n\r\n\r\n// Modifier functions\r\nvoid PerpetualAmericanOption::toggle()\t\t\t\t//\tChange the option type\r\n{\r\n\ttype = ((type == \"C\") ? \"P\" : \"C\");\r\n}\r\n\r\n// Global functions\r\ndouble PerpetualCall(const double S, const double K, const double r, const double sig, const double b)\r\n{\r\n\tdouble y1 = 0.5 - (b / (sig * sig)) + sqrt(pow(((b / (sig * sig)) - 0.5), 2) + (2 * r / (sig * sig)));\r\n\r\n\tif (y1 == 1.0)\r\n\t{\r\n\t\treturn S;\r\n\t}\r\n\tdouble C = (K / (y1 - 1)) * pow(((y1 - 1) / y1) * (S / K), y1);\r\n\r\n\treturn C;\r\n}\r\n\r\n\r\ndouble PerpetualPut(const double S, const double K, const double r, const double sig, const double b)\r\n{\r\n\tdouble y2 = 0.5 - (b / (sig * sig)) - sqrt(pow(((b / (sig * sig)) - 0.5), 2) + (2 * r / (sig * sig)));\r\n\r\n\tif (y2 == 1.0)\r\n\t{\r\n\t\treturn S;\r\n\t}\r\n\tdouble P = (K / (1 - y2)) * pow(((y2 - 1) / y2) * (S / K), y2);\r\n\r\n\treturn P;\r\n}\r\n\r\n", "meta": {"hexsha": "592df624800ba1d832d20a228a9f7ee4627e2b8a", "size": 2933, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PerpetualAmericanOption.cpp", "max_stars_repo_name": "sudhanshdua/Option_Classes", "max_stars_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PerpetualAmericanOption.cpp", "max_issues_repo_name": "sudhanshdua/Option_Classes", "max_issues_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PerpetualAmericanOption.cpp", "max_forks_repo_name": "sudhanshdua/Option_Classes", "max_forks_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2196969697, "max_line_length": 125, "alphanum_fraction": 0.6310944426, "num_tokens": 865, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972549785203, "lm_q2_score": 0.7879311906630568, "lm_q1q2_score": 0.6859707317032143}} {"text": "#include \"homography/compute_homography_model.hpp\"\n\n#include \n#include \n#include \n\n#include \"homography/compute_homography_error.hpp\"\n\nusing namespace Eigen;\nusing namespace cv;\n\nHomographyModel ComputeHomographyModel::operator()(vector m) {\n MatrixXd A = MatrixXd::Zero(2*m.size(), 8);\n VectorXd b = VectorXd::Zero(2*m.size());\n\n // normalize the points\n double m_x=0, m_y=0, d=0;\n double m_xp=0, m_yp=0, dp=0;\n\n // calculate translation\n for(size_t i = 0; i < m.size(); i++) {\n HomographyMeasurement& measurement = m[i];\n float &x = measurement.src.x, &y = measurement.src.y, &xp = measurement.dst.x, &yp = measurement.dst.y;\n m_x += x;\n m_y += y;\n m_xp += xp;\n m_yp += yp;\n }\n m_x /= m.size(), m_y /= m.size(), m_xp /= m.size(), m_yp /= m.size();\n\n // calculate distance\n for(size_t i = 0; i < m.size(); i++) {\n HomographyMeasurement& measurement = m[i];\n float &x = measurement.src.x, &y = measurement.src.y, &xp = measurement.dst.x, &yp = measurement.dst.y;\n d += sqrt((x-m_x)*(x-m_x) + (y-m_y)*(y-m_y));\n dp += sqrt((xp-m_xp)*(xp-m_xp) + (yp-m_yp)*(yp-m_yp));\n }\n d /= sqrt(2)*m.size(), dp /= sqrt(2)*m.size();\n\n // transform points\n for(size_t i = 0; i < m.size(); i++) {\n HomographyMeasurement& measurement = m[i];\n float &x = measurement.src.x, &y = measurement.src.y, &xp = measurement.dst.x, &yp = measurement.dst.y;\n x = (x-m_x)/d; \n y = (y-m_y)/d;\n xp = (xp-m_xp)/dp;\n yp = (yp-m_yp)/dp;\n }\n\n Matrix3d T = Matrix3d::Zero();\n Matrix3d Tpi = Matrix3d::Zero();\n Matrix3d S = Matrix3d::Zero();\n Matrix3d Spi = Matrix3d::Zero();\n\n T(0,2) = -m_x;\n T(1,2) = -m_y;\n T(0,0) = T(1,1) = T(2,2) = 1;\n S(0,0) = S(1,1) = 1/d;\n S(2,2) = 1;\n\n Tpi(0,2) = +m_xp;\n Tpi(1,2) = +m_yp;\n Tpi(0,0) = Tpi(1,1) = Tpi(2,2) = 1;\n Spi(0,0) = Spi(1,1) = dp;\n Spi(2,2) = 1;\n\n for(size_t i = 0; i < m.size(); i++) {\n const HomographyMeasurement& measurement = m[i];\n double x = measurement.src.x, y = measurement.src.y, xp = measurement.dst.x, yp = measurement.dst.y;\n\n A(2*i,0) = x;\n A(2*i,1) = y;\n A(2*i,2) = 1;\n A(2*i,6) = -x*xp;\n A(2*i,7) = -y*xp;\n // A(2*i,8) = -xp;\n\n A(2*i+1,3) = x;\n A(2*i+1,4) = y;\n A(2*i+1,5) = 1;\n A(2*i+1,6) = -x*yp;\n A(2*i+1,7) = -y*yp;\n // A(2*i+1,8) = -yp;\n\n b(2*i) = xp;\n b(2*i+1) = yp;\n }\n FullPivHouseholderQR solver(A);\n auto h = solver.solve(b);\n\n Matrix3d H;\n\n H(0,0) = h(0);\n H(0,1) = h(1);\n H(0,2) = h(2);\n H(1,0) = h(3);\n H(1,1) = h(4);\n H(1,2) = h(5);\n H(2,0) = h(6);\n H(2,1) = h(7);\n H(2,2) = 1;\n \n H = Tpi*Spi*H*S*T;\n \n return HomographyModel(H/H(2,2));\n};", "meta": {"hexsha": "ed3da279e3bfcd6ff65c6f19c90c3444d9363ff9", "size": 2719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/homography/compute_homography_model.cpp", "max_stars_repo_name": "matheuscarius/project-inf573", "max_stars_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/homography/compute_homography_model.cpp", "max_issues_repo_name": "matheuscarius/project-inf573", "max_issues_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/homography/compute_homography_model.cpp", "max_forks_repo_name": "matheuscarius/project-inf573", "max_forks_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.6509433962, "max_line_length": 107, "alphanum_fraction": 0.5476278043, "num_tokens": 1111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951552333005, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6859577292976937}} {"text": "#pragma once\n#ifndef PARAMETERIZATION_HPP\n#define PARAMETERIZATION_HPP\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"./lib/Mesh_Library/Mesh/mesh.h\"\n#include \"./lib/Mesh_Library/Mesh/iterators.h\"\n#include \"./lib/mesh_library/Geometry/Point.h\"\n#include \"./lib/mesh_library/Geometry/Point2.H\"\n#define M_PI 3.14159\nusing std::vector;\nusing std::set;\nusing namespace MeshLib;\nusing namespace Eigen;\n\n//Computes the harmonic weight for the edge.\nfloat HarmonicWeight(CEdge* e) {\n\t// length of edge shared by the two triangles.\n\tfloat c = e->GetLength();\n\tCHalfEdge* he = e->halfedge(0);\n\n\tauto a1_p1 = he->he_next()->vertex()->point();\n\tauto a1_p2 = he->he_next()->he_next()->vertex()->point();\n\tfloat a1 = CPoint::distance(a1_p1, a1_p2);\n\t\n\tauto b1_p1 = he->he_next()->he_next()->vertex()->point();\n\tauto b1_p2 = he->he_next()->he_next()->he_next()->vertex()->point();\n\tfloat b1 = CPoint::distance(b1_p1, b1_p2);\n\n\the = e->halfedge(1);\n\n\tauto a2_p1 = he->he_next()->vertex()->point();\n\tauto a2_p2 = he->he_next()->he_next()->vertex()->point();\n\tfloat a2 = CPoint::distance(a2_p1, a2_p2);\n\t\n\tauto b2_p1 = he->he_next()->he_next()->vertex()->point();\n\tauto b2_p2 = he->he_next()->he_next()->he_next()->vertex()->point();\n\tfloat b2 = CPoint::distance(b2_p1, b2_p2);\n\n\tfloat cos_u = (b1*b1 + a1*a1 - c*c) / (2.0 * b1 * a1);\n\tfloat cos_v = (b2*b2 + a2*a2 - c*c) / (2.0 *b2 *a2);\n\n\tfloat sin_u = sqrt(abs(1.0 - cos_u*cos_u));\n\tfloat sin_v = sqrt(abs(1.0 - cos_v*cos_v));\n\n\tfloat weight;\n\tweight = ((cos_u / sin_u) + (cos_v / sin_v)) * 0.5;\n\n\treturn weight;\n\n}\n\nvoid uvMap(CMesh* mesh, std::vector* outUvs) {\n\n\n\tstd::list mvs = mesh->vertices();\n\tstd::list mfs = mesh->faces();\n\tstd::list mes = mesh->edges();\n\tstd::list mhes = mesh->halfedges();\n\n\tstd::vector verts{ std::begin(mvs), std::end(mvs)};\n\tstd::vector faces {std::begin(mfs), std::end(mfs)};\n\tstd::vector edges { std::begin(mes), std::end(mes)};\n\n\tconst int N = verts.size();\n\n\n\tstd::list::iterator firstBoundary = mesh->EndHalfEdges();\n\tstd::list::iterator currentBoundary = mesh->EndHalfEdges();\n\n\tfor(std::list::iterator hiter = mesh->halfedges().begin(); hiter != mesh->halfedges().end(); hiter++ )\n\t{\n\t\tCHalfEdge* item = *hiter;\n\t\tif(mesh->isBoundary(hiter)) {\n\t\t\tfirstBoundary = hiter;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tstd::map vertexMap;\n\t\n\tfor (std::vector::iterator it = verts.begin(); it != verts.end(); ++it) {\n\t\tCVertex* item = *it;\n\t\titem->set_index(vertexMap.size());\n\t\tvertexMap.insert(std::make_pair(vertexMap.size(), item));\n\n\t}\n\n\tstd::vector boundaryEdges;\n\tstd::vector boundaryVertices;\n\tset boundarySet;\n\tvector edgeLengths; \n\tfloat totalEdgeLength = 0.0;\n\tstd::list::iterator previousBoundary = firstBoundary;\n\tcurrentBoundary = firstBoundary;\n\tint testi = 0;\n\n\tCVertex* prevItem;\n\tfor (std::vector::iterator it = verts.begin(); it != verts.end(); ++it) {\n\t\tCVertex* item = *it;\n\t\tif (item->boundary()) {\n\t\t\tif (testi == 0) {\n\t\t\t\ttesti++;\n\t\t\t\tprevItem = item;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tboundaryVertices.push_back(item);\n\t\t\tauto halfedge = item->halfedge();\n\t\t\tboundaryEdges.push_back(halfedge);\n\t\t\tboundarySet.insert(item->index());\n\t\t\tedgeLengths.push_back(totalEdgeLength);\n\t\t\tauto bo_p1 = prevItem->point();\n\t\t\tauto bo_p2 = item->point();\n\t\t\ttotalEdgeLength += CPoint::distance(bo_p1, bo_p2);\n\t\t\ttesti++;\n\t\t\tprevItem = item;\n\t\t}\n\t}\n\n\tEigen::VectorXd bx(N);\n\tEigen::VectorXd by(N);\n\n\tfor(int i =0; iindex()] = cos(theta);\n\t\tby[v->index()] = sin(theta);\n\t}\n\n\ttypedef Eigen::Triplet Triplet;\n\ttypedef Eigen::SparseMatrix SparseMatrix;\n\tSparseMatrix W(N, N);\n\n\tvector triplets;\n\tvector diag;\n\tdiag.resize(N, 0);\n\n\tfor (std::vector::iterator it = edges.begin(); it != edges.end(); ++it) {\n\t\tCEdge* item = *it;\n\t\tif (mesh->isBoundary(item)) {\n\t\t\tcontinue;\n\t\t}\n\t\tCVertex* v0 = item->halfedge(0)->vertex();\n\t\tCVertex* v1 = item->halfedge(1)->vertex();\n\n\t\tint i0 = v0->index();\n\t\tint i1 = v1->index();\n\n\t\tfloat weight = HarmonicWeight(item);\n\n\n\t\tif (boundarySet.count(i0) == 0) {\n\t\t\ttriplets.push_back(Triplet(i0, i1, weight));\n\t\t}\n\t\tif (boundarySet.count(i1) == 0) {\n\t\t\ttriplets.push_back(Triplet(i1, i0, weight));\n\t\t}\n\n\t\tdiag[i0] -= weight;\n\t\tdiag[i1] -= weight;\n\t}\n\n\tfor (int i = 0; i < diag.size(); i++) {\n\t\tif(boundarySet.count(i) > 0) {\n\n\t\t\ttriplets.push_back(Triplet(i, i, 1.0));\n\t\t}\n\t\telse {\n\t\t\ttriplets.push_back(Triplet(i, i, diag[i]));\n\t\t}\n\t}\n\tW.setFromTriplets(triplets.begin(), triplets.end());\n\tEigen::SparseLU solver;\n\tsolver.compute(W);\n\tif (solver.info() != Eigen::Success) {\n\t\tprintf(\"ERROR: found no decomposition of sparse matrix\");\n\t\tassert(true);\n\t}\n\n\tEigen::VectorXd x(N);\n\tEigen::VectorXd y(N);\n\tx = solver.solve(bx);\n\ty = solver.solve(by);\n\n\tstd::vector uvpoints;\n\tfor (int i = 0; i < N; i++) {\n\t\toutUvs->push_back(x[i]);\n\t\toutUvs->push_back(y[i]);\n\n\t\tCPoint2 cp(x[i], y[i]);\n\t\tuvpoints.push_back(cp);\n\t\tverts[i]->set_uv(cp);\n\n\t\tstd::ostringstream attrs;\n\t\tattrs << verts[i]->string() << \" uv=(\" << std::to_string(cp[0]) << \" \" << std::to_string(cp[1]) << \")\";\n\t\tverts[i]->set_string(attrs.str());\n\t}\n\n}\n\nvoid Parameterization(std::string meshfile, std::string outmeshfile) {\n\tCMesh mesh;\n\tstd::vector outUvs;\n\tmesh.read_m(meshfile.c_str());\n\tuvMap(&mesh, &outUvs);\n\tmesh.write_m(outmeshfile.c_str());\n\n\treturn;\n}\n\n#endif\n\n", "meta": {"hexsha": "7defb71e5d2e03f90caadc0a982f264ee8ce8f49", "size": 5831, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Parameterization.hpp", "max_stars_repo_name": "Jammyhammy/Amazing-Mesh-Processing", "max_stars_repo_head_hexsha": "73941fa0e1a37dde880c5858396ad3d2ece64f8b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Parameterization.hpp", "max_issues_repo_name": "Jammyhammy/Amazing-Mesh-Processing", "max_issues_repo_head_hexsha": "73941fa0e1a37dde880c5858396ad3d2ece64f8b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Parameterization.hpp", "max_forks_repo_name": "Jammyhammy/Amazing-Mesh-Processing", "max_forks_repo_head_hexsha": "73941fa0e1a37dde880c5858396ad3d2ece64f8b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.352173913, "max_line_length": 115, "alphanum_fraction": 0.6458583433, "num_tokens": 1835, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6859577237915074}} {"text": "/**\n * @brief Linear Discriminant Analysis with Eigen\n * \n * Dead simple, blazing fast LDA, \\cite friedman2001elements\n * \n * @file lda.hpp\n * @author François-David Collin \n * @date 2018-08-31\n */\n#pragma once\n\n#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\ntypedef Matrix VectorXs;\n\n/**\n * @brief Computes lda with Trevor/hastie algorithm\n * \n * @param x data\n * @param y labels from 0 to K \n * @param Ld computes matrix whoses columns are Ld vectors\n */\ntemplate\nstd::vector lda(const MatrixBase &x,\n const VectorXs &y,\n MatrixXd& Ld)\n{\n auto n = x.rows();\n auto K = y.maxCoeff() + 1;\n auto p = x.cols();\n\n // M = Centroids\n MatrixXd M = MatrixXd::Zero(K, p);\n VectorXd m = VectorXd::Zero(p);\n VectorXs d = VectorXs::Zero(K);\n\n for (auto i = 0; i < n; i++)\n {\n auto c = y[i];\n auto r = x.row(i);\n d[c]++;\n M.row(c) += r;\n m += r;\n }\n\n for (auto c = 0; c < K; c++)\n {\n M.row(c) /= static_cast(d[c]);\n }\n\n // m = Global mean\n m /= static_cast(n);\n\n // D is x centered data and sorted by classes\n MatrixXd D(n, p);\n\n // W = Within-class covariance matrix\n MatrixXd Wraw = MatrixXd::Zero(p, p);\n size_t slicepos = 0;\n for (auto c = 0; c < K; c++)\n {\n // Dc is a single class subrange of x\n MatrixXd Dc = x.block(slicepos, 0, d[c], p);\n // Centering\n Dc.rowwise() -= M.row(c);\n Wraw += Dc.transpose() * Dc;\n slicepos += d[c];\n }\n Wraw /= static_cast(n - K);\n auto validvars = std::vector();\n for(auto i = 0; i< x.cols(); i++) {\n if (std::abs(Wraw(i,i)) >= 1.0e-8) validvars.push_back(i);\n }\n auto W = Wraw(validvars,validvars);\n // [4,4]((0.265008,0.0927211,0.167514,0.0384014),(0.0927211,0.115388,0.0552435,0.0327102),(0.167514,0.0552435,0.185188,0.0426653),(0.0384014,0.0327102,0.0426653,0.0418816))\n\n // Calculate pseudo-inverse square root for W with SVD\n // https://math.stackexchange.com/a/1176942\n JacobiSVD svd(W,ComputeFullU|ComputeFullV);\n double tolerance = std::numeric_limits::epsilon() * std::max(W.cols(), W.rows()) * svd.singularValues().array().abs().maxCoeff();\n auto W12 = svd.matrixV() * (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse().sqrt(), 0).matrix().asDiagonal() * svd.matrixU().adjoint();\n // SelfAdjointEigenSolver svd(W);\n // if (svd.info() != Success) {\n // throw std::runtime_error(\"LDA's first solver failed\");\n // }\n //auto W12 = svd.matrixU() * svd.eigenvalues().array().inverse().sqrt().matrix().asDiagonal() * svd.matrixU().transpose();\n// auto W12 = svd.operatorInverseSqrt();\n MatrixXd Mvalid = M(all,validvars);\n MatrixXd Mstar = Mvalid * W12;\n VectorXd mstar = VectorXd::Zero(validvars.size());\n for (auto c = 0; c < K; c++)\n mstar += Mstar.row(c);\n mstar /= static_cast(K);\n\n Mstar.rowwise() -= mstar.transpose();\n auto Bstar = Mstar.transpose() * Mstar / static_cast(K - 1);\n\n // We get the eigenvectors of B* via SVD\n JacobiSVD svd2(Bstar,ComputeThinU);\n MatrixXd Vl = W12 * svd2.matrixU();\n Ld = Vl.leftCols(K-1);\n return validvars;\n}", "meta": {"hexsha": "8a05bf401d43aa4bfe242f028312ddbe6de43115", "size": 3410, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lda-eigen.hpp", "max_stars_repo_name": "diyabc/abcranger", "max_stars_repo_head_hexsha": "4df0dc1a7c5d276be7c2f8ec1d486f7fd5c5f75b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2020-02-07T12:11:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-02T16:32:37.000Z", "max_issues_repo_path": "src/lda-eigen.hpp", "max_issues_repo_name": "vitorpavinato/abcranger", "max_issues_repo_head_hexsha": "71f950817bedeebed12d13610d8747c6dcc75a72", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2019-06-20T11:39:02.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-30T04:13:46.000Z", "max_forks_repo_path": "src/lda-eigen.hpp", "max_forks_repo_name": "fradav/abcranger", "max_forks_repo_head_hexsha": "4df0dc1a7c5d276be7c2f8ec1d486f7fd5c5f75b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-07-17T03:00:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-29T13:31:10.000Z", "avg_line_length": 31.8691588785, "max_line_length": 185, "alphanum_fraction": 0.6017595308, "num_tokens": 1083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.7549149868676284, "lm_q1q2_score": 0.6859292733349153}} {"text": "#include \n#include \n#include \n\nusing namespace boost::numeric::ublas;\nusing namespace std;\n\n// A custom, more pretty way to print matrices\nstd::ostream &operator<<(std::ostream &Str, matrix const &v)\n{\n\tfor (int i = 0; i < v.size1(); i++)\n\t{\n\t\tStr << ((i == 0) ? \"[[\" : \" [\");\n\t\tfor (int j = 0; j < v.size2(); j++)\n\t\t{\n\t\t\tStr << setw(4);\n\t\t\tStr << v(i, j);\n\t\t\tStr << setw(0);\n\t\t}\n\t\tStr << ((i == v.size1() - 1) ? \"]]\" : \"]\");\n\t\tif (i != v.size1() - 1)\n\t\t\tStr << endl;\n\t}\n\treturn Str;\n}\n\nint main()\n{\n\tmatrix A(2, 2);\n\tA(0, 0) = 1;\n\tA(0, 1) = 2;\n\tA(1, 0) = 3;\n\tA(1, 1) = 4;\n\n\tmatrix B(2, 2);\n\tB(0, 0) = -1;\n\tB(0, 1) = 0;\n\tB(1, 0) = 0;\n\tB(1, 1) = -1;\n\n\tmatrix C = prod(A, B);\n\n\tcout << \"Multiplication of \" << endl\n\t\t << A << endl;\n\tcout << \"and \" << endl\n\t\t << B << endl;\n\tcout << \"is\" << endl;\n\tcout << C << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "cadf7ea1ef1ab1fb97a067ec1bac7e7a5e0de80e", "size": 910, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "Cpp SOURCE CODE/Boost/uBLAS/matmult.cxx", "max_stars_repo_name": "DevJeffersonL/OPEN-SOURCE-", "max_stars_repo_head_hexsha": "8e650337ebab7608a4bdb5106df74e17b0e0e995", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-30T06:19:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:19:22.000Z", "max_issues_repo_path": "Cpp SOURCE CODE/Boost/uBLAS/matmult.cxx", "max_issues_repo_name": "DevJeffersonL/OPEN-SOURCE-CODE", "max_issues_repo_head_hexsha": "8e650337ebab7608a4bdb5106df74e17b0e0e995", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Cpp SOURCE CODE/Boost/uBLAS/matmult.cxx", "max_forks_repo_name": "DevJeffersonL/OPEN-SOURCE-CODE", "max_forks_repo_head_hexsha": "8e650337ebab7608a4bdb5106df74e17b0e0e995", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.8431372549, "max_line_length": 68, "alphanum_fraction": 0.4934065934, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.685911058091755}} {"text": "#include \n#include \n\n// from numpy import random\nusing Eigen::MatrixXd; // Objeto que me crea una matriz DINAMICA\nusing namespace std;\n\nint main()\n{\n MatrixXd m(2,2);\n m(0,0) = 3;\n m(1,0) = 2.5;\n m(0,1) = -1;\n m(1,1) = m(1,0) + m(0,1);\n cout << m << endl;\n}", "meta": {"hexsha": "bfe90ee22cbe4a62b8f199a025e683e03b5be8c2", "size": 286, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ejercicios/semana5/matrix1.cpp", "max_stars_repo_name": "lschinchilla/FISI2028-202120", "max_stars_repo_head_hexsha": "5c4a80494f5867a91786771f388e9e3c9ef20eb2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-08-17T19:19:11.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:26:41.000Z", "max_issues_repo_path": "ejercicios/semana5/matrix1.cpp", "max_issues_repo_name": "lschinchilla/FISI2028-202120", "max_issues_repo_head_hexsha": "5c4a80494f5867a91786771f388e9e3c9ef20eb2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2021-09-18T01:33:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-16T00:11:45.000Z", "max_forks_repo_path": "ejercicios/semana5/matrix1.cpp", "max_forks_repo_name": "lschinchilla/FISI2028-202120", "max_forks_repo_head_hexsha": "5c4a80494f5867a91786771f388e9e3c9ef20eb2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 28.0, "max_forks_repo_forks_event_min_datetime": "2021-09-17T22:38:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T19:59:49.000Z", "avg_line_length": 17.875, "max_line_length": 64, "alphanum_fraction": 0.5909090909, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705732, "lm_q2_score": 0.7772998560157663, "lm_q1q2_score": 0.6859110487326173}} {"text": "// This file is part of:\n// gnss-sim: A GNSS Signal Simulator\n//\n// Copyright (c) 2020 Damien Dusha\n// SPDX-License-Identifier: MIT\n//\n// Derived from https://github.com/osqzss/gps-sdr-sim (MIT Licence):\n// Copyright (c) 2015-2020 Takuji Ebinuma\n\n#include \"geodesy.h\"\n#include \"gpssim.h\"\n#include \"gps_math.h\"\n\n#include \n\n#include \n\nGeodeticPosition xyz2llh(const Eigen::Vector3d &ecef)\n{\n\tconstexpr double a = WGS84_RADIUS;\n\tconstexpr double e = WGS84_ECCENTRICITY;\n\tconstexpr double e2 = e*e;\n\n constexpr double eps = 1.0e-3;\n\tif (ecef.norm() < eps)\n\t{\n // Invalid ECEF vector\n return GeodeticPosition::FromRadians(0.0, 0.0, -a);\n\t}\n\n\tconst double x = ecef.x();\n\tconst double y = ecef.y();\n\tconst double z = ecef.z();\n\n\tconst double rho2 = x*x + y*y;\n\tdouble dz = e2*z;\n\n double n, zdz, nh;\n\twhile (1)\n\t{\n\t\tzdz = z + dz;\n\t\tnh = std::sqrt(rho2 + zdz*zdz);\n\t\tconst double slat = zdz / nh;\n\t\tn = a / std::sqrt(1.0-e2*slat*slat);\n\t\tconst double dz_new = n*e2*slat;\n\n\t\tif (std::fabs(dz-dz_new) < eps)\n\t\t\tbreak;\n\n\t\tdz = dz_new;\n\t}\n\n const double lat_rad = std::atan2(zdz, std::sqrt(rho2));\n const double lon_rad = std::atan2(y, x);\n const double height_m = nh - n;\n\n return GeodeticPosition::FromRadians(lat_rad, lon_rad, height_m);\n}\n\nEigen::Vector3d llh2xyz(const GeodeticPosition &llh)\n{\n\tconstexpr double a = WGS84_RADIUS;\n\tconstexpr double e = WGS84_ECCENTRICITY;\n\tconstexpr double e2 = e*e;\n\n\tconst double clat = std::cos(llh.latitude_rad());\n\tconst double slat = std::sin(llh.latitude_rad());\n\tconst double clon = std::cos(llh.longitude_rad());\n\tconst double slon = std::sin(llh.longitude_rad());\n\tconst double d = e*slat;\n\n\tconst double n = a / std::sqrt(1.0-d*d);\n\tconst double nph = n + llh.height_m();\n\n\tconst double tmp = nph*clat;\n\tconst double x = tmp*clon;\n\tconst double y = tmp*slon;\n\tconst double z = ((1.0-e2)*n + llh.height_m())*slat;\n\n\treturn Eigen::Vector3d(x, y, z);\n}\n\nvoid ltcmat(const GeodeticPosition &llh, double t[3][3])\n{\n\tconst double slat = std::sin(llh.latitude_rad());\n\tconst double clat = std::cos(llh.latitude_rad());\n\tconst double slon = std::sin(llh.longitude_rad());\n\tconst double clon = std::cos(llh.longitude_rad());\n\n\tt[0][0] = -slat*clon;\n\tt[0][1] = -slat*slon;\n\tt[0][2] = clat;\n\tt[1][0] = -slon;\n\tt[1][1] = clon;\n\tt[1][2] = 0.0;\n\tt[2][0] = clat*clon;\n\tt[2][1] = clat*slon;\n\tt[2][2] = slat;\n}\n\nvoid ecef2neu(const double *xyz, double t[3][3], double *neu)\n{\n\tneu[0] = t[0][0]*xyz[0] + t[0][1]*xyz[1] + t[0][2]*xyz[2];\n\tneu[1] = t[1][0]*xyz[0] + t[1][1]*xyz[1] + t[1][2]*xyz[2];\n\tneu[2] = t[2][0]*xyz[0] + t[2][1]*xyz[1] + t[2][2]*xyz[2];\n\n\treturn;\n}\n\nAzimuthElevation neu2azel(const double *neu)\n{\n\tdouble azimuth_rad = std::atan2(neu[1],neu[0]);\n\tif (azimuth_rad < 0.0)\n\t\tazimuth_rad += 2.0*PI;\n \n\tconst double ne = std::hypot(neu[0], neu[1]);\n\tconst double elevation_rad = std::atan2(neu[2], ne);\n\n return AzimuthElevation::FromRadians(azimuth_rad, elevation_rad);\n}\n", "meta": {"hexsha": "1f4770034afd1c22c37fc023dbbf6d117917bb4d", "size": 2964, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geodesy.cpp", "max_stars_repo_name": "damiendusha/gnss-sim", "max_stars_repo_head_hexsha": "100cef74d1d14ea36ee94038405270ede9723088", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-08-12T21:27:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-18T17:44:55.000Z", "max_issues_repo_path": "geodesy.cpp", "max_issues_repo_name": "damiendusha/gnss-sim", "max_issues_repo_head_hexsha": "100cef74d1d14ea36ee94038405270ede9723088", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geodesy.cpp", "max_forks_repo_name": "damiendusha/gnss-sim", "max_forks_repo_head_hexsha": "100cef74d1d14ea36ee94038405270ede9723088", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-13T22:33:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T14:40:43.000Z", "avg_line_length": 24.4958677686, "max_line_length": 69, "alphanum_fraction": 0.6396761134, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582574225517, "lm_q2_score": 0.737158174177441, "lm_q1q2_score": 0.6858949101899317}} {"text": "#include \"nombre_modulaire.h\"\n#include \"numerique.h\"\n\n#include \n\nstd::ostream &operator<<(std::ostream &os, const nombre_modulaire &a) {\n os << a.value() << \"[\" << a.modulo() << \"]\";\n return os;\n}\n\nstd::pair nombre_modulaire::factoriel2(size_t modulo, size_t n) {\n nombre_modulaire resultat(modulo, 1);\n size_t exposant = 0;\n bool sgn = false;\n while (n > 0) {\n for (size_t i = n % modulo; i > 1; --i)\n resultat *= i;\n n /= modulo;\n sgn ^= (n % 2 == 1);\n exposant += n;\n }\n return std::make_pair(exposant, sgn ? -resultat : resultat);\n}\n\nvoid nombre_modulaire::meme_mod(const nombre_modulaire &n1, const nombre_modulaire &n2) {\n if (n1._modulo != n2._modulo) {\n throw std::domain_error(\"Modulo different !\");\n }\n}\n\nvoid nombre_modulaire::meme_mod(const nombre_modulaire &n) const {\n meme_mod(*this, n);\n}\n\nnombre_modulaire::nombre_modulaire(const nombre_modulaire &n) : _modulo(n._modulo), _value(n._value) {\n}\n\nnombre_modulaire nombre_modulaire::puissance(nombre_modulaire a, size_t n) {\n nombre_modulaire result(a._modulo, 1);\n while (n > 0) {\n if (n % 2)\n result *= a;\n a *= a;\n n /= 2;\n }\n return result;\n}\n\nnombre_modulaire nombre_modulaire::puissance(size_t a, size_t n, size_t modulo) {\n nombre_modulaire result(modulo, 1);\n nombre_modulaire p(modulo, a);\n while (n > 0) {\n if (n % 2)\n result *= p;\n p *= a;\n n /= 2;\n }\n return result;\n}\n\n\nunsigned long long nombre_modulaire::value() const { return _value; }\n\nsize_t nombre_modulaire::modulo() const { return _modulo; }\n\nnombre_modulaire nombre_modulaire::operator-() const {\n return nombre_modulaire(_modulo, _modulo - value());\n}\n\nnombre_modulaire &nombre_modulaire::operator=(const nombre_modulaire &op) {\n // meme_mod(op);\n\n _modulo = op._modulo;\n _value = op._value;\n return *this;\n}\n\nnombre_modulaire &nombre_modulaire::operator+=(const nombre_modulaire &op) {\n meme_mod(op);\n\n _value += op._value;\n if (_value >= _modulo) _value -= _modulo;\n return *this;\n}\n\nnombre_modulaire &nombre_modulaire::operator-=(const nombre_modulaire &op) {\n meme_mod(op);\n\n _value = _value < op._value ? _modulo + _value - op._value : _value - op._value;\n return *this;\n}\n\nnombre_modulaire &nombre_modulaire::operator*=(const nombre_modulaire &op) {\n meme_mod(op);\n\n uint128_t c = 0;\n boost::multiprecision::multiply(c, _value, op._value);\n _value = boost::multiprecision::integer_modulus(c, _modulo);\n\n return *this;\n}\n\nnombre_modulaire &nombre_modulaire::operator/=(const nombre_modulaire &op) {\n meme_mod(op);\n return operator*=(puissance(op, _modulo - 2));\n}\n\nnombre_modulaire nombre_modulaire::operator+(const nombre_modulaire &op) const {\n nombre_modulaire result(*this);\n result.operator+=(op);\n return result;\n}\n\nnombre_modulaire nombre_modulaire::operator-(const nombre_modulaire &op) const {\n nombre_modulaire result(*this);\n result.operator-=(op);\n return result;\n}\n\nnombre_modulaire nombre_modulaire::operator*(const nombre_modulaire &op) const {\n nombre_modulaire result(*this);\n result.operator*=(op);\n return result;\n}\n\nnombre_modulaire nombre_modulaire::operator/(const nombre_modulaire &op) const {\n nombre_modulaire result(*this);\n result.operator/=(op);\n return result;\n}\n\nnombre_modulaire nombre_modulaire::factoriel(size_t modulo, size_t n) {\n auto[exposant, resultat] = factoriel2(modulo, n);\n if (exposant > 0) {\n return nombre_modulaire(modulo, 0);\n } else {\n return resultat;\n }\n}\n\nnombre_modulaire nombre_modulaire::arrangement(size_t modulo, size_t n, size_t k) {\n auto fn = factoriel2(modulo, n);\n auto fnk = factoriel2(modulo, n - k);\n if (fn.first - fnk.first > 0)\n return nombre_modulaire(modulo, 0);\n return fn.second / fnk.second;\n}\n\nnombre_modulaire nombre_modulaire::coefficient_binomial(size_t modulo, size_t n, size_t k) {\n auto fn = factoriel2(modulo, n);\n auto fk = factoriel2(modulo, k);\n auto fnk = factoriel2(modulo, n - k);\n if (fn.first - fk.first - fnk.first > 0)\n return nombre_modulaire(modulo, 0);\n return fn.second / (fk.second * fnk.second);\n}\n", "meta": {"hexsha": "15fddd37562627dcb086243a892fa26238be8372", "size": 4328, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "maths/nombre_modulaire.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "maths/nombre_modulaire.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "maths/nombre_modulaire.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5668789809, "max_line_length": 102, "alphanum_fraction": 0.6621996303, "num_tokens": 1188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9304582632076909, "lm_q2_score": 0.7371581684030624, "lm_q1q2_score": 0.6858949090816759}} {"text": "#include \n#include \n#include \n#include \n#include // std::swap\n\n#include \"isam_plane3d.h\"\n\n\nnamespace isam {\n \n//copied from pop_up_wall rays is 3*n, each column is a ray staring from origin plane is (4,1) parameters, compute intersection output is 3*n \nvoid ray_plane_interact(const Eigen::MatrixXd &rays,const Eigen::Vector4d &plane,Eigen::MatrixXd &intersections)\n{ \n Eigen::VectorXd frac=-plane[3]/(plane.head(3).transpose()*rays).array(); //n*1 \n intersections= frac.transpose().replicate<3,1>().array() * rays.array();\n}\n// copied from pop_up_wall (update_plane_equation_from_seg_fast), don't want to depend on that. no ground. ground_seg_ray=invK*groundlines 3*2n, precomputed\n// output is not quaternion normized\nvoid get_wall_plane_equation(const Eigen::MatrixXd& ground_seg_ray, const Eigen::Matrix4d& transToWorld, Eigen::MatrixXd& all_planes_sensor_out)\n{\n if (ground_seg_ray.cols()>0)\n {\n\tEigen::Vector4d ground_plane_world(0,0,-1,0); //plane parameters for ground in world(footprint), treated as column vector\n\tEigen::Vector4d ground_plane_sensor = transToWorld.transpose()*ground_plane_world; // using a new pose to project\n\n\tEigen::MatrixXd ground_seg3d_sensor; // 3*2n\n\tray_plane_interact(ground_seg_ray,ground_plane_sensor,ground_seg3d_sensor);\n\n\tEigen::Matrix temp;\n\ttemp = ground_seg3d_sensor.transpose();\n\ttemp.resize(ground_seg3d_sensor.cols()/2,6); // n * 6\n\tground_seg3d_sensor = temp;\n\n\tint num_seg = ground_seg3d_sensor.rows();\n\tall_planes_sensor_out.resize(num_seg,4);\n\n\tfor (int seg=0;seggeneralized Schur decomposition and\n * is also known as QZ decomposition.\n *\n * The pair of matrices \\f$(A,B)\\f$ is also referred to as matrix\n * pencil and the problem of finding the eigenvalues of a pencil is called\n * the generalized eigenvalue problem.\n * A pencil is called regular if there is at least one value of\n * \\f$\\lambda\\f$ such that \\f$\\det(A-\\lambda B) \\ne 0\\f$.\n * We call eigenvalues of a matrix pencil \\f$(A,B)\\f$ all complex\n * numbers \\f$\\lambda\\f$ for which \\f$\\det(A-\\lambda B) = 0\\f$.\n * The set of the eigenvalues is called the spectrum of the pencil and\n * is written \\f$\\sigma(A,B)\\f$; specifically:\n * \\f[\n * \\sigma (A,B) = \\left\\{z \\in \\mathbb{C} : \\det(A-zB)=0\\right\\}\n * \\f]\n * If \\f$\\lambda \\in \\sigma (A,B)\\f$ and\n * \\f[\n * Ax = \\lambda Bx, \\quad x \\ne 0\n * \\f]\n * then \\f$x\\f$ is referred to as an eigenvector of \\f$A-\\lambda B\\f$.\n * Moreover, the pencil is said to have one or more eigenvalues at infinity if\n * \\f$B\\f$ has one or more \\f$0\\f$ eigenvalues.\n *\n * Although the decomposition is not unique, it yields the same generalized\n * eigenvalues that can be obtained by dividing the diagonal entries of \\f$S\\f$\n * by the corresponding diagonal entries of \\f$T\\f$.\n * Specifically, the generalized eigenvalues \\f$\\lambda\\f$ that solve the\n * generalized eigenvalue problem \\f$A x = \\lambda B x\\f$ (where \\f$x\\f$ is an\n * unknown nonzero vector) can be calculated as the ratio of the diagonal\n * elements of \\f$S\\f$ to those of \\f$T\\f$. That is, using subscripts to denote\n * matrix elements, the \\f$i\\f$-th generalized eigenvalue \\f$\\lambda_i\\f$\n * satisfies \\f$\\lambda_i = S_{ii} / T_{ii}\\f$.\n * The eigenvalues are finite when all the diagonal entries of \\f$T\\f$ are\n * nonzero.\n * By convention, the eigenvalues corresponding to zero diagonal entries of\n * \\f$T\\f$ are \\f$\\infty\\f$.\n * If both \\f$A\\f$ and \\f$B\\f$ are real, the complex eigenvalues occur in\n * conjugate pairs.\n * In this case, \\f$S\\f$ is a real quasi-upper triangular matrix.\n * Each \\f$2 \\times 2\\f$ block on the diagonal of \\f$S\\f$ corresponds to a\n * complex conjugate pair of eigenvalues, and the scalar diagonal entries\n * correspond to the real eigenvalues.\n * Such a decomposition is sometimes referred to as the generalized real\n * Schur decomposition.\n *\n * For more information see [1,2].\n *\n * \\note\n * Matlab users: the Matlab \\c qz function return the Hermitian of the \\f$Q\\f$\n * matrix computed by this decomposition, so that:\n * \\f{align}\n * S &= Q^H*A*Z,\\\\\n * T &= Q^H*B*Z\n * \\f}\n *\n * References:\n * - [1] Anderson et al,\n * The LAPACK User Guide,\n * http://www.netlib.org/lapack/lug/node56.html\n * - [2] Golub et al,\n * Matrix Computations, 3rd ed.,\n * (Sec. 7.7), Johns Hopkins University Press, 1996\n * .\n *\n * \\todo Optimize mem allocation similarly to eigen.hpp (where we used\n * work_n_LV, out_n_LV, work_n_RV, and out_n_RV).\n *\n *


\n *\n * Copyright (c) 2010-2011, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_QZ_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_QZ_HPP\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n//#include \n//#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n/// Cast the given function \\a f to the QZ selector signature.\n#define BOOST_UBLASX_DETAIL_QZ_SELECTOR_CAST(T,f) \\\n\t\t( \\\n\t\t\t::boost::is_complex::value \\\n\t\t\t\t? ( \\\n\t\t\t\t\t::boost::is_same::real_type>::value \\\n\t\t\t\t\t\t? reinterpret_cast< ::external_fp >(static_cast(f)) \\\n\t\t\t\t\t\t: reinterpret_cast< ::external_fp >(static_cast(f)) \\\n\t\t\t\t) \\\n\t\t\t\t: ( \\\n\t\t\t\t\t::boost::is_same::real_type>::value \\\n\t\t\t\t\t\t? reinterpret_cast< ::external_fp >(static_cast(f)) \\\n\t\t\t\t\t\t: reinterpret_cast< ::external_fp >(static_cast(f)) \\\n\t\t\t\t) \\\n\t\t)\n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\n/// Eigenvalues selectors for QZ factorization.\nenum qz_eigenvalues_selection\n{\n\tall_qz_eigenvalues, ///< select all eigenvalues in the order of appearance (essentially, no ordering is performed).\n\tlhp_qz_eigenvalues, ///< Stable continuous-time space: select eigenvalues in the left-half plane (\\f$\\operatorname{real}(E) < 0\\f$).\n\trhp_qz_eigenvalues, ///< Unstable continuous-time space: select eigenvalues in the right-half plane (\\f$\\operatorname{real}(E) > 0\\f$).\n\tudi_qz_eigenvalues, ///< Stable discrete-time space: select eigenvalues which are interior of unit disk (\\f$\\operatorname{abs}(E) < 1\\f$).\n\tudo_qz_eigenvalues ///< Unstable discrete-time space: select eigenvalues which are exterior of unit disk (\\f$\\operatorname{abs}(E) > 1\\f$).\n};\n\t\n\nnamespace detail {\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the left-half plane\n * (\\f$\\operatorname{real}(\\lambda) < 0\\f$) [complex single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_lhp_eigenval_sel(::std::complex a, ::std::complex b)\n{\n\t// Based on function ZB02OW.f from SLICOT 5.0\n\treturn ::std::abs(b) != 0 && ::std::complex(a/b).real() < 0;\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the left-half plane\n * (\\f$\\operatorname{real}(\\lambda) < 0\\f$) [complex double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_lhp_eigenval_sel(::std::complex a, ::std::complex b)\n{\n\t// Based on function ZB02OW.f from SLICOT 5.0\n\treturn ::std::abs(b) != 0 && ::std::complex(a/b).real() < 0;\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the left-half plane\n * (\\f$\\operatorname{real}(\\lambda) < 0\\f$) [single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_lhp_eigenval_sel(float ar, float ai, float b)\n{\n\tBOOST_UBLASX_SUPPRESS_UNUSED_VARIABLE_WARNING(ai);\n\n\t// Based on function SB02OW from SLICOT 5.0\n\treturn ((ar > 0 && b < 0) || (ar < 0 && b > 0))\n\t\t && ::std::abs(b) > (::std::abs(ar)*::std::numeric_limits::epsilon());\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the left-half plane\n * (\\f$\\operatorname{real}(\\lambda) < 0\\f$) [double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_lhp_eigenval_sel(double ar, double ai, double b)\n{\n\tBOOST_UBLASX_SUPPRESS_UNUSED_VARIABLE_WARNING(ai);\n\n\t// Based on function SB02OW from SLICOT 5.0\n\treturn ((ar > 0 && b < 0) || (ar < 0 && b > 0))\n\t\t && ::std::abs(b) > (::std::abs(ar)*::std::numeric_limits::epsilon());\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the right-half plane\n * (\\f$\\operatorname{real}(\\lambda) > 0\\f$) [complex single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_rhp_eigenval_sel(::std::complex a, ::std::complex b)\n{\n\t// Based on function ZB02OW.f from SLICOT 5.0\n\treturn ::std::abs(b) != 0 && ::std::complex(a/b).real() > 0;\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the right-half plane\n * (\\f$\\operatorname{real}(\\lambda) > 0\\f$) [complex double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_rhp_eigenval_sel(::std::complex a, ::std::complex b)\n{\n\t// Based on function ZB02OW.f from SLICOT 5.0\n\treturn ::std::abs(b) != 0 && ::std::complex(a/b).real() > 0;\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the right-half plane\n * (\\f$\\operatorname{real}(\\lambda) > 0\\f$) [single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_rhp_eigenval_sel(float ar, float ai, float b)\n{\n\tBOOST_UBLASX_SUPPRESS_UNUSED_VARIABLE_WARNING(ai);\n\n\t// Based on function SB02OW from SLICOT 5.0\n\treturn ((ar > 0 && b > 0) || (ar < 0 && b < 0))\n\t\t && ::std::abs(b) > (::std::abs(ar)*::std::numeric_limits::epsilon());\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ in the right-half plane\n * (\\f$\\operatorname{real}(\\lambda) > 0\\f$) [double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_rhp_eigenval_sel(double ar, double ai, double b)\n{\n\tBOOST_UBLASX_SUPPRESS_UNUSED_VARIABLE_WARNING(ai);\n\n\t// Based on function SB02OW from SLICOT 5.0\n\treturn ((ar > 0 && b > 0) || (ar < 0 && b < 0))\n\t\t && ::std::abs(b) > (::std::abs(ar)*::std::numeric_limits::epsilon());\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are interior of unit disk\n * (\\f$\\operatorname{abs}(\\lambda) < 1\\f$) [complex single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udi_eigenval_sel(::std::complex a, ::std::complex b)\n{\n\t// Based on function ZB02OX from SLICOT 5.0\n\treturn ::std::abs(a) < ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are interior of unit disk\n * (\\f$\\operatorname{abs}(\\lambda) < 1\\f$) [complex double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udi_eigenval_sel(::std::complex a, ::std::complex b)\n{\n\t// Based on function ZB02OX from SLICOT 5.0\n\treturn ::std::abs(a) < ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are interior of unit disk\n * (\\f$\\operatorname{abs}(\\lambda) < 1\\f$) [single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udi_eigenval_sel(float ar, float ai, float b)\n{\n\t// Based on function SB02OX from SLICOT 5.0\n\treturn ::std::abs(::std::complex(ar, ai)) < ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are interior of unit disk\n * (\\f$\\operatorname{abs}(\\lambda) < 1\\f$) [double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udi_eigenval_sel(double ar, double ai, double b)\n{\n\t// Based on function SB02OX from SLICOT 5.0\n\treturn ::std::abs(::std::complex(ar, ai)) < ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are exterior of unit disk\n * (\\f$\\operatorname{abs}(\\lambda) > 1\\f$) [complex single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udo_eigenval_sel(::std::complex a, ::std::complex b)\n{\n\t// Based on function ZB02OX from SLICOT 5.0\n\t// FIXME: Shall we use '>' instead of '>='?\n\t// In MATLAB, the 'udo' function takes the 'exterior of unit disk (abs(E) > 1)'.\n\t// In Octave, the 'big' function takes the 'leading block has all |lambda| >= 1'.\n\treturn ::std::abs(a) >= ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are exterior of unit disk\n * (\\f$\\operatorname{abs}(\\lambda) > 1\\f$) [complex double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udo_eigenval_sel(::std::complex a, ::std::complex b)\n{\n\t// Based on function ZB02OX from SLICOT 5.0\n\t// FIXME: Shall we use '>' instead of '>='?\n\t// In MATLAB, the 'udo' function takes the 'exterior of unit disk (abs(E) > 1)'.\n\t// In Octave, the 'big' function takes the 'leading block has all |lambda| >= 1'.\n\treturn ::std::abs(a) >= ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are exterior of unit disk\n * (\\f$\\operatorname{abs}(\\lambda) > 1\\f$) [single precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udo_eigenval_sel(float ar, float ai, float b)\n{\n\t// Based on function SB02OX from SLICOT 5.0\n\t// FIXME: Shall we use '>' instead of '>='?\n\t// In MATLAB, the 'udo' function takes the 'exterior of unit disk (abs(E) > 1)'.\n\t// In Octave, the 'big' function takes the 'leading block has all |lambda| >= 1'.\n\treturn ::std::abs(::std::complex(ar, ai)) >= ::std::abs(b);\n}\n\n\n/**\n * \\brief Select eigenvalues \\f$\\lambda\\f$ which are exterior of unit disk\n * (\\f$\\operatorname{abs}(\\lambda) > 1\\f$) [double precision case].\n */\nBOOST_UBLAS_INLINE\n::fortran_bool_t qz_udo_eigenval_sel(double ar, double ai, double b)\n{\n\t// Based on function SB02OX from SLICOT 5.0\n\t// FIXME: Shall we use '>' instead of '>='?\n\t// In MATLAB, the 'udo' function takes the 'exterior of unit disk (abs(E) > 1)'.\n\t// In Octave, the 'big' function takes the 'leading block has all |lambda| >= 1'.\n\treturn ::std::abs(::std::complex(ar, ai)) >= ::std::abs(b);\n}\n\n\nnamespace /**/ {\n\n/// Type for the QZ eigenvalues selector (single precision case).\ntypedef ::fortran_bool_t (*qz_single_selector_type)(float, float, float);\n/// Type for the QZ eigenvalues selector (double precision case).\ntypedef ::fortran_bool_t (*qz_double_selector_type)(double, double, double);\n/// Type for the QZ eigenvalues selector (single precision complex case).\ntypedef ::fortran_bool_t (*qz_complex_single_selector_type)(::std::complex, ::std::complex);\n/// Type for the QZ eigenvalues selector (single precision complex case).\ntypedef ::fortran_bool_t (*qz_complex_double_selector_type)(::std::complex, ::std::complex);\n\n\n/// Options to select what Schur vectors compute in the QZ decomposition.\nenum qz_schurvectors_side\n{\n\tnone_qz_schurvectors, ///< Do not compute vectors.\n\tleft_qz_schurvectors, ///< Compute only left vectors.\n\tright_qz_schurvectors, ///< Compute only right vectors.\n\tboth_qz_schurvectors ///< Compute both left and right vectors.\n};\n\n\n/// Options to select what generalized eigenvectors compute from the QZ decomposition.\nenum qz_eigenvectors_side\n{\n//\tnone_qz_eigenvectors, ///< Do not compute generalized eigenvectors.\n\tleft_qz_eigenvectors, ///< Compute only left generalized eigenvectors.\n\tright_qz_eigenvectors, ///< Compute only right generalized eigenvectors.\n\tboth_qz_eigenvectors ///< Compute both left and right generalized eigenvectors.\n};\n\n\n/// Options for reordering QZ factorizations.\nenum qz_order_option\n{\n\tno_extra_qz_option, ///< Only reorder w.r.t. SELECT. No extras.\n\tprojections_qz_option, ///< Reciprocal of norms of \\e projections onto left and righteigenspaces w.r.t. the selected cluster (PL and PR).\n\tupper_bounds_fnorm_qz_option, ///< Upper bounds on Difu and Difl. F-norm-based estimate (DIF(1:2)).\n\tupper_bounds_1norm_qz_option, ///< Estimate of Difu and Difl. 1-norm-based estimate (DIF(1:2)).\n\tprojections_upper_bounds_fnorm_qz_option, ///< Compute PL, PR and DIF (F-norm based): Economic version to get it all.\n\tprojections_upper_bounds_1norm_qz_option ///< Compute PL, PR and DIF (1-norm based).\n};\n\n\n/// Options for computing generalized Schur eigenvectors.\nenum qz_eigenvectors_option\n{\n\tall_qz_eigenvectors_option, ///< Compute all right and/or left eigenvectors.\n\tbacktransform_qz_eigenvectors_option, ///< Compute all right and/or left eigenvectors, backtransformed by the matrices in VR and/or VL.\n\tselect_qz_eigenvectors_option ///< Compute selected right and/or left eigenvectors.\n};\n\n\n/// Create a selector function according to the given \\a selection method.\ntemplate \nBOOST_UBLAS_INLINE\n::external_fp create_qz_eigvals_selector(qz_eigenvalues_selection selection)\n{\n\t::external_fp selctg = 0;\n\n\tswitch (selection)\n\t{\n\t\tcase lhp_qz_eigenvalues:\n\t\t\tselctg = BOOST_UBLASX_DETAIL_QZ_SELECTOR_CAST(ValueT, qz_lhp_eigenval_sel);\n\t\t\tbreak;\n\t\tcase rhp_qz_eigenvalues:\n\t\t\tselctg = BOOST_UBLASX_DETAIL_QZ_SELECTOR_CAST(ValueT, qz_rhp_eigenval_sel);\n\t\t\tbreak;\n\t\tcase udi_qz_eigenvalues:\n\t\t\tselctg = BOOST_UBLASX_DETAIL_QZ_SELECTOR_CAST(ValueT, qz_udi_eigenval_sel);\n\t\t\tbreak;\n\t\tcase udo_qz_eigenvalues:\n\t\t\tselctg = BOOST_UBLASX_DETAIL_QZ_SELECTOR_CAST(ValueT, qz_udo_eigenval_sel);\n\t\t\tbreak;\n\t\tcase all_qz_eigenvalues:\n\t\tdefault:\n\t\t\tselctg = 0;\n\t\t\tbreak;\n\t}\n\n\treturn selctg;\n}\n\n\n/**\n * \\brief Call the proper selector function according to the given \\a selection\n * method.\n *\n * \\todo Replace this function with something at compile-time, like below:\n *
\n *   // Declare the selector with the proper type (this should emulate the\n *   // switch below, but at compile-time)\n *   BOOST_UBLAS_DETAIL_QZ_DECLARE_SELECTOR(selection, selector);\n *   ...\n *   // Invoke the selector\n *   selector(a, b);\n *  
\n * This way, we avoid to perform the switch at every invocation of the\n * selector.\n */\ntemplate \nBOOST_UBLAS_INLINE\nbool invoke_qz_eigvals_selector(qz_eigenvalues_selection selection, AValueT a, BValueT b)\n{\n\tswitch (selection)\n\t{\n\t\tcase lhp_qz_eigenvalues:\n\t\t\treturn qz_lhp_eigenval_sel(a, b);\n\t\tcase rhp_qz_eigenvalues:\n\t\t\treturn qz_rhp_eigenval_sel(a, b);\n\t\tcase udi_qz_eigenvalues:\n\t\t\treturn qz_udi_eigenval_sel(a, b);\n\t\t\tbreak;\n\t\tcase udo_qz_eigenvalues:\n\t\t\treturn qz_udo_eigenval_sel(a, b);\n\t\tcase all_qz_eigenvalues:\n\t\tdefault:\n\t\t\treturn true;\n\t}\n}\n\n\n/// Extract the generalized Schur eigenvectors from a QZ decomposition\n/// (column-major case).\ntemplate <\n\ttypename SMatrixT,\n\ttypename TMatrixT,\n\ttypename QMatrixT,\n\ttypename ZMatrixT,\n\ttypename LVMatrixT,\n\ttypename RVMatrixT\n>\nvoid extract_eigenvectors(SMatrixT const& S, TMatrixT const& T, qz_eigenvectors_side eigvec_side, qz_eigenvectors_option eigvec_opt, vector< ::fortran_bool_t > eigvecs_sel, QMatrixT const& Q, ZMatrixT const& Z, LVMatrixT& LV, RVMatrixT& RV, column_major_tag)\n{\n\ttypedef typename matrix_traits::size_type size_type;\n\n\tsize_type nr_LV = 0;\n\tsize_type nc_LV = 0;\n\tsize_type nr_RV = 0;\n\tsize_type nc_RV = 0;\n\tbool resize_LV = true;\n\tbool resize_RV = true;\n\tchar howmny;\n\t::fortran_int_t n = static_cast< ::fortran_int_t >(num_rows(S));\n\t::fortran_int_t mm = 0;\n\t::fortran_int_t m = 0;\n\n\tswitch (eigvec_opt)\n\t{\n\t\tcase backtransform_qz_eigenvectors_option:\n\t\t\thowmny = 'B';\n\t\t\tif (eigvec_side != right_qz_eigenvectors)\n\t\t\t{\n\t\t\t\tLV = Q;\n\t\t\t}\n\t\t\tif (eigvec_side != left_qz_eigenvectors)\n\t\t\t{\n\t\t\t\tRV = Z;\n\t\t\t}\n\t\t\tmm = n;\n\t\t\tbreak;\n\t\tcase select_qz_eigenvectors_option:\n\t\t\thowmny = 'S';\n\t\t\tmm = static_cast< ::fortran_int_t >(size(eigvecs_sel));\n\t\t\tbreak;\n\t\tcase all_qz_eigenvectors_option:\n\t\tdefault:\n\t\t\thowmny = 'A';\n\t\t\tmm = n;\n\t}\n\n\tswitch (eigvec_side)\n\t{\n\t\tcase left_qz_eigenvectors:\n\t\t\tnr_RV = nc_RV = 1;\n\t\t\tnr_LV = n;\n\t\t\tif (eigvec_opt == backtransform_qz_eigenvectors_option)\n\t\t\t{\n\t\t\t\tnc_LV = mm = ::std::max(n, mm);\n\t\t\t\tresize_LV = false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnc_LV = mm;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase right_qz_eigenvectors:\n\t\t\tnr_LV = nc_LV = 1;\n\t\t\tnr_RV = n;\n\t\t\tif (eigvec_opt == backtransform_qz_eigenvectors_option)\n\t\t\t{\n\t\t\t\tnc_RV = mm = ::std::max(n, mm);\n\t\t\t\tresize_RV = false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnc_RV = mm;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase both_qz_eigenvectors:\n\t\tdefault:\n\t\t\tnr_LV = nr_RV = n;\n\t\t\tif (eigvec_opt == backtransform_qz_eigenvectors_option)\n\t\t\t{\n\t\t\t\tnc_LV = nc_RV = mm = ::std::max(n, mm);\n\t\t\t\tresize_LV = resize_RV = false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tnc_LV = nc_RV = mm;\n\t\t\t}\n\t}\n\n\tif (resize_LV)\n\t{\n\t\tLV.resize(nr_LV, nc_LV, false);\n\t}\n\tif (resize_RV)\n\t{\n\t\tRV.resize(nr_RV, nc_RV, false);\n\t}\n\n\tswitch (eigvec_side)\n\t{\n\t\tcase left_qz_eigenvectors:\n\t\t\t::boost::numeric::bindings::lapack::tgevc(\n\t\t\t\t::boost::numeric::bindings::tag::left(),\n\t\t\t\thowmny,\n\t\t\t\teigvecs_sel,\n\t\t\t\tS,\n\t\t\t\tT,\n\t\t\t\tLV,\n\t\t\t\tRV,\n\t\t\t\tmm,\n\t\t\t\tm\n\t\t\t);\n\t\t\tbreak;\n\t\tcase right_qz_eigenvectors:\n\t\t\t::boost::numeric::bindings::lapack::tgevc(\n\t\t\t\t::boost::numeric::bindings::tag::right(),\n\t\t\t\thowmny,\n\t\t\t\teigvecs_sel,\n\t\t\t\tS,\n\t\t\t\tT,\n\t\t\t\tLV,\n\t\t\t\tRV,\n\t\t\t\tmm,\n\t\t\t\tm\n\t\t\t);\n\t\t\tbreak;\n\t\tcase both_qz_eigenvectors:\n\t\tdefault:\n\t\t\t::boost::numeric::bindings::lapack::tgevc(\n\t\t\t\t::boost::numeric::bindings::tag::both(),\n\t\t\t\thowmny,\n\t\t\t\teigvecs_sel,\n\t\t\t\tS,\n\t\t\t\tT,\n\t\t\t\tLV,\n\t\t\t\tRV,\n\t\t\t\tmm,\n\t\t\t\tm\n\t\t\t);\n\t}\n}\n\n\n/**\n * \\brief Generalized (real/complex) Schur decomposition.\n *\n * Given two square matrices \\f$A\\f$ and \\f$B\\f$, its Generalized Schur\n * decomposition is given by\n * \\f{align}{\n * A &= Q S Z^T,\\\\\n * B &= Q T Z^T\n * \\f}\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate \nstruct qz_decomposition_impl;\n\n\n/**\n * \\brief Generalized real Schur decomposition.\n *\n * Given two square real matrices \\f$A\\f$ and \\f$B\\f$, its Generalized Schur\n * decomposition is given by\n * \\f{align}{\n * A &= Q S Z^T,\\\\\n * B &= Q T Z^T\n * \\f}\n *\n * The diagonal elements of \\f$S\\f$ and \\f$T\\f$,\n * \\f$\\alpha = \\operatorname{diag}{S}\\f$ and\n * \\f$\\beta = \\operatorname{diag}{S}\\f$, are the generalized eigenvalues that\n * satisfy:\n * \\f{align}{\n * A V \\beta &= B V \\alpha,\\\\\n * \\beta W A &= \\alpha W^T B.\n * \\f}\n *\n * The ratios:\n * \\f[\n * \\frac{\\alpha_i}{\\beta_i}\n * \\f]\n * are the generalized eigenvalues.\n * \\f$\\alpha_i\\f$ and \\f$\\beta_i\\f$ are the diagonals of the complex Schur\n * form (S,T) that would result if the 2-by-2 diagonal blocks of\n * the real Schur form of \\f$(A,B)\\f$ were further reduced to\n * triangular form using 2-by-2 complex unitary transformations.\n * If \\f$\\operatorname{imag}(\\alpha_i)\\f$ is zero, then the \\f$i\\f$-th\n * eigenvalue is real; if positive, then the \\f$j\\f$-th and \\f$(i+1)\\f$-st\n * eigenvalues are a complex conjugate pair, with\n * \\f$\\operatorname{imag}(\\alpha_{i+1})\\f$ negative.\n * The quotients \\f$\\alpha_i/\\beta_i\\f$ may easily over- or underflow, and\n * \\f$\\beta_i\\f$ may even be zero.\n * It should be avoided to naively computing the ratio \\f$alpha_i/beta_i\\f$.\n * However, \\f$\\alpha\\f$ will be always less than and usually\n * comparable with \\f$\\operatorname{norm}(A)\\f$ in magnitude, and \\f\\beta\\f$\n * always less than and usually comparable with \\f$\\operatorname{norm}(B)\\f$.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <>\nstruct qz_decomposition_impl\n{\n\t/**\n \t * \\brief Compute the generalized Schur (QZ) factorization (column-major\n \t * case).\n \t *\n\t * Given two square matrices \\a A and \\a B of order \\f$n\\f$, computes the\n\t * generalized eigenvalues \\a alpha\\ and \\a beta, the generalized real Schur\n\t * form (\\a S,\\a T), and the left and right matrices \\a Q and \\a Z of Schur\n\t * vectors such that the generalized Schur (QZ) factorization holds:\n\t * \\f[ \n\t * (A,B) = ( Q S Z^T, Q T Z^T )\n\t * \\f]\n\t */\n\ttemplate \n\t\tstatic void decompose(AMatrixT& A, BMatrixT& B, qz_schurvectors_side eigvecs_side, bool want_eigvals, bool reorder_eigvals, ::external_fp eigvals_selector, QMatrixT& Q, ZMatrixT& Z, AlphaVectorT& alpha, BetaVectorT& beta, column_major_tag)\n\t{\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits::value_type,\n\t\t\t\t\ttypename matrix_traits::value_type\n\t\t\t\t>::promote_type value_type;\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits::size_type,\n\t\t\t\t\ttypename matrix_traits::size_type\n\t\t\t\t>::promote_type size_type;\n\t\ttypedef vector work_vector_type;\n\n\t\tsize_type n = num_rows(A);\n\t\tchar jobvsl;\n\t\tchar jobvsr;\n\t\tchar sort;\n\t\tsize_type n_q;\n\t\tsize_type n_z;\n\n\t\tswitch (eigvecs_side)\n\t\t{\n\t\t\tcase both_qz_schurvectors:\n\t\t\t\tjobvsl = jobvsr = 'V';\n\t\t\t\tn_q = n_z = n;\n\t\t\t\tbreak;\n\t\t\tcase left_qz_schurvectors:\n\t\t\t\tjobvsl = 'V';\n\t\t\t\tjobvsr = 'N';\n\t\t\t\tn_q = n;\n\t\t\t\tn_z = 0;\n\t\t\t\tbreak;\n\t\t\tcase right_qz_schurvectors:\n\t\t\t\tjobvsl = 'N';\n\t\t\t\tjobvsr = 'V';\n\t\t\t\tn_q = 0;\n\t\t\t\tn_z = n;\n\t\t\t\tbreak;\n\t\t\tcase none_qz_schurvectors:\n\t\t\tdefault:\n\t\t\t\tjobvsl = jobvsr = 'N';\n\t\t\t\tn_q = n_z = 0;\n\t\t}\n\n\t\tif (reorder_eigvals)\n\t\t{\n\t\t\tsort = 'S';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsort = 'N';\n\t\t}\n\n\t\tif (num_rows(Q) != n)\n\t\t{\n\t\t\tQ.resize(n, n, false);\n\t\t}\n\t\tif (num_rows(Z) != n)\n\t\t{\n\t\t\tZ.resize(n, n, false);\n\t\t}\n\n\t\twork_vector_type alpha_real(n);\n\t\twork_vector_type alpha_imag(n);\n\t\tif (size(beta) != n)\n\t\t{\n\t\t\tbeta.resize(n, false);\n\t\t}\n\n\t\t::fortran_int_t sdim;\n\n\t\t::boost::numeric::bindings::lapack::gges(\n\t\t\tjobvsl,\n\t\t\tjobvsr,\n\t\t\tsort,\n\t\t\teigvals_selector,\n\t\t\tA,\n\t\t\tB,\n\t\t\tsdim,\n\t\t\talpha_real,\n\t\t\talpha_imag,\n\t\t\tbeta,\n\t\t\tQ,\n\t\t\tZ\n\t\t);\n\n\t\t// Create the alpha vector\n\t\tif (want_eigvals)\n\t\t{\n\t\t\tif (size(alpha) != n)\n\t\t\t{\n\t\t\t\talpha.resize(n, false);\n\t\t\t}\n\t\t\t// From LAPACK ?GGES documentation\n\t\t\t// \"If ALPHAI(j) is zero, then the j-th eigenvalue is real; if\n\t\t\t// positive, then the j-th and (j+1)-st eigenvalues are a\n\t\t\t// complex conjugate pair, with ALPHAI(j+1) negative.\"\n\t\t\t//\n#ifdef BOOST_UBLASX_DEBUG\n\t\t\t// Underflow threshold (used in the 'safety check' inside the 'for' loop)\n\t\t\tvalue_type rmin(::std::numeric_limits::min());\n#endif // BOOST_UBLASX_DEBUG\n\t\t\tfor (size_type i = 0; i < n; ++i)\n\t\t\t{\n#ifdef BOOST_UBLASX_DEBUG\n\t\t\t\t// Safety check: when beta_i is near to zero the corresponding\n\t\t\t\t// eigenvalue is infinite.\n\t\t\t\t// This test was inspired by the 'f08wafe.f'\n\t\t\t\t// subrouting found on NAG libraries.\n\t\t\t\tif ((::std::abs(alpha_real(i))+::std::abs(alpha_imag(i)))*rmin >= ::std::abs(beta(i)))\n\t\t\t\t{\n\t\t\t\t\tBOOST_UBLASX_DEBUG_TRACE(\"[Warning] Eigenvalue(\" << i << \") is numerically infinite or undetermined: alpha_r(\" << i << \") = \" << alpha_real(i) << \", alpha_i(\" << i << \") = \" << alpha_imag(i) << \", beta(\" << i << \") = \" << beta(i));\n\t\t\t\t}\n#endif // BOOST_UBLASX_DEBUG\n\n//\t\t\t\tif (alpha_imag(i) == value_type/*zero*/())\n//\t\t\t\t{\n//\t\t\t\t\talpha(i) = ::std::complex(alpha_real(i), value_type/*zero*/());\n//\t\t\t\t}\n//\t\t\t\telse\n//\t\t\t\t{\n//\t\t\t\t\talpha(i) = ::std::complex(alpha_real(i), alpha_imag(i));\n//\t\t\t\t\t// safety check (even if it should not happen)\n//\t\t\t\t\tif ((i+1) < n)\n//\t\t\t\t\t{\n//\t\t\t\t\t\talpha(i+1) = ::std::conj(alpha(i));\n//\t\t\t\t\t}\n//\t\t\t\t\t++i;\n//\t\t\t\t}\n\t\t\t\tif (alpha_imag(i) == value_type/*zero*/())\n\t\t\t\t{\n\t\t\t\t\talpha(i) = ::std::complex(alpha_real(i), value_type/*zero*/());\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\talpha(i) = ::std::complex(alpha_real(i), alpha_imag(i));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\talpha.resize(0, false);\n\t\t\tbeta.resize(0, false);\n\t\t}\n\n\t\tif (num_rows(Q) != n_q)\n\t\t{\n\t\t\tQ.resize(n_q, n_q, n_q > 0 ? true : false);\n\t\t}\n\t\tif (num_rows(Z) != n_z)\n\t\t{\n\t\t\tZ.resize(n_z, n_z, n_z > 0 ? true : false);\n\t\t}\n\t}\n\n\n\t/**\n \t * \\brief Compute the generalized Schur (QZ) factorization (row-major case).\n \t *\n\t * Given two square matrices \\a A and \\a B of order \\f$n\\f$, computes the\n\t * generalized eigenvalues \\a alpha\\ and \\a beta, the generalized real Schur\n\t * form (\\a S,\\a T), and the left and right matrices \\a Q and \\a Z of Schur\n\t * vectors such that the generalized Schur (QZ) factorization holds:\n\t * \\f[ \n\t * (A,B) = ( Q S Z^T, Q T Z^T )\n\t * \\f]\n\t */\n\ttemplate \n\t\tstatic void decompose(AMatrixT& A, BMatrixT& B, qz_schurvectors_side eigvecs_side, bool want_eigvals, bool reorder_eigvals, ::external_fp eigvals_selector, QMatrixT& Q, ZMatrixT& Z, AlphaVectorT& alpha, BetaVectorT& beta, row_major_tag)\n\t{\n\t\t// LAPACK works with dense column-major matrices\n\n//\t\tmatrix::value_type, typename layout_type::type> tmp_A(A);\n//\t\tmatrix::value_type, typename layout_type::type> tmp_B(B);\n//\t\tmatrix::value_type, typename layout_type::type> tmp_Q(Q);\n//\t\tmatrix::value_type, typename layout_type::type> tmp_Z(Z);\n\t\tmatrix::value_type, column_major> tmp_A(A);\n\t\tmatrix::value_type, column_major> tmp_B(B);\n\t\tmatrix::value_type, column_major> tmp_Q(Q);\n\t\tmatrix::value_type, column_major> tmp_Z(Z);\n\n\t\tdecompose(tmp_A, tmp_B, eigvecs_side, want_eigvals, reorder_eigvals, eigvals_selector, tmp_Q, tmp_Z, alpha, beta, column_major_tag());\n\n\t\tA = tmp_A;\n\t\tB = tmp_B;\n\t\tQ = tmp_Q;\n\t\tZ = tmp_Z;\n\n\t\tif (!want_eigvals)\n\t\t{\n\t\t\talpha.resize(0, false);\n\t\t\tbeta.resize(0, false);\n\t\t}\n\t}\n\n\n\t/// Reorder the given QZ decomposition (column-major case).\n\ttemplate <\n\t\ttypename SMatrixT,\n\t\ttypename TMatrixT,\n\t\ttypename QMatrixT,\n\t\ttypename ZMatrixT,\n\t\ttypename AlphaVectorT,\n\t\ttypename BetaVectorT\n\t>\n\tstatic void reorder(SMatrixT& S, TMatrixT& T, qz_order_option order_opt, vector< ::fortran_bool_t > eigvals_sel, AlphaVectorT& alpha, BetaVectorT& beta, bool update_Q, QMatrixT& Q, bool update_Z, ZMatrixT& Z, column_major_tag)\n\t{\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits::value_type,\n\t\t\t\t\ttypename matrix_traits::value_type\n\t\t\t\t>::promote_type value_type;\n\n\t\t::fortran_int_t ijob; // type of job the LAPACK function has to perform [intput]\n\t\t::fortran_int_t m; // dimension of the specified pair of left and right eigenspaces [output]\n\t\tvalue_type projl; // lower bounds on the reciprocal of the norm of \"projections\" onto left eigenspace [output]\n\t\tvalue_type projr; // lower bounds on the reciprocal of the norm of \"projections\" onto right eigenspace [output]\n\t\tvector dif; // store the estimates of Difu and Difl [output]\n\n\t\t// Decode order option\n\t\tswitch (order_opt)\n\t\t{\n\t\t\tcase projections_qz_option:\n\t\t\t\tijob = 1;\n\t\t\t\tbreak;\n\t\t\tcase upper_bounds_fnorm_qz_option:\n\t\t\t\tijob = 2;\n\t\t\t\tbreak;\n\t\t\tcase upper_bounds_1norm_qz_option:\n\t\t\t\tijob = 3;\n\t\t\t\tbreak;\n\t\t\tcase projections_upper_bounds_fnorm_qz_option:\n\t\t\t\tijob = 4;\n\t\t\t\tbreak;\n\t\t\tcase projections_upper_bounds_1norm_qz_option:\n\t\t\t\tijob = 5;\n\t\t\t\tbreak;\n\t\t\tcase no_extra_qz_option:\n\t\t\tdefault:\n\t\t\t\tijob = 0;\n\t\t}\n\n\t\tif (ijob >= 2)\n\t\t{\n\t\t\tdif.resize(2, false);\n\t\t}\n\n\t\tvector aux_alphar(real(alpha));\n\t\tvector aux_alphai(imag(alpha));\n\n\t\t::boost::numeric::bindings::lapack::tgsen(\n\t\t\tijob,\n\t\t\tstatic_cast< ::fortran_bool_t >(update_Q ? 1 : 0),\n\t\t\tstatic_cast< ::fortran_bool_t >(update_Z ? 1 : 0),\n\t\t\teigvals_sel,\n\t\t\tS,\n\t\t\tT,\n\t\t\taux_alphar,\n\t\t\taux_alphai,\n\t\t\tbeta,\n\t\t\tQ,\n\t\t\tZ,\n\t\t\tm,\n\t\t\tprojl,\n\t\t\tprojr,\n\t\t\tdif\n\t\t);\n\n\t\t// Update the alpha vector\n\t\t//\n\t\t// From LAPACK ?TGSEN documentation\n\t\t// \"If ALPHAI(j) is zero, then the j-th eigenvalue is real; if\n\t\t// positive, then the j-th and (j+1)-st eigenvalues are a\n\t\t// complex conjugate pair, with ALPHAI(j+1) negative.\"\n\t\t//\n\t\ttypedef typename vector_traits::size_type alpha_size_type;\n\t\talpha_size_type n = size(alpha);\n\t\tfor (alpha_size_type i = 0; i < n; ++i)\n\t\t{\n\t\t\tif (aux_alphai(i) == value_type/*zero*/())\n\t\t\t{\n\t\t\t\talpha(i) = ::std::complex(aux_alphar(i), value_type/*zero*/());\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\talpha(i) = ::std::complex(aux_alphar(i), aux_alphai(i));\n\t\t\t\t// safety check (even if it should not happen)\n\t\t\t\tif ((i+1) < n)\n\t\t\t\t{\n\t\t\t\t\talpha(i+1) = ::std::conj(alpha(i));\n\t\t\t\t}\n\t\t\t\t++i;\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/// Reorder the given QZ decomposition (row-major case).\n\ttemplate <\n\t\ttypename SMatrixT,\n\t\ttypename TMatrixT,\n\t\ttypename QMatrixT,\n\t\ttypename ZMatrixT,\n\t\ttypename AlphaVectorT,\n\t\ttypename BetaVectorT\n\t>\n\tstatic void reorder(SMatrixT& S, TMatrixT& T, qz_order_option order_opt, vector< ::fortran_bool_t > eigvals_sel, AlphaVectorT& alpha, BetaVectorT& beta, bool update_Q, QMatrixT& Q, bool update_Z, ZMatrixT& Z, row_major_tag)\n\t{\n\t\t// LAPACK works with dense column-major matrices\n\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits::value_type,\n\t\t\t\t\ttypename matrix_traits::value_type\n\t\t\t\t>::promote_type value_type;\n\t\ttypedef matrix colmaj_matrix_type;\n\n\t\tcolmaj_matrix_type tmp_S(S);;\n\t\tcolmaj_matrix_type tmp_T(T);;\n\t\tcolmaj_matrix_type tmp_Q;//(Q); //FIXME: maybe unnecessary if update_Q == false\n\t\tcolmaj_matrix_type tmp_Z;//(Z); //FIXME: maybe unnecessary if update_Z == false\n\n\t\tif (update_Q)\n\t\t{\n\t\t\ttmp_Q = Q;\n\t\t}\n\t\tif (update_Z)\n\t\t{\n\t\t\ttmp_Z = Z;\n\t\t}\n\n\t\treorder(tmp_S, tmp_T, order_opt, eigvals_sel, alpha, beta, update_Q, tmp_Q, update_Z, tmp_Z, column_major_tag());\n\n\t\tS = tmp_S;\n\t\tT = tmp_T;\n\t\tif (update_Q)\n\t\t{\n\t\t\tQ = tmp_Q;\n\t\t}\n\t\tif (update_Z)\n\t\t{\n\t\t\tZ = tmp_Z;\n\t\t}\n\t}\n}; // struct qz_decomposition_impl\n\n\n/**\n * \\brief Generalized complex Schur decomposition.\n *\n * Given two square complex matrices \\f$A\\f$ and \\f$B\\f$, its Generalized Schur\n * decomposition is given by\n * \\f{align}{\n * A &= Q S Z^T,\\\\\n * B &= Q T Z^T\n * \\f}\n *\n * The diagonal elements of \\f$S\\f$ and \\f$T\\f$,\n * \\f$\\alpha = \\operatorname{diag}{S}\\f$ and\n * \\f$\\beta = \\operatorname{diag}{S}\\f$, are the generalized eigenvalues that\n * satisfy:\n * \\f{align}{\n * A V \\beta &= B V \\alpha,\\\\\n * \\beta W A &= \\alpha W^T B.\n * \\f}\n *\n * The ratios\n * \\f[\n * \\lambda_i = \\frac{\\alpha_i}{\\beta_i}\n * \\f]\n * represents the generalized eigenvalues of the matrix pair \\f$(A,B)\\f$, such\n * that \\f$A - \\lambda_i*B\\f$ is singular.\n * The quotients \\f$\\alpha_i/\\beta_i\\f$ may easily over- or underflow, and\n * \\f$\\beta_i\\f$ may even be zero.\n * It should be avoided to naively computing the ratio \\f$alpha_i/beta_i\\f$.\n * However, \\f$\\alpha\\f$ will be always less than and usually\n * comparable with \\f$\\operatorname{norm}(A)\\f$ in magnitude, and \\f\\beta\\f$\n * always less than and usually comparable with \\f$\\operatorname{norm}(B)\\f$.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <>\nstruct qz_decomposition_impl\n{\n\t/**\n \t * \\brief Compute the generalized Schur (QZ) factorization (row-major case).\n \t *\n\t * Given two square matrices \\a A and \\a B of order \\f$n\\f$, computes the\n\t * generalized eigenvalues \\a alpha\\ and \\a beta, the generalized real Schur\n\t * form (\\a S,\\a T), and the left and right matrices \\a Q and \\a Z of Schur\n\t * vectors such that the generalized Schur (QZ) factorization holds:\n\t * \\f[ \n\t * (A,B) = ( Q S Z^T, Q T Z^T )\n\t * \\f]\n\t */\n\ttemplate \n\t\tstatic void decompose(AMatrixT& A, BMatrixT& B, qz_schurvectors_side eigvecs_side, bool want_eigvals, bool reorder_eigvals, ::external_fp eigvals_selector, QMatrixT& Q, ZMatrixT& Z, AlphaVectorT& alpha, BetaVectorT& beta, row_major_tag)\n\t{\n\t\t// LAPACK works with dense column-major matrices\n\n\t\tmatrix::value_type, column_major> tmp_A(A);\n\t\tmatrix::value_type, column_major> tmp_B(B);\n\t\tmatrix::value_type, column_major> tmp_Q(Q);\n\t\tmatrix::value_type, column_major> tmp_Z(Z);\n\n\t\t//decompose(tmp_A, tmp_B, tmp_Q, tmp_Z, alpha, beta, side, order, selctg, column_major_tag());\n\t\tdecompose(tmp_A, tmp_B, tmp_Q, tmp_Z, alpha, beta, eigvecs_side, reorder_eigvals, eigvals_selector, column_major_tag());\n\n\t\tA = tmp_A;\n\t\tB = tmp_B;\n\t\tQ = tmp_Q;\n\t\tZ = tmp_Z;\n\n\t\tif (!want_eigvals)\n\t\t{\n\t\t\talpha.resize(0, false);\n\t\t\tbeta.resize(0, false);\n\t\t}\n\t}\n\n\n\t/**\n \t * \\brief Compute the generalized Schur (QZ) factorization (column-major\n \t * case).\n \t *\n\t * Given two square matrices \\a A and \\a B of order \\f$n\\f$, computes the\n\t * generalized eigenvalues \\a alpha\\ and \\a beta, the generalized real Schur\n\t * form (\\a S,\\a T), and the left and right matrices \\a Q and \\a Z of Schur\n\t * vectors such that the generalized Schur (QZ) factorization holds:\n\t * \\f[ \n\t * (A,B) = ( Q S Z^T, Q T Z^T )\n\t * \\f]\n\t */\n\ttemplate \n\t\tstatic void decompose(AMatrixT& A, BMatrixT& B, qz_schurvectors_side eigvecs_side, bool want_eigvals, bool reorder_eigvals, ::external_fp eigvals_selector, QMatrixT& Q, ZMatrixT& Z, AlphaVectorT& alpha, BetaVectorT& beta, column_major_tag)\n\t{\n\t\tBOOST_UBLASX_SUPPRESS_UNUSED_VARIABLE_WARNING(want_eigvals);\n\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits::value_type,\n\t\t\t\t\ttypename matrix_traits::value_type\n\t\t\t\t>::promote_type value_type;\n\t\ttypedef typename type_traits::real_type real_type;\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits::size_type,\n\t\t\t\t\ttypename matrix_traits::size_type\n\t\t\t\t>::promote_type size_type;\n\n\t\tsize_type n = num_rows(A);\n\t\tchar jobvsl;\n\t\tchar jobvsr;\n\t\tchar sort;\n\t\tsize_type n_q;\n\t\tsize_type n_z;\n\n\t\tswitch (eigvecs_side)\n\t\t{\n\t\t\tcase both_qz_schurvectors:\n\t\t\t\tjobvsl = jobvsr = 'V';\n\t\t\t\tn_q = n_z = n;\n\t\t\t\tbreak;\n\t\t\tcase left_qz_schurvectors:\n\t\t\t\tjobvsl = 'V';\n\t\t\t\tjobvsr = 'N';\n\t\t\t\tn_q = n;\n\t\t\t\tn_z = 0;\n\t\t\t\tbreak;\n\t\t\tcase right_qz_schurvectors:\n\t\t\t\tjobvsl = 'N';\n\t\t\t\tjobvsr = 'V';\n\t\t\t\tn_q = 0;\n\t\t\t\tn_z = n;\n\t\t\t\tbreak;\n\t\t\tcase none_qz_schurvectors:\n\t\t\tdefault:\n\t\t\t\tjobvsl = jobvsr = 'N';\n\t\t\t\tn_q = n_z = 0;\n\t\t}\n\n\t\tif (reorder_eigvals)\n\t\t{\n\t\t\tsort = 'S';\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsort = 'N';\n\t\t}\n\n\t\tif (num_rows(Q) != n)\n\t\t{\n\t\t\tQ.resize(n, n, false);\n\t\t}\n\t\tif (num_rows(Z) != n)\n\t\t{\n\t\t\tZ.resize(n, n, false);\n\t\t}\n\t\tif (size(alpha) != n)\n\t\t{\n\t\t\talpha.resize(n, false);\n\t\t}\n\t\tif (size(beta) != n)\n\t\t{\n\t\t\tbeta.resize(n, false);\n\t\t}\n\n\t\t::fortran_int_t sdim;\n\n\t\t::boost::numeric::bindings::lapack::gges(\n\t\t\tjobvsl,\n\t\t\tjobvsr,\n\t\t\tsort,\n\t\t\teigvals_selector,\n\t\t\tA,\n\t\t\tB,\n\t\t\tsdim,\n\t\t\talpha,\n\t\t\tbeta,\n\t\t\tQ,\n\t\t\tZ\n\t\t);\n\n\t\tif (want_eigvals)\n\t\t{\n#ifdef BOOST_UBLASX_DEBUG\n\t\t\t// Safety check: when beta_i is near to zero the corresponding\n\t\t\t// eigenvalue is infinite.\n\t\t\t// This test was inspired by the 'f08wnfe.f'\n\t\t\t// subrouting found on NAG libraries.\n\t\t\treal_type rmin(::std::numeric_limits::min());\n\t\t\tfor (size_type i = 0; i < n; ++i)\n\t\t\t{\n\t\t\t\tif (::std::abs(alpha(i))*rmin >= ::std::abs(beta(i)))\n\t\t\t\t{\n\t\t\t\t\tBOOST_UBLASX_DEBUG_TRACE(\"[Warning] Eigenvalue(\" << i << \") is numerically infinite or undetermined: alpha(\" << i << \") = \" << alpha(i) << \", beta(\" << i << \") = \" << beta(i));\n\t\t\t\t}\n\t\t\t}\n#endif // BOOST_UBLASX_DEBUG\n\t\t}\n\t\telse\n\t\t{\n\t\t\talpha.resize(0, false);\n\t\t\tbeta.resize(0, false);\n\t\t}\n\n\t\tif (num_rows(Q) != n_q)\n\t\t{\n\t\t\tQ.resize(n_q, n_q, n_q > 0 ? true : false);\n\t\t}\n\t\tif (num_rows(Z) != n_z)\n\t\t{\n\t\t\tZ.resize(n_z, n_z, n_z > 0 ? true : false);\n\t\t}\n\t}\n\n\n\t/// Reorder the given QZ decomposition (column-major case).\n\ttemplate <\n\t\ttypename SMatrixT,\n\t\ttypename TMatrixT,\n\t\ttypename QMatrixT,\n\t\ttypename ZMatrixT,\n\t\ttypename AlphaVectorT,\n\t\ttypename BetaVectorT\n\t>\n\tstatic void reorder(SMatrixT& S, TMatrixT& T, qz_order_option order_opt, vector eigvals_sel, AlphaVectorT& alpha, BetaVectorT& beta, bool update_Q, QMatrixT& Q, bool update_Z, ZMatrixT& Z, column_major_tag)\n\t{\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits::value_type,\n\t\t\t\t\ttypename matrix_traits::value_type\n\t\t\t\t>::promote_type value_type;\n\t\ttypedef typename type_traits::real_type real_type;\n\n\t\t::fortran_int_t ijob; // type of job the LAPACK function has to perform [intput]\n\t\t::fortran_int_t m; // dimension of the specified pair of left and right eigenspaces [output]\n\t\treal_type projl; // lower bounds on the reciprocal of the norm of \"projections\" onto left eigenspace [output]\n\t\treal_type projr; // lower bounds on the reciprocal of the norm of \"projections\" onto right eigenspace [output]\n\t\tvector dif; // store the estimates of Difu and Difl [output]\n\n\t\t// Decode order option\n\t\tswitch (order_opt)\n\t\t{\n\t\t\tcase projections_qz_option:\n\t\t\t\tijob = 1;\n\t\t\t\tbreak;\n\t\t\tcase upper_bounds_fnorm_qz_option:\n\t\t\t\tijob = 2;\n\t\t\t\tbreak;\n\t\t\tcase upper_bounds_1norm_qz_option:\n\t\t\t\tijob = 3;\n\t\t\t\tbreak;\n\t\t\tcase projections_upper_bounds_fnorm_qz_option:\n\t\t\t\tijob = 4;\n\t\t\t\tbreak;\n\t\t\tcase projections_upper_bounds_1norm_qz_option:\n\t\t\t\tijob = 5;\n\t\t\t\tbreak;\n\t\t\tcase no_extra_qz_option:\n\t\t\tdefault:\n\t\t\t\tijob = 0;\n\t\t}\n\n\t\tif (ijob >= 2)\n\t\t{\n\t\t\tdif.resize(2, false);\n\t\t}\n\n\t\t::boost::numeric::bindings::lapack::tgsen(\n\t\t\tijob,\n\t\t\tstatic_cast< ::fortran_bool_t >(update_Q ? 1 : 0),\n\t\t\tstatic_cast< ::fortran_bool_t >(update_Z ? 1 : 0),\n\t\t\teigvals_sel,\n\t\t\tS,\n\t\t\tT,\n\t\t\talpha,\n\t\t\tbeta,\n\t\t\tQ,\n\t\t\tZ,\n\t\t\tm,\n\t\t\tprojl,\n\t\t\tprojr,\n\t\t\tdif\n\t\t);\n\t}\n\n\n\t/// Reorder the given QZ decomposition (row-major case).\n\ttemplate <\n\t\ttypename SMatrixT,\n\t\ttypename TMatrixT,\n\t\ttypename QMatrixT,\n\t\ttypename ZMatrixT,\n\t\ttypename AlphaVectorT,\n\t\ttypename BetaVectorT\n\t>\n\tstatic void reorder(SMatrixT& S, TMatrixT& T, qz_order_option order_opt, vector eigvals_sel, AlphaVectorT& alpha, BetaVectorT& beta, bool update_Q, QMatrixT& Q, bool update_Z, ZMatrixT& Z, row_major_tag)\n\t{\n\t\t// LAPACK works with dense column-major matrices\n\n\t\ttypedef typename promote_traits<\n\t\t\t\t\ttypename matrix_traits::value_type,\n\t\t\t\t\ttypename matrix_traits::value_type\n\t\t\t\t>::promote_type value_type;\n\t\ttypedef matrix colmaj_matrix_type;\n\n\t\tcolmaj_matrix_type tmp_S(S);;\n\t\tcolmaj_matrix_type tmp_T(T);;\n\t\tcolmaj_matrix_type tmp_Q; //(Q); //FIXME: maybe unnecessary if update_Q == false\n\t\tcolmaj_matrix_type tmp_Z; //(Z); //FIXME: maybe unnecessary if update_Z == false\n\n\t\tif (update_Q)\n\t\t{\n\t\t\ttmp_Q = Q;\n\t\t}\n\t\tif (update_Z)\n\t\t{\n\t\t\ttmp_Z = Z;\n\t\t}\n\n\t\treorder(tmp_S, tmp_T, order_opt, eigvals_sel, alpha, beta, update_Q, tmp_Q, update_Z, tmp_Z, column_major_tag());\n\n\t\tS = tmp_S;\n\t\tT = tmp_T;\n\t\tif (update_Q)\n\t\t{\n\t\t\tQ = tmp_Q;\n\t\t}\n\t\tif (update_Z)\n\t\t{\n\t\t\tZ = tmp_Z;\n\t\t}\n\t}\n}; // struct qz_decomposition_impl\n\n}} // Namespace detail::\n\n\n/**\n * \\brief Generalized Schur (QZ) decomposition.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate \nclass qz_decomposition\n{\n\tpublic: typedef ValueT value_type;\n\t//private: typedef typename type_traits::real_type real_type;\n\tprivate: typedef matrix work_matrix_type;\n\tpublic: typedef work_matrix_type S_matrix_type;\n\tpublic: typedef work_matrix_type T_matrix_type;\n\tpublic: typedef work_matrix_type Q_matrix_type;\n\tpublic: typedef work_matrix_type Z_matrix_type;\n\tpublic: typedef work_matrix_type eigvecs_matrix_type;\n\tpublic: typedef vector<\n\t\t\t\t\t\ttypename ::boost::mpl::if_<\n\t\t\t\t\t\t\t\t::boost::is_complex,\n\t\t\t\t\t\t\t\tvalue_type,\n\t\t\t\t\t\t\t\t::std::complex\n\t\t\t\t\t\t\t>::type\n\t\t\t\t> alpha_vector_type; // NOTE: alpha is a complex vector both for real and complex case. \n\tpublic: typedef vector beta_vector_type; // NOTE: beta is a complex vector only for complex case.\n\tpublic: typedef alpha_vector_type eigvals_vector_type;\n\tprivate: typedef typename matrix_traits::size_type size_type;\n\n\n\t/// Default constructor.\n\tpublic: qz_decomposition()\n\t{\n\t\t// empty\n\t}\n\n\n\t/**\n\t * \\brief A constructor: QZ decomposition of \\a A and \\a B with optional\n\t * reordering.\n\t *\n\t * \\param A The first input matrix.\n\t * \\param B The second input matrix.\n\t * \\param selection The type of eigevalues selection to use for reordering.\n\t */\n\tpublic: template \n\t\tqz_decomposition(matrix_expression const& A, matrix_expression const& B, qz_eigenvalues_selection selection = all_qz_eigenvalues)\n\t\t: S_(A),\n\t\t T_(B)\n\t{\n\t\t// NOTE: preconditions check moved inside decompose.\n\n\t\tdecompose(selection);\n\t}\n\n\n\t/**\n\t * \\brief QZ decomposition of \\a A and \\a B with optional reordering.\n\t *\n\t * \\param A The first input matrix.\n\t * \\param B The second input matrix.\n\t * \\param selection The type of eigevalues selection to use for reordering.\n\t */\n\tpublic: template \n\t\tvoid decompose(matrix_expression const& A, matrix_expression const& B, qz_eigenvalues_selection selection = all_qz_eigenvalues)\n\t{\n\t\t// precondition: A and B have same orientation category\n\t\tBOOST_MPL_ASSERT(\n\t\t\t(\n\t\t\t\t::boost::is_same<\n\t\t\t\t\t\ttypename matrix_traits::orientation_category,\n\t\t\t\t\t\ttypename matrix_traits::orientation_category\n\t\t\t\t>\n\t\t\t)\n\t\t);\n\t\t// precondition: A is square\n\t\tBOOST_UBLAS_CHECK( num_rows(A) == num_columns(A), bad_size() );\n\t\t// precondition: B is square\n\t\tBOOST_UBLAS_CHECK( num_rows(B) == num_columns(B), bad_size() );\n\n\t\tS_ = A;\n\t\tT_ = B;\n\n\t\tdecompose(selection);\n\t}\n\n\n\t/**\n\t * \\brief Get the Schur form of the first input matrix \\f$A\\f$ in the\n\t * QZ decomposition of \\f$(A,B)\\f$.\n\t *\n\t * \\return The Schur form of the input matrix \\f$A\\f$.\n\t */\n\tpublic: S_matrix_type const& S() const\n\t{\n\t\treturn S_;\n\t}\n\n\n\t/**\n\t * \\brief Get the Schur form of the second input matrix \\f$B\\f$ in the\n\t * QZ decomposition of \\f$(A,B)\\f$.\n\t *\n\t * \\return The Schur form of the input matrix \\f$B\\f$.\n\t */\n\tpublic: T_matrix_type const& T() const\n\t{\n\t\treturn T_;\n\t}\n\n\n\t/**\n\t * \\brief Get the orthogonal (or unitary) \\f$Q\\f$ matrix in the\n\t * QZ decomposition of \\f$(A,B)\\f$.\n\t *\n\t * \\return The orthogonal (or unitary) \\f$Q\\f$ matrix.\n\t */\n\tpublic: Q_matrix_type const& Q() const\n\t{\n\t\treturn Q_;\n\t}\n\n\n\t/**\n\t * \\brief Get the orthogonal (or unitary) \\f$Z\\f$ matrix in the\n\t * QZ decomposition of \\f$(A,B)\\f$.\n\t *\n\t * \\return The orthogonal (or unitary) \\f$Z\\f$ matrix.\n\t */\n\tpublic: Z_matrix_type const& Z() const\n\t{\n\t\treturn Z_;\n\t}\n\n\n\t/**\n\t * \\brief Get the numerators of the generalized eigenvalues.\n\t *\n\t * \\return The numerators of the generalized eigenvalues.\n\t */\n\tpublic: alpha_vector_type const& alpha() const\n\t{\n\t\treturn alpha_;\n\t}\n\n\n\t/**\n\t * \\brief Get the denominators of the generalized eigenvalues.\n\t *\n\t * \\return The denominators of the generalized eigenvalues.\n\t */\n\tpublic: beta_vector_type const& beta() const\n\t{\n\t\treturn beta_;\n\t}\n\n\n\t/**\n\t * \\brief Compute the generalized eigenvalues.\n\t *\n\t * Compute the generalized eigenvalues as the ratio:\n\t * \\f[\n\t * \\frac{\\alpha_i}{\\beta_i}\n\t * \\f]\n\t * where \\f$\\alpha_i\\f$ and \\f$\\beta_i\\f$ are the are the diagonals of the\n\t * Schur form of the original input matrices \\f$(A,B)\\f$.\n\t *\n\t * \\return The generalized eigenvalues.\n\t *\n\t * \\note\n\t * It is generally not safe to directly compute this ratio since it may\n\t * easily over- or underflow, and \\f$\\beta_i\\f$ may even be zero.\n\t * However, \\f$\\alpha\\f$ will be always less than and usually comparable\n\t * with \\f$\\operatorname{norm}(A)\\f$ in magnitude, and \\f$\\beta\\f$ always\n\t * less than and usually comparable with \\f$\\operatorname{norm}(B)\\f$.\n\t */\n\tpublic: eigvals_vector_type eigenvalues() const\n\t{\n\t\treturn element_div(alpha_, beta_);\n\n//Another (more costly) alternative to get eigenvalues\n//\t\teigvals_vector_type l;\n//\t\tmatrix::value_type,column_major> L;\n//\t\tmatrix::value_type,column_major> V;\n//\t\teigen(S_, T_, l, L, V);\n\n//Try to balance before computing eigenvalues (really needed?)\n//\t\tS_matrix_type SS(S_);\n//\t\tT_matrix_type TT(T_);\n//\n//\t\tbalance_inplace(SS, TT, false, true);\n//\t\teigen(SS, TT, l, L, V);\n//\n//\t\treturn l;\n\t}\n\n\n\t/**\n\t * \\brief Compute the generalized left eigenvectors.\n\t *\n\t * \\param backtransform Compute the generalized left eigenvectors of matrix\n\t * pair \\f$(A,B)\\f$ instead of \\f$(S,T)\\f$.\n\t * \\return A matrix whose columns are the generalized left eigenvectors.\n\t *\n\t * The right eigenvector \\f$x\\f$ and the left eigenvector \\f$y\\f$ of\n\t * \\f$(S,T)\\f$, corresponding to an eigenvalue \\f$w\\f$ are defined by:\n\t * \\f{align}{ \n\t * S x &= w T x,\\\\\n\t * y^{H} S = w y^{H} T\n\t * \\f}\n\t * where \\f$y^{H}\\f$ denotes the conjugate tranpose of \\f$y\\f$, and \\f$S\\f$\n\t * and \\f$T\\f$ are the Schur form of the input matrix pair \\f$(A,B)\\f$, as\n\t * computed by the QZ decomposition.\n\t * The eigenvalues are not input parameters, but are computed\n\t * directly from the diagonal blocks of \\f$S\\f$ and \\f$T\\f$.\n\t * \n\t * This function returns the matrix \\f$Y\\f$ of left eigenvectors of\n\t * \\f$(S,T)\\f$, or the product \\f$Q*Y\\f$, where \\f$Q\\f$ and \\f$Z\\f$ are the\n\t * Schur vectors computed by the QZ decomposition, representing the left\n\t * eigenvectors of \\f$(A,B)\\f$.\n\t */\n\tpublic: eigvecs_matrix_type left_eigenvectors(bool backtransform=true) const\n\t{\n\t\tvector< ::fortran_bool_t > dummy_eigvecs_sel;\n\t\teigvecs_matrix_type LV;\n\t\teigvecs_matrix_type dummy_RV;\n\n\t\textract_eigenvectors(\n\t\t\tS_,\n\t\t\tT_,\n\t\t\tdetail::left_qz_eigenvectors,\n\t\t\t(backtransform\n\t\t\t\t? detail::backtransform_qz_eigenvectors_option\n\t\t\t\t: detail::all_qz_eigenvectors_option),\n\t\t\tdummy_eigvecs_sel,\n\t\t\tQ_,\n\t\t\tZ_,\n\t\t\tLV,\n\t\t\tdummy_RV,\n\t\t\tcolumn_major_tag()\n\t\t);\n\n\t\treturn LV;\n\t}\n\n\n\t/**\n\t * \\brief Compute the generalized right eigenvectors.\n\t *\n\t * \\param backtransform Compute the generalized left eigenvectors of matrix\n\t * pair \\f$(A,B)\\f$ instead of \\f$(S,T)\\f$.\n\t * \\return A matrix whose columns are the generalized right eigenvectors.\n\t *\n\t * The right eigenvector \\f$x\\f$ and the left eigenvector \\f$y\\f$ of\n\t * \\f$(S,T)\\f$, corresponding to an eigenvalue \\f$w\\f$ are defined by:\n\t * \\f{align}{ \n\t * S x &= w T x,\\\\\n\t * y^{H} S = w y^{H} T\n\t * \\f}\n\t * where \\f$y^{H}\\f$ denotes the conjugate tranpose of \\f$y\\f$, and \\f$S\\f$\n\t * and \\f$T\\f$ are the Schur form of the input matrix pair \\f$(A,B)\\f$, as\n\t * computed by the QZ decomposition.\n\t * The eigenvalues are not input parameters, but are computed\n\t * directly from the diagonal blocks of \\f$S\\f$ and \\f$T\\f$.\n\t * \n\t * This function returns the matrix \\f$X\\f$ of right eigenvectors of\n\t * \\f$(S,T)\\f$, or the product \\f$Z*X\\f$, where \\f$Q\\f$ and \\f$Z\\f$ are the\n\t * Schur vectors computed by the QZ decomposition, representing the right\n\t * eigenvectors of \\f$(A,B)\\f$.\n\t */\n\tpublic: eigvecs_matrix_type right_eigenvectors(bool backtransform=true) const\n\t{\n\t\tvector< ::fortran_bool_t > dummy_eigvecs_sel;\n\t\teigvecs_matrix_type dummy_Y;\n\t\teigvecs_matrix_type X;\n\n\t\textract_eigenvectors(\n\t\t\tS_,\n\t\t\tT_,\n\t\t\tdetail::right_qz_eigenvectors,\n\t\t\t(backtransform\n\t\t\t\t? detail::backtransform_qz_eigenvectors_option\n\t\t\t\t: detail::all_qz_eigenvectors_option),\n\t\t\tdummy_eigvecs_sel,\n\t\t\tQ_,\n\t\t\tZ_,\n\t\t\tdummy_Y,\n\t\t\tX,\n\t\t\tcolumn_major_tag()\n\t\t);\n\n\t\treturn X;\n\t}\n\n\n\t/**\n\t * \\brief Compute the generalized eigenvectors.\n\t *\n\t * \\param LV A matrix whose columns are the generalized left eigenvectors.\n\t * \\param RV A matrix whose columns are the generalized right eigenvectors.\n\t * \\param backtransform Compute the generalized left eigenvectors of matrix\n\t * pair \\f$(A,B)\\f$ instead of \\f$(S,T)\\f$.\n\t * \\return None, but output parameters \\a LV and \\a RV stores, on exit, the\n\t * left and right eigenvectors, respectively.\n\t *\n\t * The right eigenvector \\f$x\\f$ and the left eigenvector \\f$y\\f$ of\n\t * \\f$(S,T)\\f$, corresponding to an eigenvalue \\f$w\\f$ are defined by:\n\t * \\f{align}{ \n\t * S x &= w T x,\\\\\n\t * y^{H} S = w y^{H} T\n\t * \\f}\n\t * where \\f$y^{H}\\f$ denotes the conjugate tranpose of \\f$y\\f$, and \\f$S\\f$\n\t * and \\f$T\\f$ are the Schur form of the input matrix pair \\f$(A,B)\\f$, as\n\t * computed by the QZ decomposition.\n\t * The eigenvalues are not input parameters, but are computed\n\t * directly from the diagonal blocks of \\f$S\\f$ and \\f$T\\f$.\n\t * \n\t * This function returns the matrices \\f$X\\f$ and \\f$Y\\f$ of right and\n\t * left eigenvectors of \\f$(S,T)\\f$, or the products \\f$Z*X\\f$ and\n\t * \\f$Q*Y\\f$, where \\f$Q\\f$ and \\f$Z\\f$ are the Schur vectors computed by\n\t * the QZ decomposition, representing the right and left eigenvectors of\n\t * \\f$(A,B)\\f$.\n\t */\n\tpublic: void eigenvectors(eigvecs_matrix_type& X, eigvecs_matrix_type& Y, bool backtransform=true) const\n\t{\n\t\tvector< ::fortran_bool_t > dummy_eigvecs_sel;\n\n\t\textract_eigenvectors(\n\t\t\tS_,\n\t\t\tT_,\n\t\t\tdetail::both_qz_eigenvectors,\n\t\t\t(backtransform\n\t\t\t\t? detail::backtransform_qz_eigenvectors_option\n\t\t\t\t: detail::all_qz_eigenvectors_option),\n\t\t\tdummy_eigvecs_sel,\n\t\t\tQ_,\n\t\t\tZ_,\n\t\t\tY,\n\t\t\tX,\n\t\t\tcolumn_major_tag()\n\t\t);\n\t}\n\n\n\t/**\n\t * \\brief Reorder the QZ decomposition.\n\t *\n\t * Reorders the generalized real Schur decomposition so that a\n\t * selected cluster of eigenvalues appears in the leading diagonal blocks\n\t * of the upper quasi-triangular matrix \\c S and the upper triangular\n\t * \\c T.\n\t * The leading columns of \\c Q and \\c Z form orthonormal bases of the\n\t * corresponding left and right eigenspaces (deflating subspaces).\n\t *\n\t * \\note\n\t * The \\c i-th element of the input vector \\a selection must evaluate\n\t * to \\c true if the \\c i-th eigenvalue is to be selected.\n\t * \\note\n\t * As a side effect this function changes the original QZ decomposition\n\t * (i.e., matrices \\c S, \\c T, \\c Q, and \\c Z, and vector \\c alpha and\n\t * \\c beta).\n\t */\n\tpublic: void reorder(qz_eigenvalues_selection selection)\n\t{\n\t\t//::external_fp selctg;\n\t\tsize_type n = size(alpha_);\n\t\tvector< ::fortran_bool_t > eigvals_sel(n);\n\n\t\tfor (size_type i = 0; i < n; ++i)\n\t\t{\n\t\t\tif (detail::invoke_qz_eigvals_selector(selection, alpha_(i), beta_(i)))\n\t\t\t{\n\t\t\t\teigvals_sel(i) = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\teigvals_sel(i) = 0;\n\t\t\t}\n\t\t}\n\t\t\t\n\t\tdetail::qz_decomposition_impl<\n\t\t\t\t::boost::is_complex<\n\t\t\t\t\tvalue_type\n\t\t\t\t>::value\n\t\t\t>::template reorder(S_, T_, detail::no_extra_qz_option, eigvals_sel, alpha_, beta_, true, Q_, true, Z_, column_major_tag());\n\t}\n\n\n\t/**\n\t * \\brief Reorder the QZ decomposition.\n\t *\n\t * \\tparam VectorExprT The type of the input selection vector.\n\t * \\param selection Logical vector whose i-th element specifies whether the\n\t * \ti-th eigenvalue is to be selected.\n\t *\n\t * Reorders the generalized real Schur decomposition so that a\n\t * selected cluster of eigenvalues appears in the leading diagonal blocks\n\t * of the upper quasi-triangular matrix \\c S and the upper triangular\n\t * \\c T.\n\t * The leading columns of \\c Q and \\c Z form orthonormal bases of the\n\t * corresponding left and right eigenspaces (deflating subspaces).\n\t *\n\t * \\note\n\t * The \\c i-th element of the input vector \\a selection must evaluate\n\t * to \\c true if the \\c i-th eigenvalue is to be selected.\n\t * \\note\n\t * As a side effect this function changes the original QZ decomposition\n\t * (i.e., matrices \\c S, \\c T, \\c Q, and \\c Z, and vector \\c alpha and\n\t * \\c beta).\n\t */\n\tpublic: template \n\t\tvoid reorder(vector_expression const& selection)\n\t{\n\t\t// precondition: size(selection) == size(alpha_) [ == size(beta_) ]\n\t\tBOOST_UBLAS_CHECK( size(selection) == size(alpha_), bad_size() );\n\n\t\tsize_type n = size(selection);\n\t\tvector< ::fortran_bool_t > eigvals_sel(n);\n\n\t\tfor (size_type i = 0; i < n; ++i)\n\t\t{\n\t\t\tif (static_cast(selection()(i)))\n\t\t\t{\n\t\t\t\teigvals_sel(i) = 1;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\teigvals_sel(i) = 0;\n\t\t\t}\n\t\t}\n\t\t\t\n\t\tdetail::qz_decomposition_impl<\n\t\t\t\t::boost::is_complex<\n\t\t\t\t\tvalue_type\n\t\t\t\t>::value\n\t\t\t>::template reorder(S_, T_, detail::no_extra_qz_option, eigvals_sel, alpha_, beta_, true, Q_, true, Z_, column_major_tag());\n\t}\n\n\n\t/**\n\t * \\brief QZ decomposition with optional reordering.\n\t *\n\t * \\param selection The type of eigevalues selection to use for reordering.\n\t */\n\tprivate: void decompose(qz_eigenvalues_selection selection)\n\t{\n\t\t//typedef typename type_traits::real_type real_type;\n\n\t\tbool sort = false;\n\t\t::external_fp selctg = 0;\n\n\t\tselctg = detail::create_qz_eigvals_selector(selection);\n\t\tif (selctg != 0)\n\t\t{\n\t\t\tsort = true;\n\t\t}\n\n\t\tdetail::qz_decomposition_impl<\n\t\t\t\t::boost::is_complex::value\n\t\t\t>::template decompose(S_, T_, detail::both_qz_schurvectors, true, sort, selctg, Q_, Z_, alpha_, beta_, column_major_tag());\n\t}\n\n\n\t/// The Schur form of the input matrix \\f$A\\f$.\n\tprivate: S_matrix_type S_;\n\t/// The Schur form of the input matrix \\f$B\\f$.\n\tprivate: T_matrix_type T_;\n\t/// The orthogonal/unitary matrix such that \\f$QAZ=S\\f$ and \\f$QBZ=T\\f$.\n\tprivate: Q_matrix_type Q_;\n\t/// The orthogonal/unitary matrix such that \\f$QAZ=S\\f$ and \\f$QBZ=T\\f$.\n\tprivate: Z_matrix_type Z_;\n\t/// The numerator of the generalized Schur eigenvalues.\n\tprivate: alpha_vector_type alpha_; // == diag(S_)\n\t/// The denominator of the generalized Schur eigenvalues.\n\tprivate: beta_vector_type beta_;\n}; // qz_decomposition\n\n\n/**\n * \\brief QZ decomposition of a matrix pair \\f$(A,B)\\f$.\n *\n * \\tparam AMatrixExprT The type of the first matrix expression.\n * \\tparam BMatrixExprT The type of the second matrix expression.\n *\n * \\param A The first matrix expression.\n * \\param B The second matrix expression.\n * \\return An object containing information on the QZ decomposition of\n * \\f$(A,B)\\f$ (\\see qz_decomposition).\n *\n * For square matrices A and B, produces upper quasi-triangular matrices \\a S\n * and \\a T, and unitary matrices \\a Q and \\a Z such that\n * \\f{align}{\n * QSZ' &= A,\\\\\n * QTZ' &= B.\n * \\f}\n * For complex matrices, S and T are triangular.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate \nBOOST_UBLAS_INLINE\nqz_decomposition<\n\ttypename promote_traits<\n\t\ttypename matrix_traits::value_type,\n\t\ttypename matrix_traits::value_type\n\t>::promote_type\n> qz_decompose(matrix_expression const& A, matrix_expression const& B, qz_eigenvalues_selection selection = all_qz_eigenvalues)\n{\n\ttypedef typename promote_traits<\n\t\t\ttypename matrix_traits::value_type,\n\t\t\ttypename matrix_traits::value_type\n\t\t>::promote_type value_type;\n\n\treturn qz_decomposition(A, B, selection);\n}\n\n\n/**\n * \\brief QZ decomposition of a matrix pair \\f$(A,B)\\f$.\n *\n * \\tparam AMatrixT The type of the first input matrix.\n * \\tparam BMatrixT The type of the second input matrix.\n *\n * \\param A On entry, the first input matrix.\n * On exit, the generalized Schur form of matrix \\a A.\n * \\param B On entry, the second input matrix.\n * On exit, the generalized Schur form of matrix \\a B.\n * \\param Q An orthogonal (or unitary) matrix such that \\f$QAZ=S\\f$ and\n * \\f$QBZ=T\\f$, where \\f$S\\f$ and \\f$T\\f$ denote the generalized Schur form\n * of matrices \\a A and \\a B, respectively.\n * \\param Z An orthogonal (or unitary) matrix such that \\f$QAZ=S\\f$ and\n * \\f$QBZ=T\\f$, where \\f$S\\f$ and \\f$T\\f$ denote the generalized Schur form\n * of matrices \\a A and \\a B, respectively.\n * \\return No return value, but the function returns the computed QZ\n * decomposition in the arguments \\a A, \\a B, \\a Q, and \\a Z.\n *\n * For square matrices A and B, produces upper quasi-triangular matrices \\f$S\\f$\n * and \\f$T\\f$, and unitary matrices \\a Q and \\a Z such that\n * \\f{align}{\n * QAZ &= S,\\\\\n * QBZ &= T.\n * \\f}\n * For complex matrices, S and T are triangular.\n * Matrix \\f$S\\f$ and \\f$T\\f$ are stored, at the exit of the function call, in\n * the arguments \\a A and \\a B, respectively.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <\n\ttypename AMatrixT,\n\ttypename BMatrixT,\n\ttypename QMatrixT,\n\ttypename ZMatrixT\n>\nBOOST_UBLAS_INLINE\nvoid qz_decompose_inplace(AMatrixT& A, BMatrixT& B, QMatrixT& Q, ZMatrixT& Z, qz_eigenvalues_selection selection = all_qz_eigenvalues)\n{\n\ttypedef typename promote_traits<\n\t\t\ttypename matrix_traits::value_type,\n\t\t\ttypename matrix_traits::value_type\n\t\t>::promote_type value_type;\n\n\tqz_decomposition qz(A, B, selection);\n\n\tA = qz.S();\n\tB = qz.T();\n\tQ = qz.Q();\n\tZ = qz.Z();\n}\n\n\n/**\n * \\brief QZ decomposition of a matrix pair \\f$(A,B)\\f$.\n *\n * \\tparam AMatrixExprT The type of the first matrix expression.\n * \\tparam BMatrixExprT The type of the second matrix expression.\n *\n * \\param A The first matrix expression.\n * \\param B The second matrix expression.\n * \\param S The generalized Schur form of matrix \\a A.\n * \\param T The generalized Schur form of matrix \\a B.\n * \\param Q An orthogonal (or unitary) matrix such that \\f$QAZ=S\\f$ and\n * \\f$QBZ=T\\f$.\n * \\param Z An orthogonal (or unitary) matrix such that \\f$QAZ=S\\f$ and\n * \\f$QBZ=T\\f$.\n * \\return No return value, but the function returns the computed QZ\n * decomposition in the arguments \\a S, \\a T, \\a Q, and \\a Z.\n *\n * For square matrices A and B, produces upper quasi-triangular matrices \\a S\n * and \\a T, and unitary matrices \\a Q and \\a Z such that\n * \\f{align}{\n * QAZ &= S,\\\\\n * QBZ &= T.\n * \\f}\n * For complex matrices, S and T are triangular.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <\n\ttypename AMatrixExprT,\n\ttypename BMatrixExprT,\n\ttypename SMatrixT,\n\ttypename TMatrixT,\n\ttypename QMatrixT,\n\ttypename ZMatrixT\n>\nBOOST_UBLAS_INLINE\nvoid qz_decompose(matrix_expression const& A, matrix_expression const& B, SMatrixT& S, TMatrixT& T, QMatrixT& Q, ZMatrixT& Z, qz_eigenvalues_selection selection = all_qz_eigenvalues)\n{\n\ttypedef typename promote_traits<\n\t\t\ttypename matrix_traits::value_type,\n\t\t\ttypename matrix_traits::value_type\n\t\t>::promote_type value_type;\n\n\tqz_decomposition qz(A, B, selection);\n\n\tS = qz.S();\n\tT = qz.T();\n\tQ = qz.Q();\n\tZ = qz.Z();\n}\n\n\n/**\n * \\brief Reorder the QZ decomposition.\n *\n * \\tparam SMatrixT The type of the \\a S matrix.\n * \\tparam TMatrixT The type of the \\a T matrix.\n * \\tparam QMatrixT The type of the \\a Q matrix.\n * \\tparam ZMatrixT The type of the \\a Z matrix.\n * \\tparam SelVectorExprT The type of the \\a selection vector.\n * \\param S The Schur form of the matrix \\f$A\\f$ in QZ decomposition of the\n * matrix pair \\f$(A,B)\\f$.\n * \\param T The Schur form of the matrix \\f$B\\f$ in the QZ decomposition of the\n * matrix pair \\f$(A,B)\\f$.\n * \\param Q The orthogonal (or unitary) matrix obtained by the QZ decomposition\n * of the matrix pair \\f$(A,B)\\f$.\n * \\param Z The orthogonal (or unitary) matrix obtained by the QZ decomposition\n * of the matrix pair \\f$(A,B)\\f$.\n * \\param selection A vector where the i-th element specifies whether or not the\n * i-th eigenvalue should be selected in order to appear in the leading (upper\n * left) diagonal blocks of the quasi-triangular pair \\f$(SS,TS)\\f$,\n * \\return None, but the result of the reordering is stored in the parameters\n * \\a S, \\a T, \\a Q, and \\a Z.\n *\n * Reorders the generalized Schur decomposition\n * \\f{align}\n * Q*A*Z &= S,\n * Q*B*Z &= T.\n * \\f}\n * for a matrix pair \\f$(A,B)\\f$ so that a selected cluster of eigenvalues\n * appears in the leading diagonal blocks of the upper quasi-triangular matrix\n * \\a SS and the upper triangular \\a TS.\n * The leading columns of cumulative orthogonal transformation \\a QS and \\a ZS\n * form orthonormal bases of the corresponding left and right eigenspaces\n * (deflating subspaces).\n * After reordering, the following relations are still valid:\n * \\f{align}\n * Q*A*Z &= S,\n * Q*B*Z &= T.\n * \\f}\n */\ntemplate <\n\ttypename SMatrixT,\n\ttypename TMatrixT,\n\ttypename QMatrixT,\n\ttypename ZMatrixT,\n\ttypename SelVectorT\n>\nBOOST_UBLAS_INLINE\nvoid qz_reorder_inplace(SMatrixT& S, TMatrixT& T, QMatrixT& Q, ZMatrixT& Z, vector_expression const& selection)\n{\n\ttypedef typename matrix_traits::orientation_category orientation_category;\n\n\t// precondition: check that orientation category is the same for all the matrices\n\tBOOST_MPL_ASSERT(\n\t\t(::boost::mpl::and_<\n\t\t\t::boost::is_same<\n\t\t\t\torientation_category,\n\t\t\t\ttypename matrix_traits::orientation_category\n\t\t\t>,\n\t\t\t::boost::mpl::and_<\n\t\t\t\t::boost::is_same<\n\t\t\t\t\torientation_category,\n\t\t\t\t\ttypename matrix_traits::orientation_category\n\t\t\t\t>,\n\t\t\t\t::boost::is_same<\n\t\t\t\t\torientation_category,\n\t\t\t\t\ttypename matrix_traits::orientation_category\n\t\t\t\t>\n\t\t\t>\n\t\t>)\n\t);\n\n\ttypedef typename promote_traits<\n\t\t\t\ttypename matrix_traits::value_type,\n\t\t\t\ttypename matrix_traits::value_type\n\t\t\t>::promote_type value_type;\n\ttypedef typename type_traits::real_type real_type;\n\n\t// NOTE: alpha is always a complex vector while beta is complex only for the complex case\n\tvector< ::std::complex > dummy_alpha(num_columns(S));\n\tvector dummy_beta(num_columns(S));\n\n\tdetail::qz_decomposition_impl<\n\t\t\t::boost::is_complex<\n\t\t\t\ttypename promote_traits<\n\t\t\t\t\ttypename matrix_traits::value_type,\n\t\t\t\t\ttypename matrix_traits::value_type\n\t\t\t\t>::promote_type\n\t\t\t>::value\n\t\t>::template reorder(S, T, detail::no_extra_qz_option, selection, dummy_alpha, dummy_beta, true, Q, true, Z, orientation_category());\n}\n\n\n/**\n * \\brief Reorder the QZ decomposition.\n *\n * \\tparam SMatrixT The type of the \\a S matrix.\n * \\tparam TMatrixT The type of the \\a T matrix.\n * \\tparam QMatrixT The type of the \\a Q matrix.\n * \\tparam ZMatrixT The type of the \\a Z matrix.\n * \\tparam SelVectorExprT The type of the \\a selection vector.\n * \\param S The Schur form of the matrix \\f$A\\f$ in QZ decomposition of the\n * matrix pair \\f$(A,B)\\f$.\n * \\param T The Schur form of the matrix \\f$B\\f$ in the QZ decomposition of the\n * matrix pair \\f$(A,B)\\f$.\n * \\param Q The orthogonal (or unitary) matrix obtained by the QZ decomposition\n * of the matrix pair \\f$(A,B)\\f$.\n * \\param Z The orthogonal (or unitary) matrix obtained by the QZ decomposition\n * of the matrix pair \\f$(A,B)\\f$.\n * \\param selection A vector where the i-th element specifies whether or not the\n * i-th eigenvalue should be selected in order to appear in the leading (upper\n * left) diagonal blocks of the quasi-triangular pair \\f$(SS,TS)\\f$,\n * \\param SS The new matrix \\a S obtained after the reordering.\n * \\param TS The new matrix \\a T obtained after the reordering.\n * \\param QS The new matrix \\a Q obtained after the reordering.\n * \\param ZS The new matrix \\a Z obtained after the reordering.\n * \\return None, but the result of the reordering is stored in the output\n * parameters \\a SS, \\a TS, \\a QS, and \\a ZS.\n *\n * Reorders the generalized Schur decomposition\n * \\f{align}\n * Q*A*Z &= S,\n * Q*B*Z &= T.\n * \\f}\n * for a matrix pair \\f$(A,B)\\f$ so that a selected cluster of eigenvalues\n * appears in the leading diagonal blocks of the upper quasi-triangular matrix\n * \\a SS and the upper triangular \\a TS.\n * The leading columns of cumulative orthogonal transformation \\a QS and \\a ZS\n * form orthonormal bases of the corresponding left and right eigenspaces\n * (deflating subspaces).\n * After reordering, the following relations are still valid:\n * \\f{align}\n * QS*A*ZS &= SS,\n * QS*B*ZS &= TS.\n * \\f}\n */\ntemplate <\n\ttypename SMatrixT,\n\ttypename TMatrixT,\n\ttypename QMatrixT,\n\ttypename ZMatrixT,\n\ttypename SelVectorExprT\n>\nBOOST_UBLAS_INLINE\nvoid qz_reorder(SMatrixT const& S, TMatrixT const& T, QMatrixT const& Q, ZMatrixT const& Z, vector_expression const& selection, SMatrixT& SS, TMatrixT& TS, QMatrixT& QS, ZMatrixT& ZS)\n{\n\tSS = S;\n\tTS = T;\n\tQS = Q;\n\tZS = Z;\n\n\tqz_reorder_inplace(SS, TS, QS, ZS, selection);\n}\n\n}}} // Namespace boost::numeric::ublas\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_QZ_HPP\n", "meta": {"hexsha": "a133fdd4bf68c764b05d0e71fefbed9f7ac0a138", "size": 67603, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/qz.hpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/ublasx/operation/qz.hpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/ublasx/operation/qz.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1247697974, "max_line_length": 258, "alphanum_fraction": 0.6842595743, "num_tokens": 20859, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759584, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.685728239408573}} {"text": "/**\n * @file TestProblem02.hpp\n * @author Brahayam Ponton (brahayam.ponton@tuebingen.mpg.de)\n * @license License BSD-3-Clause\n * @copyright Copyright (c) 2019, New York University and Max Planck Gesellschaft.\n * @date 2019-10-06\n */\n\n#pragma once\n\n#include \n#include \n#include \n\n#include \n\nnamespace nlp_test_problems\n{\n\n class TestProblem02 : public solver::NlpDescription\n {\n public:\n\t TestProblem02(){};\n virtual ~TestProblem02(){};\n\n // definition of problem size\n void getNlpParameters(int& n_vars, int& n_cons)\n {\n n_vars = 2;\n n_cons = 0;\n }\n\n // definition of problem box constraints\n void getNlpBounds(int n_vars, int /*n_cons*/, double* x_l, double* x_u, double* /*g_l*/, double* /*g_u*/)\n {\n \t for (int i=0; i // arma::datum/mat/vec\n#include // std::cos/sin\n#include // std::setprecision/setw\n#include // std::cout/fixed\n\nusing namespace std;\n\nint main()\n{\n arma::vec pos{1.0, 0.0};\n\n auto& pi = arma::datum::pi;\n double angle = pi / 2;\n arma::mat rot = {\n {cos(angle), -sin(angle)},\n {sin(angle), cos(angle)}};\n\n cout << \"Current position:\\n\" << pos;\n cout << \"Rotating \" << angle * 180 / pi << \" deg\\n\";\n\n arma::vec new_pos = rot * pos;\n cout << \"New position:\\n\" << new_pos;\n\n cout << fixed << setw(9) << setprecision(4);\n new_pos.raw_print(cout, \"New position:\");\n\n cout << fixed << setw(9) << setprecision(4);\n new_pos.t().raw_print(cout, \"New position:\");\n}\n", "meta": {"hexsha": "235c2e24dcd3e8d21f5a37d5a50f1e7f9704acc6", "size": 765, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "23/armadillo/arma_test.cpp", "max_stars_repo_name": "qsyttkx/geek_time_cpp", "max_stars_repo_head_hexsha": "7650fb6f073822710609da31fc8206f1055bb05a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 171.0, "max_stars_repo_stars_event_min_datetime": "2020-02-11T01:12:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T07:12:48.000Z", "max_issues_repo_path": "23/armadillo/arma_test.cpp", "max_issues_repo_name": "qsyttkx/geek_time_cpp", "max_issues_repo_head_hexsha": "7650fb6f073822710609da31fc8206f1055bb05a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "23/armadillo/arma_test.cpp", "max_forks_repo_name": "qsyttkx/geek_time_cpp", "max_forks_repo_head_hexsha": "7650fb6f073822710609da31fc8206f1055bb05a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 69.0, "max_forks_repo_forks_event_min_datetime": "2020-02-16T08:50:52.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T07:12:13.000Z", "avg_line_length": 25.5, "max_line_length": 56, "alphanum_fraction": 0.5647058824, "num_tokens": 232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037323284109, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6856262794396248}} {"text": "#include \n\n#include \n\n#include \n\nnamespace common_robotics_utilities\n{\nnamespace conversions\n{\nEigen::Quaterniond QuaternionFromRPY(const double R,\n const double P,\n const double Y)\n{\n const Eigen::AngleAxisd roll(R, Eigen::Vector3d::UnitX());\n const Eigen::AngleAxisd pitch(P, Eigen::Vector3d::UnitY());\n const Eigen::AngleAxisd yaw(Y, Eigen::Vector3d::UnitZ());\n const Eigen::Quaterniond quat(roll * pitch * yaw);\n return quat;\n}\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Quaterniond QuaternionFromUrdfRPY(const double R,\n const double P,\n const double Y)\n{\n const Eigen::AngleAxisd roll(R, Eigen::Vector3d::UnitX());\n const Eigen::AngleAxisd pitch(P, Eigen::Vector3d::UnitY());\n const Eigen::AngleAxisd yaw(Y, Eigen::Vector3d::UnitZ());\n const Eigen::Quaterniond quat(yaw * pitch * roll);\n return quat;\n}\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromRotationMatrix(\n const Eigen::Matrix3d& rot_matrix)\n{\n // Use XYZ angles\n const Eigen::Vector3d euler_angles = rot_matrix.eulerAngles(0, 1, 2);\n return euler_angles;\n}\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromQuaternion(const Eigen::Quaterniond& quat)\n{\n return EulerAnglesFromRotationMatrix(quat.toRotationMatrix());\n}\n\n// Returns XYZ Euler angles\nEigen::Vector3d EulerAnglesFromIsometry3d(const Eigen::Isometry3d& trans)\n{\n return EulerAnglesFromRotationMatrix(trans.rotation());\n}\n\nEigen::Isometry3d TransformFromXYZRPY(const double x,\n const double y,\n const double z,\n const double roll,\n const double pitch,\n const double yaw)\n{\n const Eigen::Isometry3d transform = Eigen::Translation3d(x, y, z)\n * QuaternionFromRPY(roll, pitch, yaw);\n return transform;\n}\n\nEigen::Isometry3d TransformFromRPY(const Eigen::Vector3d& translation,\n const Eigen::Vector3d& rotation)\n{\n const Eigen::Isometry3d transform = (Eigen::Translation3d)translation\n * QuaternionFromRPY(rotation.x(),\n rotation.y(),\n rotation.z());\n return transform;\n}\n\nEigen::Isometry3d TransformFromRPY(const Eigen::VectorXd& components)\n{\n if (components.size() == 6)\n {\n return Eigen::Translation3d(components(0),\n components(1),\n components(2))\n * QuaternionFromRPY(components(3),\n components(4),\n components(5));\n }\n else\n {\n throw std::invalid_argument(\n \"VectorXd source vector is not 6 elements in size\");\n }\n}\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfXYZRPY(const double x,\n const double y,\n const double z,\n const double roll,\n const double pitch,\n const double yaw)\n{\n const Eigen::Isometry3d transform = Eigen::Translation3d(x, y, z)\n * QuaternionFromUrdfRPY(roll, pitch, yaw);\n return transform;\n}\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfRPY(const Eigen::Vector3d& translation,\n const Eigen::Vector3d& rotation)\n{\n const Eigen::Isometry3d transform = (Eigen::Translation3d)translation\n * QuaternionFromUrdfRPY(rotation.x(),\n rotation.y(),\n rotation.z());\n return transform;\n}\n\n// URDF RPY IS ACTUALLY APPLIED Y*P*R\nEigen::Isometry3d TransformFromUrdfRPY(const Eigen::VectorXd& components)\n{\n if (components.size() == 6)\n {\n return Eigen::Translation3d(components(0),\n components(1),\n components(2))\n * QuaternionFromUrdfRPY(components(3),\n components(4),\n components(5));\n }\n else\n {\n throw std::invalid_argument(\n \"VectorXd source vector is not 6 elements in size\");\n }\n}\n\nEigen::VectorXd TransformToRPY(const Eigen::Isometry3d& transform)\n{\n Eigen::VectorXd components = Eigen::VectorXd::Zero(6);\n const Eigen::Vector3d translation = transform.translation();\n const Eigen::Vector3d rotation\n = EulerAnglesFromRotationMatrix(transform.rotation());\n components << translation, rotation;\n return components;\n}\n\nEigen::Vector3d StdVectorDoubleToEigenVector3d(\n const std::vector& vector)\n{\n if (vector.size() == 3)\n {\n return Eigen::Vector3d(vector[0], vector[1], vector[2]);\n }\n else\n {\n throw std::invalid_argument(\n \"Vector3d source vector is not 3 elements in size\");\n }\n}\n\nEigen::VectorXd StdVectorDoubleToEigenVectorXd(\n const std::vector& vector)\n{\n Eigen::VectorXd eigen_vector(vector.size());\n for (size_t idx = 0; idx < vector.size(); idx++)\n {\n const double val = vector[idx];\n eigen_vector((ssize_t)idx) = val;\n }\n return eigen_vector;\n}\n\nstd::vector EigenVector3dToStdVectorDouble(\n const Eigen::Vector3d& point)\n{\n return std::vector{point.x(), point.y(), point.z()};\n}\n\nstd::vector EigenVectorXdToStdVectorDouble(\n const Eigen::VectorXd& eigen_vector)\n{\n std::vector vector((size_t)eigen_vector.size());\n for (size_t idx = 0; idx < (size_t)eigen_vector.size(); idx++)\n {\n const double val = eigen_vector[(ssize_t)idx];\n vector[idx] = val;\n }\n return vector;\n}\n\n// Takes as is the ROS custom!\nEigen::Quaterniond StdVectorDoubleToEigenQuaterniond(\n const std::vector& vector)\n{\n if (vector.size() == 4)\n {\n return Eigen::Quaterniond(vector[3], vector[0], vector[1], vector[2]);\n }\n else\n {\n throw std::invalid_argument(\n \"Quaterniond source vector is not 4 elements in size\");\n }\n}\n\n// Returns as is the ROS custom!\nstd::vector EigenQuaterniondToStdVectorDouble(\n const Eigen::Quaterniond& quat)\n{\n return std::vector{quat.x(), quat.y(), quat.z(), quat.w()};\n}\n\nEigen::Vector3d GeometryPointToEigenVector3d(\n const geometry_msgs::Point& point)\n{\n Eigen::Vector3d eigen_point(point.x, point.y, point.z);\n return eigen_point;\n}\n\ngeometry_msgs::Point EigenVector3dToGeometryPoint(\n const Eigen::Vector3d& point)\n{\n geometry_msgs::Point geom_point;\n geom_point.x = point.x();\n geom_point.y = point.y();\n geom_point.z = point.z();\n return geom_point;\n}\n\nEigen::Vector4d GeometryPointToEigenVector4d(\n const geometry_msgs::Point& point)\n{\n Eigen::Vector4d eigen_point(point.x, point.y, point.z, 1.0);\n return eigen_point;\n}\n\ngeometry_msgs::Point EigenVector4dToGeometryPoint(\n const Eigen::Vector4d& point)\n{\n geometry_msgs::Point geom_point;\n geom_point.x = point(0);\n geom_point.y = point(1);\n geom_point.z = point(2);\n return geom_point;\n}\n\ngeometry_msgs::PointStamped EigenVector3dToGeometryPointStamped(\n const Eigen::Vector3d& point, const std::string& frame_id)\n{\n geometry_msgs::PointStamped point_stamped;\n point_stamped.header.frame_id = frame_id;\n point_stamped.point = EigenVector3dToGeometryPoint(point);\n return point_stamped;\n}\n\nEigen::Vector3d GeometryVector3ToEigenVector3d(\n const geometry_msgs::Vector3& vector)\n{\n Eigen::Vector3d eigen_vector(vector.x, vector.y, vector.z);\n return eigen_vector;\n}\n\ngeometry_msgs::Vector3 EigenVector3dToGeometryVector3(\n const Eigen::Vector3d& vector)\n{\n geometry_msgs::Vector3 geom_vector;\n geom_vector.x = vector.x();\n geom_vector.y = vector.y();\n geom_vector.z = vector.z();\n return geom_vector;\n}\n\nEigen::Vector4d GeometryVector3ToEigenVector4d(\n const geometry_msgs::Vector3& vector)\n{\n Eigen::Vector4d eigen_vector(vector.x, vector.y, vector.z, 0.0);\n return eigen_vector;\n}\n\ngeometry_msgs::Vector3 EigenVector4dToGeometryVector3(\n const Eigen::Vector4d& vector)\n{\n geometry_msgs::Vector3 geom_vector;\n geom_vector.x = vector(0);\n geom_vector.y = vector(1);\n geom_vector.z = vector(2);\n return geom_vector;\n}\n\nEigen::Quaterniond GeometryQuaternionToEigenQuaterniond(\n const geometry_msgs::Quaternion& quat)\n{\n Eigen::Quaterniond eigen_quaternion(quat.w, quat.x, quat.y, quat.z);\n return eigen_quaternion;\n}\n\ngeometry_msgs::Quaternion EigenQuaterniondToGeometryQuaternion(\n const Eigen::Quaterniond& quat)\n{\n geometry_msgs::Quaternion geom_quaternion;\n geom_quaternion.w = quat.w();\n geom_quaternion.x = quat.x();\n geom_quaternion.y = quat.y();\n geom_quaternion.z = quat.z();\n return geom_quaternion;\n}\n\nEigen::Isometry3d GeometryPoseToEigenIsometry3d(\n const geometry_msgs::Pose& pose)\n{\n const Eigen::Translation3d trans(pose.position.x,\n pose.position.y,\n pose.position.z);\n const Eigen::Quaterniond quat(pose.orientation.w,\n pose.orientation.x,\n pose.orientation.y,\n pose.orientation.z);\n const Eigen::Isometry3d eigen_pose = trans * quat;\n return eigen_pose;\n}\n\ngeometry_msgs::Pose EigenIsometry3dToGeometryPose(\n const Eigen::Isometry3d& transform)\n{\n const Eigen::Vector3d trans = transform.translation();\n const Eigen::Quaterniond quat(transform.rotation());\n geometry_msgs::Pose geom_pose;\n geom_pose.position.x = trans.x();\n geom_pose.position.y = trans.y();\n geom_pose.position.z = trans.z();\n geom_pose.orientation.w = quat.w();\n geom_pose.orientation.x = quat.x();\n geom_pose.orientation.y = quat.y();\n geom_pose.orientation.z = quat.z();\n return geom_pose;\n}\n\ngeometry_msgs::PoseStamped EigenIsometry3dToGeometryPoseStamped(\n const Eigen::Isometry3d& transform, const std::string& frame_id)\n{\n geometry_msgs::PoseStamped pose_stamped;\n pose_stamped.header.frame_id = frame_id;\n pose_stamped.pose = EigenIsometry3dToGeometryPose(transform);\n return pose_stamped;\n}\n\nEigen::Isometry3d GeometryTransformToEigenIsometry3d(\n const geometry_msgs::Transform& transform)\n{\n const Eigen::Translation3d trans(transform.translation.x,\n transform.translation.y,\n transform.translation.z);\n const Eigen::Quaterniond quat(transform.rotation.w,\n transform.rotation.x,\n transform.rotation.y,\n transform.rotation.z);\n const Eigen::Isometry3d eigen_transform = trans * quat;\n return eigen_transform;\n}\n\ngeometry_msgs::Transform EigenIsometry3dToGeometryTransform(\n const Eigen::Isometry3d& transform)\n{\n const Eigen::Vector3d trans = transform.translation();\n const Eigen::Quaterniond quat(transform.rotation());\n geometry_msgs::Transform geom_transform;\n geom_transform.translation.x = trans.x();\n geom_transform.translation.y = trans.y();\n geom_transform.translation.z = trans.z();\n geom_transform.rotation.w = quat.w();\n geom_transform.rotation.x = quat.x();\n geom_transform.rotation.y = quat.y();\n geom_transform.rotation.z = quat.z();\n return geom_transform;\n}\n\ngeometry_msgs::TransformStamped EigenIsometry3dToGeometryTransformStamped(\n const Eigen::Isometry3d& transform, const std::string& frame_id,\n const std::string& child_frame_id)\n{\n geometry_msgs::TransformStamped transform_stamped;\n transform_stamped.header.frame_id = frame_id;\n transform_stamped.child_frame_id = child_frame_id;\n transform_stamped.transform = EigenIsometry3dToGeometryTransform(transform);\n return transform_stamped;\n}\n\nEigen::Matrix3Xd VectorGeometryPointToEigenMatrix3Xd(\n const std::vector& vector_geom)\n{\n Eigen::Matrix3Xd eigen_matrix = Eigen::MatrixXd(3, vector_geom.size());\n for (size_t idx = 0; idx < vector_geom.size(); idx++)\n {\n eigen_matrix.block<3,1>(0, (ssize_t)idx)\n = GeometryPointToEigenVector3d(vector_geom[idx]);\n }\n return eigen_matrix;\n}\n\nstd::vector EigenMatrix3XdToVectorGeometryPoint(\n const Eigen::Matrix3Xd& eigen_matrix)\n{\n std::vector vector_geom((size_t)eigen_matrix.cols());\n for (size_t idx = 0; idx < vector_geom.size(); idx++)\n {\n vector_geom[idx]\n = EigenVector3dToGeometryPoint(\n eigen_matrix.block<3,1>(0, (ssize_t)idx));\n }\n return vector_geom;\n}\n\nstd::vector\nVectorEigenVector3dToVectorGeometryPoint(\n const common_robotics_utilities::math::VectorVector3d& vector_eigen)\n{\n std::vector vector_geom(vector_eigen.size());\n for (size_t idx = 0; idx < vector_eigen.size(); idx++)\n {\n vector_geom[idx] = EigenVector3dToGeometryPoint(vector_eigen[idx]);\n }\n return vector_geom;\n}\n\ncommon_robotics_utilities::math::VectorVector3d\nVectorGeometryPointToVectorEigenVector3d(\n const std::vector& vector_geom)\n{\n common_robotics_utilities::math::VectorVector3d vector_eigen(\n vector_geom.size());\n for (size_t idx = 0; idx < vector_geom.size(); idx++)\n {\n vector_eigen[idx] = GeometryPointToEigenVector3d(vector_geom[idx]);\n }\n return vector_eigen;\n}\n\ncommon_robotics_utilities::math::VectorVector3d\nVectorGeometryVector3ToEigenVector3d(\n const std::vector& vector_geom)\n{\n common_robotics_utilities::math::VectorVector3d vector_eigen(\n vector_geom.size());\n for (size_t idx = 0; idx < vector_geom.size(); idx++)\n {\n vector_eigen[idx] = GeometryVector3ToEigenVector3d(vector_geom[idx]);\n }\n return vector_eigen;\n}\n\ncommon_robotics_utilities::math::VectorIsometry3d\nVectorGeometryPoseToVectorIsometry3d(\n const std::vector& vector_geom)\n{\n common_robotics_utilities::math::VectorIsometry3d vector_eigen(\n vector_geom.size());\n for (size_t idx = 0; idx < vector_geom.size(); idx++)\n {\n vector_eigen[idx] = GeometryPoseToEigenIsometry3d(vector_geom[idx]);\n }\n return vector_eigen;\n}\n\ncommon_robotics_utilities::math::VectorIsometry3d\nVectorGeometryPoseToVectorIsometry3d(\n const std::vector& vector_geom)\n{\n common_robotics_utilities::math::VectorIsometry3d vector_eigen(\n vector_geom.size());\n for (size_t idx = 0; idx < vector_geom.size(); idx++)\n {\n vector_eigen[idx] = GeometryTransformToEigenIsometry3d(vector_geom[idx]);\n }\n return vector_eigen;\n}\n\nstd::vector VectorIsometry3dToVectorGeometryPose(\n const common_robotics_utilities::math::VectorIsometry3d& vector_eigen)\n{\n std::vector vector_geom(vector_eigen.size());\n for (size_t idx = 0; idx < vector_eigen.size(); idx++)\n {\n vector_geom[idx] = EigenIsometry3dToGeometryPose(vector_eigen[idx]);\n }\n return vector_geom;\n}\n\nstd::vector VectorIsometry3dToVectorGeometryTransform(\n const common_robotics_utilities::math::VectorIsometry3d& vector_eigen)\n{\n std::vector vector_geom(vector_eigen.size());\n for (size_t idx = 0; idx < vector_eigen.size(); idx++)\n {\n vector_geom[idx] = EigenIsometry3dToGeometryTransform(vector_eigen[idx]);\n }\n return vector_geom;\n}\n} // namespace conversions\n} // namespace common_robotics_utilities\n", "meta": {"hexsha": "6c9c1511bd4a85acc0d0e59a6f9b7ebae36a2f3e", "size": 15782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common_robotics_utilities/conversions.cpp", "max_stars_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_stars_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common_robotics_utilities/conversions.cpp", "max_issues_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_issues_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common_robotics_utilities/conversions.cpp", "max_forks_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_forks_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.500998004, "max_line_length": 80, "alphanum_fraction": 0.6658218223, "num_tokens": 3723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012732322216, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.685583235757676}} {"text": "#include \"utils.hpp\"\n#include \n#include \n#include \n#include \nusing namespace std;\nusing Bint = boost::multiprecision::cpp_int;\n\nstring RSAPrivateKeyFactorizer_cppfunc(string s, string d_, string e_){\n Bint n(s);\n Bint d(d_);\n Bint e(e_);\n Bint t = e*d-1;\n Bint u = 0;\n using engine = boost::random::independent_bits_engine;\n engine gen;\n while(true){\n Bint quotient = t/2;\n Bint remainder = t%2;\n if(remainder!=0){break;}\n u += 1;\n t = quotient;\n }\n bool found = false;\n Bint c1, c2;\n while(!found){\n Bint i(\"1\");\n Bint a = (gen()+1)%n;\n while(i<=u and !found){\n Bint c1_ = powm(Bint(\"2\"),i-1,n);\n c1 = powm(a,c1_*t,n);\n Bint c2_ = powm(Bint(\"2\"),i,n);\n c2 = powm(a,c2_*t,n);\n found = (c1!=1) and (c1!=-1%n) and (c2==1);\n i+=1;\n }\n }\n Bint retval = gcd(c1-1, n);\n return retval.str();\n \n}\n", "meta": {"hexsha": "a04edbc690ef5faa3d8ef17361c6c925dd74f916", "size": 1065, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/RSAPrivateKeyFactorizer_cpp.cpp", "max_stars_repo_name": "FullteaR/factorizer", "max_stars_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RSAPrivateKeyFactorizer_cpp.cpp", "max_issues_repo_name": "FullteaR/factorizer", "max_issues_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RSAPrivateKeyFactorizer_cpp.cpp", "max_forks_repo_name": "FullteaR/factorizer", "max_forks_repo_head_hexsha": "f4beb7a14d6cda38d69b9ff6dbe673575b554288", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.3571428571, "max_line_length": 87, "alphanum_fraction": 0.5305164319, "num_tokens": 338, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.945801271704518, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6855832346502889}} {"text": "/*\n * warp_statistics.hpp\n *\n * Created on: Nov 14, 2018\n * Author: Gregory Kramida\n * Copyright: 2018 Gregory Kramida\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#pragma once\n\n//libraries\n#include \n#include \n\n//local\n#include \"typedefs.hpp\"\n\nnamespace math {\n\n/**\n * Locates the maximum L2 norm (length) of the vector in the given field.\n * @param[out] max_norm length of the longest vector\n * @param[out] coordinate the location of the longest vector\n * @param[in] vector_field the vector field to look at\n */\ntemplate\nvoid locate_max_norm(typename Scalar::Scalar& max_norm, math::Vector2i& coordinates,\n\t\tconst Eigen::Matrix& vector_field);\n/**\n * Locates the maximum L2 norm (length) of the vector in the given field.\n * @overload\n */\ntemplate\nvoid locate_max_norm(typename Scalar::Scalar& max_norm, math::Vector3i& coordinates,\n\t\tconst Eigen::Tensor& vector_field);\n/**\n * Locates the minimum L2 norm (length) of the vector in the given field.\n * @param[out] max_norm length of the longest vector\n * @param[out] coordinate the location of the longest vector\n * @param[in] vector_field the vector field to look at\n */\ntemplate\nvoid locate_min_norm(typename Scalar::Scalar& min_norm, math::Vector2i& coordinates,\n\t\tconst Eigen::Matrix& vector_field);\n\n/**\n * Locates the minimum L2 norm (length) of the vector in the given field.\n * @overload\n */\ntemplate\nvoid locate_min_norm(typename Scalar::Scalar& min_norm, math::Vector3i& coordinates,\n\t\tconst Eigen::Tensor& vector_field);\n/**\n * Locates the maximum in the given field.\n * @param[out] maximum the maximum coefficient\n * @param[out] coordinates coordinate of the maximum coefficient\n * @param[in] scalar_field the scalar field to look at\n */\ntemplate\nvoid locate_maximum(Scalar& maximum, math::Vector2i& coordinates,\n\t\tconst Eigen::Matrix& scalar_field);\n/**\n * Locates the maximum in the given field.\n * @overload\n */\ntemplate\nvoid locate_maximum(Scalar& maximum, math::Vector3i& coordinates,\n\t\tconst Eigen::Tensor& scalar_field);\n\ntemplate\ninline\nScalar maximum(const Eigen::Tensor& scalar_field){\n\treturn static_cast >(scalar_field.maximum())(0);\n}\n\ntemplate\ninline\nScalar maximum(const Eigen::Matrix& scalar_field){\n\treturn scalar_field.maxCoeff();\n}\n\ntemplate\ninline\nScalar minimum(const Eigen::Tensor& scalar_field){\n\treturn static_cast >(scalar_field.minimum())(0);\n}\n\ntemplate\ninline\nScalar minimum(const Eigen::Matrix& scalar_field){\n\treturn scalar_field.minCoeff();\n}\n\n\n\n//uses traversal function/functor combo, otherwise the same as locate_max_norm\nvoid locate_max_norm2(float& max_norm, math::Vector2i& coordinates, const math::MatrixXv2f& vector_field);\n\n/**\n * Locate the maximum L2 norm (length) of the vector in the given field.\n * @param[out] min_norm length of the shortest vector\n * @param[out] coordinate the location of the shortest vector\n * @param[in] vector_field the field to look at\n */\ntemplate\ntypename Scalar::Scalar max_norm(const Eigen::Matrix& vector_field);\n/**\n * Locate the maximum L2 norm (length) of the vector in the given field.\n * @override\n */\ntemplate\ntypename Scalar::Scalar max_norm(const Eigen::Tensor& vector_field);\n/**\n * Locate the minimum L2 norm (length) of the vector in the given field.\n * @param[out] min_norm length of the shortest vector\n * @param[out] coordinate the location of the shortest vector\n * @param[in] vector_field the field to look at\n */\ntemplate\ntypename Scalar::Scalar min_norm(const Eigen::Matrix& vector_field);\n/**\n * Locate the minimum L2 norm (length) of the vector in the given field.\n * @override\n */\ntemplate\ntypename Scalar::Scalar min_norm(const Eigen::Tensor& vector_field);\n\ntemplate\nScalar mean(const Eigen::Matrix& field);\n\ntemplate\nScalar mean(const Eigen::Tensor& field);\n\ntemplate\nScalar std(const Eigen::Matrix& field);\n\ntemplate\nScalar std(const Eigen::Tensor& field);\n\nfloat ratio_of_vector_lengths_above_threshold(const math::MatrixXv2f& vector_field, float threshold);\nfloat mean_vector_length(const math::MatrixXv2f& vector_field);\nvoid mean_and_std_vector_length(float& mean, float& standard_deviation, const math::MatrixXv2f& vector_field);\n\n}\n", "meta": {"hexsha": "fe4cabd980a7afa4d12c4615389273126737e8bb", "size": 5836, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/statistics.hpp", "max_stars_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_stars_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-01-07T14:12:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T01:48:03.000Z", "max_issues_repo_path": "src/math/statistics.hpp", "max_issues_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_issues_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2018-12-19T16:43:33.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-06T19:50:22.000Z", "max_forks_repo_path": "src/math/statistics.hpp", "max_forks_repo_name": "Algomorph/LevelSetFusionExperimentsCPP", "max_forks_repo_head_hexsha": "f56962f0ad5c62e6706f818062782a2e1660afda", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-01-07T14:12:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-06T06:30:24.000Z", "avg_line_length": 37.1719745223, "max_line_length": 125, "alphanum_fraction": 0.7553118574, "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310357, "lm_q2_score": 0.7956580952177051, "lm_q1q2_score": 0.6854898506731701}} {"text": "//\n// Multivariate Guassian Class.\n// Original from Humphrey Hu \n// (https://github.com/Humhu/argus_utils/blob/devel/include/argus_utils/random/MultivariateGaussian.hpp)\n// Adapted by Arun Venkatraman\n//\n\n#pragma once\n\n#include \n#include \n\n#include \n#include \n\nnamespace math\n{\n\nclass MultivariateGaussian \n{\npublic:\n\n\t// Seeds the engine using a true random number. Sets mean_ to zero\n\t// and covariance to identity. \n\tMultivariateGaussian(const int dim);\n\n\t// Seeds the engine using the specified seed. Sets mean_ to zero\n\t// and _covariance to identity.\n\tMultivariateGaussian(const int dim, const int seed);\n\t\n\t// Sets the mean to mu and covariance to sigma.\n\tMultivariateGaussian(const Eigen::VectorXd& mu, const Eigen::MatrixXd& sigma);\n \n\t// Sets the mean to mu and covariance to sigma. Seeds the engine using a specified seed. \n\tMultivariateGaussian(const Eigen::VectorXd& mu, const Eigen::MatrixXd& sigma, const int seed);\n\n\tMultivariateGaussian(const MultivariateGaussian& other);\n\tMultivariateGaussian& operator=(const MultivariateGaussian& other);\n \n void set_mean(const Eigen::VectorXd& mu);\n void set_covariance(const Eigen::MatrixXd& sigma);\n\tvoid set_information(const Eigen::MatrixXd& inv_sigma);\n\n\tunsigned int get_dimension() const { return mean_.size(); }\n\tconst Eigen::VectorXd& mean() const { return mean_; }\n\tconst Eigen::MatrixXd covariance() const { return llt_.reconstructedMatrix(); }\n\tconst Eigen::MatrixXd cholesky() const { return llt_.matrixL(); }\n\t\n\t// Generate a sample truncated at a specified number of standard deviations.\n\tEigen::VectorXd sample(double max_var = 3.0);\n\n\t// Evaluate the multivariate normal PDF for the specified sample.\n double evaluate_probability(const Eigen::VectorXd& x) const;\n \nprotected:\n\t\n std::mt19937 gen_;\n\tstd::normal_distribution distribution_;\n\n // Mean of the distribution.\n\tEigen::VectorXd mean_;\n // Store covariance as its cholesky decomposition.\n\tEigen::LLT llt_;\n\n // Normalization constant;\n\tdouble z_; \n\n\tvoid initialize_cov(const Eigen::MatrixXd& cov);\n};\n\n}\n", "meta": {"hexsha": "4a24da8f3cb2edbf1a9b8e53dca7142075c3ea47", "size": 2136, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/utils/multivariate_gaussian.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/utils/multivariate_gaussian.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/multivariate_gaussian.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 29.6666666667, "max_line_length": 104, "alphanum_fraction": 0.7457865169, "num_tokens": 503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7905303211371898, "lm_q1q2_score": 0.6854180576338373}} {"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n// modified version of Normalization.hpp code\n#pragma once\n\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include \n#include \n#include \n\nnamespace fluid {\nnamespace algorithm {\n\nclass RobustScaling\n{\npublic:\n using ArrayXd = Eigen::ArrayXd;\n using ArrayXXd = Eigen::ArrayXXd;\n\n void init(double low, double high, RealMatrixView in)\n {\n using namespace Eigen;\n using namespace _impl;\n const double epsilon = std::numeric_limits::epsilon();\n mLow = low;\n mHigh = high;\n ArrayXXd input = asEigen(in);\n mDataLow.resize(input.cols());\n mDataHigh.resize(input.cols());\n mMedian.resize(input.cols());\n mRange.resize(input.cols());\n index length = input.rows();\n for (index i = 0; i < input.cols(); i++)\n {\n ArrayXd sorted = input.col(i);\n std::sort(sorted.data(), sorted.data() + length);\n mMedian(i) = sorted(lrint(0.5 * (length - 1)));\n mDataLow(i) = sorted(lrint((mLow / 100.0) * (length - 1)));\n mDataHigh(i) = sorted(lrint((mHigh / 100.0) * (length - 1)));\n }\n mRange = mDataHigh - mDataLow;\n mRange = mRange.max(epsilon);\n mInitialized = true;\n }\n\n void init(double low, double high, RealVectorView dataLow,\n RealVectorView dataHigh, RealVectorView median,\n RealVectorView range)\n {\n using namespace Eigen;\n using namespace _impl;\n const double epsilon = std::numeric_limits::epsilon();\n mLow = low;\n mHigh = high;\n mDataLow = asEigen(dataLow);\n mDataHigh = asEigen(dataHigh);\n mMedian = asEigen(median);\n mRange = asEigen(range);\n mRange =\n mRange.max(epsilon); // in case it is imported from the outside world\n mInitialized = true;\n }\n\n void processFrame(const RealVectorView in, RealVectorView out,\n bool inverse = false) const\n {\n using namespace Eigen;\n using namespace _impl;\n ArrayXd input = asEigen(in);\n ArrayXd result;\n if (!inverse) { result = (input - mMedian) / mRange; }\n else\n {\n result = (input * mRange) + mMedian;\n }\n out = asFluid(result);\n }\n\n void process(const RealMatrixView in, RealMatrixView out,\n bool inverse = false) const\n {\n using namespace Eigen;\n using namespace _impl;\n ArrayXXd input = asEigen(in);\n ArrayXXd result;\n if (!inverse)\n {\n result = (input.rowwise() - mMedian.transpose());\n result = result.rowwise() / mRange.transpose();\n }\n else\n {\n result = (input.rowwise() * mRange.transpose());\n result = (result.rowwise() + mMedian.transpose());\n }\n out = asFluid(result);\n }\n\n void setLow(double low) { mLow = low; }\n void setHigh(double high) { mHigh = high; }\n bool initialized() const { return mInitialized; }\n\n double getLow() const { return mLow; }\n double getHigh() const { return mHigh; }\n\n void getDataLow(RealVectorView out) const\n {\n using namespace _impl;\n out = asFluid(mDataLow);\n }\n\n void getDataHigh(RealVectorView out) const\n {\n using namespace _impl;\n out = asFluid(mDataHigh);\n }\n\n void getMedian(RealVectorView out) const\n {\n using namespace _impl;\n out = asFluid(mMedian);\n }\n\n void getRange(RealVectorView out) const\n {\n using namespace _impl;\n out = asFluid(mRange);\n }\n\n index dims() const { return mMedian.size(); }\n index size() const { return 1; }\n\n void clear()\n {\n mLow = 0;\n mHigh = 1.0;\n mMedian.setZero();\n mRange.setZero();\n mRange.setZero();\n mInitialized = false;\n }\n\n double mLow{0.0};\n double mHigh{1.0};\n ArrayXd mDataHigh;\n ArrayXd mDataLow;\n ArrayXd mMedian;\n ArrayXd mRange;\n bool mInitialized{false};\n};\n}; // namespace algorithm\n}; // namespace fluid\n", "meta": {"hexsha": "3de029baef15e8801cea1a0e184536ad01228f74", "size": 4212, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/RobustScaling.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/public/RobustScaling.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/public/RobustScaling.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 26.0, "max_line_length": 77, "alphanum_fraction": 0.6495726496, "num_tokens": 1097, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009526726545, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.685340604913568}} {"text": "#include \n#include \n#include \n\n#include \"homography/compute_homography_model.hpp\"\n#include \"homography/compute_homography_error.hpp\"\n#include \"ransac.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid random_measurements(Matrix3d& H, vector& src, vector& dst, int n) {\n src.clear();\n dst.clear();\n H = Matrix3d::Random();\n H /= H(2,2);\n VectorXd x = 1000*VectorXd::Random(n);\n VectorXd y = 1000*VectorXd::Random(n);\n for(int i = 0; i < n; i++) {\n Vector3d p(x(i), y(i), 1);\n Vector3d pp = H*p+Vector3d(1.*rand()/RAND_MAX, 1.*rand()/RAND_MAX, 0);\n src.emplace_back(p.x()/p.z(), p.y()/p.z());\n dst.emplace_back(pp.x()/pp.z(), pp.y()/pp.z());\n }\n}\n\nint main() {\n ComputeHomographyModel chm;\n ComputeHomographyError che;\n vector measurements;\n\n measurements.emplace_back(Point2f(0,0), Point2f(1,1));\n measurements.emplace_back(Point2f(1,1), Point2f(2,2));\n measurements.emplace_back(Point2f(2,1), Point2f(3,4));\n measurements.emplace_back(Point2f(4,3), Point2f(1,5));\n\n auto start = chrono::high_resolution_clock::now();\n HomographyModel hm = chm(measurements);\n auto finish = chrono::high_resolution_clock::now();\n\n // cout << che(hm, measurements[0]) << endl;\n\n cout << \"Simple homography calculation\\n\";\n cout << \"Both matrices should be equal\\n\";\n cout << \"Ours: \" << chrono::duration(finish-start).count() << \" s\" << endl;\n hm.print();\n\n vector src, dst;\n src.emplace_back(0,0);\n src.emplace_back(1,1);\n src.emplace_back(2,1);\n src.emplace_back(4,3);\n dst.emplace_back(1,1);\n dst.emplace_back(2,2);\n dst.emplace_back(3,4);\n dst.emplace_back(1,5);\n\n start = chrono::high_resolution_clock::now();\n Mat H = findHomography(src, dst);\n finish = chrono::high_resolution_clock::now();\n cout << \"OpenCV's: \" << chrono::duration(finish-start).count() << \" s\" << endl;\n cout << H << endl;\n\n Matrix3d real_H;\n double opencv = 0, our = 0;\n for(int i = 0; i < 1000; i++) {\n random_measurements(real_H, src, dst, 10000);\n start = chrono::high_resolution_clock::now();\n H = findHomography(src, dst, CV_RANSAC);\n finish = chrono::high_resolution_clock::now();\n opencv += chrono::duration(finish-start).count();\n // cout << \"Real H:\\n\" << real_H << endl;\n // cout << \"OpenCV's H: \" << chrono::duration(finish - start).count()\n // << \" s\" << endl;\n // cout << H << endl;\n\n measurements.clear();\n for (size_t i = 0; i < src.size(); i++) {\n measurements.emplace_back(src[i], dst[i]);\n }\n\n start = chrono::high_resolution_clock::now();\n auto my_H =\n ransac(measurements);\n finish = chrono::high_resolution_clock::now();\n our += chrono::duration(finish-start).count();\n\n // cout << \"Our H: \" << chrono::duration(finish - start).count()\n // << \" s\" << endl;\n // my_H.print();\n }\n cout << \"OpenCV's: \" << opencv << \" s\" << endl;\n cout << \"Ours: \" << our << \" s\" << endl;\n\n return EXIT_SUCCESS;\n}", "meta": {"hexsha": "d4efbc87436083e825d65335d3322630825e01da", "size": 3145, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/test/test.cpp", "max_stars_repo_name": "matheuscarius/project-inf573", "max_stars_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/test/test.cpp", "max_issues_repo_name": "matheuscarius/project-inf573", "max_issues_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/test/test.cpp", "max_forks_repo_name": "matheuscarius/project-inf573", "max_forks_repo_head_hexsha": "0e19e40ee52254e7ad66f9d0c94629499d74150e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4226804124, "max_line_length": 90, "alphanum_fraction": 0.6359300477, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6853139073661535}} {"text": "// Copyright Paul A. Bristow 2016\n// Copyright John Z. Maddock 2016\n\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or\n// copy at http ://www.boost.org/LICENSE_1_0.txt).\n\n/*! brief Example of using Lambert W function to compute current through a diode connected transistor with preset series resistance.\n \\details T. C. Banwell and A. Jayakumar,\n Exact analytical solution of current flow through diode with series resistance,\n Electron Letters, 36(4):291-2 (2000)\n DOI: doi.org/10.1049/el:20000301 \n\n The current through a diode connected NPN bipolar junction transistor (BJT) \n type 2N2222 (See https://en.wikipedia.org/wiki/2N2222 and \n https://www.fairchildsemi.com/datasheets/PN/PN2222.pdf Datasheet)\n was measured, for a voltage between 0.3 to 1 volt, see Fig 2 for a log plot,\n showing a knee visible at about 0.6 V.\n\n The transistor parameter isat was estimated to be 25 fA and the ideality factor = 1.0.\n The intrinsic emitter resistance re was estimated from the rsat = 0 data to be 0.3 ohm.\n\n The solid curves in Figure 2 are calculated using equation 5 with rsat included with re.\n\n http://www3.imperial.ac.uk/pls/portallive/docs/1/7292572.PDF\n*/\n\n#include \nusing boost::math::lambert_w0;\n\n#include \n// using std::cout;\n// using std::endl;\n#include \n#include \n#include \n#include \n#include \n\n/*!\nCompute thermal voltage as a function of temperature,\nabout 25 mV at room temperature.\nhttps://en.wikipedia.org/wiki/Boltzmann_constant#Role_in_semiconductor_physics:_the_thermal_voltage\n\n\\param temperature Temperature (degrees centigrade).\n*/\nconst double v_thermal(double temperature)\n{\n constexpr const double boltzmann_k = 1.38e-23; // joules/kelvin.\n const double charge_q = 1.6021766208e-19; // Charge of an electron (columb).\n double temp =+ 273; // Degrees C to K.\n return boltzmann_k * temp / charge_q;\n} // v_thermal\n\n/*!\nBanwell & Jayakumar, equation 2\n*/\ndouble i(double isat, double vd, double vt, double nu)\n{\n double i = isat * (exp(vd / (nu * vt)) - 1);\n return i;\n} // \n\n/*!\n\nBanwell & Jayakumar, Equation 4.\ni current flow = isat\nv voltage source.\nisat reverse saturation current in equation 4.\n(might implement equation 4 instead of simpler equation 5?).\nvd voltage drop = v - i* rs (equation 1).\nvt thermal voltage, 0.0257025 = 25 mV.\nnu junction ideality factor (default = unity), also known as the emission coefficient.\nre intrinsic emitter resistance, estimated to be 0.3 ohm from low current.\nrsat reverse saturation current\n\n\\param v Voltage V to compute current I(V).\n\\param vt Thermal voltage, for example 0.0257025 = 25 mV, computed from boltzmann_k * temp / charge_q; \n\\param rsat Resistance in series with the diode.\n\\param re Instrinsic emitter resistance (estimated to be 0.3 ohm from the Rs = 0 data)\n\\param isat Reverse saturation current (See equation 2).\n\\param nu Ideality factor (default = unity).\n\n\\returns I amp as function of V volt.\n\n*/\ndouble iv(double v, double vt, double rsat, double re, double isat, double nu = 1.)\n{ \n // V thermal 0.0257025 = 25 mV\n // was double i = (nu * vt/r) * lambert_w((i0 * r) / (nu * vt)); equ 5.\n\n rsat = rsat + re; \n double i = nu * vt / rsat;\n std::cout << \"nu * vt / rsat = \" << i << std::endl; // 0.000103223\n\n double x = isat * rsat / (nu * vt);\n std::cout << \"isat * rsat / (nu * vt) = \" << x << std::endl;\n\n double eterm = (v + isat * rsat) / (nu * vt);\n std::cout << \"(v + isat * rsat) / (nu * vt) = \" << eterm << std::endl;\n\n double e = exp(eterm);\n std::cout << \"exp(eterm) = \" << e << std::endl;\n\n double w0 = lambert_w0(x * e);\n std::cout << \"w0 = \" << w0 << std::endl;\n return i * w0 - isat;\n\n} // double iv\n\nstd::array rss = {0., 2.18, 10., 51., 249}; // series resistance (ohm).\nstd::array vds = { 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 }; // Diode voltage.\n\nint main()\n{\n try\n {\n std::cout << \"Lambert W diode current example.\" << std::endl;\n\n //[lambert_w_diode_example_1\n double x = 0.01;\n //std::cout << \"Lambert W (\" << x << \") = \" << lambert_w(x) << std::endl; // 0.00990147\n\n double nu = 1.0; // Assumed ideal.\n double vt = v_thermal(25); // v thermal, Shockley equation, expect about 25 mV at room temperature.\n double boltzmann_k = 1.38e-23; // joules/kelvin\n double temp = 273 + 25;\n double charge_q = 1.6e-19; // column\n vt = boltzmann_k * temp / charge_q;\n std::cout << \"V thermal \" \n << vt << std::endl; // V thermal 0.0257025 = 25 mV\n double rsat = 0.;\n double isat = 25.e-15; // 25 fA;\n std::cout << \"Isat = \" << isat << std::endl;\n\n double re = 0.3; // Estimated from slope of straight section of graph (equation 6).\n\n double v = 0.9;\n double icalc = iv(v, vt, 249., re, isat);\n\n std::cout << \"voltage = \" << v << \", current = \" << icalc << \", \" << log(icalc) << std::endl; // voltage = 0.9, current = 0.00108485, -6.82631\n //] [/lambert_w_diode_example_1]\n }\n catch (std::exception& ex)\n {\n std::cout << ex.what() << std::endl;\n }\n} // int main()\n\n/*\n Output:\n//[lambert_w_output_1\n Lambert W diode current example.\n V thermal 0.0257025\n Isat = 2.5e-14\n nu * vt / rsat = 0.000103099\n isat * rsat / (nu * vt) = 2.42486e-10\n (v + isat * rsat) / (nu * vt) = 35.016\n exp(eterm) = 1.61167e+15\n w0 = 10.5225\n voltage = 0.9, current = 0.00108485, -6.82631\n\n//] [/lambert_w_output_1]\n*/\n\n", "meta": {"hexsha": "cad03b1c6a9010c4f1b70322e5c40a877a5fd494", "size": 5554, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "3rdParty/boost/1.71.0/libs/math/example/lambert_w_diode.cpp", "max_stars_repo_name": "rajeev02101987/arangodb", "max_stars_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "3rdParty/boost/1.71.0/libs/math/example/lambert_w_diode.cpp", "max_issues_repo_name": "rajeev02101987/arangodb", "max_issues_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "3rdParty/boost/1.71.0/libs/math/example/lambert_w_diode.cpp", "max_forks_repo_name": "rajeev02101987/arangodb", "max_forks_repo_head_hexsha": "817e6c04cb82777d266f3b444494140676da98e2", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 33.4578313253, "max_line_length": 146, "alphanum_fraction": 0.650882247, "num_tokens": 1820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.8006920068519376, "lm_q1q2_score": 0.6852731783195742}} {"text": "#include \n#include \n\n#ifndef M_PI\n#define M_PI 3.1415926535897932384626433832795\n#endif\n\n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n Matrix2f m = Matrix2f::Random();\nm = (m + m.adjoint()).eval();\nJacobiRotation J;\nJ.makeJacobi(m, 0, 1);\ncout << \"Here is the matrix m:\" << endl << m << endl;\nm.applyOnTheLeft(0, 1, J.adjoint());\nm.applyOnTheRight(0, 1, J);\ncout << \"Here is the matrix J' * m * J:\" << endl << m << endl;\n return 0;\n}\n", "meta": {"hexsha": "9c15c8e1e2dd099918408fac3cff580ec5312348", "size": 512, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_Jacobi_makeJacobi.cpp", "max_stars_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_stars_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-14T23:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-14T23:59:05.000Z", "max_issues_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_Jacobi_makeJacobi.cpp", "max_issues_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_issues_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-10-19T02:43:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-10-31T14:53:06.000Z", "max_forks_repo_path": "third_party/eigen-eigen-50812b426b7c/build_dir/doc/snippets/compile_Jacobi_makeJacobi.cpp", "max_forks_repo_name": "shishaochen/TensorFlow-0.8-Win", "max_forks_repo_head_hexsha": "63221dfc4f1a1d064308e632ba12e6a54afe1fd8", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-10-23T00:50:02.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-21T11:11:57.000Z", "avg_line_length": 20.48, "max_line_length": 62, "alphanum_fraction": 0.654296875, "num_tokens": 169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640646, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6852185865642837}} {"text": "// 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 \n#include \n#include \n#include \n\n#include \"pyinterp/eigen.hpp\"\n\nnamespace pyinterp::detail::math {\n\n/// Known radial functions.\nenum RadialBasisFunction : uint8_t {\n Cubic,\n Gaussian,\n InverseMultiquadric,\n Linear,\n Multiquadric,\n ThinPlate\n};\n\n//// A radial basis function (RBF) is a real-valued function φ whose value\n/// depends only on the distance between the input and some fixed point,\n/// either the origin, so that φ(x) = φ(║x║), or some other fixed point\n/// c, called a center, so that φ(x) = φ(║x - c║). Any function φ that\n/// satisfies the property φ(x) = φ(║x║) is a radial function.\ntemplate \nclass RBF {\n public:\n /// Pointer to the Radial function used\n using PtrRadialBasisFunction =\n Matrix (*)(const Eigen::Ref>& r, const T);\n\n /// Default constructor\n ///\n /// @param epsilon Adjustable constant for gaussian or multiquadrics\n /// functions - defaults to approximate average distance between nodes\n /// (which is a good start).\n /// @param smooth Values greater than zero increase the smoothness of the\n /// approximation. 0 is for interpolation (default), the function will always\n /// go through the nodal points in this case.\n /// @param rbf The radial basis function, based on the radius, r, given by the\n /// norm (Euclidean distance)\n RBF(const T& epsilon, const T& smooth, const RadialBasisFunction rbf)\n : epsilon_(T(1) / epsilon), smooth_(smooth) {\n switch (rbf) {\n case RadialBasisFunction::Cubic:\n function_ = &RBF::cubic;\n break;\n case RadialBasisFunction::Gaussian:\n function_ = &RBF::gaussian;\n break;\n case RadialBasisFunction::InverseMultiquadric:\n function_ = &RBF::inverse_multiquadric;\n break;\n case RadialBasisFunction::Linear:\n function_ = &RBF::linear;\n break;\n case RadialBasisFunction::Multiquadric:\n function_ = &RBF::multiquadric;\n break;\n case RadialBasisFunction::ThinPlate:\n function_ = &RBF::thin_plate;\n break;\n default:\n throw std::invalid_argument(\"Radial function unknown: \" +\n std::to_string(static_cast(rbf)));\n }\n }\n\n /// Calculates the interpolated values\n ///\n /// @param xk Coordinates of the nodes\n /// @param yk Values of the nodes\n /// @param xi Coordinates to evaluate the interpolant at.\n /// @return interpolated values for each coordinates provided.\n [[nodiscard]] auto interpolate(const Eigen::Ref>& xk,\n const Eigen::Ref>& yk,\n const Eigen::Ref>& xi) const\n -> Vector {\n // Matrix of distances between the coordinates provided.\n const auto r = RBF::distance_matrix(xk, xk);\n\n // Default epsilon to approximate average distance between nodes\n const auto epsilon =\n std::isnan(epsilon_) ? 1 / RBF::average(r) : epsilon_;\n\n // TODO(fbriol)\n auto A = function_(r, epsilon);\n\n // Apply smoothing factor if needed\n if (smooth_) {\n A -= Matrix::Identity(xk.cols(), xk.cols()) * smooth_;\n }\n\n return function_(distance_matrix(xk, xi), epsilon) *\n RBF::solve_linear_system(A, yk);\n }\n\n private:\n /// Adjustable constant for gaussian or multiquadrics functions\n T epsilon_;\n\n /// Smooth factor\n T smooth_;\n\n /// Radial bassis function, based on the radius\n PtrRadialBasisFunction function_;\n\n // Calculates the distance average excluding the diagonal\n static auto average(const Eigen::Ref>& distance) -> T {\n assert(distance.cols() == distance.rows());\n auto sum = T(0);\n auto n = distance.cols();\n for (Eigen::Index ix = 0; ix < distance.rows() - 1; ++ix) {\n for (Eigen::Index jx = ix + 1; jx < distance.cols(); ++jx) {\n sum += distance(ix, jx);\n }\n }\n return static_cast(sum / (n * (n - 1) * 0.5));\n };\n\n /// Returns the distance between two points in a euclidean space\n static auto euclidean_distance(const Eigen::Ref>& x,\n const Eigen::Ref>& y) -> T {\n return std::sqrt((x - y).array().pow(2).sum());\n }\n\n /// Multiquadric\n static auto multiquadric(const Eigen::Ref>& r,\n const T epsilon) -> Matrix {\n return ((epsilon * r).array().pow(2) + 1).sqrt();\n }\n\n /// Inverse multiquadric\n static auto inverse_multiquadric(const Eigen::Ref>& r,\n const T epsilon) -> Matrix {\n return 1.0 / multiquadric(r, epsilon).array();\n }\n\n /// Gauss\n static auto gaussian(const Eigen::Ref>& r, const T epsilon)\n -> Matrix {\n return (-(epsilon * r).array().pow(2)).exp();\n }\n\n /// Linear spline\n static auto linear(const Eigen::Ref>& r, const T /*epsilon*/)\n -> Matrix {\n return r;\n }\n\n /// Cubic spline\n static auto cubic(const Eigen::Ref>& r, const T /*epsilon*/)\n -> Matrix {\n return r.array().pow(3);\n }\n\n /// Thin plate spline\n static auto thin_plate(const Eigen::Ref>& r,\n const T /*epsilon*/) -> Matrix {\n return (r.array() == 0).select(0, r.array().pow(2) * r.array().log());\n }\n\n /// Calculation of distances between the coordinates provided.\n static auto distance_matrix(const Eigen::Ref>& xk,\n const Eigen::Ref>& xi)\n -> Matrix {\n assert(xk.rows() == xi.rows());\n\n auto result = Matrix(xi.cols(), xk.cols());\n\n for (Eigen::Index i0 = 0; i0 < xi.cols(); ++i0) {\n for (Eigen::Index i1 = 0; i1 < xk.cols(); ++i1) {\n result(i0, i1) = euclidean_distance(xi.col(i0), xk.col(i1));\n }\n }\n return result;\n }\n\n /// Resolution of the linear system\n static auto solve_linear_system(const Matrix& A, const Vector& di)\n -> Vector {\n Eigen::FullPivLU> lu(A);\n return lu.solve(di);\n }\n};\n\n} // namespace pyinterp::detail::math\n", "meta": {"hexsha": "a8e5f33db79852e3f84847a94958f182365c78cf", "size": 6329, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/radial_basis_functions.hpp", "max_stars_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_stars_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/radial_basis_functions.hpp", "max_issues_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_issues_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pyinterp/core/include/pyinterp/detail/math/radial_basis_functions.hpp", "max_forks_repo_name": "readthedocs-assistant/pangeo-pyinterp", "max_forks_repo_head_hexsha": "e9dc18445dce36638d5a90f64c8e2f1b53164f90", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.792746114, "max_line_length": 80, "alphanum_fraction": 0.6179491231, "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9219218412907381, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6851428136441765}} {"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Schüttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearloadvector.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace ElementMatrixComputation {\n\nnamespace {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Vector4d computeLoadVector(\n const Eigen::MatrixXd &vertices,\n std::function f) {\n // Number of nodes of the element: triangles = 3, rectangles = 4\n const int num_nodes = vertices.cols();\n // Vector for returning element vector\n Eigen::Vector4d elem_vec = Eigen::Vector4d::Zero();\n\n //====================\n\n // first two midpoints of edges of cell\n Eigen::Vector2d m1 = 0.5*(vertices.col(0) + vertices.col(1));\n Eigen::Vector2d m2 = 0.5*(vertices.col(1) + vertices.col(2));\n\n // == TRIANGLE ==\n if (num_nodes == 3) {\n // Third midpoint of edge\n Eigen::Vector2d m3 = 0.5*(vertices.col(2) + vertices.col(0));\n \n // Area\n double K = 0.5*( (vertices(0,1) - vertices(0,0)) * (vertices(1,2) - vertices(1,0)) -\n (vertices(1,1) - vertices(1,0)) * (vertices(0,2) - vertices(0,0)));\n K /= num_nodes;\n\n elem_vec(0) = f(m1) + f(m3);\n elem_vec(1) = f(m1) + f(m2);\n elem_vec(2) = f(m2) + f(m3);\n elem_vec *= K/2.0;\n\n // == QUADRILITERA ==\n } else if (num_nodes == 4) {\n // Third and forth midpoints of edge\n Eigen::Vector2d m3 = 0.5*(vertices.col(2) + vertices.col(3));\n Eigen::Vector2d m4 = 0.5*(vertices.col(3) + vertices.col(0));\n \n // Area\n double K = ( vertices(0,1) - vertices(0,0) )*\n ( vertices(1,3) - vertices(1,0) );\n K /= num_nodes;\n\n elem_vec(0) = f(m1) + f(m4);\n elem_vec(1) = f(m1) + f(m2);\n elem_vec(2) = f(m2) + f(m3);\n elem_vec(3) = f(m3) + f(m4);\n elem_vec *= K/2.0;\n }\n\n //====================\n\n return elem_vec;\n}\n/* SAM_LISTING_END_1 */\n\n} // namespace\n\nEigen::Vector4d MyLinearLoadVector::Eval(const lf::mesh::Entity &cell) {\n // Topological type of the cell\n const lf::base::RefEl ref_el{cell.RefEl()};\n const lf::base::size_type num_nodes{ref_el.NumNodes()};\n\n // Obtain the vertex coordinates of the cell, which completely\n // describe its shape.\n const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n\n // Matrix storing corner coordinates in its columns\n auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n\n return computeLoadVector(vertices, f_);\n}\n\n} // namespace ElementMatrixComputation\n", "meta": {"hexsha": "af3c184129c271229c6bbce6b0f8ce9e35094cfa", "size": 2614, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearloadvector.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8085106383, "max_line_length": 88, "alphanum_fraction": 0.6205049732, "num_tokens": 815, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6850618796788954}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n Matrix4f A = MatrixXf::Random(4,4);\ncout << \"Here is a random 4x4 matrix:\" << endl << A << endl;\nHessenbergDecomposition hessOfA(A);\nMatrixXf H = hessOfA.matrixH();\ncout << \"The Hessenberg matrix H is:\" << endl << H << endl;\nMatrixXf Q = hessOfA.matrixQ();\ncout << \"The orthogonal matrix Q is:\" << endl << Q << endl;\ncout << \"Q H Q^T is:\" << endl << Q * H * Q.transpose() << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "7bd58627a52776c821df0fa0c745b8771aab348b", "size": 542, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_HessenbergDecomposition_matrixH.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_HessenbergDecomposition_matrixH.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_HessenbergDecomposition_matrixH.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8095238095, "max_line_length": 63, "alphanum_fraction": 0.6420664207, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7853085758631159, "lm_q1q2_score": 0.6850618744664725}} {"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n#include \"premiers.h\"\n\n#include \n#include \n\ntypedef unsigned long long nombre;\ntypedef std::vector vecteur;\n\nENREGISTRER_PROBLEME(108, \"Diophantine reciprocals I\") {\n // In the following equation x, y, and n are positive integers.\n //\n // 1/x + 1/y = 1/n\n //\n // For n = 4 there are exactly three distinct solutions:\n //\n // 1/5 + 1/20 = 1/4\n // 1/6 + 1/12 = 1/4\n // 1/8 + 1/8 = 1/4\n //\n // What is the least value of n for which the number of distinct solutions exceeds one-thousand?\n //\n // NOTE: This problem is an easier version of Problem 110; it is strongly advised that you solve this one first.\n vecteur premiers;\n premiers::crible23(1000000, std::back_inserter(premiers));\n\n nombre resultat = 0;\n for (nombre n = 2;; ++n) {\n std::map decomposition;\n arithmetique::decomposition(n, premiers, decomposition);\n nombre solutions = 1;\n for (const auto &d: decomposition) {\n solutions *= (2 * d.second + 1);\n }\n solutions = (solutions + 1) / 2;\n if (solutions > 1000) {\n resultat = n;\n break;\n }\n }\n\n return std::to_string(resultat);\n}\n", "meta": {"hexsha": "a022a59ea7047d11cbe658a273c55b85f0ad3161", "size": 1359, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme108.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme1xx/probleme108.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme1xx/probleme108.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.2, "max_line_length": 116, "alphanum_fraction": 0.5791022811, "num_tokens": 379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6849885785132712}} {"text": "#include \n#include \n#include \n#include \n\nusing namespace std;\n\nusing column_vector = dlib::matrix;\n\ndouble f(const column_vector& col) {\n assert(col.nr() == 2);\n\n const double x1 = col(0);\n const double x2 = col(1);\n\n const double ret = -(x1 - 2) * (x1 - 2) - (x2 - 3) * (x2 - 3) + 5;\n\n printf(\"func called at x1 = %f, x2 = %f, f = %f\\n\", x1, x2, ret);\n\n return ret;\n}\n\nint main() {\n column_vector x = {0, 0};\n\n double ret = dlib::find_max_bobyqa(\n f, x, 5, dlib::uniform_matrix(2, 1, -100.0),\n dlib::uniform_matrix(2, 1, 100.0), 10, 1.E-6, 100);\n\n cout << x << endl;\n cout << ret << endl;\n\n return 0;\n}", "meta": {"hexsha": "23132a05dfb95db1cd75f527921b8155f0228b48", "size": 734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dlib-test/main.cpp", "max_stars_repo_name": "xwang233/bot-build", "max_stars_repo_head_hexsha": "7bd87a4da2da2302f13e7b0864e41547f75569f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-02-16T06:28:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-16T06:28:30.000Z", "max_issues_repo_path": "dlib-test/main.cpp", "max_issues_repo_name": "society765/bot-build", "max_issues_repo_head_hexsha": "7bd87a4da2da2302f13e7b0864e41547f75569f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dlib-test/main.cpp", "max_forks_repo_name": "society765/bot-build", "max_forks_repo_head_hexsha": "7bd87a4da2da2302f13e7b0864e41547f75569f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.5882352941, "max_line_length": 70, "alphanum_fraction": 0.5667574932, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6849885752769691}} {"text": "#include \"BoostOdeint.hpp\"\n\n#include \n\n#include \n#include \n\nusing namespace sodes::odeint;\nusing namespace Eigen;\n\n// System to be solved\nArrayXd lorenz(const Ref x, Ref dxdt, const double &t)\n{\n double sigma = 10.0;\n double R = 28.0;\n double b = 8.0 / 3.0;\n\n dxdt[0] = sigma * (x[1] - x[0]);\n dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n dxdt[2] = -b * x[2] + x[0] * x[1];\n\n return dxdt;\n}\n\nint main (){\n // Defining the state vector with initial conditions\n int num_of_states = 3;\n ArrayXd X(num_of_states);\n X << 0., 1., 0.1;\n\n // Set time range and increment\n auto t_init = 0.0;\n auto t_final = 10.0;\n auto t_span = std::make_tuple(t_init, t_final);\n auto dt = 0.01;\n\n // Containers to store solution\n std::vector x_sol;\n std::vector times;\n std::tie(times, x_sol) = solve_ivp_const(lorenz, t_span, dt, X, \"runge_kutta_cash_karp54\");\n\n // Displaying result on terminal\n auto steps = times.size();\n for (size_t i = 0; i < steps; i++)\n {\n std::cout << times[i] << '\\t' << x_sol[i][0] << '\\t' << x_sol[i][1] << '\\t' << x_sol[i][2] << '\\n';\n }\n}\n", "meta": {"hexsha": "3ed229b7e4090b830ca69cf3574abea98504883f", "size": 1189, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/boost/call_sodes_rk4.cpp", "max_stars_repo_name": "volpatto/pysodes", "max_stars_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T08:28:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T07:29:11.000Z", "max_issues_repo_path": "examples/boost/call_sodes_rk4.cpp", "max_issues_repo_name": "volpatto/pysodes", "max_issues_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/boost/call_sodes_rk4.cpp", "max_forks_repo_name": "volpatto/pysodes", "max_forks_repo_head_hexsha": "48add3ce16ee48e2f3af7a928935f9b22d74d908", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-09T07:29:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-09T07:29:15.000Z", "avg_line_length": 24.2653061224, "max_line_length": 107, "alphanum_fraction": 0.5777964676, "num_tokens": 411, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6849885744520516}} {"text": "#pragma once\n\n#include \n#include \n#include \n\n#include \n\nnamespace common_robotics_utilities\n{\nnamespace gaussian_distributions\n{\n/// See https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf\n/// for details on the implementations here.\n\n/// Evaluate the value of the CDF of the gaussian distribution specified by\n/// @param mean and @param std_dev at @param val.\ninline double EvaluateGaussianCDF(\n const double mean, const double std_dev, const double val)\n{\n return 0.5 * (1.0 + std::erf(((val - mean) / std_dev) / std::sqrt(2.0)));\n}\n\n/// Evaluate the value of the PDF of the gaussian distribution specified by\n/// @param mean and @param std_dev at @param val.\ninline double EvaluateGaussianPDF(\n const double mean, const double std_dev, const double val)\n{\n const double exponent = ((val - mean) * (val - mean))\n / (2.0 * std_dev * std_dev);\n const double fraction = 1.0 / (std_dev * std::sqrt(2.0 * M_PI));\n const double pdf = fraction * std::exp(-exponent);\n return pdf;\n}\n\n/// Evaluate the value of the CDF of the truncated gaussian distribution\n/// specified by @param mean and @param std_dev and bounds @param lower_bound\n/// and @param upper_bound at @param val.\ninline double EvaluateTruncatedGaussianCDF(\n const double mean, const double lower_bound, const double upper_bound,\n const double std_dev, const double val)\n{\n if (lower_bound > upper_bound)\n {\n throw std::invalid_argument(\"lower_bound > upper_bound\");\n }\n if (val <= lower_bound)\n {\n return 0.0;\n }\n else if (val >= upper_bound)\n {\n return 1.0;\n }\n else\n {\n const double cdf_lower_bound\n = EvaluateGaussianCDF(mean, std_dev, lower_bound);\n const double numerator\n = EvaluateGaussianCDF(mean, std_dev, val) - cdf_lower_bound;\n const double denominator\n = EvaluateGaussianCDF(mean, std_dev, upper_bound) - cdf_lower_bound;\n return numerator / denominator;\n }\n}\n\n/// Evaluate the value of the PDF of the truncated gaussian distribution\n/// specified by @param mean and @param std_dev and bounds @param lower_bound\n/// and @param upper_bound at @param val.\ninline double EvaluateTruncatedGaussianPDF(\n const double mean, const double lower_bound, const double upper_bound,\n const double std_dev, const double val)\n{\n if (lower_bound > upper_bound)\n {\n throw std::invalid_argument(\"lower_bound > upper_bound\");\n }\n if (val <= lower_bound)\n {\n return 0.0;\n }\n else if (val >= upper_bound)\n {\n return 0.0;\n }\n else\n {\n const double cdf_upper = EvaluateGaussianCDF(mean, std_dev, upper_bound);\n const double cdf_lower = EvaluateGaussianCDF(mean, std_dev, lower_bound);\n const double probability_enclosed = cdf_upper - cdf_lower;\n const double gaussian_pdf = EvaluateGaussianPDF(mean, std_dev, val);\n const double pdf = gaussian_pdf / probability_enclosed;\n return pdf;\n }\n}\n\n/// Integrate the probability contained between @param lower_limit and @param\n/// upper_limit for the gaussian distribution specified by @param mean and\n/// @param std_dev.\ninline double IntegrateGaussian(\n const double mean, const double std_dev, const double lower_limit,\n const double upper_limit)\n{\n if (lower_limit > upper_limit)\n {\n throw std::invalid_argument(\"lower_limit > upper_limit\");\n }\n const double upper_limit_cdf\n = EvaluateGaussianCDF(mean, std_dev, upper_limit);\n const double lower_limit_cdf\n = EvaluateGaussianCDF(mean, std_dev, lower_limit);\n const double probability = upper_limit_cdf - lower_limit_cdf;\n return probability;\n}\n\n/// Integrate the probability contained between @param lower_limit and @param\n/// upper_limit for the truncated gaussian distribution specified by @param mean\n/// and @param std_dev and bounds @param lower_bound and @param upper_bound.\ninline double IntegrateTruncatedGaussian(\n const double mean, const double lower_bound, const double upper_bound,\n const double std_dev, const double lower_limit, const double upper_limit)\n{\n if (lower_bound > upper_bound)\n {\n throw std::invalid_argument(\"lower_bound > upper_bound\");\n }\n if (lower_limit > upper_limit)\n {\n throw std::invalid_argument(\"lower_limit > upper_limit\");\n }\n const double lower_limit_cdf\n = EvaluateTruncatedGaussianCDF(\n mean, lower_bound, upper_bound, std_dev, lower_limit);\n const double upper_limit_cdf\n = EvaluateTruncatedGaussianCDF(\n mean, lower_bound, upper_bound, std_dev, upper_limit);\n const double probability = upper_limit_cdf - lower_limit_cdf;\n return probability;\n}\n\n/// Note that comments come from (and refer to) parts of the original R plugin\n/// that this implementation was derived from.\nclass TruncatedGaussianDistribution\n{\nprivate:\n\n double mean_ = 0.0;\n double stddev_ = 0.0;\n double std_lower_bound_ = 0.0;\n double std_upper_bound_ = 0.0;\n\n enum class DrawCases {TYPE_1, TYPE_2, TYPE_3, TYPE_4, NONE};\n DrawCases case_ = NONE;\n std::uniform_real_distribution uniform_unit_dist_;\n std::uniform_real_distribution uniform_range_dist_;\n std::exponential_distribution exponential_dist_;\n std::normal_distribution normal_dist_;\n\n bool CheckSimple(const double lower_bound, const double upper_bound) const\n {\n // Init Values Used in Inequality of Interest\n const double val1\n = (2 * std::sqrt(std::exp(1)))\n / (lower_bound + std::sqrt(std::pow(lower_bound, 2) + 4));\n const double val2\n = std::exp((std::pow(lower_bound, 2)\n - lower_bound * std::sqrt(std::pow(lower_bound, 2) + 4))\n / (4));\n if (upper_bound > lower_bound + val1 * val2)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n\n // Naive Accept-Reject algorithm\n template\n double NaiveAcceptReject(\n const double lower_bound, const double upper_bound, Generator& prng)\n {\n while (true)\n {\n // In the R plugin, this was a call to Rf_rnorm(0.0, 1.0), in pure C++ it\n // is a call to std::normal_distribution.\n const double draw = normal_dist_(prng);\n if ((draw <= upper_bound) && (draw >= lower_bound))\n {\n return draw;\n }\n }\n }\n\n // Accept-Reject Algorithm\n template\n double SimpleAcceptReject(const double lower_bound, Generator& prng)\n {\n // Init Values\n const double alpha\n = (lower_bound + std::sqrt(std::pow(lower_bound, 2) + 4.0)) / (2.0);\n while (true)\n {\n // In the R plugin, this was a call to Rf_rexp(1.0), in pure C++ it is a\n // call to std::exponential_distribution.\n const double e = exponential_dist_(prng);\n const double z = lower_bound + e / alpha;\n const double rho = std::exp(-std::pow(alpha - z, 2) / 2);\n // In the R plugin, this was a call to Rf_rnorm(0.0, 1.0), in pure C++ it\n // is a call to std::normal_distribution.\n const double u = uniform_unit_dist_(prng);\n if (u <= rho)\n {\n return z;\n }\n }\n }\n\n // Accept-Reject Algorithm\n template\n double ComplexAcceptReject(\n const double lower_bound, const double upper_bound, Generator& prng)\n {\n while (true)\n {\n // In the R plugin, this was a call to Rf_rnorm(lower_bound, upper_bound),\n // in pure C++ it is a call to std::normal_distribution.\n const double z = uniform_range_dist_(prng);\n double rho = 0.0;\n if (0 < lower_bound)\n {\n rho = std::exp((std::pow(lower_bound, 2) - std::pow(z, 2)) / 2);\n }\n else if (upper_bound < 0)\n {\n rho = std::exp((std::pow(upper_bound, 2) - std::pow(z, 2)) / 2);\n }\n else if (0 < upper_bound && lower_bound < 0)\n {\n rho = std::exp(-std::pow(z, 2) / 2);\n }\n // In the R plugin, this was a call to Rf_rnorm(0.0, 1.0), in pure C++ it\n // is a call to std::normal_distribution.\n const double u = uniform_unit_dist_(prng);\n if (u <= rho)\n {\n return z;\n }\n }\n }\n\n template\n double Sample(Generator& prng)\n {\n if (case_ == DrawCases::TYPE_1)\n {\n const double draw\n = NaiveAcceptReject(std_lower_bound_, std_upper_bound_, prng);\n return mean_ + stddev_ * draw;\n }\n else if (case_ == DrawCases::TYPE_2)\n {\n const double draw = SimpleAcceptReject(std_lower_bound_, prng);\n return mean_ + stddev_ * draw;\n }\n else if (case_ == DrawCases::TYPE_3)\n {\n while (true)\n {\n const double draw = SimpleAcceptReject(std_lower_bound_, prng);\n if (draw <= std_upper_bound_)\n {\n return mean_ + stddev_ * draw;\n }\n }\n }\n else if (case_ == DrawCases::TYPE_4)\n {\n const double draw\n = ComplexAcceptReject(std_lower_bound_, std_upper_bound_, prng);\n return mean_ + stddev_ * draw;\n }\n else\n {\n if (case_ == DrawCases::NONE)\n {\n return mean_;\n }\n else\n {\n throw std::runtime_error(\"Invalid case\");\n }\n }\n }\n\npublic:\n\n TruncatedGaussianDistribution(\n const double mean, const double stddev, const double lower_bound,\n const double upper_bound)\n : uniform_unit_dist_(0.0, 1.0),\n uniform_range_dist_(lower_bound, upper_bound),\n exponential_dist_(1.0), normal_dist_(0.0, 1.0)\n {\n // Set operating parameters\n mean_ = mean;\n stddev_ = stddev;\n if (std::abs(stddev_) == 0.0)\n {\n case_ = DrawCases::NONE;\n }\n else\n {\n // Standardize the lower and upper bounds\n std_lower_bound_ = (lower_bound - mean_) / stddev_;\n std_upper_bound_ = (upper_bound - mean_) / stddev_;\n // Set the operating case - i.e. which sampling method we will use\n case_ = DrawCases::NONE;\n if (0.0 <= std_upper_bound_ && 0.0 >= std_lower_bound_)\n {\n case_ = DrawCases::TYPE_1;\n }\n if (0.0 < std_lower_bound_\n && std_upper_bound_ == std::numeric_limits::infinity())\n {\n case_ = DrawCases::TYPE_2;\n }\n if (0.0 > std_upper_bound_\n && std_lower_bound_ == -std::numeric_limits::infinity())\n {\n std_lower_bound_ = -1 * std_upper_bound_;\n std_upper_bound_ = std::numeric_limits::infinity();\n stddev_ = -1 * stddev_;\n case_ = DrawCases::TYPE_2;\n }\n if ((0.0 > std_upper_bound_ || 0.0 < std_lower_bound_)\n && !(std_upper_bound_ == std::numeric_limits::infinity()\n || std_lower_bound_ == -std::numeric_limits::infinity()))\n {\n if (CheckSimple(std_lower_bound_, std_upper_bound_))\n {\n case_ = DrawCases::TYPE_3;\n }\n else\n {\n case_ = DrawCases::TYPE_4;\n }\n }\n if ((case_ != DrawCases::TYPE_1) && (case_ != DrawCases::TYPE_2)\n && (case_ != DrawCases::TYPE_3) && (case_ != DrawCases::TYPE_4))\n {\n throw std::invalid_argument(\"case cannot be NONE with stddev == 0\");\n }\n }\n }\n\n template\n double operator()(Generator& prng)\n {\n return Sample(prng);\n }\n};\n\n/// Simple multivariate gaussian distribution.\nclass MultivariteGaussianDistribution\n{\nprivate:\n const Eigen::VectorXd mean_;\n const Eigen::MatrixXd norm_transform_;\n\n std::normal_distribution unit_gaussian_dist_;\n\n template\n Eigen::VectorXd Sample(Generator& prng)\n {\n Eigen::VectorXd draw;\n draw.resize(mean_.rows());\n for (ssize_t idx = 0; idx < draw.rows(); idx++)\n {\n draw(idx) = unit_gaussian_dist_(prng);\n }\n return norm_transform_ * draw + mean_;\n }\n\n static Eigen::MatrixXd CalculateNormTransform(\n const Eigen::MatrixXd& covariance)\n {\n Eigen::MatrixXd norm_transform;\n Eigen::LLT chol_solver(covariance);\n if (chol_solver.info() == Eigen::Success)\n {\n // Use cholesky solver\n norm_transform = chol_solver.matrixL();\n }\n else\n {\n // Use eigen solver\n Eigen::SelfAdjointEigenSolver eigen_solver(covariance);\n norm_transform\n = eigen_solver.eigenvectors()\n * eigen_solver.eigenvalues().cwiseMax(0.0).cwiseSqrt().asDiagonal();\n }\n return norm_transform;\n }\n\npublic:\n MultivariteGaussianDistribution(\n const Eigen::VectorXd& mean, const Eigen::MatrixXd& covariance)\n : mean_(mean), norm_transform_(CalculateNormTransform(covariance)),\n unit_gaussian_dist_(0.0, 1.0)\n {\n if (mean_.rows() != covariance.rows() || mean_.cols() != covariance.cols())\n {\n throw std::invalid_argument(\"mean and covariance are different sizes\");\n }\n const auto nan_check = [] (const double& val) { return std::isnan(val); };\n if ((norm_transform_.unaryExpr(nan_check)).any())\n {\n throw std::runtime_error(\n \"NaN Found in norm_transform in MultivariateGaussianDistribution\");\n }\n const auto inf_check = [] (const double& val) { return std::isinf(val); };\n if ((norm_transform_.unaryExpr(inf_check)).any())\n {\n throw std::runtime_error(\n \"Inf Found in norm_transform in MultivariateGaussianDistribution\");\n }\n }\n\n template\n Eigen::VectorXd operator()(Generator& prng)\n {\n return Sample(prng);\n }\n};\n} // namespace gaussian_distributions\n} // namespace common_robotics_utilities\n", "meta": {"hexsha": "438f308b88a0d5c8aacdfa0a8909c45566561073", "size": 13464, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common_robotics_utilities/gaussian_distributions.hpp", "max_stars_repo_name": "hidmic/common_robotics_utilities", "max_stars_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-10-15T19:04:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T01:35:16.000Z", "max_issues_repo_path": "include/common_robotics_utilities/gaussian_distributions.hpp", "max_issues_repo_name": "hidmic/common_robotics_utilities", "max_issues_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 13.0, "max_issues_repo_issues_event_min_datetime": "2018-10-18T19:14:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-21T15:08:21.000Z", "max_forks_repo_path": "include/common_robotics_utilities/gaussian_distributions.hpp", "max_forks_repo_name": "hidmic/common_robotics_utilities", "max_forks_repo_head_hexsha": "b3e10e0e0bfa9a968efdaa57e0a4422d9327bb9c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-10-17T21:12:01.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-18T03:53:47.000Z", "avg_line_length": 30.6697038724, "max_line_length": 80, "alphanum_fraction": 0.6530005942, "num_tokens": 3453, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312221360624, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6849435986761924}} {"text": "#include \n\nusing namespace std;\n\n#include \n#include \n\nusing namespace Eigen;\n\nint main(int argc, char **argv){\n\n Matrix originMat = Matrix::Random(10, 10);\n cout << \"original matrix: \\n\" << originMat << endl;\n\n Matrix eyeMat = Matrix::Identity(3,3);\n cout << \"3x3 identity matrix: \\n\" << eyeMat << endl;\n\n originMat.block<3, 3>(0, 0) = eyeMat;\n cout << \"original matrix with 3x3 identity block: \\n\" << originMat << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "3550847577c7cd49c0c854faf5aaf0b163b9702e", "size": 547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch3/exercise/ex_5.cpp", "max_stars_repo_name": "carmelocs/slambook2", "max_stars_repo_head_hexsha": "2b1ca4fc4bdc6a4f673e1201d88eb15431882a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch3/exercise/ex_5.cpp", "max_issues_repo_name": "carmelocs/slambook2", "max_issues_repo_head_hexsha": "2b1ca4fc4bdc6a4f673e1201d88eb15431882a45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch3/exercise/ex_5.cpp", "max_forks_repo_name": "carmelocs/slambook2", "max_forks_repo_head_hexsha": "2b1ca4fc4bdc6a4f673e1201d88eb15431882a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7826086957, "max_line_length": 79, "alphanum_fraction": 0.6288848263, "num_tokens": 172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122163480666, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6849435798834428}} {"text": "/*!\n * @file basis_q1.hpp\n * @brief Contains implementation of \\f$Q_1\\f$-basis functions for a given quadrilateral.\n * @author Konrad Simon\n * @date August 2019\n */\n\n#ifndef INCLUDE_BASIS_Q1_HPP_\n#define INCLUDE_BASIS_Q1_HPP_\n\n// Deal.ii\n#include \n\n#include \n\n#include \n#include \n#include \n\n// STL\n#include \n#include \n\n// My Headers\n#include \"coefficients.h\"\n\nnamespace Coefficients\n{\nusing namespace dealii;\n\n/*!\n * @class BasisQ1\n * @brief Class implements scalar \\f$Q_1\\f$-basis functions for a given quadrilateral.\n */\ntemplate \nclass BasisQ1 : public Function\n{\npublic:\n\tBasisQ1();\n\n\tvoid set_index (unsigned int index);\n\n\tvoid set_coeff(const typename Triangulation::active_cell_iterator &cell);\n\n\tvirtual double value(const Point &p,\n\t\t\t\t\t\tconst unsigned int component = 0) const override;\n\tvirtual void value_list(const std::vector> &points,\n\t\t\t\t\t\t\t\tstd::vector &values,\n\t\t\t\t\t\t\t\tconst unsigned int component = 0) const override;\n\nprivate:\n\t/*!\n\t * Index of current basis function to be evaluated.\n\t */\n\tunsigned int \t\tindex_basis;\n\n\t/*!\n\t * Matrix columns hold coefficients of basis functions.\n\t */\n\tFullMatrix\tcoeff_matrix;\n\tbool is_set_coeff_matrix;\n};\n\n\n/*!\n * Constructor.\n * @param cell\n */\ntemplate\nBasisQ1::BasisQ1 ()\n:\nFunction(),\nindex_basis(0),\ncoeff_matrix(FullMatrix(std::pow(2,dim),std::pow(2,dim))),\nis_set_coeff_matrix(false)\n{\n}\n\n\n\n/*!\n * Set the coefficients. Template specialization \\f$dim=2\\f$.\n * @param cell\n *\n * Build up coefficient matrix \\f$A=(a_{ij})\\f$ for basis polynomial\n * \\f$\\varphi_i(x,y)=a_i^0 + a_i^1 x + a_i^2 y + a_i^3 xy \\f$. The \\f$i\\f$-th column\n * of the matrix hence contains the coefficients for the \\f$i\\f$-th basis associated\n * to the \\f$i\\f$-th vertex.\n */\ntemplate<>\nvoid\nBasisQ1<2>::set_coeff (const typename Triangulation<2>::active_cell_iterator &cell)\n\n{\n\tFullMatrix\tpoint_matrix(4,4);\n\n\tfor (unsigned int i=0; i<4; ++i)\n\t{\n\t\tconst Point<2>& p = cell->vertex(i);\n\n\t\tpoint_matrix(i,0) = 1;\n\t\tpoint_matrix(i,1) = p(0);\n\t\tpoint_matrix(i,2) = p(1);\n\t\tpoint_matrix(i,3) = p(0)*p(1);\n\t}\n\n\t// Columns of coeff_matrix are the coefficients of the polynomial\n\tcoeff_matrix.invert (point_matrix);\n\n\tis_set_coeff_matrix = true;\n}\n\n\n/*!\n * Set the coefficients. Template specialization \\f$dim=3\\f$.\n * @param cell\n *\n * Build up coefficient matrix \\f$A=(a_{ij})\\f$ for basis polynomial\n * \\f$\\varphi_i(x,y)=a_i^0 + a_i^1 x + a_i^2 y + a_i^3 xy \\f$. The \\f$i\\f$-th column\n * of the matrix hence contains the coefficients for the \\f$i\\f$-th basis associated\n * to the \\f$i\\f$-th vertex.\n */\ntemplate<>\nvoid\nBasisQ1<3>::set_coeff (const typename Triangulation<3>::active_cell_iterator &cell)\n{\n\tFullMatrix\tpoint_matrix(8,8);\n\n\tfor (unsigned int i=0; i<8; ++i)\n\t{\n\t\tconst Point<3>& p = cell->vertex(i);\n\n\t\tpoint_matrix(i,0) = 1;\n\t\tpoint_matrix(i,1) = p(0);\n\t\tpoint_matrix(i,2) = p(1);\n\t\tpoint_matrix(i,3) = p(2);\n\t\tpoint_matrix(i,4) = p(0)*p(1);\n\t\tpoint_matrix(i,5) = p(1)*p(2);\n\t\tpoint_matrix(i,6) = p(0)*p(2);\n\t\tpoint_matrix(i,7) = p(0)*p(1)*p(2);\n\t}\n\n\t// Columns of coeff_matrix are the coefficients of the polynomial\n\tcoeff_matrix.invert (point_matrix);\n\n\tis_set_coeff_matrix = true;\n}\n\n\n/*!\n * Set the index of the basis function to be evaluated.\n *\n * @param index\n */\ntemplate\nvoid\nBasisQ1::set_index (unsigned int index)\n{\n\tindex_basis = index;\n}\n\n\n/*!\n * Evaluate a basis function with a preset index at one given point in 2D.\n *\n * @param p\n * @param component\n */\ntemplate<>\ndouble\nBasisQ1<2>::value (const Point<2> &p,\n\t\t\t\t\tconst unsigned int /* component */) const\n{\n\tAssert (is_set_coeff_matrix,\n\t\t\tExcMessage (\"Coefficient matrix must be set first.\"));\n\n\tdouble value = coeff_matrix(0,index_basis)\n\t\t\t\t\t+ coeff_matrix(1,index_basis)*p(0)\n\t\t\t\t\t+ coeff_matrix(2,index_basis)*p(1)\n\t\t\t\t\t+ coeff_matrix(3,index_basis)*p(0)*p(1);\n\n\treturn value;\n}\n\n\n/*!\n * Evaluate a basis function with a preset index at one given point in 3D.\n *\n * @param p\n * @param component\n */\ntemplate<>\ndouble\nBasisQ1<3>::value (const Point<3> &p,\n\t\t\t\t\tconst unsigned int /* component */) const\n{\n\tAssert (is_set_coeff_matrix,\n\t\t\tExcMessage (\"Coefficient matrix must be set first.\"));\n\n\tdouble value = coeff_matrix(0,index_basis)\n\t\t\t\t\t+ coeff_matrix(1,index_basis)*p(0)\n\t\t\t\t\t+ coeff_matrix(2,index_basis)*p(1)\n\t\t\t\t\t+ coeff_matrix(3,index_basis)*p(2)\n\t\t\t\t\t+ coeff_matrix(4,index_basis)*p(0)*p(1)\n\t\t\t\t\t+ coeff_matrix(5,index_basis)*p(1)*p(2)\n\t\t\t\t\t+ coeff_matrix(6,index_basis)*p(0)*p(2)\n\t\t\t\t\t+ coeff_matrix(7,index_basis)*p(0)*p(1)*p(2);\n\n\treturn value;\n}\n\n\n/*!\n * Evaluate a basis function with a preset index on a given set of points in 2D.\n *\n * @param points\n * @param values\n */\ntemplate<>\nvoid\nBasisQ1<2>::value_list(const std::vector> &points,\n\t\t\t\t\t\t\t\tstd::vector &values,\n\t\t\t\t\t\t\t\tconst unsigned int /*component = 0*/) const\n{\n\tAssert (points.size() == values.size(),\n\t\t\tExcDimensionMismatch (points.size(), values.size()) );\n\tAssert (is_set_coeff_matrix,\n\t\t\tExcMessage (\"Coefficient matrix must be set first.\"));\n\n\tfor ( unsigned int p=0; p\nvoid\nBasisQ1<3>::value_list(const std::vector> &points,\n\t\t\t\t\t\t\t\tstd::vector &values,\n\t\t\t\t\t\t\t\tconst unsigned int /*component = 0*/) const\n{\n\tAssert (points.size() == values.size(),\n\t\t\tExcDimensionMismatch (points.size(), values.size()) );\n\tAssert (is_set_coeff_matrix,\n\t\t\tExcMessage (\"Coefficient matrix must be set first.\"));\n\n\tfor ( unsigned int p=0; p\n#include \n#include \n#include \n#include \n\ntypedef Eigen::VectorXd Vector;\n\n//----------------solveBegin----------------\n//! Solve the FEM system.\n//!\n//! @param[out] u will at the end contain the FEM solution.\n//! @param[in] quadraticDofs containing mesh data\n//! @param[in] f the RHS f (as in the exercise)\n//! return number of degrees of freedom (without the boundary dofs)\nint solveFiniteElement(Vector & u,\n const QDofs &quadraticDofs,\n const std::function &f) {\n\t// get quadratic dofs\n\tEigen::MatrixXi qdof;\n\tint N = quadraticDofs.get_dofs(qdof);\n\n\t// get mesh vertices\n\tconst Eigen::MatrixXd &vertices = quadraticDofs.get_vertices();\n\n\tSparseMatrix A;\n\t// (write your solution here)\n\tassembleStiffnessMatrix(A, vertices, qdof, N);\n\n\tVector F;\n\t// (write your solution here)\n\tassembleLoadVector(F, vertices, qdof, N, f);\n\n\tu.resize(N);\n\tu.setZero();\n\tEigen::VectorXi interiorDofs;\n\n\tauto zerobc = [](double x, double y) {\n\t\tstd::ignore = x;\n\t\tstd::ignore = y;\n\t\treturn 0;\n\t};\n\t// set homogeneous Dirichlet Boundary conditions\n\tsetDirichletBoundary(u, interiorDofs, quadraticDofs, zerobc);\n\tF -= A * u;\n\n\tSparseMatrix AInterior;\n\tigl::slice(A, interiorDofs, interiorDofs, AInterior);\n\tEigen::SimplicialLDLT solver;\n\n\tVector FInterior;\n\tigl::slice(F, interiorDofs, FInterior);\n\n\t//initialize solver for AInterior\n\t// (write your solution here)\n\tsolver.compute(AInterior);\n\n\tif (solver.info() != Eigen::Success) {\n\t\tthrow std::runtime_error(\"Could not decompose the matrix\");\n\t}\n\n\t//solve interior system\n\t// (write your solution here)\n\tVector uInterior = solver.solve(FInterior);\n\tigl::slice_into(uInterior, interiorDofs, u);\n\n\treturn interiorDofs.size();\n}\n//----------------solveEnd----------------\n", "meta": {"hexsha": "c9aefbd9cc800ec0d7c33a742f3b5bdc655407f1", "size": 2013, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/fem_solve.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series3/2d-poissonqFEM/fem_solve.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series3/2d-poissonqFEM/fem_solve.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.84, "max_line_length": 72, "alphanum_fraction": 0.6810730253, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.8175744739711883, "lm_q1q2_score": 0.6848167141661192}} {"text": "#include \"reverse.hpp\"\n#include \"forward.hpp\"\n#include \n#include \n#include \n\nnamespace autodiff {\n\n/**\n * Set the value and derivative of the specified function at the\n * specified input. The functor must define the method\n * `dual operator()(const dual& x) const;`\n *\n * @tparam F type of function\n * @param[in] f function\n * @param[in] x input\n * @param[out] y function applied to input\n * @param[out] dy_dx derivative of y w.r.t. x\n */\ntemplate \nvoid derivative(const F& f, double x, double& y, double& dy_dx) {\n dual xd{ x, 1 };\n auto yd = f(xd);\n y = yd.val();\n dy_dx = yd.tan();\n}\n\n\n/**\n * Set the value and gradient of the specified function at the\n * specified input. The functor must define the method\n * `adj operator()(const Eigen::Matrix& x) const;`.\n *\n * @tparam F type of function\n * @param[in] f function\n * @param[in] x input\n * @param[out] fx function applied to input\n * @param[out] grad gradient of function applied to input\n */\ntemplate \nvoid gradient(const F& f, const Eigen::VectorXd& x,\n double& fx, Eigen::RowVectorXd& grad) {\n Eigen::Matrix xa(x.size());\n for (int i = 0; i < xa.size(); ++i)\n xa(i) = x(i);\n adj y = f(xa);\n std::vector adjoints = chain(y);\n fx = y.val();\n grad.resize(x.size());\n for (int i = 0; i < x.size(); ++i)\n grad(i) = adjoints[xa(i).idx()];\n}\n\n/**\n * Set the value of the specified function at the specified value and\n * the product of the gradient of the function at the specified value\n * and the specified vector.\n *\n * @tparam F type of function\n * @param[in] f function\n * @param[in] x input\n * @param[in] v vector to multiply\n * @param[out] fx value of f(x)\n * @param[out] gradv product of gradient of f(x) and v\n */\ntemplate \nvoid vector_gradient_product(const F& f, const Eigen::VectorXd& x,\n const Eigen::VectorXd v, double& fx,\n double& gradv) {\n Eigen::Matrix, -1, 1> xd(x.size());\n for (int i = 0; i < xd.size(); ++i)\n xd(i) = { x(i), v(i) };\n dual fxd = f(xd);\n fx = fxd.val();\n gradv = fxd.tan();\n}\n\n/**\n * Set the specified Hessian matrix to the Hessian of the specified\n * function at the specified value.\n *\n * @tparam F type of function\n * @param[in] f function\n * @param[in] x input\n * @param[out] H set to Hessian of function at input\n */\ntemplate \nvoid hessian(const F& f, const Eigen::VectorXd& x, Eigen::MatrixXd& H) {\n int N = x.size();\n H.resize(N, N);\n for (int m = 0; m < N; ++m) { // m-th row of H\n Eigen::Matrix, -1, 1> xd(N);\n for (int n = 0; n < N; ++n)\n xd(n) = { x(n), m == n }; // d.x(n)/d.x(m) = 1 iff m == n\n auto y = f(xd);\n std::vector adjoints = chain(y.tan());\n for (int n = 0; n < N; ++n)\n H(m, n) = adjoints[xd(n).val().idx()]; // = bar(dot(x[m, n]))\n }\n}\n\n}\n", "meta": {"hexsha": "4aba3ac658ae01a24664aa47af7634b6839208ac", "size": 2954, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/functional.hpp", "max_stars_repo_name": "mortonjt/ad-handbook", "max_stars_repo_head_hexsha": "4a52a76c043c65836cdee6051f225605a660a493", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 119.0, "max_stars_repo_stars_event_min_datetime": "2020-01-14T23:18:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T19:57:08.000Z", "max_issues_repo_path": "cpp/functional.hpp", "max_issues_repo_name": "mortonjt/ad-handbook", "max_issues_repo_head_hexsha": "4a52a76c043c65836cdee6051f225605a660a493", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2020-01-15T11:33:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-24T20:12:19.000Z", "max_forks_repo_path": "cpp/functional.hpp", "max_forks_repo_name": "mortonjt/ad-handbook", "max_forks_repo_head_hexsha": "4a52a76c043c65836cdee6051f225605a660a493", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2020-01-16T04:04:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-13T12:42:58.000Z", "avg_line_length": 28.6796116505, "max_line_length": 72, "alphanum_fraction": 0.6032498307, "num_tokens": 902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6847831154337717}} {"text": "#include \n\n#include \"quaternion_product.h\"\n\n/*\n Assume quaternion data format is (x, y, z, w) and translational format is (x,\n y, z)\n\n Verifies against Eigen cross product implementation\n*/\n\n__attribute__((always_inline)) Eigen::Vector3f crossProduct(Eigen::Vector3f lhs,\n Eigen::Vector3f rhs) {\n\n Eigen::Vector3f result(\n lhs.coeff(1) * rhs.coeff(2) - lhs.coeff(2) * rhs.coeff(1),\n lhs.coeff(2) * rhs.coeff(0) - lhs.coeff(0) * rhs.coeff(2),\n lhs.coeff(0) * rhs.coeff(1) - lhs.coeff(1) * rhs.coeff(0));\n return result;\n}\n\n/*\n Computes the point product\n*/\n__attribute__((always_inline)) Eigen::Vector3f pointProduct(Eigen::Vector4f &q,\n Eigen::Vector3f &p) {\n Eigen::Vector3f qvec(q(0), q(1), q(2));\n\n Eigen::Vector3f uv = crossProduct(qvec, p); // qvec.cross(p);\n for (int i = 0; i < 3; i++) {\n uv(i) = uv(i) * 2;\n }\n Eigen::Vector3f qxuv = crossProduct(qvec, uv); // qvec.cross(uv);\n\n Eigen::Vector3f result;\n result = p + (q(3) * uv) + qxuv;\n\n return result;\n}\n\n/*\n Takes two quaternions and multiplies them together\n\n Verified against the SE3 product in Sophus\n*/\nSE3T quaternionProduct(SE3T &a, SE3T &b) {\n Eigen::Vector3f resultTranslation;\n Eigen::Vector4f resultQuaternion;\n\n Eigen::Vector4f aq = a.quaternion;\n Eigen::Vector4f bq = b.quaternion;\n\n // Hamilton product\n resultQuaternion(3) =\n aq(3) * bq(3) - aq(0) * bq(0) - aq(1) * bq(1) - aq(2) * bq(2);\n resultQuaternion(0) =\n aq(3) * bq(0) + aq(0) * bq(3) + aq(1) * bq(2) - aq(2) * bq(1);\n resultQuaternion(1) =\n aq(3) * bq(1) + aq(1) * bq(3) + aq(2) * bq(0) - aq(0) * bq(2);\n resultQuaternion(2) =\n aq(3) * bq(2) + aq(2) * bq(3) + aq(0) * bq(1) - aq(1) * bq(0);\n\n Eigen::Vector3f r = pointProduct(a.quaternion, b.translation);\n\n resultTranslation = a.translation + r;\n\n SE3T result = {resultQuaternion, resultTranslation};\n return result;\n}\n", "meta": {"hexsha": "253ba8e5c4a119b3caed1165262d18d552e7654d", "size": 1955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "evaluation/q-prod/quaternion_product.cpp", "max_stars_repo_name": "sgpthomas/diospyros", "max_stars_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2020-02-16T22:26:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-17T04:17:19.000Z", "max_issues_repo_path": "evaluation/q-prod/quaternion_product.cpp", "max_issues_repo_name": "sgpthomas/diospyros", "max_issues_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 77.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T15:37:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T19:48:43.000Z", "max_forks_repo_path": "evaluation/q-prod/quaternion_product.cpp", "max_forks_repo_name": "sgpthomas/diospyros", "max_forks_repo_head_hexsha": "27d4e5e5d4e56a6dc5860d7c7d5eefb27de24a5d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-09-27T20:35:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-27T20:35:15.000Z", "avg_line_length": 27.9285714286, "max_line_length": 80, "alphanum_fraction": 0.6040920716, "num_tokens": 670, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.88720460564669, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6847831014650312}} {"text": "/*\nCopyright (C) 2012 Mathias Eitz and Ronald Richter.\nAll rights reserved.\n\nThis file is part of the imdb library and is made available under\nthe terms of the BSD license (see the LICENSE file).\n*/\n\n#ifndef DISTANCE_HPP\n#define DISTANCE_HPP\n\n#include \n#include \n#include \n\n#include \n\n#include \"../util/types.hpp\"\n\n// ----------------------------------------------------------------\n// Note: only distance metrics allowed here, i.e. functions that\n// describe the distance between two descriptors and thus smaller\n// distances denote more similar objects. The dotproduct itself\n// e.g. is NOT a distance measure, it is a similarity measure\n// ----------------------------------------------------------------\n\n\nnamespace imdb\n{\n\n\n/**\n * \\addtogroup distfn\n * @{\n */\n\n\n/// L1 norm\ntemplate \nstruct l1norm\n{\n // stl\n typedef T first_argument_type;\n typedef T second_argument_type;\n typedef R result_type;\n\n /// L1 distance between a and b.\n R operator() (const T& a, const T& b) const\n {\n R s = 0;\n for (typename T::const_iterator ai = a.begin(), bi = b.begin(); ai != a.end(); ++ai, ++bi)\n {\n R d = static_cast(*ai) - static_cast(*bi);\n s += std::abs(d);\n }\n return s;\n }\n};\n\n\n/**\n * @brief Squared L2 (Euclidean) distance function.\n *\n * Using the squared Euclidean distance is a bit faster than the L2 norm as we avoid the call to sqrt.\n */\ntemplate \nstruct l2norm_squared\n{\n // stl\n typedef T first_argument_type;\n typedef T second_argument_type;\n typedef R result_type;\n\n /// Squared L2 distance between a and b.\n R operator() (const T& a, const T& b) const\n {\n R s = 0;\n for (typename T::const_iterator ai = a.begin(), bi = b.begin(); ai != a.end(); ++ai, ++bi)\n {\n R d = static_cast(*ai) - static_cast(*bi);\n s += d*d;\n }\n return s;\n }\n};\n\n\n/**\n * @brief L2 (Euclidean) distance function\n */\ntemplate \nstruct l2norm\n{\n // stl\n typedef T first_argument_type;\n typedef T second_argument_type;\n typedef R result_type;\n\n l2norm_squared n;\n\n /// L2 (Euclidean) distance between a and b.\n R operator() (const T& a, const T& b) const\n {\n return std::sqrt(n(a,b));\n }\n};\n\n\n\n/**\n * @brief One minus dot product distance function.\n *\n * 1 - distance function. Assumes a and b are two vectors in R^d\n * having \\b unit length\n */\ntemplate \nstruct one_minus_dot\n{\n // stl\n typedef T first_argument_type;\n typedef T second_argument_type;\n typedef R result_type;\n\n /// Computes 1 - . As we assume that both a and b have unit length, the\n /// result is guaranteed to lie in [0,2]\n R operator() (const T& a, const T& b) const\n {\n R s = 0;\n for (typename T::const_iterator ai = a.begin(), bi = b.begin(); ai != a.end(); ++ai, ++bi)\n {\n s += static_cast(*ai) * static_cast(*bi);\n }\n return (1.0 - s);\n }\n};\n\n/// Jensen-Shannon divergence\ntemplate \nstruct jsd\n{\n // stl\n typedef T first_argument_type;\n typedef T second_argument_type;\n typedef R result_type;\n\n R operator() (const T& a, const T& b) const\n {\n R s = 0;\n for (typename T::const_iterator ai = a.begin(), bi = b.begin(); ai != a.end(); ++ai, ++bi)\n {\n R v0 = *ai;\n R v1 = *bi;\n R n = 2.0 / (v0 + v1);\n\n s += ((v0 > 0.0) ? v0 * std::log(v0*n):0.0) + ((v1 > 0.0) ? v1 * std::log(v1*n):0.0);\n }\n return s;\n }\n};\n\n\n\n/**\n * @brief Chi squared distance function.\n *\n * Chi squared distance function between two vectors k and h; d = sum_i[(ai - bi)^2 / (ai+bi)].\n * We avoid division through zero by adding a tiny value to the denominator:\n * -# if ki == hi == 0 then the nominator is zero and the overall result is zero as desired\n * -# if ki or hi != 0 then ki + hi == ki + hi + float_min\n */\ntemplate \nstruct chi2\n{\n\n // stl\n typedef T first_argument_type;\n typedef T second_argument_type;\n typedef R result_type;\n\n R operator() (const T& a, const T& b) const\n {\n R s = 0;\n for (typename T::const_iterator ai = a.begin(), bi = b.begin(); ai != a.end(); ++ai, ++bi)\n {\n R v0 = *ai;\n R v1 = *bi;\n R nom = v0-v1;\n R denom = v0+v1+std::numeric_limits::epsilon();\n s += nom*nom / denom;\n }\n return s;\n }\n};\n\n\n/**\n * @brief Distance function from 'Eitz et al. - An evaluation of descriptors for large-scale image retrieval from sketched feature lines'\n *\n * Used to compare two Tensor descriptors generated by a tensor_generator. Note that this distance function\n * is different from all others in that before you can actually use operator() you need to set the member\n * variable mask, a vector of size a.size()/3 which contains a boolean for each grid cell of the\n * Tensor descriptor. mask[i] = true indicates that cell i is masked out, i.e. this cell is ignored when\n * computing the distance.\n */\ntemplate \nstruct dist_frobenius\n{\n // stl\n typedef T first_argument_type;\n typedef T second_argument_type;\n typedef R result_type;\n\n R operator() (const T& a, const T& b) const\n {\n assert(a.size() % 3 == 0);\n assert(a.size() == b.size());\n\n size_t numCells = a.size() / 3;\n assert(mask->size() == numCells);\n size_t index = 0;\n R dist = 0;\n\n for (size_t i = 0; i < numCells; i++)\n {\n // masking vector provided by query sketch, if\n // a cell in the query is empty (i.e. contains\n // no lines, we ignore it in the distance computation\n if ((*mask)[i]) continue;\n\n // difference tensor\n R dE = a[index] - b[index]; index++;\n R dF = a[index] - b[index]; index++;\n R dG = a[index] - b[index]; index++;\n\n // frobenius norm of difference tensor\n dist += std::sqrt(dE*dE + 2*dF*dF + dG*dG);\n }\n\n // normalization not required since the number of cells that are masked out\n // is defined by the query sketch and thus is constant for all comparison\n // required for one query\n return dist;\n }\n\n // if you use this distance function, you will need to manually set the correct\n // mask to be used for the query image\n const vector* mask;\n};\n\n\n\n/**\n * @brief Distance function from 'Lee & Funkhouser - Sketch-Based Search and Composition of 3D Models'.\n */\ntemplate \nstruct dist_df\n{\n // stl\n typedef T first_argument_type;\n typedef T second_argument_type;\n typedef R result_type;\n\n\n /**\n * @brief a and b are two descriptors we want to compare. First half of the vectors\n * is expected to contain the distance transform, second half the image/sketch itself.\n *\n * @param a\n * @param b\n * @return Computes + , result range is [0,inf] where 0 means that a and b are equal\n */\n R operator() (const T& a, const T& b) const\n {\n assert(a.size() % 2 == 0);\n assert(a.size() == b.size());\n\n result_type dist = 0;\n size_t offset = a.size() / 2;\n for (size_t i = 0; i < offset; i++) {\n dist += a[i]*b[i+offset];\n dist += b[i]*a[i+offset];\n }\n return dist;\n }\n};\n\n\n/**\n * @brief 'Base' template factory class for generating a distance function\n * by name, we typically use the partially specialized version for vector, though.\n */\ntemplate \nstruct distance_functions\n{\n typedef boost::function distfn_t;\n\n distfn_t make(const std::string& /*name*/)\n {\n return distfn_t();\n }\n};\n\n\n/**\n * @brief Factory class that generates a distance function from its name.\n *\n * Note that this is a partial specialization of distance_functions\n * for data of type vector. This makes constructing our typical\n * distance function that actually work on a vector just\n * a little bit more convenient than if we would use the more general version.\n */\ntemplate \nstruct distance_functions, R>\n{\n typedef std::vector T;\n typedef boost::function distfn_t;\n\n distfn_t make(const std::string& name)\n {\n if (name == \"l1norm\") return l1norm();\n if (name == \"l2norm\") return l2norm();\n if (name == \"l2norm_squared\") return l2norm_squared();\n if (name == \"jsd\") return jsd();\n if (name == \"chi2\") return chi2();\n if (name == \"one_minus_dot\") return one_minus_dot();\n if (name == \"df\") return dist_df();\n if (name == \"frobenius\") return dist_frobenius();\n\n return distfn_t();\n }\n};\n\n/** @} */\n\n} // namespace imdb\n\n#endif // DISTANCE_HPP\n", "meta": {"hexsha": "80b8160d11bd55dd93adaa7dbadd535e9257ac13", "size": 9124, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "search/distance.hpp", "max_stars_repo_name": "mathiaseitz/imdb_framework", "max_stars_repo_head_hexsha": "f8512447613bbbd19f62329c0ba121f28b8b52e7", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-08-19T04:52:22.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-26T20:11:12.000Z", "max_issues_repo_path": "search/distance.hpp", "max_issues_repo_name": "zddhub/imdb_framework", "max_issues_repo_head_hexsha": "f8512447613bbbd19f62329c0ba121f28b8b52e7", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "search/distance.hpp", "max_forks_repo_name": "zddhub/imdb_framework", "max_forks_repo_head_hexsha": "f8512447613bbbd19f62329c0ba121f28b8b52e7", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-12-21T13:37:16.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-03T01:29:11.000Z", "avg_line_length": 26.9940828402, "max_line_length": 137, "alphanum_fraction": 0.5854888207, "num_tokens": 2379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357327, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6847621246562531}} {"text": "// Eigen lib Tutorial\n// Source: http://eigen.tuxfamily.org/dox/group__TutorialMatrixArithmetic.html\n// Compile: g++ -I /usr/include/eigen3/ eigen_ex4.cpp -o eigen_ex4\n\n#include \n#include \n\nusing namespace Eigen;\n\nint main(void)\n{\n // addition and subtraction\n Matrix2d a;\n a << 1, 2,\n 3, 4;\n MatrixXd b(2,2);\n b << 2, 3,\n 1, 4;\n std::cout << \"a + b =\\n\" << a + b << std::endl;\n std::cout << \"a - b =\\n\" << a - b << std::endl;\n std::cout << \"Doing a += b;\" << std::endl;\n a += b;\n std::cout << \"Now a = \\n\" << a << std::endl;\n Vector3d v(1,2,3);\n Vector3d w(1,0,0);\n std::cout << \"-v + w - v =\\n\" << -v + w - v << std::endl;\n\n // Scalar multiplication and division\n a -= b;\n std::cout << \"a * 2,5 =\\n\" << a * 2.5 << std::endl;\n std::cout << \"0.1 * v =\\n\" << 0.1 * v << std::endl;\n std::cout << \"Doing v *= 2;\" << std::endl;\n v *= 2;\n std::cout << \"Now v =\\n\" << v << std::endl;\n\n // Transposition and conjugation\n MatrixXcf c = MatrixXcf::Random(2,2);\n std::cout << \"Here is the matrix c\\n\" << c << std::endl;\n std::cout << \"Here is the matrix c^T\\n\" << c.transpose() << std::endl;\n std::cout << \"Here is the conjugate of c\\n\" <<\n c.conjugate() << std::endl;\n std::cout << \"Here is the matrix c^*\\n\" << c.adjoint() << std::endl;\n\n // Matrix-matrix and matrix-vector multiplication\n Matrix2d mat;\n mat << 1, 2,\n 3, 4;\n Vector2d u(-1,1), x(2,0);\n std::cout << \"Here is mat*mat:\\n\" << mat*mat << std::endl;\n std::cout << \"Here is mat*u:\\n\" << mat*u << std::endl;\n std::cout << \"Here is u^T*mat:\\n\" << u.transpose()*mat << std::endl;\n std::cout << \"Here is u^T*x\\n\" << u.transpose()*x << std::endl;\n std::cout << \"Here is u*x^T\\n\" << u*x.transpose() << std::endl;\n std::cout << \"let's multiply mat by itself\" << std::endl;\n mat = mat*mat;\n std::cout << \"Now mat is mat:\\n\" << mat << std::endl;\n\n // Dot product and cross product\n Vector3d e(1,2,3);\n Vector3d f(0,1,2);\n\n std::cout << \"Dot product: \" << e.dot(f) << std::endl;\n double dp = e.adjoint()*f; // automatic converiosn of the inner product to a scalar\n std::cout << \"Dot product via a matrix product:\" << dp << std::endl;\n std::cout << \"Cross product:\\n\" << e.cross(f) << std::endl;\n\n // Basic arithmetic reduction operations\n Matrix2d mat2;\n mat2 << 1, 2,\n 3, 4;\n std::cout << \"Here is mat2.sum(): \" << mat2.sum() << std::endl;\n std::cout << \"Here is mat2.prod(): \" << mat2.prod() << std::endl;\n std::cout << \"Here is mat2.mean(): \" << mat2.mean() << std::endl;\n std::cout << \"Here is mat2.minCoeff(): \" << mat2.minCoeff() << std::endl;\n std::cout << \"Here is mat2.maxCoeff(): \" << mat2.maxCoeff() << std::endl;\n std::cout << \"Here is mat2.trace(): \" << mat2.trace() << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "4e08b786ef46b9975a38929708516a20adb86e20", "size": 2910, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen_practice/eigen_ex4.cpp", "max_stars_repo_name": "RobinCPC/ros_tutorials", "max_stars_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Eigen_practice/eigen_ex4.cpp", "max_issues_repo_name": "RobinCPC/ros_tutorials", "max_issues_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Eigen_practice/eigen_ex4.cpp", "max_forks_repo_name": "RobinCPC/ros_tutorials", "max_forks_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T06:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-29T06:32:54.000Z", "avg_line_length": 36.375, "max_line_length": 88, "alphanum_fraction": 0.5250859107, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7931059487389968, "lm_q1q2_score": 0.6847610163858822}} {"text": "/**\n * Barrier functions that grow to infinity as x -> 0+. Includes gradient and\n * hessian functions, too. These barrier functions can be used to impose\n * inequlity constraints on a function.\n */\n\n#pragma once\n\n#include \n\n#include \n\nnamespace ipc::rigid {\n\n/// @brief Barrier functions to choose from.\nenum BarrierType {\n IPC,\n POLY_LOG,\n SPLINE,\n};\n\n///////////////////////////////////////////////////////////////////////////\n// Choose your barrier!\n\n/**\n * @brief Function that grows to infinity as x approaches 0 from the right.\n *\n * @param x The x value at which to evaluate.\n * @param s Activation value of the barrier.\n * @param barrier_type Barrier function type to use.\n * @return The value of the barrier function at x.\n */\ntemplate T barrier(const T& x, double s, BarrierType barrier_type);\n\ndouble barrier_gradient(double x, double s, BarrierType barrier_type);\n\ndouble barrier_hessian(double x, double s, BarrierType barrier_type);\n\n///////////////////////////////////////////////////////////////////////////\n// Poly-Log Barrier\n\n/// y := x/eps; b(x, ϵ) = -log(y)*(2*y^3-3*y^2+1)\ntemplate T poly_log_barrier(const T& x, double s);\n\ndouble poly_log_barrier_gradient(double x, double s);\n\ndouble poly_log_barrier_hessian(double x, double s);\n\n///////////////////////////////////////////////////////////////////////////\n// Spline Barrier\n\n/**\n * @brief Function that grows to infinity as x approaches 0 from the right.\n *\n * \\begin{align}\n * g(x, s) = \\frac{1}{s^3}x^3 - \\frac{3}{s^2}x^2 + \\frac{3}{s}x\n * \\end{align}\n * \\begin{align}\n * \\phi_{\\text{spline}}(x, s) = \\frac{1}{g(x, s)} - 1\n * \\end{align}\n *\n * where \\f$s\\f$ is a constant. See here\n * for the original definition and a discussion.\n *\n * @param x The x value at which to evaluate \\f$\\phi_{\\text{spline}}(x)\\f$.\n * @param s Denominator inside x which steepens the function.\n * @return The value of the barrier function at x.\n */\ntemplate T spline_barrier(const T& x, double s);\n\n/**\n * @brief Derivative of the spline_barrier function with respect to x.\n *\n * \\begin{align}\n * g'(x, s) = \\frac{3}{s^3}x^2 - \\frac{6}{s^2}x + \\frac{3}{s}\n * \\end{align}\n * \\begin{align}\n * \\phi'_{\\text{spline}}(x, s) = \\frac{-1}{[g(x)]^2}g'(x)\n * \\end{align}\n *\n * where \\f$s\\f$ is a constant. See here\n * for the original definition and a discussion.\n *\n * @param x The x value at which to evaluate \\f$\\phi_{\\text{spline}}(x)\\f$.\n * @param s Denominator inside x which steepens the function.\n * @return The value of the derivative of the barrier function at x.\n */\ndouble spline_barrier_gradient(double x, double s);\n\n/**\n * @brief Second derivative of the spline_barrier function with respect to\n * x.\n *\n * \\begin{align}\n * g''(x, s) = \\frac{6}{s^3}x - \\frac{6}{s^2}\n * \\end{align}\n * \\begin{align}\n * \\phi''_{\\text{spline}}(x, s) = \\frac{2}{[g(x)]^3}[g'(x)]^2 +\n * \\frac{-1}{[g(x)]^2}g''(x) \\end{align}\n *\n * where \\f$s\\f$ is a constant. See here\n * for the original definition and a discussion.\n *\n * @param x The x value at which to evaluate \\f$\\phi_{\\text{spline}}(x)\\f$.\n * @param s Denominator inside x which steepens the function.\n * @return The value of the second derivative of the barrier function at x.\n */\ndouble spline_barrier_hessian(double x, double s);\n\n} // namespace ipc::rigid\n\n#include \"barrier.tpp\"\n", "meta": {"hexsha": "81bbd41f33215199920b734e708d5d3195473282", "size": 3589, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/barrier/barrier.hpp", "max_stars_repo_name": "ipc-sim/rigid-ipc", "max_stars_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2021-09-08T13:16:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T10:23:33.000Z", "max_issues_repo_path": "src/barrier/barrier.hpp", "max_issues_repo_name": "ipc-sim/rigid-ipc", "max_issues_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-09-08T00:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-05T17:44:08.000Z", "max_forks_repo_path": "src/barrier/barrier.hpp", "max_forks_repo_name": "ipc-sim/rigid-ipc", "max_forks_repo_head_hexsha": "d839af457236e7363b14c2e482a01d8160fa447e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-18T15:15:38.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-21T15:15:38.000Z", "avg_line_length": 30.9396551724, "max_line_length": 80, "alphanum_fraction": 0.6216216216, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6847076895416744}} {"text": "#include \nusing namespace std;\n\n#include \n\n// use eigin in c++\n// Eigen Core part\n#include \n// 稠密矩阵的代数运算\n#include \n\n#define MATRIX_SIZE 50\n\n//---------------------介绍eigen库的基本用法-----------------------\n//内置类型:Eigen::Matrix<>,适用于所有向量和矩阵\n//这是一个模版类,三个参数为:数据类型,行,列\n\nint main(int argc, char const *argv[])\n{\n //---------------------创建不同类型的向量或者矩阵------------------\n\n //声明一个2*3的float矩阵\n Eigen::Matrix matrix_23;\n\n //Eigen 通过 typedef 提供了许多内置类型,不过底层仍然是 Eigen::Matrix\n //例如, Vector3d三位向量 就是 Eigen::Matrix\n Eigen::Vector3d v_3d; //这两个等价, 但是这个数据类型是double\n Eigen::Matrix v_3d_1; //这两个等价,这个数据类型是float\n\n //Matrix3d 实质上是 Eigen::Matrix\n Eigen::Matrix3d matrix_33 = Eigen::Matrix3d::Zero(); //初始化为零\n\n //动态大小的矩阵,矩阵大小不确定\n //第一行用最基本的类型,第二行是eigen用typedef提供的\n Eigen::Matrix matrix_dynamic;\n Eigen::MatrixXd matrix_dynamic_1;\n\n //---------------------对Eigen矩阵的操作------------------\n\n //数据初始化\n matrix_23 << 1, 2, 3, 4, 5, 6;\n\n //输出\n cout << \"直接用cout输出\\n\" << matrix_23 << endl;\n //遍历矩阵元素\n //\n // for (size_t i = 0; i < 2; i++)\n // {\n // for (size_t j = 0; j < 3; j++)\n // {\n // cout << matrix_23(i, j) << \"\\t\";\n // }\n // cout << endl;\n // }\n\n //矩阵间乘法,或者矩阵和向量\n //要注意的:\n //1. 两个对象内元素的数据类型要一样\n // Wrong example:\n // Eigen::Matrix result_wrong_type = matrix_23 * v_3d;\n //2. 遵循矩阵乘法规则, 例如矩阵维度\n // Wrong example:\n // Eigen::Matrix result_wrong_dimension = matrix_23.cast() * v_3d;\n v_3d << 3, 2, 1; //v_3d数据类型是double\n v_3d_1 << 4, 5, 6; //v_3d_1数据类型是float\n\n //四则运算 用 + - * /\n //这里展示乘法\n //matrix_23数据类型是float,如果要和v_3d相乘,需要显示转换\n //Eigen为了性能,不会提供隐士转换,转换成员函数是 .cast()\n Eigen::Matrix result = matrix_23.cast() * v_3d;\n Eigen::Matrix result2 = matrix_23 * v_3d_1;\n\n //矩阵运算\n matrix_33 = Eigen::Matrix3d::Random(); //随机3x3的矩阵,但是感觉怎么都不变...\n cout << \"matrix \\n\" << matrix_33 << endl << endl;\n cout << \"matrix transpose\\n\" << matrix_33.transpose() << endl; // 转置\n cout << \"matrix sum\\n\" << matrix_33.sum() << endl; // 各元素和\n cout << \"matrix trace\\n\" << matrix_33.trace() << endl; // 迹\n cout << \"matrix inverse\\n\" << matrix_33.inverse() << endl; // 逆\n cout << \"matrix determinant\\n\" << matrix_33.determinant() << endl; // 行列式\n\n\n //----------------------eigenvalues & eigenvectors-----------------\n // Computes eigenvalues and eigenvectors of selfadjoint matrices.\n // define a selfadjoint Matrix\n Eigen::Matrix3d S = matrix_33.transpose() * matrix_33;\n // use solver on 3x3 matrix S\n Eigen::SelfAdjointEigenSolver es(S);\n cout << \"Eigen values = \\n\" << es.eigenvalues() << endl;\n cout << \"Eigen vectors = \\n\" << es.eigenvectors() << endl;\n\n\n //-------------------------解方程-----------------------------\n //Solve matrix_NN * x = v_Nd\n //直接求逆求解 与 QR decomposition求解\n //define matrix_NN and v_Nd\n Eigen::Matrix matrix_NN;\n matrix_NN = Eigen::MatrixXd::Random(MATRIX_SIZE, MATRIX_SIZE); //另一种使用random的用法\n Eigen::Matrix v_Nd;\n v_Nd = Eigen::MatrixXd::Random(MATRIX_SIZE, 1);\n Eigen::Matrix x;\n //set timer\n clock_t time_start = clock();\n //1. solve by inverse, time used is4.151ms\n x = matrix_NN.inverse() * v_Nd;\n cout << \"time used is\" << 1000 * (clock() - time_start) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\n //2. solve by QR decomposition, time used is0.082ms\n time_start = clock();\n x = matrix_NN.colPivHouseholderQr().solve(v_Nd);\n cout << \"time used is\" << 1000 * (clock() - time_start) / (double)CLOCKS_PER_SEC << \"ms\" << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "f5fd875276fb73b8ae2e62151f8cf8f4d57c2fed", "size": 3891, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libEigen/main.cpp", "max_stars_repo_name": "Qilko/VisualSLAM", "max_stars_repo_head_hexsha": "06fb8b7b62b161d9bce4f34463ff68e21524b47c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-01-19T02:35:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-05T17:52:55.000Z", "max_issues_repo_path": "libEigen/main.cpp", "max_issues_repo_name": "Qilko/VisualSLAM", "max_issues_repo_head_hexsha": "06fb8b7b62b161d9bce4f34463ff68e21524b47c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libEigen/main.cpp", "max_forks_repo_name": "Qilko/VisualSLAM", "max_forks_repo_head_hexsha": "06fb8b7b62b161d9bce4f34463ff68e21524b47c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8347826087, "max_line_length": 100, "alphanum_fraction": 0.5833975842, "num_tokens": 1504, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6846591643584707}} {"text": "/**\n * @file exponentialintegrator_main.cc\n * @brief NPDE homework ExponentialIntegrator code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \n#include \n#include \n#include \n/**\n * @file exponentialintegrator_main.cc\n * @brief NPDE homework ExponentialIntegrator code\n * @author Unknown, Oliver Rietmann\n * @date 04.04.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"exponentialintegrator.h\"\n\nint main() {\n /* SAM_LISTING_BEGIN_0 */\n // Final time\n double T = 1.0;\n // Initial value\n Eigen::VectorXd y0(1);\n y0 << 0.1;\n // Function and Jacobian and exact solution\n auto f = [](const Eigen::VectorXd &y) { return y(0) * (1.0 - y(0)); };\n auto df = [](const Eigen::VectorXd &y) {\n Eigen::VectorXd dfy(1);\n dfy << 1.0 - 2.0 * y(0);\n return dfy;\n };\n double exactyT = y0(0) / (y0(0) + (1.0 - y0(0)) * std::exp(-T));\n\n // Container for errors\n std::vector error(15);\n\n // Test many step sizes\n for (int j = 0; j < 15; ++j) {\n int N = std::pow(2, j + 1);\n Eigen::VectorXd y = y0;\n double h = T / N;\n#if SOLUTION\n for (int k = 0; k < N; ++k) {\n y = ExponentialIntegrator::exponentialEulerStep(y, f, df, h);\n }\n#else\n //====================\n // Your code goes here\n // TODO: Perform N timesteps with inital data y0 and store the result in y.\n //====================\n#endif\n\n error[j] = std::abs(y(0) - exactyT);\n std::cout << std::left << std::setfill(' ') << std::setw(3)\n << \"N = \" << std::setw(7) << N << std::setw(8)\n << \"Error = \" << std::setw(13) << error[j];\n if (j > 0) {\n std::cout << std::left << std::setfill(' ') << std::setw(10)\n << \"Approximated order = \" << std::log2(error[j - 1] / error[j])\n << std::endl;\n } else\n std::cout << std::endl;\n }\n /* SAM_LISTING_END_0 */\n return 0;\n}\n", "meta": {"hexsha": "28ffb908101114a1493795ec1b1c13e187669d52", "size": 2034, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/ExponentialIntegrator/mastersolution/exponentialintegrator_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "developers/ExponentialIntegrator/mastersolution/exponentialintegrator_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "developers/ExponentialIntegrator/mastersolution/exponentialintegrator_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0769230769, "max_line_length": 80, "alphanum_fraction": 0.5634218289, "num_tokens": 645, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7981867777396212, "lm_q2_score": 0.8577681049901037, "lm_q1q2_score": 0.684659159769872}} {"text": "/**\n * \\file boost/numeric/ublasx/operation/linspace.hpp\n *\n * \\brief Linearly spaced vector\n *\n * Inspired by MATLAB's linspace function.\n *\n *
\n *\n * Copyright (c) 2013, Marco Guazzone\n * \n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_LINSPACE_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_LINSPACE_HPP\n\n\n#include \n#include \n#include \n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n/**\n * \\brief Generates a linearly spaced vector.\n *\n * Generates \\a n values linearly spaced between \\a a and \\a b.\n * Note, in case \\f$an=1, returns \\a b.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate \nBOOST_UBLAS_INLINE\nvector linspace(ValueT a, ValueT b, std::size_t n = 100)\n{\n\t// pre: n > 0\n\tBOOST_UBLAS_CHECK( n > 0,\n\t\t\t\t\t bad_argument() );\n\n\tif (n < 2)\n\t{\n\t\treturn scalar_vector(1, b);\n\t}\n\n\tvector x(n);\n\n\t--n;\n\n\t// Check for possible overflows generated by opposite signs\n\tconst ValueT c = (b-a)*(n-1);\n\tif (std::isinf(c) && std::isinf(b-a))\n\t{\n\t\t// Overflows is happened => split computations\n\n\t\tconst ValueT an = a/n;\n\t\tconst ValueT bn = b/n;\n\n\t\tfor (std::size_t i = 0; i <= n; ++i)\n\t\t{\n\t\t\tx[i] = a + bn*i - an*i;\n\t\t}\n\t}\n\telse\n\t{\n\t\t// No overflow\n\n\t\tconst ValueT step = (b-a)/n;\n\n\t\tfor (std::size_t i = 0; i <= n; ++i)\n\t\t{\n\t\t\tx[i] = a + step*i;\n\t\t}\n\t}\n\n\t// just make sure that endpoints are honored\n\tx[0] = a;\n\tx[n] = b;\n\n\treturn x;\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_LINSPACE_HPP\n", "meta": {"hexsha": "dca26e7f13b34d1e099a23cd6d1d8d82bc6f803e", "size": 2177, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/linspace.hpp", "max_stars_repo_name": "comcon1/boost-ublasx", "max_stars_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "boost/numeric/ublasx/operation/linspace.hpp", "max_issues_repo_name": "comcon1/boost-ublasx", "max_issues_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "boost/numeric/ublasx/operation/linspace.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.3431372549, "max_line_length": 66, "alphanum_fraction": 0.6688102894, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.8152324848629214, "lm_q1q2_score": 0.6845784090892397}} {"text": "/*\nThis program is meant to compute maximal Lyapunov expoennt of Lorenz system.\n*/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace blitz;\n// ============ Declaration of functions ===================\ndouble Euclidean_measure(Array);\nArray Lorenz_system(Array);\nArray RK4_integrator(Array, double, Array (*F)(Array) );\nArray linearized_Lorenz_system(Array, Array);\nArray error_RK4_integrator(Array, Array, double, Array (*F)(Array, Array));\ndouble max_lypo_expo(Array , double, Array (*F)(Array) );\n\n// =========== I/O files ==================================\nofstream time_series_file;\n\n\nint main(int argc, char const *argv[])\n{\n\tArray X(3);\t\t\t\t\t\t\t\t// State vector for the reference trajectory\n\tX = -3.16,-5.31,13.31;\t\t\t\t\t\t\t// Initial condition r = 28\n\t// X = 0.62225717,-0.08232857,30.60845379;\t\t\t\t// Initial condition r = 45.92\n\t// X = 4.29033, -0.577049, 28.8962;\n\tdouble dt = 0.001;\n\tmax_lypo_expo(X, dt, Lorenz_system);\n\treturn 0;\n}\n\ndouble Euclidean_measure(Array A)\n{\n\tint N = A.numElements();\n\tdouble d = 0;\n\tfor (int i = 0; i < N; ++i)\n\t{\n\t\td += pow(A(i),2);\n\t}\n\td = sqrt(d);\n\treturn d;\n}\n\nArray RK4_integrator(Array X0, double dt, Array (*F)(Array) )\n{\n\tint dim = X0.numElements();\n\tArray X(dim);\t\t\t\t// State vector\n\t// -------- Intermediate derivatives --------\n\tArray K1(dim);\n\tArray K2(dim);\n\tArray K3(dim);\n\tArray K4(dim);\n\t// ------------------------------------------\n\tK1 = dt*F(X0);\n\tX = X0 + 0.5*K1;\n\tK2 = dt*F(X);\n\tX = X0 + 0.5*K2;\n\tK3 = dt*F(X);\n\tX = X0 + K3;\n\tK4 = dt*F(X);\n\tX = X0 + (1.0/6)*(K1 + 2*K2 + 2*K3 + K4);\n\treturn X;\n\n}\n\nArray error_RK4_integrator( Array E0, Array X, double dt, Array (*F)(Array, Array))\n{\n\t// X is the state vector\n\tint dim = E0.numElements();\n\tArray E(dim);\t\t\t\t// Tangent vector\n\t// -------- Intermediate derivatives --------\n\tArray K1(dim);\n\tArray K2(dim);\n\tArray K3(dim);\n\tArray K4(dim);\n\t// ------------------------------------------\n\tK1 = dt*F(E0, X);\n\tE = E0 + 0.5*K1;\n\tK2 = dt*F(E0, X);\n\tE = E0 + 0.5*K2;\n\tK3 = dt*F(E0, X);\n\tE = E0 + K3;\n\tK4 = dt*F(E0, X);\n\tE = E0 + (1.0/6)*(K1 + 2*K2 + 2*K3 + K4);\n\treturn E;\n\n}\n\nArray Lorenz_system(Array X)\n{\n\t// ------ Parameters ------------------------\n\tdouble sigma = 10;//16; //10;\n\tdouble r = 28;//45.92; //28;\n\tdouble b = 8.0/3;//4; //8.0/3;\n\t// ------------------------------------------\n\n\tArray F(3);\n\tF(0) = sigma*(-X(0) + X(1));\n\tF(1) = (r- X(2))*X(0) - X(1);\n\tF(2) = X(0)*X(1) - b*X(2);\n\treturn F;\n}\n\n/*Array Rotating_Lorenz_system(Array X)\n{\n\t// ------ Parameters ------------------------\n\tdouble sigma = 16; //10;\n\tdouble r = 45.92; //28;\n\tdouble b = 4; //8.0/3;\n\t// ------------------------------------------\n\n\tArray F(3);\n\tF(0) = sigma*(-X(0) + X(1));\n\tF(1) = (r- X(2))*X(0) - X(1);\n\tF(2) = X(0)*X(1) - b*X(2);\n\treturn F;\n}*/\n\nArray linearized_Lorenz_system(Array E, Array X)\n{\n\t// X is the reference trajectory while\n\t// E is the error along the refrence trajectory.\n\t// ------ Parameters ------------------------\n\tdouble sigma = 10;\n\tdouble r = 28;\n\tdouble b = 8.0/3;\n\t// ------------------------------------------\n\n\tArray F(3);\n\tF(0) = sigma*(-E(0) + E(1));\n\tF(1) = (r- X(2))*E(0) - E(1)- X(0)*E(2);\n\tF(2) = X(1)*E(0) + X(0)*E(1)- b*E(2);\n\treturn F;\n}\n\ndouble max_lypo_expo(Array X, double dt, Array (*F)(Array) )\n{\n\t\n\t// Array X(3);\t\t\t\t// State vector for the reference trajectory\n\t// X = -3.16,-5.31,13.31;\t\t\t\t// Initial condition r = 28\n\t// X = 0.62225717,-0.08232857,30.60845379;\t\t\t\t// Initial condition r = 45.92\n\t// X = 4.29033, -0.577049, 28.8962;\n\n\n\tint T_transient = 32000;\n\t// ====== Removing the transience to enter the attractor========\n\tfor (int i = 0; i < T_transient; ++i)\n\t{\n\t\tX = RK4_integrator(X, dt, F);\n\t}\n\t// ==============================================================\n\n\tcout< Y(3);\t\t\t\t// State vector for the second trajectory\n\n\tArray E(3);\t\t\t\t// Tangent vector\n\tE = 1e-8,0,0;\t\t\t\t\t\t// Initial tangent vector\n\n\tdouble d0;\n\td0 = Euclidean_measure(E); \t\t\t// Initial error\t\t\t\t\t\n\tdouble d = 0;\t\t\t\t\t\t// length of tangent vector after one iteration\n\tdouble div_rate = 0;\t\t\t\t// divergence rate of trajectories defined as log(d/d0).\n\tdouble le=0;\t\t\t\t\t\t// Lyapunov exponent defined as the average of div_rate along the trajectories.\n\tint T = 100000;\n\t// time_series_file.open(\"test_data_lypo_r45.d\");\n\tfor (int i = 1; i <= T; ++i)\n\t{\n\t\tY = X+E;\t\t\t\t\t\t// Initial condition for the second trajectory\n\n\t\t//------Simultaneous evolution of the two trajectories by one time step ------\n\t\tX = RK4_integrator(X, dt, F);\n\t\tY = RK4_integrator(Y, dt, F);\n\t\t//---------------------------------------------------------------------------\n\n\t\tE = Y-X;\t\t\t\t\t\t// The tangent vector after one time step\n\t\t// cout<\r\n#include \r\n#include \r\n#include \r\n#include \"Point.h\"\r\n#include \"Vector.h\"\r\n#include \"matrix.h\"\r\n#include \"BezierCurve.h\"\r\n#include \r\n\r\nusing namespace std;\r\nusing namespace math;\r\n\r\nBezierCurve::BezierCurve(Point p1, Point p2, Point p3, Point p4) {\r\n\tthis->controls.SetSize(4,4);\r\n\tcontrols(0,0) = p1;\r\n\tcontrols(1,0) = p2;\r\n\tcontrols(2,0) = p3;\r\n\tcontrols(3,0) = p4;\r\n\tcurve.push_back(p1);\r\n\tcurve.push_back(p2);\r\n\tcurve.push_back(p3);\r\n\tcurve.push_back(p4);\r\n\tinitMatrices();\r\n}\r\n\r\nBezierCurve::BezierCurve(vector controls) : curve(controls) {\r\n\tassert(controls.size() == 4);\r\n\tthis->controls(0,0) = controls[0];\r\n\tthis->controls(1,0) = controls[1];\r\n\tthis->controls(2,0) = controls[2];\r\n\tthis->controls(3,0) = controls[3];\r\n\tinitMatrices();\r\n}\r\n\r\nBezierCurve::BezierCurve(matrix c) : controls(c) {\r\n\tcurve.push_back(c(0,0));\r\n\tcurve.push_back(c(1,0));\r\n\tcurve.push_back(c(2,0));\r\n\tcurve.push_back(c(3,0));\r\n\tinitMatrices();\r\n}\r\n\r\nBezierCurve::~BezierCurve() {\r\n\r\n}\r\n\r\nvoid BezierCurve::initMatrices() {\r\n\tSk.SetSize(4,4);\r\n\tSk(0,0) = 1.0;\r\n\tSk(1,0) = Sk(1,1) = Sk(2,1) = 0.5;\r\n\tSk(2,0) = Sk(2,2) = 0.25;\r\n\tSk(3,0) = Sk(3,3) = 1.0 / 8.0;\r\n\tSk(3,1) = Sk(3,2) = 3.0 / 8.0;\r\n\r\n\tSi.SetSize(4,4);\r\n\tSi(0,3) = Si(2,1) = 1.0;\r\n\tSi(1,2) = Si(3,0) = -1.0;\r\n\tSi(1,3) = 2.0;\r\n\tSi(2,2) = -4.0;\r\n\tSi(2,3) = 4.0;\r\n\tSi(3,1) = 6.0;\r\n\tSi(3,2) = -12.0;\r\n\tSi(3,3) = 8.0;\r\n}\r\n\r\nmatrix BezierCurve::apply(matrix S, matrix controls) {\r\n\tmatrix newControls(4,1);\r\n\tnewControls(0,0) = S(0,0) * controls(0,0) + S(0,1) * controls(1,0) +\r\n\t\t\t\t\t\tS(0,2) * controls(2,0) + S(0,3) * controls(3,0);\r\n\tnewControls(1,0) = S(1,0) * controls(0,0) + S(1,1) * controls(1,0) +\r\n\t\t\t\t\t\tS(1,2) * controls(2,0) + S(1,3) * controls(3,0);\r\n\tnewControls(2,0) = S(2,0) * controls(0,0) + S(2,1) * controls(1,0) +\r\n\t\t\t\t\t\tS(2,2) * controls(2,0) + S(2,3) * controls(3,0);\r\n\tnewControls(3,0) = S(3,0) * controls(0,0) + S(3,1) * controls(1,0) +\r\n\t\t\t\t\t\tS(3,2) * controls(2,0) + S(3,3) * controls(3,0);\r\n\treturn newControls;\r\n}\r\n\r\nvoid BezierCurve::refine(int level) {\r\n\tmatrix subdivision = controls;\r\n\tcurve.clear();\r\n\r\n\t// get the first subdivision by applying Sk level times\r\n\tfor (int k = 0; k < level; k++)\r\n\t\tsubdivision = apply(Sk, subdivision);\r\n\tcurve.push_back(subdivision(0,0));\r\n\tcurve.push_back(subdivision(1,0));\r\n\tcurve.push_back(subdivision(2,0));\r\n\tcurve.push_back(subdivision(3,0));\r\n\r\n\t// get subsequent subdivisions by applying Si 2^level - 1 times\r\n\tfor (int i = 0; i < (int)pow(2.0,level) - 1; i++) {\r\n\t\tsubdivision = apply(Si, subdivision);\r\n\t\tcurve.push_back(subdivision(0,0));\r\n\t\tcurve.push_back(subdivision(1,0));\r\n\t\tcurve.push_back(subdivision(2,0));\r\n\t\tcurve.push_back(subdivision(3,0));\r\n\t}\r\n}\r\n\r\nvoid BezierCurve::print() {\r\n\tBOOST_FOREACH(Point p, curve) {\r\n\t\tcout << p << endl;\r\n\t}\r\n}\r\n", "meta": {"hexsha": "bf3a839228f07137f463ae7b9865497bdc422391", "size": 2967, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BezierCurve.cpp", "max_stars_repo_name": "eddy-chan/midas", "max_stars_repo_head_hexsha": "549842e97c4f8e019a620b9b664454a494b0df41", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "BezierCurve.cpp", "max_issues_repo_name": "eddy-chan/midas", "max_issues_repo_head_hexsha": "549842e97c4f8e019a620b9b664454a494b0df41", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BezierCurve.cpp", "max_forks_repo_name": "eddy-chan/midas", "max_forks_repo_head_hexsha": "549842e97c4f8e019a620b9b664454a494b0df41", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.0263157895, "max_line_length": 77, "alphanum_fraction": 0.5995955511, "num_tokens": 1123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6845373052796001}} {"text": "/**\n * \\file RobertBristowJohnsonFilter.cpp\n */\n\n#include \n\n#include \"RobertBristowJohnsonFilter.h\"\n#include \"IIRFilter.h\"\n\nnamespace ATK\n{\n template\n RobertBristowJohnsonLowPassCoefficients::RobertBristowJohnsonLowPassCoefficients(int nb_channels)\n :Parent(nb_channels), Q(1)\n {\n }\n\n template \n void RobertBristowJohnsonLowPassCoefficients::setup()\n {\n Parent::setup();\n\n DataType w0 = 2 * boost::math::constants::pi() * cut_frequency / input_sampling_rate;\n DataType cosw0 = std::cos(w0);\n DataType alpha = std::sin(w0) / (2 * Q);\n\n coefficients_in[2] = (1 - cosw0)/2 / (1 + alpha);\n coefficients_in[1] = (1 - cosw0) / (1 + alpha);\n coefficients_in[0] = (1 - cosw0) / 2 / (1 + alpha);\n coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n coefficients_out[0] = (alpha - 1) / (1 + alpha);\n }\n\n template \n void RobertBristowJohnsonLowPassCoefficients::set_Q(DataType_ Q)\n {\n if (Q <= 0)\n {\n throw std::out_of_range(\"Q must be positive\");\n }\n this->Q = Q;\n setup();\n }\n\n template \n DataType_ RobertBristowJohnsonLowPassCoefficients::get_Q() const\n {\n return Q;\n }\n\n template\n RobertBristowJohnsonHighPassCoefficients::RobertBristowJohnsonHighPassCoefficients(int nb_channels)\n :Parent(nb_channels), Q(1)\n {\n }\n\n template \n void RobertBristowJohnsonHighPassCoefficients::setup()\n {\n Parent::setup();\n\n DataType w0 = 2 * boost::math::constants::pi() * cut_frequency / input_sampling_rate;\n DataType cosw0 = std::cos(w0);\n DataType alpha = std::sin(w0) / (2 * Q);\n\n coefficients_in[2] = (1 + cosw0) / 2 / (1 + alpha);\n coefficients_in[1] = -(1 + cosw0) / (1 + alpha);\n coefficients_in[0] = (1 + cosw0) / 2 / (1 + alpha);\n coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n coefficients_out[0] = (alpha - 1) / (1 + alpha);\n }\n\n template \n void RobertBristowJohnsonHighPassCoefficients::set_Q(DataType_ Q)\n {\n if (Q <= 0)\n {\n throw std::out_of_range(\"Q must be positive\");\n }\n this->Q = Q;\n setup();\n }\n\n template \n DataType_ RobertBristowJohnsonHighPassCoefficients::get_Q() const\n {\n return Q;\n }\n\n template\n RobertBristowJohnsonBandPassCoefficients::RobertBristowJohnsonBandPassCoefficients(int nb_channels)\n :Parent(nb_channels), Q(1)\n {\n }\n\n template \n void RobertBristowJohnsonBandPassCoefficients::setup()\n {\n Parent::setup();\n\n DataType w0 = 2 * boost::math::constants::pi() * cut_frequency / input_sampling_rate;\n DataType cosw0 = std::cos(w0);\n DataType alpha = std::sin(w0) / (2 * Q);\n\n coefficients_in[2] = Q * alpha / (1 + alpha);\n coefficients_in[1] = 0;\n coefficients_in[0] = - Q * alpha / (1 + alpha);\n coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n coefficients_out[0] = (alpha - 1) / (1 + alpha);\n }\n\n template \n void RobertBristowJohnsonBandPassCoefficients::set_Q(DataType_ Q)\n {\n if (Q <= 0)\n {\n throw std::out_of_range(\"Q must be positive\");\n }\n this->Q = Q;\n setup();\n }\n\n template \n DataType_ RobertBristowJohnsonBandPassCoefficients::get_Q() const\n {\n return Q;\n }\n\n template\n RobertBristowJohnsonBandPass2Coefficients::RobertBristowJohnsonBandPass2Coefficients(int nb_channels)\n :Parent(nb_channels), Q(1)\n {\n }\n\n template \n void RobertBristowJohnsonBandPass2Coefficients::setup()\n {\n Parent::setup();\n\n DataType w0 = 2 * boost::math::constants::pi() * cut_frequency / input_sampling_rate;\n DataType cosw0 = std::cos(w0);\n DataType alpha = std::sin(w0) / (2 * Q);\n\n coefficients_in[2] = alpha / (1 + alpha);\n coefficients_in[1] = 0;\n coefficients_in[0] = -alpha / (1 + alpha);\n coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n coefficients_out[0] = (alpha - 1) / (1 + alpha);\n }\n\n template \n void RobertBristowJohnsonBandPass2Coefficients::set_Q(DataType_ Q)\n {\n if (Q <= 0)\n {\n throw std::out_of_range(\"Q must be positive\");\n }\n this->Q = Q;\n setup();\n }\n\n template \n DataType_ RobertBristowJohnsonBandPass2Coefficients::get_Q() const\n {\n return Q;\n }\n \n template\n RobertBristowJohnsonBandStopCoefficients::RobertBristowJohnsonBandStopCoefficients(int nb_channels)\n :Parent(nb_channels), Q(1)\n {\n }\n \n template \n void RobertBristowJohnsonBandStopCoefficients::setup()\n {\n Parent::setup();\n \n DataType w0 = 2 * boost::math::constants::pi() * cut_frequency / input_sampling_rate;\n DataType cosw0 = std::cos(w0);\n DataType alpha = std::sin(w0) / (2 * Q);\n \n coefficients_in[2] = 1 / (1 + alpha);\n coefficients_in[1] = -2 * cosw0 / (1 + alpha);\n coefficients_in[0] = 1 / (1 + alpha);\n coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n coefficients_out[0] = (alpha - 1) / (1 + alpha);\n }\n \n template \n void RobertBristowJohnsonBandStopCoefficients::set_Q(DataType_ Q)\n {\n if (Q <= 0)\n {\n throw std::out_of_range(\"Q must be positive\");\n }\n this->Q = Q;\n setup();\n }\n \n template \n DataType_ RobertBristowJohnsonBandStopCoefficients::get_Q() const\n {\n return Q;\n }\n\n template\n RobertBristowJohnsonAllPassCoefficients::RobertBristowJohnsonAllPassCoefficients(int nb_channels)\n :Parent(nb_channels), Q(1)\n {\n }\n\n template \n void RobertBristowJohnsonAllPassCoefficients::setup()\n {\n Parent::setup();\n\n DataType w0 = 2 * boost::math::constants::pi() * cut_frequency / input_sampling_rate;\n DataType cosw0 = std::cos(w0);\n DataType alpha = std::sin(w0) / (2 * Q);\n\n coefficients_in[2] = (1 - alpha) / (1 + alpha);\n coefficients_in[1] = -2 * cosw0 / (1 + alpha);\n coefficients_in[0] = 1;\n coefficients_out[1] = 2 * cosw0 / (1 + alpha);\n coefficients_out[0] = (alpha - 1) / (1 + alpha);\n }\n\n template \n void RobertBristowJohnsonAllPassCoefficients::set_Q(DataType_ Q)\n {\n if (Q <= 0)\n {\n throw std::out_of_range(\"Q must be positive\");\n }\n this->Q = Q;\n setup();\n }\n\n template \n DataType_ RobertBristowJohnsonAllPassCoefficients::get_Q() const\n {\n return Q;\n }\n \n template\n RobertBristowJohnsonBandPassPeakCoefficients::RobertBristowJohnsonBandPassPeakCoefficients(int nb_channels)\n :Parent(nb_channels), Q(1)\n {\n }\n \n template \n void RobertBristowJohnsonBandPassPeakCoefficients::setup()\n {\n Parent::setup();\n \n DataType w0 = 2 * boost::math::constants::pi() * cut_frequency / input_sampling_rate;\n DataType cosw0 = std::cos(w0);\n DataType alpha = std::sin(w0) / (2 * Q);\n \n coefficients_in[2] = (1 + alpha * gain) / (1 + alpha / gain);\n coefficients_in[1] = -2 * cosw0 / (1 + alpha / gain);\n coefficients_in[0] = (1 - alpha * gain) / (1 + alpha / gain);\n coefficients_out[1] = 2 * cosw0 / (1 + alpha / gain);\n coefficients_out[0] = (alpha / gain - 1) / (1 + alpha / gain);\n }\n \n template \n void RobertBristowJohnsonBandPassPeakCoefficients::set_Q(DataType_ Q)\n {\n if (Q <= 0)\n {\n throw std::out_of_range(\"Q must be positive\");\n }\n this->Q = Q;\n setup();\n }\n \n template \n DataType_ RobertBristowJohnsonBandPassPeakCoefficients::get_Q() const\n {\n return Q;\n }\n \n template \n void RobertBristowJohnsonBandPassPeakCoefficients::set_gain(DataType_ gain)\n {\n if (gain <= 0)\n {\n throw std::out_of_range(\"gain must be positive\");\n }\n this->gain = gain;\n setup();\n }\n \n template \n DataType_ RobertBristowJohnsonBandPassPeakCoefficients::get_gain() const\n {\n return gain;\n }\n \n template\n RobertBristowJohnsonLowShelvingCoefficients::RobertBristowJohnsonLowShelvingCoefficients(int nb_channels)\n :Parent(nb_channels), Q(1), gain(1)\n {\n }\n \n template \n void RobertBristowJohnsonLowShelvingCoefficients::setup()\n {\n Parent::setup();\n \n DataType w0 = 2 * boost::math::constants::pi() * cut_frequency / input_sampling_rate;\n DataType cosw0 = std::cos(w0);\n DataType alpha = std::sin(w0) / (2 * Q);\n DataType d = (gain + 1) + (gain - 1) * cosw0 + 2 * std::sqrt(gain) * alpha;\n\n coefficients_in[2] = gain * ((gain + 1) - (gain - 1) * cosw0 + 2 * sqrt(gain) * alpha) / d;\n coefficients_in[1] = 2 * gain * ((gain - 1) - (gain + 1) * cosw0) / d;\n coefficients_in[0] = gain * ((gain + 1) - (gain - 1) * cosw0 - 2 * sqrt(gain) * alpha) / d;\n coefficients_out[1] = 2 * ((gain - 1) + (gain + 1) * cosw0) / d;\n coefficients_out[0] = -((gain + 1) + (gain - 1) * cosw0 - 2 * sqrt(gain) * alpha) / d;\n }\n \n template \n void RobertBristowJohnsonLowShelvingCoefficients::set_Q(DataType_ Q)\n {\n if (Q <= 0)\n {\n throw std::out_of_range(\"Q must be positive\");\n }\n this->Q = Q;\n setup();\n }\n \n template \n DataType_ RobertBristowJohnsonLowShelvingCoefficients::get_Q() const\n {\n return Q;\n }\n \n template \n void RobertBristowJohnsonLowShelvingCoefficients::set_gain(DataType_ gain)\n {\n if (gain <= 0)\n {\n throw std::out_of_range(\"gain must be positive\");\n }\n this->gain = gain;\n setup();\n }\n \n template \n DataType_ RobertBristowJohnsonLowShelvingCoefficients::get_gain() const\n {\n return gain;\n }\n \n template\n RobertBristowJohnsonHighShelvingCoefficients::RobertBristowJohnsonHighShelvingCoefficients(int nb_channels)\n :Parent(nb_channels), Q(1), gain(1)\n {\n }\n \n template \n void RobertBristowJohnsonHighShelvingCoefficients::setup()\n {\n Parent::setup();\n \n DataType w0 = 2 * boost::math::constants::pi() * cut_frequency / input_sampling_rate;\n DataType cosw0 = std::cos(w0);\n DataType alpha = std::sin(w0) / (2 * Q);\n DataType d = (gain + 1) - (gain - 1) * cosw0 + 2 * std::sqrt(gain) * alpha;\n \n coefficients_in[2] = gain * ((gain + 1) + (gain - 1) * cosw0 + 2 * sqrt(gain) * alpha) / d;\n coefficients_in[1] = -2 * gain * ((gain - 1) + (gain + 1) * cosw0) / d;\n coefficients_in[0] = gain * ((gain + 1) + (gain - 1) * cosw0 - 2 * sqrt(gain) * alpha) / d;\n coefficients_out[1] = -2 * ((gain - 1) - (gain + 1) * cosw0) / d;\n coefficients_out[0] = -((gain + 1) - (gain - 1) * cosw0 - 2 * sqrt(gain) * alpha) / d;\n }\n \n template \n void RobertBristowJohnsonHighShelvingCoefficients::set_Q(DataType_ Q)\n {\n if (Q <= 0)\n {\n throw std::out_of_range(\"Q must be positive\");\n }\n this->Q = Q;\n setup();\n }\n \n template \n DataType_ RobertBristowJohnsonHighShelvingCoefficients::get_Q() const\n {\n return Q;\n }\n \n template \n void RobertBristowJohnsonHighShelvingCoefficients::set_gain(DataType_ gain)\n {\n if (gain <= 0)\n {\n throw std::out_of_range(\"gain must be positive\");\n }\n this->gain = gain;\n setup();\n }\n \n template \n DataType_ RobertBristowJohnsonHighShelvingCoefficients::get_gain() const\n {\n return gain;\n }\n\n template class RobertBristowJohnsonLowPassCoefficients;\n template class RobertBristowJohnsonLowPassCoefficients;\n template class RobertBristowJohnsonHighPassCoefficients;\n template class RobertBristowJohnsonHighPassCoefficients;\n template class RobertBristowJohnsonBandPassCoefficients;\n template class RobertBristowJohnsonBandPassCoefficients;\n template class RobertBristowJohnsonBandPass2Coefficients;\n template class RobertBristowJohnsonBandPass2Coefficients;\n template class RobertBristowJohnsonAllPassCoefficients;\n template class RobertBristowJohnsonAllPassCoefficients;\n template class RobertBristowJohnsonBandStopCoefficients;\n template class RobertBristowJohnsonBandStopCoefficients;\n template class RobertBristowJohnsonBandPassPeakCoefficients;\n template class RobertBristowJohnsonBandPassPeakCoefficients;\n template class RobertBristowJohnsonLowShelvingCoefficients;\n template class RobertBristowJohnsonLowShelvingCoefficients;\n template class RobertBristowJohnsonHighShelvingCoefficients;\n template class RobertBristowJohnsonHighShelvingCoefficients;\n\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n}\n", "meta": {"hexsha": "5d085961b67bf0f19028e9e74290ed9d2dc117e2", "size": 14662, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/RobertBristowJohnsonFilter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "ATK/EQ/RobertBristowJohnsonFilter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ATK/EQ/RobertBristowJohnsonFilter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 32.295154185, "max_line_length": 119, "alphanum_fraction": 0.6944482335, "num_tokens": 4241, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533013520765, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6845321818692344}} {"text": "#include \n\n#include // std::runtime_error\n\n#include \n\n#include \n\nnamespace ipc {\n\n// Matrix Projection onto Positive Definite Cone\ntemplate <\n typename _Scalar,\n int _Rows,\n int _Cols,\n int _Options,\n int _MaxRows,\n int _MaxCols>\nEigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>\nproject_to_pd(\n const Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& A,\n double eps)\n{\n assert(eps > 0);\n\n // https://math.stackexchange.com/q/2776803\n Eigen::SelfAdjointEigenSolver<\n Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>>\n eigensolver(A);\n if (eigensolver.info() != Eigen::Success) {\n IPC_LOG(error(\"unable to project matrix onto positive definite cone\"));\n throw std::runtime_error(\n \"unable to project matrix onto positive definite cone\");\n }\n // Check if all eigen values are positive.\n // The eigenvalues are sorted in increasing order.\n if (eigensolver.eigenvalues()[0] > 0.0) {\n return A;\n }\n Eigen::DiagonalMatrix D(eigensolver.eigenvalues());\n // Save a little time and only project the negative or zero values\n for (int i = 0; i < A.rows(); i++) {\n if (D.diagonal()[i] <= 0.0) {\n D.diagonal()[i] = eps;\n } else {\n break;\n }\n }\n return eigensolver.eigenvectors() * D\n * eigensolver.eigenvectors().transpose();\n}\n\n// Matrix Projection onto Positive Semi-Definite Cone\ntemplate <\n typename _Scalar,\n int _Rows,\n int _Cols,\n int _Options,\n int _MaxRows,\n int _MaxCols>\nEigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>\nproject_to_psd(\n const Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>& A)\n{\n // https://math.stackexchange.com/q/2776803\n Eigen::SelfAdjointEigenSolver<\n Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols>>\n eigensolver(A);\n if (eigensolver.info() != Eigen::Success) {\n IPC_LOG(\n error(\"unable to project matrix onto positive semi-definite cone\"));\n throw std::runtime_error(\n \"unable to project matrix onto positive definite cone\");\n }\n // Check if all eigen values are zero or positive.\n // The eigenvalues are sorted in increasing order.\n if (eigensolver.eigenvalues()[0] >= 0.0) {\n return A;\n }\n Eigen::DiagonalMatrix D(eigensolver.eigenvalues());\n // Save a little time and only project the negative values\n for (int i = 0; i < A.rows(); i++) {\n if (D.diagonal()[i] < 0.0) {\n D.diagonal()[i] = 0.0;\n } else {\n break;\n }\n }\n return eigensolver.eigenvectors() * D\n * eigensolver.eigenvectors().transpose();\n}\n\ntemplate \nResult cross(\n const Eigen::MatrixBase& a, const Eigen::MatrixBase& b)\n{\n assert(a.size() == 3 && b.size() == 3);\n Result c(a.rows(), a.cols());\n c(0) = a(1) * b(2) - a(2) * b(1);\n c(1) = a(2) * b(0) - a(0) * b(2);\n c(2) = a(0) * b(1) - a(1) * b(0);\n return c;\n}\n\n} // namespace ipc\n", "meta": {"hexsha": "aa50b82c34aec209a1253da6456cd28456682454", "size": 3281, "ext": "tpp", "lang": "C++", "max_stars_repo_path": "src/utils/eigen_ext.tpp", "max_stars_repo_name": "ipc-sim/ipc-toolk", "max_stars_repo_head_hexsha": "81873d0288810e30166d871419da4104329860e3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 61.0, "max_stars_repo_stars_event_min_datetime": "2020-08-04T21:08:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-25T02:24:31.000Z", "max_issues_repo_path": "src/utils/eigen_ext.tpp", "max_issues_repo_name": "dbelgrod/ipc-toolkit", "max_issues_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-12T05:54:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-10T18:39:30.000Z", "max_forks_repo_path": "src/utils/eigen_ext.tpp", "max_forks_repo_name": "dbelgrod/ipc-toolkit", "max_forks_repo_head_hexsha": "0b7ca9b5f867db63bd68dd02ce54a9d00b0fc337", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-11-26T12:47:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T04:55:49.000Z", "avg_line_length": 30.9528301887, "max_line_length": 80, "alphanum_fraction": 0.6205425175, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6845112654451907}} {"text": "#include \n#include \n\n#include \n\n#include \n\nnamespace pcp {\n\n// see https://perso.liris.cnrs.fr/julie.digne/articles/compute_wavejets.m\nPointWiseEstimationData CurvatureComputer_WJets::compute(const Geometry& points, int i0, Scalar s) const\n{\n constexpr auto order = 2;\n constexpr auto I = std::complex(0,1); // complex number 0+i\n\n // % compute PCA normal\n Matrix3 C = Matrix3::Zero();\n Vector3 m = Vector3::Zero();\n int nneigh = 0;\n\n for(int i : points.kdtree().range_neighbors(i0, s))\n {\n m += points[i];\n C += points[i] * points[i].transpose();\n nneigh += 1;\n }\n\n if(nneigh < NEI_COUNT_MIN) return PointWiseEstimationData::Invalid();\n\n m /= nneigh;\n C = C/nneigh - m * m.transpose();\n\n // eigenvalues are positive and ordered\n // eigenvectors are normalized\n Eigen::SelfAdjointEigenSolver solver(C);\n// const Vector3 normal = solver.eigenvectors().col(0);\n const Vector3 t2 = solver.eigenvectors().col(1);\n const Vector3 t1 = solver.eigenvectors().col(2);\n const Vector3 normal = t1.cross(t2);\n\n Matrix3 P;\n P.col(0) = t1;\n P.col(1) = t2;\n P.col(2) = normal;\n\n // % compute Phi\n constexpr int ncolM = order*order/2 + 3*order/2+1; // = 6\n PCP_ASSERT(ncolM == 6);\n\n Eigen::Matrix, Eigen::Dynamic, Eigen::Dynamic> M(nneigh,ncolM);\n Eigen::Matrix, Eigen::Dynamic, 1> b(nneigh);\n\n M.setZero();\n b.setZero();\n\n int nei_count = 0;\n\n int j=0;\n for(int i : points.kdtree().range_neighbors(i0, s))\n {\n // % express neighbors in local coord system\n const Vector3 locneighbors = P.transpose() * (points[i] - points[i0]);\n\n // % switch to polar coordinates\n const Scalar r = locneighbors.head<2>().norm();\n const Scalar theta = std::atan2(locneighbors.y(), locneighbors.x());\n Scalar z = locneighbors.z();\n\n const Scalar normalized_r = r / s;\n z = z / s;\n\n const Scalar w = std::exp(-normalized_r * normalized_r/18.0);\n\n int idx = 0;\n for(int k=0; k<=order; ++k)\n {\n const Scalar rk = std::pow(normalized_r, k);\n for(int n = -k; n <= k; n += 2)\n {\n M(j,idx) = rk * std::exp(I * Scalar(n) * theta) * w;\n ++idx;\n }\n }\n b[j] = z * w;\n ++j;\n ++nei_count;\n }\n if(nei_count < NEI_COUNT_MIN) return PointWiseEstimationData::Invalid();\n\n Eigen::Matrix, Eigen::Dynamic, 1> Phi = M.colPivHouseholderQr().solve(b);\n\n // % correct normal\n Vector3 u = - t1 * std::imag(Phi(1) - Phi(2)) + t2 * std::real(Phi(2) + Phi(1)); // % axis\n u.normalize();\n Scalar gamma = - std::atan( 2 * std::abs(Phi(2))); // % angle\n\n Vector3 nc = std::cos(gamma) * normal + (1 - std::cos(gamma)) * (normal.dot(u)) * u + std::sin(gamma) * u.cross(normal);\n nc.normalize();\n Vector3 t1c = t1 - (t1.transpose() * nc) * nc;\n t1c.normalize();\n Vector3 t2c = nc.cross(t1c);\n t2c.normalize();\n\n // % redo everything (instead of correcting the coefficients - quick and dirty method, to be improved later)\n Matrix3 Pc;\n Pc.col(0) = t1c;\n Pc.col(1) = t2c;\n Pc.col(2) = nc;\n\n M.setZero();\n b.setZero();\n\n nei_count = 0;\n\n j=0;\n for(int i : points.kdtree().range_neighbors(i0, s))\n {\n // % express neighbors in local coord system\n const Vector3 locneighbors = Pc.transpose() * (points[i] - points[i0]); // Pc not P !\n\n // switch to polar coordinates\n const Scalar r = locneighbors.head<2>().norm();\n const Scalar theta = std::atan2(locneighbors.y(), locneighbors.x());\n Scalar z = locneighbors.z();\n\n const Scalar normalized_r = r / s;\n z = z / s;\n\n const Scalar w = std::exp(-normalized_r*normalized_r/18.0);\n\n int idx = 0;\n for(int k=0; k<=order; ++k)\n {\n const Scalar rk = std::pow(normalized_r, k);\n for(int n = -k; n <= k; n += 2)\n {\n M(j,idx) = rk * std::exp(I * Scalar(n) * theta) * w;\n ++idx;\n }\n }\n b[j] = z * w;\n ++j;\n ++nei_count;\n }\n if(nei_count < NEI_COUNT_MIN) return PointWiseEstimationData::Invalid();\n\n Eigen::Matrix, Eigen::Dynamic, 1> Phicorr = M.colPivHouseholderQr().solve(b);\n\n // % compute real(a0) and |an| n>=1\n// idx = 1;\n// an=zeros(order+1,1);\n// for k=0:order\n// for n = -k:2:k\n// if n>=0\n// an(n+1) = an(n+1) + Phicorr(idx)/(k+2);\n// end\n// idx=idx+1;\n// end\n// end\n// an(1)=real(an(1));%imaginary part is 0\n// an(2:end)=abs(an(2:end));\n\n\n// const std::complex phi_0_0 = Phicorr(0);\n// const std::complex phi_1_m1 = Phicorr(1);\n// const std::complex phi_1_p1 = Phicorr(2);\n const std::complex phi_2_m2 = Phicorr(3);\n const std::complex phi_2_0 = Phicorr(4);\n const std::complex phi_2_p2 = Phicorr(5);\n\n const Vector3 N = nc; // corrected normal !\n\n Scalar k1 = 2 * std::real(phi_2_0 + phi_2_p2 + phi_2_m2);\n Scalar k2 = 2 * std::real(phi_2_0 - phi_2_p2 - phi_2_m2);\n\n if(std::abs(k2) > std::abs(k1)) std::swap(k1,k2);\n\n // reset to original scale\n k1 /= s;\n k2 /= s;\n\n const Scalar H = 0.5 * (k1 + k2);\n\n return PointWiseEstimationData(k1, k2, H, N, Vector3::Constant(666), Vector3::Constant(666), nei_count);\n}\n\n} // namespace pcp\n", "meta": {"hexsha": "31b8f0486404ef1428106862865fefedbd7b90e5", "size": 5725, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "figures/src/PCP/Curvature/Methods/WJets.cpp", "max_stars_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_stars_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2021-07-29T18:19:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-12T12:42:52.000Z", "max_issues_repo_path": "figures/src/PCP/Curvature/Methods/WJets.cpp", "max_issues_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_issues_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-07-12T08:51:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-14T09:38:17.000Z", "max_forks_repo_path": "figures/src/PCP/Curvature/Methods/WJets.cpp", "max_forks_repo_name": "STORM-IRIT/algebraic-shape-operator", "max_forks_repo_head_hexsha": "8de592549562cf8cff51044a459ce64a75176e42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-07-12T08:52:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-17T11:40:21.000Z", "avg_line_length": 30.4521276596, "max_line_length": 124, "alphanum_fraction": 0.5591266376, "num_tokens": 1766, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.936285002192296, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6844791774091362}} {"text": "#include \n\nnamespace Eigen {\nnamespace Vector {\ntemplate \ninline void push_back(Eigen::Matrix& v, const T d) {\n Eigen::Matrix tmp = v;\n v.resize(tmp.size() + 1);\n v.head(tmp.size()) = tmp;\n v[v.size()-1] = d;\n}\ntemplate \ninline void wedge(Eigen::Matrix& mat, const Eigen::Matrix&v) {\n mat(0,0) = 0.0;\n mat(0,1) = -v[2];\n mat(0,2) = v[1];\n mat(1,0) = v[2];\n mat(1,1) = 0.0;\n mat(1,2) = -v[0];\n mat(2,0) = -v[1];\n mat(2,1) = v[0];\n mat(2,2) = 0.0;\n}\n}\n}\n", "meta": {"hexsha": "8fd963421694aa8d3fa32e3520e3b4e27ca78a89", "size": 549, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils.hpp", "max_stars_repo_name": "RyodoTanaka/eigen_example", "max_stars_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/utils.hpp", "max_issues_repo_name": "RyodoTanaka/eigen_example", "max_issues_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils.hpp", "max_forks_repo_name": "RyodoTanaka/eigen_example", "max_forks_repo_head_hexsha": "55da46919e02d0eb7cbea9da97ffa0f9067a6d98", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-30T03:32:04.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-30T03:32:04.000Z", "avg_line_length": 21.1153846154, "max_line_length": 76, "alphanum_fraction": 0.5591985428, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765163620469, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6844233953300184}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nusing boost::multiprecision::cpp_int;\n\n\n\n\nconst int MOD = 1000000007;\n\ncpp_int gcd(cpp_int a, cpp_int b) {\n if (a < b) swap(a, b);\n return b == 0 ? a : gcd(b, a % b);\n}\n\ncpp_int lcm(cpp_int a, cpp_int b) {\n return a * b / gcd(a, b);\n}\n\nint main() {\n int n;\n const int SIZE = 10007;\n\n cpp_int A[SIZE];\n scanf(\"%d\", &n);\n for (auto i = 0; i < n; i ++) {\n cin >> A[i];\n }\n cpp_int prod = lcm(A[0], A[1]);\n for(auto i = 2; i < n; i ++) prod = lcm(prod, cpp_int(A[i]));\n cpp_int sum = 0;\n for(auto i = 0; i < n; i++) {\n sum += (prod / A[i]);\n sum %= MOD;\n }\n std::cout << sum << endl;\n return 0;\n}\n", "meta": {"hexsha": "a741dd9af1817a3e942dfdbac7441a1ac49ba560", "size": 846, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "abc/152/E.cpp", "max_stars_repo_name": "515hikaru/solutions", "max_stars_repo_head_hexsha": "9fb3e4600f9a97b78211a5736c98354d4cbebc38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "abc/152/E.cpp", "max_issues_repo_name": "515hikaru/solutions", "max_issues_repo_head_hexsha": "9fb3e4600f9a97b78211a5736c98354d4cbebc38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-12-29T17:57:39.000Z", "max_issues_repo_issues_event_max_datetime": "2020-02-16T16:36:04.000Z", "max_forks_repo_path": "abc/152/E.cpp", "max_forks_repo_name": "515hikaru/solutions", "max_forks_repo_head_hexsha": "9fb3e4600f9a97b78211a5736c98354d4cbebc38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6744186047, "max_line_length": 65, "alphanum_fraction": 0.5413711584, "num_tokens": 274, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545304202039, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6843240965259647}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"FFT.h\"\n#include \"params.h\"\n\nusing namespace std;\nusing namespace NTL;\n\n\nvoid FFTStep(CC_t * const f_fft, RR_t const * const f, const unsigned long N, const CC_t w0)\n{\n if(N==1)\n {\n f_fft[0] = f[0];\n }\n else\n {\n if(N==2)\n {\n f_fft[0] = f[0] + ii*f[1];\n f_fft[1] = f[0] - ii*f[1];\n }\n else\n {\n assert(N%2==0);\n RR_t f0[N0/2], f1[N0/2];\n CC_t f0_fft[N0/2], f1_fft[N0/2], wk, w02;\n unsigned int k;\n for(k=0; k<(N/2); k++)\n {\n f0[k] = f[2*k];\n f1[k] = f[2*k+1];\n }\n\n w02 = w0*w0;\n wk = w0;\n FFTStep(f0_fft, f0, N/2, w02);\n FFTStep(f1_fft, f1, N/2, w02);\n for(k=0; k(f[i]) ) );\n }\n\n FFTStep(f_FFT, f_double, N0, omega);\n}\n\n\nvoid FFTToZZX(ZZX& f, CC_t const * const f_FFT)\n{\n double f_double[N0];\n unsigned int i;\n MyRealReverseFFT(f_double, f_FFT);\n\n f.SetLength(N0);\n for(i=0; i(round(f_double[i]));\n }\n\n}\n", "meta": {"hexsha": "2e947e3968413563e49be8513e6220048e86a131", "size": 3178, "ext": "cc", "lang": "C++", "max_stars_repo_path": "NTRU-PEKS/FFT.cc", "max_stars_repo_name": "Rbehnia/Full_PEKS", "max_stars_repo_head_hexsha": "6a841872579f9a079075049b1186be41b3a6f886", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2017-12-28T22:18:16.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-06T08:25:19.000Z", "max_issues_repo_path": "NTRU-PEKS/FFT.cc", "max_issues_repo_name": "Rbehnia/Full_PEKS", "max_issues_repo_head_hexsha": "6a841872579f9a079075049b1186be41b3a6f886", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2017-12-19T09:58:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-31T12:56:22.000Z", "max_forks_repo_path": "NTRU-PEKS/FFT.cc", "max_forks_repo_name": "Rbehnia/Full_PEKS", "max_forks_repo_head_hexsha": "6a841872579f9a079075049b1186be41b3a6f886", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T05:28:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-30T08:17:57.000Z", "avg_line_length": 19.8625, "max_line_length": 99, "alphanum_fraction": 0.4647577093, "num_tokens": 1124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6843014277758498}} {"text": "#include \n#include \n#include \n#include \n\nint main(int argc, char **argv) \n{\n // exploit namespaces to shorten code\n using namespace boost::numeric::ublas;\n using std::cout; \n using std::endl;\n\n // declare three 3x3 matrices of complex elements\n matrix > m(3, 3), n(3, 3), o(3, 3);\n\n // iterate over 3x3 matrix entries\n // r : row index\n // c : column index\n for (unsigned r = 0; r < m.size1(); r++) {\n for (unsigned c = 0; c < m.size2(); c++) {\n // enumerated matrix entries\n m(r,c) = 3 * r + c;\n\n // complex numbers designating rows and cols\n n(r,c) = r + c * std::complex(0,1); \n\n // elementwise square of n\n o(r,c) = std::pow(n(r,c), 2);\n }\n }\n \n std::array real = {-1, 0, 1};\n std::array imag = {-1, 0, 1};\n int rs = real.size()-1;\n \n matrix > p(3,3);\n \n for (unsigned r = 0; r < real.size(); r++) {\n for (unsigned c = 0; c < imag.size(); c++) {\n p(r,c) = real[rs-r] + imag[c] * std::complex(0,1);\n }\n }\n\n // print to screen as demonstration\n cout << \"m:\" << endl;\n cout << m << endl;\n cout << endl << \"n:\" << endl;\n cout << n << endl;\n cout << endl << \"o:\" << endl;\n cout << n << endl;\n cout << endl << \"m + n:\" << endl;\n cout << m + n << endl;\n cout << endl << \"m * n:\" << endl;\n cout << prod(m, n) << endl;\n cout << endl << \"n * n - o:\" << endl;\n cout << prod(n, n) - o << endl;\n \n cout << \"complex plane:\" << endl;\n for(unsigned i = 0;i\n#include \n\n#include \n#include \"utils/tools.h\"\n#include \"mat_l.h\"\n#include \n#include \n\nNTL_CLIENT\n\n//#define DEBUG\n\n//X = I * n, set the dimension to n, clear and then set to value\nvoid ident(mat_l& X, long n)\n{\n X.SetDims(n,n);\n clear(X);\n for (long i = 0; i < n; i++)\n X[i][i] = 1L;\n}\n\nbool isZero(const mat_l& M)\n{\n for (long i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include //needed?\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nvoid example_scalar_rp(std::ostream& out){\n out << \"-> example_scalar_rp : \";\n using namespace boost;\n\n // This example shows how to compute a Rosenblatt-Parzen estimate of the \n // density, p(x). The type used for each data-unit, here, is double\n\n //Types\n typedef double val_;\n typedef std::vector vec_;\n typedef mt19937 urng_;\n typedef normal_distribution norm_;\n typedef variate_generator gen_;\n typedef statistics::detail::kernel::scalar::gaussian_kernel gauss_k_;\n typedef statistics::detail::kernel::rp_visitor rp_visitor_;\n\n // Contants\n const val_ bandwidth = 0.5;\n const val_ eps = math::tools::epsilon();\n const unsigned n = 10;\n\n // Initialization\n vec_ dataset(n);\n vec_ vec_rp; vec_rp.reserve(n);\n urng_ urng;\n norm_ norm;\n gen_ gen(urng,norm);\n std::generate_n(\n begin(dataset),\n n,\n gen\n );\n\n // Computes a density estimate for each x in dataset\n BOOST_FOREACH(val_& x,dataset){\n val_ rp = for_each(\n boost::begin(dataset),\n boost::end(dataset),\n rp_visitor_(bandwidth,x)\n ).estimate();\n vec_rp.push_back(rp);\n } \n\n // Same as previous but calls estimator instead of for_each\n typedef sub_range sub_x_;\n typedef \n statistics::detail::kernel::estimator<\n sub_x_,\n statistics::detail::kernel::rp_visitor,\n gauss_k_\n > estimator_;\n estimator_ estimator(bandwidth); \n sub_x_ sub_x(dataset);\n estimator.train(sub_x);\n vec_ vec_rp2; vec_rp2.reserve(n);\n \n for(unsigned i = 0; i\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate\nvoid print_point ( CGAL::Point_2 const& p )\n{\n //CGAL::exact(p);\n std::cout << p.x() << \" \" << p.y();\n}\n\ntemplate\nvoid print_straight_skeleton( CGAL::Straight_skeleton_2 const& ss )\n{\n typedef CGAL::Straight_skeleton_2 Ss ;\n \n typedef typename Ss::Vertex_const_handle Vertex_const_handle ;\n typedef typename Ss::Halfedge_const_handle Halfedge_const_handle ;\n typedef typename Ss::Halfedge_const_iterator Halfedge_const_iterator ;\n \n Halfedge_const_handle null_halfedge ;\n Vertex_const_handle null_vertex ;\n\n std::cerr << \"Straight skeleton with \" << ss.size_of_vertices() \n << \" vertices, \" << ss.size_of_halfedges()\n << \" halfedges and \" << ss.size_of_faces()\n << \" faces\" << std::endl ;\n \n for ( Halfedge_const_iterator i = ss.halfedges_begin(); i != ss.halfedges_end(); ++i )\n {\n if ( !i->is_bisector() ) continue;\n std::cout << \"2 \" ;\n print_point(i->opposite()->vertex()->point()) ;\n std::cout << \" 0 \" ;\n print_point(i->vertex()->point());\n std::cout << \" 0\\n\" ;\n //std::cout << \" \" << ( i->is_bisector() ? \"bisector\" : \"contour\" ) << std::endl;\n }\n}\n\n\n\ntypedef CGAL::Exact_predicates_exact_constructions_kernel EPEC;\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel EPIC;\ntypedef CGAL::Simple_cartesian< CGAL::Lazy_exact_nt > SCLGQ;\ntypedef EPEC::Exact_kernel::FT EPEC_exact_ft;\ntypedef CGAL::Exact_predicates_exact_constructions_kernel_with_sqrt EPEC_with_sqrt;\n\n\n\ntemplate< class Kernel, class FT>\nvoid build_skeleton(const char* fname)\n{\n typedef typename Kernel::Point_2 Point_2;\n typedef CGAL::Polygon_2 Polygon_2;\n typedef CGAL::Straight_skeleton_builder_traits_2 SsBuilderTraits;\n typedef CGAL::Straight_skeleton_2 Ss;\n typedef CGAL::Straight_skeleton_builder_2 SsBuilder;\n \n Polygon_2 pgn;\n \n std::ifstream input(fname);\n \n FT x,y;\n while(input)\n {\n input >> x;\n if (!input) break;\n input >> y;\n if (!input) break;\n pgn.push_back( Point_2( typename Kernel::FT(x), typename Kernel::FT(y) ) );\n }\n input.close();\n \n std::cout << \"Polygon has \" << pgn.size() << \" points\\n\";\n \n if(!pgn.is_counterclockwise_oriented()) {\n std::cerr << \"Polygon is not CCW Oriented\" << std::endl;\n }\n if(!pgn.is_simple()) {\n std::cerr << \"Polygon is not simple\" << std::endl;\n } \n\n CGAL::Timer time;\n time.start();\n SsBuilder ssb;\n ssb.enter_contour(pgn.vertices_begin(), pgn.vertices_end());\n boost::shared_ptr straight_ske = ssb.construct_skeleton();\n time.stop();\n \n std::cout << \"Time spent to build skeleton \" << time.time() << \"\\n\";\n \n if(!straight_ske->is_valid()) {\n std::cerr << \"Straight skeleton is not valid\" << std::endl;\n }\n\n std::cerr.precision(60);\n print_straight_skeleton(*straight_ske);\n \n}\n\n\n\n\nint main(int argc, char** argv) {\n if (argc!=2)\n std::cerr << \"Usage: \" << argv[0] << \" polygon_points.txt\\n\";\n else\n {\n\n std::cout <<\"Running with EPIC\\n\";\n build_skeleton(argv[1]);\n \n std::cout <<\"Running with SCLGQ\\n\";\n build_skeleton(argv[1]);\n\n std::cout <<\"Running with EPEC_with_sqrt\\n\";\n build_skeleton(argv[1]);\n\n std::cout <<\"Running with EPEC\\n\";\n build_skeleton(argv[1]);\n }\n\n return 0;\n}\n", "meta": {"hexsha": "58ddbe5bdcb7839d375664b13e28f095f768caa2", "size": 4066, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "graphics/cgal/Straight_skeleton_2/benchmark/Straight_skeleton_2/compare_kernels_simple_polygon_skeleton.cpp", "max_stars_repo_name": "hlzz/dotfiles", "max_stars_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T14:31:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-02-02T05:01:32.000Z", "max_issues_repo_path": "graphics/cgal/Straight_skeleton_2/benchmark/Straight_skeleton_2/compare_kernels_simple_polygon_skeleton.cpp", "max_issues_repo_name": "hlzz/dotfiles", "max_issues_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "graphics/cgal/Straight_skeleton_2/benchmark/Straight_skeleton_2/compare_kernels_simple_polygon_skeleton.cpp", "max_forks_repo_name": "hlzz/dotfiles", "max_forks_repo_head_hexsha": "0591f71230c919c827ba569099eb3b75897e163e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4637681159, "max_line_length": 89, "alphanum_fraction": 0.6524840138, "num_tokens": 1137, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513675912912, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6842733720425409}} {"text": "/*!\n * @file neumann_bc.hpp\n * @brief Contains implementation of Neumann boundary conditions.\n * @author Konrad Simon\n * @date August 2019\n */\n\n#ifndef INCLUDE_NEUMANN_BC_HPP_\n#define INCLUDE_NEUMANN_BC_HPP_\n\n// Deal.ii\n#include \n\n// STL\n#include \n#include \n\n// My Headers\n#include \"coefficients.h\"\n\nnamespace Coefficients\n{\nusing namespace dealii;\n\n/*!\n * @class NeumannBC\n * @brief Class implements scalar Neumann conditions.\n */\ntemplate \nclass NeumannBC : public Function\n{\npublic:\n\tNeumannBC() : Function() {}\n\n\tvirtual double value(const Point &p,\n\t\t\t\t\t\tconst unsigned int component = 0) const override;\n\tvirtual void value_list(const std::vector> &points,\n\t\t\t\t\t\t\t\tstd::vector &values,\n\t\t\t\t\t\t\t\tconst unsigned int component = 0) const override;\n};\n\n\ntemplate \ndouble\nNeumannBC::value(const Point &p,\n\t\t\t\t\t\t\t const unsigned int /*component*/) const\n{\n\tdouble return_value = cos(2*PI_D*p(0)) * cos(2*PI_D*p(1));\n\n\treturn return_value;\n}\n\n\ntemplate \nvoid\nNeumannBC::value_list(const std::vector> &points,\n\t\t\t\t\t\t\t\tstd::vector &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\r\n#include \r\n#include \r\n#include \r\n#include \r\nusing Eigen::MatrixXd;\r\nusing Eigen::VectorXd;\r\nusing namespace std;\r\n\r\nint n_aug = 7;\r\ndouble glambda;\r\ndouble weight1;\r\ndouble weightn;\r\ndouble dt;\r\nVectorXd x = VectorXd(5);//state vector\r\nVectorXd x_aug(7);//augmented vector\r\nMatrixXd P_aug(7,7);//augmented covariance matrix\r\nMatrixXd P = MatrixXd(5, 5);//covariance matrix\r\nMatrixXd sigma_aug(7,15);//augmented sigma point matrix\r\nMatrixXd predict_sigma_aug(5,15);//predicted augmented sigma point matrix\r\nMatrixXd measured_predict_sigma_aug(3,15);// predicted sigma points in measurement space\r\nVectorXd stateMean(5);\r\nMatrixXd stateCovariance(5,5);\r\nVectorXd measurementMean(3);\r\nMatrixXd measurementCovariance(3,3);\r\nMatrixXd crossCorrelationMatrix(5,3);\r\nMatrixXd kalmanGain;\r\nVectorXd z(3);\r\nint ccount = 0;\r\nfloat m_rho,m_pi,m_rdot;\r\n //Process noise standard deviation longitudinal acceleration in m/s^2\r\n double std_a = 0.2;\r\n\r\n //Process noise standard deviation yaw acceleration in rad/s^2\r\n double std_yawdd = 0.2;\r\n \r\nMatrixXd R_radar_(3,3);\r\n\r\n // Radar measurement noise standard deviation radius in m\r\n double std_radr_ = 0.3;\r\n\r\n // Radar measurement noise standard deviation angle in rad\r\n double std_radphi_ = 0.03;\r\n\r\n // Radar measurement noise standard deviation radius change in m/s\r\n double std_radrd_ = 0.3;\r\n\r\n \r\nvoid calculateError(VectorXd state,VectorXd groundTruth){\r\n double error;\r\n for(int i=0;i<3;i++){\r\n error += abs(state(i)) - abs(groundTruth(i));\r\n }\r\n //print result\r\n cout<<\"-------------------------------------------------------------\"< M_PI) z_diff(1)-=2.*M_PI;\r\n while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;\r\n S = S + weights(i) * z_diff * z_diff.transpose();\r\n }\r\n\r\n //add measurement noise covariance matrix\r\n S = S + R_radar_;\r\n //create example vector for incoming radar measurement\r\n\r\n //create matrix for cross correlation Tc\r\n MatrixXd Tc = MatrixXd(n_x, n_z);\r\n\r\n //calculate cross correlation matrix\r\n Tc.fill(0.0);\r\n for (int i = 0; i < 2 * n_aug + 1; i++) { //2n+1 simga points\r\n\r\n //residual\r\n VectorXd z_diff = Zsig.col(i) - z_pred;\r\n //angle normalization\r\n while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI;\r\n while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;\r\n\r\n // state difference\r\n VectorXd x_diff = Xsig_pred.col(i) - x;\r\n //angle normalization\r\n while (x_diff(3)> M_PI) x_diff(3)-=2.*M_PI;\r\n while (x_diff(3)<-M_PI) x_diff(3)+=2.*M_PI;\r\n\r\n Tc = Tc + weights(i) * x_diff * z_diff.transpose();\r\n }\r\n\r\n //Kalman gain K;\r\n MatrixXd K = Tc * S.inverse();\r\n\r\n //residual\r\n VectorXd z_diff = z - z_pred;\r\n\r\n //angle normalization\r\n while (z_diff(1)> M_PI) z_diff(1)-=2.*M_PI;\r\n while (z_diff(1)<-M_PI) z_diff(1)+=2.*M_PI;\r\n\r\n //update state mean and covariance matrix\r\n x = stateMean + K * z_diff;\r\n P = stateCovariance - K*S*K.transpose();\r\n\r\n}\r\n\r\n\r\nVectorXd radar2State(VectorXd m_radar){\r\n double r_m_rho = m_radar(0);\r\n double r_m_pi = m_radar(1);\r\n double r_m_rdot = m_radar(2);\r\n double r_m_px = r_m_rho*cos(r_m_pi);\r\n if ( r_m_px < 0.0001 ) {\r\n r_m_px = 0.0001;\r\n }\r\n double r_m_py = r_m_rho*sin(r_m_pi);\r\n if(r_m_py< 0.0001){\r\n r_m_py = 0.0001;\r\n } \r\n double r_m_vx = r_m_rdot*cos(r_m_pi);\r\n double r_m_vy = r_m_rdot*sin(r_m_pi);\r\n double r_m_v = sqrt(r_m_vx*r_m_vx + r_m_vy*r_m_vy);\r\n VectorXd r_x(5);\r\n r_x << r_m_px,r_m_py,r_m_v,0,0;\r\n return r_x;\r\n}\r\n\r\nvoid NormalizeAngleOnComponent(VectorXd vector, int index) {\r\n while (vector(index)> M_PI) vector(index)-=2.*M_PI;\r\n while (vector(index)<-M_PI) vector(index)+=2.*M_PI;\r\n}\r\n\r\n\r\nvoid convertIntoMeasurementSpace(){\r\n double rho,theta,r_rho;\r\n for(int i=0;i M_PI) theta-=2.*M_PI;\r\n while (theta<-M_PI) theta+=2.*M_PI;\r\n r_rho = (predict_sigma_aug(0,i)*cos(predict_sigma_aug(3,i))*predict_sigma_aug(2,i) + predict_sigma_aug(1,i)*sin(predict_sigma_aug(3,i))*predict_sigma_aug(2,i))/rho;\r\n measured_predict_sigma_aug.col(i) << rho,theta,r_rho;\r\n }\r\n \r\n}\r\n\r\nvoid predictMeanAndCovariance(MatrixXd x,int distinction){\r\n VectorXd extractedMean(x.rows());\r\n extractedMean.fill(0.0);\r\n MatrixXd extractedCovariance(x.rows(),x.rows());\r\n extractedCovariance.fill(0.0);\r\n weight1 = glambda/(glambda+n_aug);\r\n weightn = 0.5/(glambda+n_aug);\r\n VectorXd x_diff(x.rows());\r\n for(int i = 0;i3){\r\n select = 3;\r\n }\r\n else{\r\n select = 1;\r\n }\r\n if(i==0){\r\n while (x_diff(select)> M_PI) x_diff(select)-=2.*M_PI;\r\n while (x_diff(select)<-M_PI) x_diff(select)+=2.*M_PI;\r\n x_diff = x.col(i)-extractedMean;\r\n extractedCovariance += weight1*x_diff*(x_diff.transpose());\r\n }\r\n else{\r\n while (x_diff(select)> M_PI) x_diff(select)-=2.*M_PI;\r\n while (x_diff(select)<-M_PI) x_diff(select)+=2.*M_PI;\r\n x_diff = x.col(i)-extractedMean;\r\n extractedCovariance += weightn*x_diff*(x_diff.transpose());\r\n }\r\n }\r\n if(distinction==0){\r\n stateMean = extractedMean;\r\n stateCovariance = extractedCovariance;\r\n }\r\n else{\r\n measurementMean = extractedMean;\r\n measurementCovariance = extractedCovariance;\r\n }\r\n\r\n}\r\n\r\nvoid predictSigmaPoints(double dt){\r\n for(int i=0;i>type;\r\n if(type=='R'){\r\n my_stream>>m_rho;\r\n my_stream>>m_pi;\r\n my_stream>>m_rdot;\r\n z<< m_rho,m_pi,m_rdot;\r\n my_stream>>c_timestamp;\r\n if(count==0){\r\n x = radar2State(z);\r\n P << 1, 0, 0, 0, 0,\r\n 0, 1, 0, 0, 0,\r\n 0, 0, 1, 0, 0,\r\n 0, 0, 0, 1, 0,\r\n 0, 0, 0, 0, 1;\r\n\r\n p_timestamp = c_timestamp;\r\n count++;\r\n continue;\r\n }\r\n dt = (c_timestamp - p_timestamp)/1000000.0;\r\n p_timestamp = c_timestamp;\r\n my_stream>>gt_x;\r\n my_stream>>gt_y;\r\n my_stream>>gt_vx;\r\n my_stream>>gt_vy;\r\n gt_v = sqrt(gt_vx*gt_vx + gt_vy*gt_vy);\r\n VectorXd gt(3);\r\n gt << gt_x,gt_y,gt_v;\r\n generateAugmentedMatrix(x,P);//converts vector of size 5 to 7 and matrix of 5x5 to 7x7\r\n sigma_aug = genarateSigmaPoints(x_aug,P_aug);//outputs 7x15 matrix\r\n predictSigmaPoints(0.1);//outputs 5x15 matrix\r\n predictMeanAndCovariance(predict_sigma_aug,0);//outputs a vector of size 5 and matrix of size 5x5\r\n convertIntoMeasurementSpace();//outputs 3x15 matrix from 5x15 matrix\r\n predictMeanAndCovariance(measured_predict_sigma_aug,1);//mean and covariance in measurement space\r\n updateState();\r\n calculateError(x,gt);\r\n }\r\n }\r\n return 0;\r\n}", "meta": {"hexsha": "65a26813817c382f3fe9a1044ef56031c05185da", "size": 11399, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "UKF.cpp", "max_stars_repo_name": "YASH-ROCKY/Unscented-Kalman-Filter", "max_stars_repo_head_hexsha": "83fd2a56cc9e4bcc8ac3c7ce324cf89c4859e415", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-06T05:40:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T05:40:32.000Z", "max_issues_repo_path": "UKF.cpp", "max_issues_repo_name": "YASH-ROCKY/Unscented-Kalman-Filter", "max_issues_repo_head_hexsha": "83fd2a56cc9e4bcc8ac3c7ce324cf89c4859e415", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "UKF.cpp", "max_forks_repo_name": "YASH-ROCKY/Unscented-Kalman-Filter", "max_forks_repo_head_hexsha": "83fd2a56cc9e4bcc8ac3c7ce324cf89c4859e415", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3159340659, "max_line_length": 173, "alphanum_fraction": 0.5973330994, "num_tokens": 3377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6840260904258679}} {"text": "/**\n * @file lqr_controller.h\n * @brief Infinite-horizon Linear Quadratic Regulator.\n * \n */\n\n#ifndef LQR_CONTROLLER_H\n#define LQR_CONTROLLER_H\n\n#include \n\nnamespace controller\n{\n\nclass LQR\n{\n public:\n LQR(const Eigen::MatrixXd& Q, const Eigen::MatrixXd& R);\n ~LQR() {};\n \n /**\n * @brief An infinite-horizon LQR controller with penalties on the state feedback and input signal (Q and R, respectively).\n * @brief LQR gain is solved by searching for stable poles of the system through the Hamiltonian matrix.\n * \n * @param A System dynamics matrix.\n * @param B Input matrix.\n * @param E State error.\n * @return Eigen::MatrixXd LQR gain, K.\n */\n Eigen::MatrixXd computeHamiltonian(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B, const Eigen::MatrixXd& E);\n\n private:\n // Declare generic MAT for LQR computations.\n Eigen::MatrixXd K;\n Eigen::MatrixXd Q;\n Eigen::MatrixXd R;\n Eigen::MatrixXd I;\n Eigen::MatrixXd P;\n\n // Declare Hamilton matrix.\n Eigen::MatrixXd Ham;\n\n // Output.\n Eigen::MatrixXd cmd_vel;\n Eigen::MatrixXd controlUpdate;\n};\n\n} // namespace controller\n\n#endif /* LQR_CONTROLLER_H */", "meta": {"hexsha": "f5a77ef5dc844bd03c4d3b0ec475d90731fa4048", "size": 1292, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/control_system/include/lqr_controller.hpp", "max_stars_repo_name": "duckstarr/controller", "max_stars_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-05-15T21:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T04:34:54.000Z", "max_issues_repo_path": "src/control_system/include/lqr_controller.hpp", "max_issues_repo_name": "duckstarr/controller", "max_issues_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/control_system/include/lqr_controller.hpp", "max_forks_repo_name": "duckstarr/controller", "max_forks_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.84, "max_line_length": 131, "alphanum_fraction": 0.6160990712, "num_tokens": 289, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6840260904258678}} {"text": "#ifndef _VGUGV_COMMON_HELPER_FUNCTIONS__\n#define _VGUGV_COMMON_HELPER_FUNCTIONS_\n\n#include \n#include \n#include \"commDefs.h\"\n#include \n#include \"cameraBase.h\"\n#include \"cudaDefs.h\"\n\nnamespace VGUGV\n{\n namespace Common\n {\n typedef long long T_int64;\n typedef std::chrono::high_resolution_clock T_clock;\n typedef std::chrono::time_point T_time;\n \n /*-------------------------------------------------------------------------------------------------*/\n /*------------------------------------ FUNCTION PROTOTYPES ----------------------------------------*/\n /*-------------------------------------------------------------------------------------------------*/\n \n template T INPI(T angle);\n template T deg2rad(T deg);\n template T rad2deg(T rad);\n template void rotMatrix2Euler(T r00, T r01, T r02, \n\t\t\t\t\t T r10, T r11, T r12,\n\t\t\t\t\t T r20, T r21, T r22,\n\t\t\t\t\t T& phi, T& theta, T& psi);\n template void euler2rotMatrix(T phi, T theta, T psi,\n\t\t\t\t\t T& r00, T& r01, T& r02, \n\t\t\t\t\t T& r10, T& r11, T& r12,\n\t\t\t\t\t T& r20, T& r21, T& r22);\n \n T_time currentTime();\n T_int64 elapsedTime(T_time start, TIME_TYPE type);\n \n Eigen::Matrix3f so3Exp(Eigen::Vector3f omega);\n Eigen::Matrix3f fov2K(float fovDeg, int pixelWidth, int pixelHeight);\n Eigen::Vector2f distort_radialNtangential(CameraBase::Ptr cameraModel, Eigen::Vector2f pixel0);\n Eigen::Matrix3f computePlanarHomography(Eigen::Matrix4f T_l2r, float planeDepth_ref, Eigen::Vector3f planeNormal_ref);\n \n float bilinearInterpolation(const unsigned char* pData, int nRows, int nCols, float r, float c); \n __m128 bilinearInterpolation(const unsigned char* pData, int nRows, int nCols, const SSE_m128_v2& pixels);\n bool getImagePatch(unsigned char* pImageData, int nRows, int nCols, int r, int c, int nPatchSize, unsigned char* pPatch);\n bool getImagePatch(CameraBase::Ptr pRefCamera, \n\t\t CameraBase::Ptr pCurCamera, \n\t\t unsigned char* pCurImgData, \n\t\t Eigen::Matrix3f Hl2r, \n\t\t int r, \n\t\t int c, \n\t\t int nPatchSize, \n\t\t unsigned char* pPatch);\n \n float znccScore(unsigned char* pRefPatch, unsigned char* pCurPatch, int nSize);\n \n //! Method to cluster 1D data into different clusters, each cluster is approximated by a Gaussian distribution\n /*!\n \\param inputData (data, weight), data is already sorted ascendingly. \n \\param dataSize total number of data pairs \n \\param Th threshold value used to split two clusters\n \\param models fitted Gaussian models (mean, variance, weight) \n \\return (nModels, nBestModelIndex)\n */\n Eigen::Vector2i cluster_1Ddata(Eigen::Vector2f* inputData, int dataSize, float Th, Eigen::Vector3f* models);\n \n //! Method to fit 1D data into a Gaussian distribution\n /*!\n \\param inputData (data, weight), data is already sorted ascendingly. \n \\param dataSize total number of data pairs \n \\return (mean, variance, weight)\n */\n Eigen::Vector3f gaussian_fit(Eigen::Vector2f* inputData, int dataSize);\n \n float depthFromSubpixelInterpolation(const std::array& depths, const std::array& similarityScores);\n \n int intergerDivUp(int a, int b);\n \n // SSE related functions\n void printSSE_m128(const __m128& a);\n __m128 _mm_floor_ps2(const __m128& a);\n }\n}\n#endif", "meta": {"hexsha": "e9bc497a5839f7ef8eab364d79943375bb9003d9", "size": 3485, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/DynSLAM/Direct/helperFunctions.hpp", "max_stars_repo_name": "Frozenheart1998/DynSLAM", "max_stars_repo_head_hexsha": "2de2c58c6eadbc037a19d393951b0f9d15191eab", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 530.0, "max_stars_repo_stars_event_min_datetime": "2017-06-24T16:51:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T23:13:03.000Z", "max_issues_repo_path": "src/DynSLAM/Direct/helperFunctions.hpp", "max_issues_repo_name": "38100514/DynSLAM", "max_issues_repo_head_hexsha": "5fa4374872af63192e0c6b367a5577548ffd6b87", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 65.0, "max_issues_repo_issues_event_min_datetime": "2017-06-14T11:43:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-25T01:25:03.000Z", "max_forks_repo_path": "src/DynSLAM/Direct/helperFunctions.hpp", "max_forks_repo_name": "38100514/DynSLAM", "max_forks_repo_head_hexsha": "5fa4374872af63192e0c6b367a5577548ffd6b87", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 166.0, "max_forks_repo_forks_event_min_datetime": "2017-06-02T06:41:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T11:10:02.000Z", "avg_line_length": 41.4880952381, "max_line_length": 125, "alphanum_fraction": 0.6241032999, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637648915617, "lm_q2_score": 0.7956581097540519, "lm_q1q2_score": 0.6839984461976717}} {"text": "///////////////////////////////////////////////////////////////\n// Copyright 2018 John Maddock. Distributed under the Boost\n// Software License, Version 1.0. (See accompanying file\n// LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt\n\n//[mpfr_variable\n\n/*`\nThis example illustrates the use of variable-precision arithmetic with\nthe `mpfr_float` number type. We'll calculate the median of the\nbeta distribution to an absurdly high precision and compare the\naccuracy and times taken for various methods. That is, we want\nto calculate the value of `x` for which ['I[sub x](a, b) = 0.5].\n\nUltimately we'll use Newtons method and set the precision of\nmpfr_float to have just enough digits at each iteration.\n\nThe full source of the this program is in [@../../example/mpfr_precision.cpp]\n\nWe'll skip over the #includes and using declations, and go straight to\nsome support code, first off a simple stopwatch for performance measurement:\n\n*/\n\n//=template \n//=struct stopwatch { /*details \\*/ };\n\n/*`\nWe'll use `stopwatch` as our performance measuring device.\n\nWe also have a small utility class for controlling the current precision of mpfr_float:\n\n struct scoped_precision\n {\n unsigned p;\n scoped_precision(unsigned new_p) : p(mpfr_float::default_precision())\n {\n mpfr_float::default_precision(new_p);\n }\n ~scoped_precision()\n {\n mpfr_float::default_precision(p);\n }\n };\n\n*/\n//<-\n#include \n#include \n#include \n#include \n#include \n\nusing boost::multiprecision::mpfr_float;\nusing boost::math::ibeta_inv;\nusing namespace boost::math::policies;\n\ntemplate \nstruct stopwatch\n{\npublic:\n typedef typename clock_type::duration duration_type;\n\n stopwatch() : m_start(clock_type::now()) { }\n\n stopwatch(const stopwatch& other) : m_start(other.m_start) { }\n\n stopwatch& operator=(const stopwatch& other)\n {\n m_start = other.m_start;\n return *this;\n }\n\n ~stopwatch() { }\n\n float elapsed() const\n {\n return float(std::chrono::nanoseconds((clock_type::now() - m_start)).count()) / 1e9f;\n }\n\n void reset()\n {\n m_start = clock_type::now();\n }\n\nprivate:\n typename clock_type::time_point m_start;\n};\n\nstruct scoped_precision\n{\n unsigned p;\n scoped_precision(unsigned new_p) : p(mpfr_float::default_precision())\n {\n mpfr_float::default_precision(new_p);\n }\n ~scoped_precision()\n {\n mpfr_float::default_precision(p);\n }\n};\n//->\n\n/*`\nWe'll begin with a reference method that simply calls the Boost.Math function `ibeta_inv` and uses the\nfull working precision of the arguments throughout. Our reference function takes 3 arguments:\n\n* The 2 parameters `a` and `b` of the beta distribution, and\n* The number of decimal digits precision to achieve in the result.\n\nWe begin by setting the default working precision to that requested, and then, since we don't know where\nour arguments `a` and `b` have been or what precision they have, we make a copy of them - note that since\ncopying also copies the precision as well as the value, we have to set the precision expicitly with a\nsecond argument to the copy. Then we can simply return the result of `ibeta_inv`:\n*/\nmpfr_float beta_distribution_median_method_1(mpfr_float const& a_, mpfr_float const& b_, unsigned digits10)\n{\n scoped_precision sp(digits10);\n mpfr_float half(0.5), a(a_, digits10), b(b_, digits10);\n return ibeta_inv(a, b, half);\n}\n/*`\nYou be wondering why we needed to change the precision of our variables `a` and `b` as well as setting the default -\nthere are in fact two ways in which this can go wrong if we don't do that:\n\n* The variables have too much precision - this will cause all arithmetic operations involving those types to be\npromoted to the higher precision wasting precious calculation time.\n* The variables have too little precision - this will cause expressions involving only those variables to be\ncalculated at the lower precision - for example if we calculate `exp(a)` internally, this will be evaluated at\nthe precision of `a`, and not the current default.\n\nSince our reference method carries out all calculations at the full precision requested, an obvious refinement\nwould be to calculate a first approximation to `double` precision and then to use Newton steps to refine it further.\n\nOur function begins the same as before: set the new default precision and then make copies of our arguments\nat the correct precision. We then call `ibeta_inv` with all double precision arguments, promote the result\nto an `mpfr_float` and perform Newton steps to obtain the result. Note that our termination condition is somewhat\ncude: we simply assume that we have approximately 14 digits correct from the double-precision approximation and\nthat the precision doubles with each step. We also cheat, and use an internal Boost.Math function that calculates\n['I[sub x](a, b)] and it's derivative in one go:\n\n*/\nmpfr_float beta_distribution_median_method_2(mpfr_float const& a_, mpfr_float const& b_, unsigned digits10)\n{\n scoped_precision sp(digits10);\n mpfr_float half(0.5), a(a_, digits10), b(b_, digits10);\n mpfr_float guess = ibeta_inv((double)a, (double)b, 0.5);\n unsigned current_digits = 14;\n mpfr_float f, f1;\n while (current_digits < digits10)\n {\n f = boost::math::detail::ibeta_imp(a, b, guess, boost::math::policies::policy<>(), false, true, &f1) - half;\n guess -= f / f1;\n current_digits *= 2;\n }\n return guess;\n}\n/*`\nBefore we refine the method further, it might be wise to take stock and see how method's 1 and 2 compare.\nWe'll ask them both for 1500 digit precision, and compare against the value produced by `ibeta_inv` at 1700 digits.\nHere's what the results look like:\n\n[pre\nMethod 1 time = 0.611647\nRelative error: 2.99991e-1501\nMethod 2 time = 0.646746\nRelative error: 7.55843e-1501\n]\n\nClearly they are both equally accurate, but Method 1 is actually faster and our plan for improved performance\nhasn't actually worked. It turns out that we're not actually comparing like with like, because `ibeta_inv` uses\nHalley iteration internally which churns out more digits of precision rather more rapidly than Newton iteration.\nSo the time we save by refining an initial `double` approximation, then loose it again by taking more iterations\nto get to the result.\n\nTime for a more refined approach. It follows the same form as Method 2, but now we set the working precision\nwithin the Newton iteration loop, to just enough digits to cover the expected precision at each step. That means\nwe also create new copies of our arguments at the correct precision within the loop, and likewise change the precision\nof the current `guess` each time through:\n\n*/\n\nmpfr_float beta_distribution_median_method_3(mpfr_float const& a_, mpfr_float const& b_, unsigned digits10)\n{\n mpfr_float guess = ibeta_inv((double)a_, (double)b_, 0.5);\n unsigned current_digits = 14;\n mpfr_float f(0, current_digits), f1(0, current_digits), delta(1);\n while (current_digits < digits10)\n {\n current_digits *= 2;\n scoped_precision sp((std::min)(current_digits, digits10));\n mpfr_float a(a_, mpfr_float::default_precision()), b(b_, mpfr_float::default_precision());\n guess.precision(mpfr_float::default_precision());\n f = boost::math::detail::ibeta_imp(a, b, guess, boost::math::policies::policy<>(), false, true, &f1) - 0.5f;\n guess -= f / f1;\n }\n return guess;\n}\n\n/*`\nThe new performance results look much more promising:\n\n[pre\nMethod 1 time = 0.591244\nRelative error: 2.99991e-1501\nMethod 2 time = 0.622679\nRelative error: 7.55843e-1501\nMethod 3 time = 0.143393\nRelative error: 4.03898e-1501\n]\n\nThis time we're 4x faster than `ibeta_inv`, and no doubt that could be improved a little more by carefully\noptimising the number of iterations and the method (Halley vs Newton) taken.\n\nFinally, here's the driver code for the above methods:\n\n*/\n\nint main()\n{\n try {\n mpfr_float a(10), b(20);\n\n mpfr_float true_value = beta_distribution_median_method_1(a, b, 1700);\n\n stopwatch my_stopwatch;\n\n mpfr_float v1 = beta_distribution_median_method_1(a, b, 1500);\n float hp_time = my_stopwatch.elapsed();\n std::cout << \"Method 1 time = \" << hp_time << std::endl;\n std::cout << \"Relative error: \" << boost::math::relative_difference(v1, true_value) << std::endl;\n\n my_stopwatch.reset();\n mpfr_float v2 = beta_distribution_median_method_2(a, b, 1500);\n hp_time = my_stopwatch.elapsed();\n std::cout << \"Method 2 time = \" << hp_time << std::endl;\n std::cout << \"Relative error: \" << boost::math::relative_difference(v2, true_value) << std::endl;\n\n my_stopwatch.reset();\n mpfr_float v3 = beta_distribution_median_method_3(a, b, 1500);\n hp_time = my_stopwatch.elapsed();\n std::cout << \"Method 3 time = \" << hp_time << std::endl;\n std::cout << \"Relative error: \" << boost::math::relative_difference(v3, true_value) << std::endl;\n }\n catch (const std::exception& e)\n {\n std::cout << \"Found exception with message: \" << e.what() << std::endl;\n }\n return 0;\n}\n//]\n\n", "meta": {"hexsha": "eb559cbe86a8bdee6e7db6a49a702b05c7d7ff7c", "size": 9352, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/multiprecision/example/mpfr_precision.cpp", "max_stars_repo_name": "btzy/boost-1.72.0-mirror", "max_stars_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-01T03:04:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T03:04:05.000Z", "max_issues_repo_path": "libs/multiprecision/example/mpfr_precision.cpp", "max_issues_repo_name": "btzy/boost-1.72.0-mirror", "max_issues_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/multiprecision/example/mpfr_precision.cpp", "max_forks_repo_name": "btzy/boost-1.72.0-mirror", "max_forks_repo_head_hexsha": "defad0f34b0abc884032b57dd4eb93f18f679bf1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.9644268775, "max_line_length": 118, "alphanum_fraction": 0.7209153122, "num_tokens": 2308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950907764118, "lm_q2_score": 0.8104788995148791, "lm_q1q2_score": 0.6839591644784752}} {"text": "// stochastic_regression.cpp\n/*\n This program performs a stochastic regression imputation\n for a target variable y with missing values using completely\n observed data X. The calculations are run in serial and then\n in parallel. The parallel implementation is based on C++'s \n std::thread. For matrix computations the C++ header only \n library Eigen is used. You need Eigen to compile this code.\n Eigen is free software and available at \n https://eigen.tuxfamily.org/\n \n To comopile this program use one of the following:\n $ g++ -I eigen-3.4.0 stochastic_regression.cpp -o stochastic_regression.out -std=c++2a -lpthread -O3\n $ clang++ -I eigen-3.4.0 stochastic_regression.cpp -o stochastic_regression.out -std=c++2a -lpthread -O3\n\n To run it, type\n $ ./stochastic_regression.out\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\n// Linear model object that can fit data in the form of a target y\n// and features X using multiple linear regression. \nclass LinearModel\n{\npublic:\n double sigma;\n Eigen::VectorXd beta;\n Eigen::VectorXd residuals;\n Eigen::MatrixXd design;\n Eigen::MatrixXd inv_matrix_prod;\n\n LinearModel();\n ~LinearModel();\n void fit(Eigen::MatrixXd X, Eigen::VectorXd y);\n Eigen::VectorXd predict(Eigen::MatrixXd X);\n};\n\nLinearModel::LinearModel()\n{\n}\n\nLinearModel::~LinearModel()\n{\n}\n\n// Predicts y for a given Matrix X using the Matrix-Vector-Product\n// of X and beta.\nEigen::VectorXd LinearModel::predict(Eigen::MatrixXd X)\n{\n return(X * beta);\n}\n\n// Fit a linear model of the form y = X * beta + epsilon\n// using least squares.\nvoid LinearModel::fit(Eigen::MatrixXd X, Eigen::VectorXd y)\n{ \n // Add ones to the model for the intercept parameter.\n // Therefore resize and reshape the matrix X.\n X.conservativeResize(X.rows(), X.cols() + 1);\n for (int i = X.cols() - 1; i > 0 ; i--) \n {\n X.col(i) = X.col(i - 1);\n }\n X.col(0) = Eigen::VectorXd::Ones(X.rows());\n design = X;\n\n // Calculate OLS estimates beta.\n Eigen::MatrixXd XX = X.transpose() * X;\n inv_matrix_prod = XX.inverse();\n beta = X.transpose() * y;\n beta = inv_matrix_prod * beta;\n\n // Calculate the residuals.\n Eigen::VectorXd predictions = predict(X);\n residuals = y - predictions;\n Eigen::VectorXd residuals_sq = residuals.array().pow(2);\n\n // Calculate sigma, that is the variance of the error terms.\n sigma = sqrt(1.0f / (X.rows() - beta.size()) * residuals_sq.sum());\n}\n\n\n// Generates draws from a multivariate normal distribution.\n// For reference see:\n// https://stackoverflow.com/questions/6142576/sample-from-multivariate-normal-gaussian-distribution-in-c\nstruct normal_random_variable\n{\n normal_random_variable(Eigen::MatrixXd const& covar)\n : normal_random_variable(Eigen::VectorXd::Zero(covar.rows()), covar)\n {}\n\n normal_random_variable(Eigen::VectorXd const& mean, Eigen::MatrixXd const& covar)\n : mean(mean)\n {\n Eigen::SelfAdjointEigenSolver eigenSolver(covar);\n transform = eigenSolver.eigenvectors() * eigenSolver.eigenvalues().cwiseSqrt().asDiagonal();\n }\n\n Eigen::VectorXd mean;\n Eigen::MatrixXd transform;\n\n Eigen::VectorXd operator()() const\n {\n static std::mt19937 gen{ std::random_device{}() };\n static std::normal_distribution<> dist;\n\n return mean + transform * Eigen::VectorXd{ mean.size() }.unaryExpr([&](auto x) { return dist(gen); });\n }\n};\n\n\n// Reads a CSV file and pushes its content into an Eigen::MatrixXd.\n// For reference see:\n// https://stackoverflow.com/questions/34247057/how-to-read-csv-file-and-assign-to-eigen-matrix/39146048\n// https://www.py4u.net/discuss/80056\nEigen::MatrixXd read_matrix_csv(const std::string & filepath) \n{\n // Read values form file and write it to buffer vector.\n std::ifstream indata;\n indata.open(filepath);\n std::string line;\n std::vector values;\n uint rows = 0;\n while (std::getline(indata, line)) \n {\n std::stringstream lineStream(line);\n std::string cell;\n while (std::getline(lineStream, cell, ',')) \n {\n values.push_back(std::stod(cell));\n }\n ++rows;\n }\n\n // Detect or set number of rows/columns\n size_t num_rows = rows;\n size_t num_cols = values.size() / rows;\n\n // Map buffer to Eigen::Matrix and return it.\n Eigen::MatrixXd csv_matrix = Eigen::Map> (&values.data()[0], num_rows, num_cols);\n return csv_matrix;\n}\n\n\n// Performs stochastic regression imputation on a data vector y\n// and observed variables X. \nEigen::VectorXd stochastic_regression_imputation(Eigen::MatrixXd X_miss, Eigen::MatrixXd X_obs, Eigen::VectorXd y_obs)\n{\n int n_obs = X_obs.rows();\n int n_miss = X_miss.rows();\n\n std::default_random_engine generator;\n std::chi_squared_distribution chi(n_obs - 3); \n\n // Fit linear model only on the observed values.\n LinearModel regmod;\n regmod.fit(X_obs, y_obs);\n Eigen::VectorXd beta_hat = regmod.beta;\n\n // Random draws for sigma^2 from the scaled inverse Chi^2-distribution.\n double sigma_sq_tilde = (n_obs - 3) * pow(regmod.sigma, 2) / chi(generator);\n\n // Random draws for beta from a mv. normal distribution.\n Eigen::MatrixXd variance = regmod.inv_matrix_prod * sigma_sq_tilde;\n normal_random_variable sample {beta_hat, variance};\n Eigen::VectorXd beta_tilde = sample();\n Eigen::VectorXd means = regmod.design * beta_tilde;\n\n // Draw the imputations for y from a normal distribution.\n Eigen::VectorXd y_imputation(n_miss);\n for (int i = 0; i < n_miss; i++) \n {\n std::normal_distribution normal(means[i], sqrt(sigma_sq_tilde));\n y_imputation[i] = normal(generator);\n }\n\n return y_imputation;\n}\n\n\n// Performs M multiple imputations using stochastic_regression\n// and a Bayesian linear model. \nEigen::MatrixXd multiple_imputation(int num_imp, Eigen::MatrixXd X_miss, Eigen::MatrixXd X_obs, Eigen::VectorXd y_obs) \n{\n Eigen::MatrixXd imputations(X_obs.rows() + X_miss.rows(), num_imp);\n\n for (int m = 0; m < num_imp; m++)\n {\n // Calculate imputations for y and concantenate to one vector.\n Eigen::VectorXd y_imp = stochastic_regression_imputation(X_miss, X_obs, y_obs);\n Eigen::VectorXd y_complete(y_obs.size() + y_imp.size());\n y_complete << y_obs, y_imp;\n imputations.col(m) = y_complete;\n }\n\n return imputations;\n}\n\n\n// Performs M multiple imputations using stochastic_regression\n// and a Bayesian linear model. This function wraps the calculation\n// output for the use in a parallel setting.\nvoid parallel_multiple_imputation(int num_imp, Eigen::MatrixXd X_miss, Eigen::MatrixXd X_obs, Eigen::VectorXd y_obs, std::promise && p) \n{ \n Eigen::MatrixXd imputations(X_obs.rows() + X_miss.rows(), num_imp);\n imputations = multiple_imputation(num_imp, X_miss, X_obs, y_obs);\n p.set_value(imputations);\n}\n\n\n// Calculates the time difference between \"end\" and \"begin\" and prints\n// the result to the terminal.\nvoid print_runtime(std::chrono::steady_clock::time_point begin, std::chrono::steady_clock::time_point end, const std::string & msg)\n{\n std::cout << msg << \" Runtime = \" << std::chrono::duration_cast(end - begin).count() << \" [µs]\" << std::endl;\n std::cout << msg << \" Runtime = \" << std::chrono::duration_cast(end - begin).count() / 1e6 << \" [s]\" << std::endl;\n}\n \n\n// Prints the global mean of an matrix to the terminal.\n// If col_means is ture, the mean for each column of \n// the data matrix is printed.\nvoid print_means(Eigen::MatrixXd data, const std::string & msg, bool col_means = false)\n{\n std::cout << msg << \" Mean = \" << data.mean() << std::endl;\n std::cout << std::endl;\n\n if (col_means) \n {\n for (int i = 0; i < data.cols(); i++)\n {\n std::cout << \"Mean of imputation \" << i << \" is \" << data.col(i).mean() << std::endl;\n }\n }\n}\n\n\nint main() \n{ \n // Imputation parameters.\n int num_imp = 10000;\n\n // Load the data.\n Eigen::MatrixXd X_miss = read_matrix_csv(\"data/X_miss.csv\");\n Eigen::VectorXd y_miss = read_matrix_csv(\"data/y_miss.csv\");\n Eigen::MatrixXd X_obs = read_matrix_csv(\"data/X_obs.csv\");\n Eigen::VectorXd y_obs = read_matrix_csv(\"data/y_obs.csv\");\n Eigen::MatrixXd imputations(X_obs.rows() + X_miss.rows(), num_imp);\n\n std::chrono::steady_clock::time_point begin, end;\n\n // Calculate one imputation.\n //Eigen::VectorXd y_imp = stochastic_regression_imputation(X_miss, X_obs, y_obs);\n //std::cout << y_imp << std::endl;\n\n // Calculate multiple imputations in serial execution.\n begin = std::chrono::steady_clock::now();\n imputations = multiple_imputation(num_imp, X_miss, X_obs, y_obs);\n end = std::chrono::steady_clock::now();\n print_runtime(begin, end, \"(Serial)\");\n print_means(imputations, \"(Serial)\");\n //std::cout << imputations << std::endl;\n\n // Parallel version using std::thread. Here the number of\n // multiple imputations is distributed to different threads.\n int num_cores = std::thread::hardware_concurrency();\n begin = std::chrono::steady_clock::now();\n \n std::vector threads;\n std::vector> futures;\n\n for (int i = 0; i < num_cores; i++) \n {\n std::promise p;\n futures.push_back(p.get_future());\n threads.push_back(std::thread(parallel_multiple_imputation, num_imp / num_cores, X_miss, X_obs, y_obs, std::move(p)));\n }\n \n for (auto &th : threads) \n {\n th.join();\n }\n\n // Get the results from the parallel execution and \n // assemble them in a matrix.\n int col_counter = 0;\n for (auto &f : futures) \n { \n imputations.block(0, (num_imp / num_cores) * col_counter, imputations.rows(), num_imp / num_cores) = f.get();\n col_counter++;\n }\n \n end = std::chrono::steady_clock::now();\n std::cout << \"Running in parallel on \" << num_cores << \" core(s).\" << std::endl;\n print_runtime(begin, end, \"(Parallel)\");\n print_means(imputations, \"(Parallel)\");\n \n return 0;\n}\n", "meta": {"hexsha": "d5d4b05c32513797d233de256bf7118361575f27", "size": 10457, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/C++/stochastic_regression.cpp", "max_stars_repo_name": "JoshuaSimon/Parallelization-Of-MI-Algorithms", "max_stars_repo_head_hexsha": "50767be6e9e5d70e9e927cac9f33dfa522916fd1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-01-27T15:45:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T15:59:52.000Z", "max_issues_repo_path": "src/C++/stochastic_regression.cpp", "max_issues_repo_name": "JoshuaSimon/Parallelization-Of-MI-Algorithms", "max_issues_repo_head_hexsha": "50767be6e9e5d70e9e927cac9f33dfa522916fd1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/C++/stochastic_regression.cpp", "max_forks_repo_name": "JoshuaSimon/Parallelization-Of-MI-Algorithms", "max_forks_repo_head_hexsha": "50767be6e9e5d70e9e927cac9f33dfa522916fd1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4089456869, "max_line_length": 157, "alphanum_fraction": 0.6662522712, "num_tokens": 2638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898254600903, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6839452871981956}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n// Input: m Vector, k Vector, l Vector (even though it is not needed as we later realized), dimension N\nEigen::ArrayXcd springchain(Eigen::VectorXd& m, Eigen::VectorXd& k, Eigen::VectorXd& l, int N){\n // Initialisation of relative coordinates x (in protocol eta)\n Eigen::VectorXd x(N);\n x(0) = 0.;\n std::partial_sum(l.begin(), l.end(), &x(1), std::plus());\n\n // Definition of M^-1 and K matrix\n Eigen::MatrixXd M_inv = m.asDiagonal().inverse();\n Eigen::MatrixXd K(N, N);\n for (int i= 0; i < N; i++){\n for(int j= 0; j <= i; j++){\n K(i,j) = 0;\n if(i==j){\n if(i == 0){\n K(i,i) = k(i);\n K(i, i+1) = -k(i);\n }\n else if(i== N-1){\n K(i,i) = k(i-1);\n K(i, i-1) = -k(i-1);\n }\n else{\n K(i,i) = k(i-1)+k(i);\n K(i, i-1) = -k(i-1);\n K(i, i+1) = -k(i);\n }\n }\n }\n }\n Eigen::MatrixXd A = M_inv*K;\n // Calculate Eigenvalues \n return A.eigenvalues();\n}\n\n// Lanczos algorithm, sadly not finished. Returns only the tridiag matrix\nEigen::MatrixXd lanczos(Eigen::MatrixXd& A){\n\n // Implementation as defined in the lecture\n\n // q matrix with the new basis q\n Eigen::MatrixXd q(A.rows(), A.cols()+2);\n q(0,0) = 0;\n q(0,1) = 1;\n // gamma vector with all the normalisations\n Eigen::VectorXd gamma(A.cols()+2);\n gamma(1) = 1;\n // delta vector with diagonal elements of the new tridiag matrix\n Eigen::VectorXd delta(A.cols()+1);\n \n // the new basis build with a for loop\n for (int i=1; i<=A.rows(); i++){\n gamma(i+1) = std::sqrt(q.col(i).transpose()* q.col(i));\n delta(i) = q.col(i).transpose()*A*q.col(i);\n q.col(i+1) = 1/gamma(i+1) * (A- delta(1)*Eigen::MatrixXd::Identity(A.rows(), A.cols()))*q.col(i) - gamma(i)*q.col(i-1);\n }\n\n // make new tridiag matrix based on gamma-, and delta-vector, with some error\n Eigen::MatrixXd T(A.rows(), A.cols());\n for (int i= 0; i < A.rows()-1; i++){\n T(i,i) = delta(i+1);\n T(i, i+1) = gamma(i+3);\n T(i+1, i) = gamma(i+3);\n }\n T(A.rows()-1, A.cols()-1) = delta(A.cols());\n\n return T;\n \n // Begin of Jacobi-Rotation Implementation, sadly not finished\n Eigen::MatrixXd Z = Eigen::MatrixXd::Identity(T.rows(), T.cols());\n\n for (int i=0; i < T.rows()-1; i++){\n Eigen::JacobiRotation J;\n Eigen::MatrixXd J_1 = Eigen::MatrixXd::Identity(T.rows(), T.cols());\n J.makeJacobi(T(Eigen::seq(i,i+1), Eigen::seq(i,i+1)), 0, 1);\n J_1(Eigen::seq(i,i+1), Eigen::seq(i,i+1)) << J.c(), J.s(), -J.s(), J.c();\n T(Eigen::seq(i,i+1), Eigen::seq(i,i+1)).applyOnTheLeft(0, 1, J.adjoint());\n T(Eigen::seq(i,i+1), Eigen::seq(i,i+1)).applyOnTheRight(0, 1, J);\n Z = Z * J_1;\n }\n\n}\n\nint main()\n{\n\t// Ex. 1\n // N is the dimension, here 10 for part b)\n int N = 10;\n Eigen::VectorXd m(N), k(N-1), l(N-1);\n // Initialisation of m, k and l\n for (int i=0; i\n#include \n//#include \n//#include \n//#include \n//#include \n\n//tf2_ros::Buffer tfBuffer;\n//tf2_ros::TransformListener tfListener(tfBuffer);\n\n\n/*\nusing namespace Eigen;\n//Roll pitch and yaw in Radians\nQuaternionf euler2quaternions(double roll, double pitch, double yaw){\n Quaternionf q;\n q = AngleAxisf(roll, Vector3f::UnitX())\n * AngleAxisf(pitch, Vector3f::UnitY())\n * AngleAxisf(yaw, Vector3f::UnitZ());\n return q;\n}*/\n/*\ngeometry_msgs::TransformStamped broadcast_tf(std:string parent, std:string child, std::vector trans, double[] rot){\n geometry_msgs::TransformStamped t;\n t.header.frame_id = parent;\n t.child_frame_id = child;\n t.transform.translation.x = x;\n t.transform.translation.y = y;\n t.transform.translation.z = z;\n tf2::Quaternion q;\n q.setRPY(rot[0], rot[1], rot[2]);\n q.normalize();\n t.transform.rotation.x = q.x();\n t.transform.rotation.y = q.y();\n t.transform.rotation.z = q.z();\n t.transform.rotation.w = q.w();\n\n return t;\n}*/\n\n\nstd::vector lla2nedPiren(double lat_deg, double long_deg, double altitude){\n double lat0_deg = 63.4389029083;\n double long0_deg = 10.39908278;\n double altitude0 = 39.923;\n\n double deg2rad = M_PI/180;\n double rad2deg = 180/M_PI;\n\n double lat_rad = lat_deg * deg2rad;\n double long_rad = long_deg * deg2rad;\n double lat0_rad = lat0_deg * deg2rad;\n double long0_rad = long0_deg * deg2rad;\n\n //From vik 2012 - page 4 - table 1.1\n double re = 6378137.0; // [m]\n double rp = 6356752.0; // [m]\n double rad_curve = pow(re,2) / (sqrt(pow(re,2) * pow(cos(lat_rad),2) + pow(rp,2) * pow(sin(lat_rad),2))); //N in vik\n\n // LLA to ECEF\n double xe = (rad_curve + altitude) * cos(lat_rad) * cos(long_rad);\n double ye = (rad_curve + altitude) * cos(lat_rad) * sin(long_rad);\n double ze = ((pow(rp, 2) / pow(re, 2)) * rad_curve + altitude) * sin(lat_rad);\n\n double xe0 = (rad_curve + altitude0) * cos(lat0_rad) * cos(long0_rad);\n double ye0 = (rad_curve + altitude0) * cos(lat0_rad) * sin(long0_rad);\n double ze0 = ((pow(rp, 2) / pow(re, 2)) * rad_curve + altitude0) * sin(lat0_rad);\n\n // ECEF to NED\n double cosPhi = cos(lat0_rad);\n double sinPhi = sin(lat0_rad);\n double cosLambda = cos(long0_rad);\n double sinLambda = sin(long0_rad);\n\n double dist = cosLambda * xe + sinLambda * ye;\n double uNorth = -sinPhi * dist + cosPhi * ze;\n double vEast = -sinLambda * xe + cosLambda * ye;\n double wDown = -(cosPhi * dist + sinPhi * ze);\n\n // ECEF0 to NED0\n double cosPhi0 = cosPhi;\n double sinPhi0 = sinPhi;\n double cosLambda0 = cosLambda;\n double sinLambda0 = sinLambda;\n\n double dist0 = cosLambda0 * xe0 + sinLambda0 * ye0;\n double vEast0 = -sinLambda0 * xe0 + cosLambda0 * ye0;\n double wDown0 = -(cosPhi0 * dist0 + sinPhi0 * ze0);\n double uNorth0 = -sinPhi0 * dist0 + cosPhi0 * ze0;\n\n // Compute difference\n double N = uNorth - uNorth0; // [m]\n double E = vEast - vEast0; // [m]\n double D = wDown - wDown0; // [m]\n\n std::vector NED;\n NED.push_back(N);\n NED.push_back(E);\n NED.push_back(D);\n\n return NED;\n\n}\n\n\n\nstd::vector lla2ned(double lat_deg, double long_deg, double altitude, double lat0_deg, double long0_deg, double altitude0){\n double deg2rad = M_PI/180;\n double rad2deg = 180/M_PI;\n\n double lat_rad = lat_deg * deg2rad;\n double long_rad = long_deg * deg2rad;\n double lat0_rad = lat0_deg * deg2rad;\n double long0_rad = long0_deg * deg2rad;\n\n //From vik 2012 - page 4 - table 1.1\n double re = 6378137.0; // [m]\n double rp = 6356752.0; // [m]\n double rad_curve = pow(re,2) / (sqrt(pow(re,2) * pow(cos(lat_rad),2) + pow(rp,2) * pow(sin(lat_rad),2))); //N in vik\n\n // LLA to ECEF\n double xe = (rad_curve + altitude) * cos(lat_rad) * cos(long_rad);\n double ye = (rad_curve + altitude) * cos(lat_rad) * sin(long_rad);\n double ze = ((pow(rp, 2) / pow(re, 2)) * rad_curve + altitude) * sin(lat_rad);\n\n double xe0 = (rad_curve + altitude0) * cos(lat0_rad) * cos(long0_rad);\n double ye0 = (rad_curve + altitude0) * cos(lat0_rad) * sin(long0_rad);\n double ze0 = ((pow(rp, 2) / pow(re, 2)) * rad_curve + altitude0) * sin(lat0_rad);\n\n // ECEF to NED\n double cosPhi = cos(lat0_rad);\n double sinPhi = sin(lat0_rad);\n double cosLambda = cos(long0_rad);\n double sinLambda = sin(long0_rad);\n\n double dist = cosLambda * xe + sinLambda * ye;\n double uNorth = -sinPhi * dist + cosPhi * ze;\n double vEast = -sinLambda * xe + cosLambda * ye;\n double wDown = -(cosPhi * dist + sinPhi * ze);\n\n // ECEF0 to NED0\n double cosPhi0 = cosPhi;\n double sinPhi0 = sinPhi;\n double cosLambda0 = cosLambda;\n double sinLambda0 = sinLambda;\n\n double dist0 = cosLambda0 * xe0 + sinLambda0 * ye0;\n double vEast0 = -sinLambda0 * xe0 + cosLambda0 * ye0;\n double wDown0 = -(cosPhi0 * dist0 + sinPhi0 * ze0);\n double uNorth0 = -sinPhi0 * dist0 + cosPhi0 * ze0;\n\n // Compute difference\n double N = uNorth - uNorth0; // [m]\n double E = vEast - vEast0; // [m]\n double D = wDown - wDown0; // [m]\n\n std::vector NED;\n NED.push_back(N);\n NED.push_back(E);\n NED.push_back(D);\n\n return NED;\n\n}\n\n\nstd::vector objectCoord2NED(double x, double y, double z, double n_MA, double e_MA, double d_MA, double heading_MA){\n double E = (x*cos(heading_MA) - sin(heading_MA)*z)+e_MA;\n double N = (x*sin(heading_MA) + cos(heading_MA)*z)+n_MA;\n double D = d_MA;\n/*\n double N = (x+n_MA)*cos(heading_MA) - sin(heading_MA)*(y+e_MA);\n double E = (x+n_MA)*sin(heading_MA) + cos(heading_MA)*(y+e_MA);\n double D = d_MA;\n*/\n std::vector NED;\n NED.push_back(N);\n NED.push_back(E);\n NED.push_back(D);\n\n return NED;\n}\n\n/*\nstd::vector objectCoord_to_NED(double[] object_coord, std::vector ma_NED, double ma_heading){\n //Parent=piren, child=gps_antenna, translation = NED posisjon nå, orientation\n //transform fra origio til nåværende posisjon\n\n geometry_msgs::TransformStamped t = broadcast_tf(\"piren\", \"camera_frame\", ma_NED, [0, 0, heading]);\n //NED i forhold til camera frame\n geometry_msgs::TransformStamped tarns = t.lookup_transform(\"camera_frame\", \"camera_frame\", 2);\n\n double N_cam = trans.transform.translation.x + object_coord[0];\n double E_cam = trans.transform.translation.y + object_coord[1];\n double D_cam = MA_d;\n\n std::vector NED_cam;\n NED_cam.push_back(N_cam);\n NED_cam.push_back(E_cam);\n NED_cam.push_back(D_cam);\n\n geometry_msgs::TransformStamped t1 = broadcast_tf(\"piren\", \"camera_frame\", ma_NED, [0, 0, heading]);\n\n return NED;\n\n\n}*/\n", "meta": {"hexsha": "4de3cced354b66d99783c95cd9b55dd3f290e19e", "size": 6886, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/custom_libraries/src/convert_to_NED.cpp", "max_stars_repo_name": "trineoo/stereo", "max_stars_repo_head_hexsha": "f76d6740e05b92b095bbcb20761d1b0ba0669eff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/custom_libraries/src/convert_to_NED.cpp", "max_issues_repo_name": "trineoo/stereo", "max_issues_repo_head_hexsha": "f76d6740e05b92b095bbcb20761d1b0ba0669eff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/custom_libraries/src/convert_to_NED.cpp", "max_forks_repo_name": "trineoo/stereo", "max_forks_repo_head_hexsha": "f76d6740e05b92b095bbcb20761d1b0ba0669eff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9473684211, "max_line_length": 131, "alphanum_fraction": 0.6488527447, "num_tokens": 2173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.931462503162843, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6838048121471666}} {"text": "#ifndef EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_CHAIN_HPP\n#define EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_CHAIN_HPP\n\n#include \n#include \n#include \n#include \n\n\nnamespace exactsolution{\n\nclass PartitionFunctionClassicalXYChain{\npublic :\n static std::string name() { return \"Exact partition function , classical XY, open boundary\"; }\n PartitionFunctionClassicalXYChain(double J,unsigned int num) : J_(J), num_(num) {}\n \n double operator()(double T) const {\n double value = 0.0;\n value = 2.0 * M_PI * boost::math::cyl_bessel_i(0,J_/T);\n value = 2.0 * M_PI * std::pow(value , num_-1);\n value += std::pow( std::sqrt(2.0 * M_PI * T), num_);\n return value;\n }\n\n double logZ(double T) const {\n double value = std::log(2.0 * M_PI);\n value += (double)(num_ - 1) * std::log(2.0 * M_PI * boost::math::cyl_bessel_i(0,J_/T));\n value += (double)(num_) * 0.5 * std::log(2.0 * M_PI * T );\n return value;\n }\n\nprivate :\n double J_;\n unsigned int num_;\n}; \n\n} //end namespce\n\n#endif //EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_CHAIN_HPP\n", "meta": {"hexsha": "3c87de2bd8ab56b00711b97b0af322f3311021d0", "size": 1139, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "clstatphys/clstatphys/physics/partition_function_classical_xy_chain.hpp", "max_stars_repo_name": "FIshikawa/ClassicalStatPhys", "max_stars_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clstatphys/clstatphys/physics/partition_function_classical_xy_chain.hpp", "max_issues_repo_name": "FIshikawa/ClassicalStatPhys", "max_issues_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T08:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T09:29:10.000Z", "max_forks_repo_path": "clstatphys/clstatphys/physics/partition_function_classical_xy_chain.hpp", "max_forks_repo_name": "FIshikawa/ClassicalStatPhys", "max_forks_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-18T03:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-21T22:58:27.000Z", "avg_line_length": 28.475, "max_line_length": 96, "alphanum_fraction": 0.6918349429, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465134460244, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6837930816850699}} {"text": "/**\n * @file crossprod.cc\n * @brief NPDE homework CrossProd code\n * @author Unknown, Oliver Rietmann\n * @date 31.03.2021\n * @copyright Developed at ETH Zurich\n */\n\n#include \"crossprod.h\"\n\n#include \n#include \n#include \n#include \n\nnamespace CrossProd {\n\n/* SAM_LISTING_BEGIN_0 */\nvoid tab_crossprod() {\n // Solve the cross-product ODE with the implicit RK method\n // defined in solve_imp_mid. Tabulate the norms of the results at all steps.\n //====================\n // Your code goes here\n\n // set data \n\n double T =10; \n int M =128; \n int c=1; \n Eigen::Vector3d y0(1.0, 1.0, 1.0); \n Eigen::Vector3d a(1,0,0); \n\n\n\n // define right hand side function fy\n auto f [a,c] (Eigen::Vector3d y) -> Eigen::Vector3d {\n return a.cross(y)+c*y.cross(a.cross(y)); \n }\n\n auto Jf [a,c] (Eigen::Vector3d y) -> Eigen::Matrix3d{\n Eigen::Matrix3d Jf; \n Jf << -c * (a(1) * y(1) + a(2) * y(2)),\n c * (2 * a(0) * y(1) - a(1) * y(0)) - a(2),\n a(1) + c * (2 * a(0) * y(2) - a(2) * y(0)),\n a(2) - c * (a(0) * y(1) - 2 * a(1) * y(0)),\n -c * (a(0) * y(0) + a(2) * y(2)),\n c * (2 * a(1) * y(2) - a(2) * y(1)) - a(0),\n -a(1) - c * (a(0) * y(2) - 2 * a(2) * y(0)),\n a(0) - c * (a(1) * y(2) - 2 * a(2) * y(1)),\n -c * (a(0) * y(0) + a(1) * y(1));\n return Jf; \n }\n\n // define the Jacobian of rhs\n\n std::vector sol_imp = solve_imp_mid(f, Jf, T, y0, M); \n\n std::cout << \"1. Implicit midpoint method\" << std::endl; \n std::cout << std::setw(10) << \"t\" << std::setw(15) << \"norm(y(t))\" << std::endl; \n\n for (int i=0; i sol_lin = sol_lin_mid(f, Jf, T, y0, M); \n\n std::cout << \"\\n2. Linear implicit midpoint method\" << std::endl; \n std::cout << std::setw(10) << \"t\" << std::setw(15) << \"norm(y(t))\" << std::endl; \n\n for (int i =0; i\n#include \n#include \n#include \n\n\nnamespace alma {\n/// Perform spline interpolation of a tabulated function Y(X) at\n/// Xtarget.\ninline Eigen::VectorXd splineInterpolation(\n const Eigen::Ref& X,\n const Eigen::Ref& Y,\n const Eigen::Ref& Xtarget) {\n Eigen::VectorXd result(Xtarget.size());\n\n // map X values to 1D chord lengths ranging from 0 to 1\n Eigen::VectorXd X_norm =\n (X.array() - X.minCoeff()) / (X.maxCoeff() - X.minCoeff());\n\n // construct cubic spline over the base points\n typedef Eigen::Spline Spline1D;\n Spline1D S(Eigen::SplineFitting::Interpolate(\n Y.transpose(), 3, X_norm.transpose()));\n\n // convert Xtarget values to their equivalent chord length\n Eigen::VectorXd Xtarget_norm =\n (Xtarget.array() - X.minCoeff()) / (X.maxCoeff() - X.minCoeff());\n\n // obtain spline value at each of these chord lengths\n\n for (int nx = 0; nx < Xtarget.size(); nx++) {\n result(nx) = S(Xtarget_norm(nx))(0);\n }\n\n return result;\n}\n\n\n/// Perform linear interpolation of a tabulated function Y(X) at\n/// Xtarget.\n/// X must be strictly ascending (no duplicate entries).\ninline Eigen::VectorXd linearInterpolation(\n const Eigen::Ref& X,\n const Eigen::Ref& Y,\n const Eigen::Ref& Xtarget) {\n Eigen::VectorXd result(Xtarget.size());\n int N = X.size();\n\n // perform linear interpolation for each of the specified targets\n\n for (int nx = 0; nx < Xtarget.size(); nx++) {\n if (Xtarget(nx) < X(0)) {\n std::cout << \"alma::linearInterpolation > \" << std::endl;\n std::cout << \"WARNING: encountered target element out of bounds.\"\n << std::endl;\n std::cout << \"Interpolated result will be clipped.\" << std::endl;\n\n result(nx) = X(0);\n }\n\n else if (Xtarget(nx) > X(N - 1)) {\n std::cout << \"alma::linearInterpolation > \" << std::endl;\n std::cout << \"WARNING: encountered target element out of bounds.\"\n << std::endl;\n std::cout << \"Interpolated result will be clipped.\" << std::endl;\n\n result(nx) = X(N - 1);\n }\n\n else {\n // use bisection algorithm to determine base array bin the target\n // sits\n // in.\n\n int leftindex = 0;\n int rightindex = N - 1;\n\n while (rightindex - leftindex > 1) {\n int midindex = (leftindex + rightindex) / 2;\n\n if (X(midindex) > Xtarget(nx)) {\n rightindex = midindex;\n }\n else {\n leftindex = midindex;\n }\n }\n\n double yleft = Y(leftindex);\n double yright = Y(rightindex);\n double xleft = X(leftindex);\n double xright = X(rightindex);\n\n result(nx) = yleft + (Xtarget(nx) - xleft) * (yright - yleft) /\n (xright - xleft);\n }\n }\n\n return result;\n}\n\n\n\n\n\nclass CubicSpline1D {\nprivate:\n Eigen::MatrixXd splines;\n std::vector x;\n\npublic:\n /// Default constructors\n CubicSpline1D() = default;\n CubicSpline1D(const CubicSpline1D& A) = default;\n\n /// Constructor from data\n CubicSpline1D(const Eigen::Ref& X,\n const Eigen::Ref& Y);\n\n /// Build interpolation from given data\n /// it discards the data\n void BuildCubicSpline1D(const Eigen::Ref& X,\n const Eigen::Ref& Y);\n\n /// Interpolates Y for newX\n double Interpolate(double newX);\n};\n\n\n} // namespace alma\n", "meta": {"hexsha": "73f2313fb08aaf5affcbcdf2a684a9e544a92006", "size": 4583, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/interpolation.hpp", "max_stars_repo_name": "sousaw/BTE-Barna", "max_stars_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2022-02-07T03:36:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T13:11:20.000Z", "max_issues_repo_path": "include/interpolation.hpp", "max_issues_repo_name": "sousaw/BTE-Barna", "max_issues_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/interpolation.hpp", "max_forks_repo_name": "sousaw/BTE-Barna", "max_forks_repo_head_hexsha": "029ca43ef096c4b725d3aeb2955bc0df9ca544a9", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5533333333, "max_line_length": 77, "alphanum_fraction": 0.5978616627, "num_tokens": 1094, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.7690802264851919, "lm_q1q2_score": 0.6835268073917052}} {"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include \n#include \n\ntypedef long long nombre;\ntypedef std::vector vecteur;\ntypedef boost::rational fraction;\ntypedef std::pair paire;\n\nnamespace {\n fraction aire(const paire &A, const paire &B, const paire &C) {\n nombre abc = (B.first - A.first) * (C.second - A.second) - (C.first - A.first) * (B.second - A.second);\n if (abc < 0)\n abc = -abc;\n return fraction(abc, 2);\n }\n\n bool contient(const paire &A, const paire &B, const paire &C) {\n static const paire O = std::make_pair(0, 0);\n const fraction ABC = aire(A, B, C);\n const fraction OBC = aire(O, B, C);\n const fraction AOC = aire(A, O, C);\n const fraction ABO = aire(A, B, O);\n\n return (ABC == OBC + AOC + ABO);\n }\n}\n\nENREGISTRER_PROBLEME(102, \"Triangle containment\") {\n // Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≤ x, y ≤ 1000, such that a\n // triangle is formed.\n //\n // Consider the following two triangles:\n // \n // A(-340,495), B(-153,-910), C(835,-947)\n //\n // X(-175,41), Y(-421,-714), Z(574,-645)\n // \n // It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not.\n // \n // Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the co-ordinates of\n // one thousand \"random\" triangles, find the number of triangles for which the interior contains the origin.\n // \n // NOTE: The first two examples in the file represent the triangles in the example given above.\n std::ifstream ifs(\"data/p102_triangles.txt\");\n nombre resultat = 0;\n std::string ligne;\n while (ifs >> ligne) {\n std::vector v;\n boost::split(v, ligne, boost::is_any_of(\",\"));\n const paire A(stoll(v[0]), stoll(v[1]));\n const paire B(stoll(v[2]), stoll(v[3]));\n const paire C(stoll(v[4]), stoll(v[5]));\n if (contient(A, B, C))\n ++resultat;\n }\n return std::to_string(resultat);\n}\n", "meta": {"hexsha": "73cb0158d6016ecd4b7f28a95a1bd920849ea312", "size": 2213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme102.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme1xx/probleme102.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme1xx/probleme102.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2786885246, "max_line_length": 117, "alphanum_fraction": 0.5892453683, "num_tokens": 603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6835139632779077}} {"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include \n#include \n\nnamespace fluid {\nnamespace algorithm {\n\nclass NNDSVD\n{\n\npublic:\n using MatrixXd = Eigen::MatrixXd;\n\n index process(RealMatrixView X, RealMatrixView W, RealMatrixView H,\n index minRank = 0, index maxRank = 200, double amount = 0.8,\n index method = 0) // 0 - NMF-SVD, 1 NNDSVDar, 2 NNDSVDa 3 NNDSVD\n {\n using namespace _impl;\n using namespace Eigen;\n MatrixXd XT = asEigen(X).transpose();\n MatrixXd WT = asEigen(W).transpose();\n MatrixXd HT = asEigen(H).transpose();\n\n assert(amount > 0 || minRank > 0);\n\n BDCSVD svd(XT, ComputeThinV | ComputeThinU);\n\n MatrixXd U = svd.matrixU();\n MatrixXd V = svd.matrixV().transpose();\n VectorXd s = svd.singularValues();\n MatrixXd S = svd.singularValues().asDiagonal();\n index k = 0;\n if (amount == 0)\n k = minRank;\n else\n {\n double current = 0;\n double total = s.sum();\n while ((current / total) < amount) current += s[k++];\n }\n if (k < minRank) k = minRank;\n if (k > maxRank) k = maxRank;\n\n if (method == 0)\n {\n WT.block(0, 0, WT.rows(), k) = U.block(0, 0, U.rows(), k).array().abs();\n HT.block(0, 0, k, HT.cols()) =\n (S.block(0, 0, k, S.cols()) * V).array().abs();\n }\n else\n {\n // avoid scaling for NMF with normalized W\n WT.col(0) = U.col(0).array().abs();\n HT.row(0) = sqrt(s(0)) * V.row(0).array().abs();\n\n for (index j = 1; j < k; j++)\n {\n VectorXd x = U.col(j);\n VectorXd y = V.row(j);\n VectorXd xP = x.array().max(0.0);\n VectorXd yP = y.array().max(0.0);\n VectorXd xN = x.array().min(0.0).abs();\n VectorXd yN = y.array().min(0.0).abs();\n double xPNorm = xP.norm();\n double yPNorm = yP.norm();\n double xNNorm = xN.norm();\n double yNNorm = xN.norm();\n double mP = xPNorm * yPNorm;\n double mN = xNNorm * yNNorm;\n ArrayXd u;\n ArrayXd v;\n double sigma;\n if (mP > mN)\n {\n u = xP / xPNorm;\n v = yP / yPNorm;\n sigma = mP;\n }\n else\n {\n u = xN / xNNorm;\n v = yN / yNNorm;\n sigma = mN;\n }\n auto lbd = std::sqrt(s[j] * sigma);\n WT.col(j) = u; // avoid scaling for NMF with normalized W\n HT.row(j) = lbd * v;\n }\n WT = WT.array().max(epsilon);\n HT = HT.array().max(epsilon);\n if (method == 1)\n {\n auto Wrand =\n MatrixXd::Random(WT.rows(), WT.cols()).array().abs() / 100.0;\n auto Hrand =\n MatrixXd::Random(HT.rows(), HT.cols()).array().abs() / 100.0;\n WT = (WT.array() < epsilon).select(Wrand, WT);\n HT = (HT.array() < epsilon).select(Hrand, HT);\n }\n else if (method == 2)\n {\n double mean = XT.mean();\n WT = (WT.array() < epsilon)\n .select(MatrixXd::Constant(WT.rows(), WT.cols(), mean), WT);\n HT = (HT.array() < epsilon)\n .select(MatrixXd::Constant(HT.rows(), HT.cols(), mean), HT);\n }\n }\n MatrixXd W1 = WT.transpose();\n W <<= asFluid(W1);\n MatrixXd H1 = HT.transpose();\n H <<= asFluid(H1);\n return k;\n }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "243eeda5d2aa5257dd664fa9a3ec5f066e6a7e14", "size": 3915, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/NNDSVD.hpp", "max_stars_repo_name": "jamesb93/flucoma-core", "max_stars_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/algorithms/public/NNDSVD.hpp", "max_issues_repo_name": "jamesb93/flucoma-core", "max_issues_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/algorithms/public/NNDSVD.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4360902256, "max_line_length": 80, "alphanum_fraction": 0.5463601533, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9511422172230211, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6834854695659527}} {"text": "// Copyright (c) 2017 Evan S Weinberg\n// A reference piece of code which computes matrix elements\n// of a reference sparse first derivative operator to fill a dense\n// Eigen matrix, then computes the spectrum and prints\n// the Eigenvalues.\n\n// This code is for real, indefinite matrices.\n// This code lives on github at github.com/weinbe2/eigens-with-eigen/\n\n#include \n#include \n#include \n#include \n\n// Borrow dense matrix eigenvalue routines.\n#include \n\nusing namespace std; \nusing namespace Eigen;\n\n\n// This is just for convenience. By default, all matrices\n// in Eigen are column major. You can replace \"Dynamic\"\n// with a specific number to template just one size.\n// You can also ust use \"MatrixXd\".\ntypedef Matrix dMatrix;\n// Likewise, we can use \"MatrixXcd\".\ntypedef Matrix, Dynamic, Dynamic, ColMajor> cMatrix;\n// We need both real and complex because, while the matrix itself is real,\n// the eigenvalues and eigenvectors can generically be complex.\n\n\n// Reference 1-D central difference operator\nvoid central_diff_1d(double* out, double* in, const int L, const double m2);\n\nint main(int argc, char** argv)\n{ \n double *in_real;\n double *out_real;\n complex *out_cplx; // needed for eigenvectors\n\n // Set output precision to be long.\n cout << setprecision(10);\n\n // Basic information about the lattice.\n const int length = 8;\n const double mass = 0.001;\n\n // Print the basic info.\n std::cout << \"1D central difference operator, length \" << length << \", mass \" << mass << \", periodic boundary conditions.\\n\";\n std::cout << \"Change the length and mass by modifying the source.\\n\";\n \n // Allocate.\n in_real = new double[length];\n out_real = new double[length];\n out_cplx = new complex[length];\n\n // Zero out.\n for (int i = 0; i < length; i++)\n {\n in_real[i] = out_real[i] = 0.0;\n }\n\n ///////////////////////////\n // REAL, INDEFINITE CASE //\n ///////////////////////////\n\n std::cout << \"Real, Indefinite case.\\n\\n\";\n\n // Allocate a sufficiently gigantic matrix.\n dMatrix mat_real = dMatrix::Zero(length, length);\n\n // Form matrix elements. This is where it's important that\n // dMatrix is column major.\n for (int i = 0; i < length; i++)\n {\n // Set a point on the rhs for a matrix element.\n // If appropriate, zero out the previous point.\n if (i > 0)\n {\n in_real[i-1] = 0.0;\n }\n in_real[i] = 1.0;\n\n // Zero out the \"out\" vector. I defined \"laplace_1d\" to\n // not require this, but I put this here for generality.\n for (int j = 0; j < length; j++)\n out_real[j] = 0.0;\n\n // PUT YOUR MAT-VEC HERE.\n central_diff_1d(out_real, in_real, length, mass);\n\n // Copy your output into the right memory location.\n // If your data layout supports it, you can also pass\n // \"mptr\" directly as your \"output vector\" when you call\n // your mat-vec.\n double* mptr = &(mat_real(i*length));\n \n for (int j = 0; j < length; j++)\n {\n mptr[j] = out_real[j];\n }\n }\n\n // We've now formed the dense matrix. We print it here\n // as a sanity check if it's small enough.\n if (length <= 16)\n {\n std::cout << mat_real << \"\\n\";\n }\n\n // Get the eigenvalues and eigenvectors.\n EigenSolver< dMatrix > eigsolve_real_indef(length);\n eigsolve_real_indef.compute(mat_real);\n\n // Remark: if you only want the eigenvalues, you can call\n // eigsolve_real.compute(mat_real, EigenvaluesOnly);\n\n // Print the eigenvalues.\n // Note that the eigenvalues are of type \"cMatrix\" as typedef'd above or\n // MatrixXcd generically.\n cMatrix evals = eigsolve_real_indef.eigenvalues();\n std::cout << \"The eigenvalues are:\\n\" << evals << \"\\n\\n\";\n // You can also index individual eigenvalues as \"evals(i)\", where\n // \"i\" zero-indexes the eigenvalues.\n\n // Print the eigenvectors if the matrix is small enough.\n // As a remark, this also shows you how to access the eigenvectors. \n if (length <= 16)\n {\n for (int i = 0; i < length; i++)\n {\n // You can use \"VectorXcd\" as the type instead.\n cMatrix evec = eigsolve_real_indef.eigenvectors().col(i);\n \n // Print the eigenvector.\n std::cout << \"Eigenvector \" << i << \" equals:\\n\" << evec << \"\\n\\n\";\n\n // You can also copy the eigenvector into another array as such:\n for (int j = 0; j < length; j++)\n {\n out_cplx[j] = evec(j);\n }\n }\n }\n\n // Clean up.\n delete[] in_real;\n delete[] out_real;\n delete[] out_cplx;\n\n return 0;\n}\n\n\n\n// Reference 1-D central difference function.\nvoid central_diff_1d(double* out, double* in, const int L, const double mass)\n{\n // Central difference operator with periodic boundary conditions.\n for (int i = 0; i < L; i++)\n {\n out[i] = mass*in[i] + 0.5*(in[(i+1)%L] - in[(i-1+L)%L]);\n }\n\n // Done.\n return;\n}\n\n", "meta": {"hexsha": "2cb86fae8d29e35f0368b125e3e22c6c0cbb8e30", "size": 4854, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigens-with-eigen/real_indefinite/example_real_indefinite.cpp", "max_stars_repo_name": "weinbe2/utilities-esw", "max_stars_repo_head_hexsha": "b4d36b214316147c3ce850d9fa1fe80ac42dcc6c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "eigens-with-eigen/real_indefinite/example_real_indefinite.cpp", "max_issues_repo_name": "weinbe2/utilities-esw", "max_issues_repo_head_hexsha": "b4d36b214316147c3ce850d9fa1fe80ac42dcc6c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigens-with-eigen/real_indefinite/example_real_indefinite.cpp", "max_forks_repo_name": "weinbe2/utilities-esw", "max_forks_repo_head_hexsha": "b4d36b214316147c3ce850d9fa1fe80ac42dcc6c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-01-22T21:51:46.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-22T21:51:46.000Z", "avg_line_length": 28.5529411765, "max_line_length": 127, "alphanum_fraction": 0.6456530696, "num_tokens": 1350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110368115781, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6833891378622109}} {"text": "#include \n#include \n#include \n#include \n#include \"../simple_lib/include/two_layer_net.h\"\n\nusing namespace Eigen;\nusing namespace MyDL;\n\nint main(){\n using std::cout;\n using std::endl;\n using std::string;\n using std::map;\n\n int batch_size = 2;\n int input_size = 2;\n int hidden_size = 3;\n int output_size = 2;\n\n // int batch_size = 3;\n // int input_size = 2;\n // int hidden_size = 3;\n // int output_size = 5;\n\n// int batch_size = 5;\n// int input_size = 28 * 28;\n// int hidden_size = 100;\n// int output_size = 10;\n\n TwoLayerNet net(input_size, hidden_size, output_size, 0.01);\n\n MatrixXd X = MatrixXd::Random(batch_size, input_size);\n MatrixXd y; // (batch_size, output_size)\n MatrixXd t = MatrixXd::Zero(batch_size, output_size);\n// MatrixXd t = MatrixXd::Random(batch_size, output_size);\n double loss;\n double accuracy;\n map grads, numerical_grads;\n\n X = -2 * MatrixXd::Identity(2, 2) + MatrixXd::Ones(2, 2);\n t = MatrixXd::Identity(2, 2);\n\n // X << 1, 2,\n // 3, 4,\n // 5, 6;\n // t << 0, 1, 0, 0, 0,\n // 0, 0, 0, 1, 0,\n // 0, 0, 0, 1, 0;\n \n y = net.predict(X);\n cout << \"y = \" << y << endl; // predictの結果は、行方向に総和を取った場合、「1」となっていることを確認\n\n loss = net.loss(X, t);\n cout << \"loss: \" << loss << endl;\n\n accuracy = net.accuracy(X, t);\n cout << \"accuracy: \" << accuracy << endl; // この入力の場合、accuracyは0.666..が正解\n\n grads = net.gradient(X, t);\n cout << \"gradient of W1: \" << grads[\"W1\"] << endl;\n cout << \"gradient of W2: \" << grads[\"W2\"] << endl;\n cout << \"gradient of b1: \" << grads[\"b1\"] << endl;\n cout << \"gradient of b2: \" << grads[\"b2\"] << endl;\n\n cout << \"numerical gradient\" << endl;\n numerical_grads = net.numerical_gradient(X, t);\n cout << \"gradient of W1: \" << numerical_grads[\"W1\"] << endl;\n cout << \"gradient of W2: \" << numerical_grads[\"W2\"] << endl;\n cout << \"gradient of b1: \" << numerical_grads[\"b1\"] << endl;\n cout << \"gradient of b2: \" << numerical_grads[\"b2\"] << endl;\n\n return 0;\n}", "meta": {"hexsha": "13374538c22c396fa3f28e151fed8ad3549d9c96", "size": 2120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch4/test_two_layer_net.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "ch4/test_two_layer_net.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch4/test_two_layer_net.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6486486486, "max_line_length": 76, "alphanum_fraction": 0.5702830189, "num_tokens": 713, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102419, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6833606484180889}} {"text": "#ifndef AMT_ML_MODEL_LINEAR_REGRESSION_OPTIMIZER_HPP\n#define AMT_ML_MODEL_LINEAR_REGRESSION_OPTIMIZER_HPP\n\n#include \n#include \n\nnamespace amt::regression{\n \n struct default_opt{\n\n auto operator()(arma::Mat& beta, arma::Mat const& x, arma::Mat const& y, double lm) const {\n // x_t = x^T\n auto x_t = x.t();\n \n // xt_y = x^T * y\n auto xt_y = x_t * y;\n\n if( lm == 0 ){\n // xt_x = x^T * x\n auto xt_x = x_t * x;\n\n // (X * X^T) * B = X^T * Y\n beta = arma::solve(xt_x,xt_y,arma::solve_opts::fast);\n }else{\n \n arma::Mat l_I = arma::eye(x.n_cols, x.n_cols) * lm;\n\n // xt_x = x^T * x + l_I\n auto xt_x_lI = ( x_t * x ) + l_I;\n\n // (X * X^T) * B = X^T * Y\n beta = arma::solve(xt_x_lI,xt_y,arma::solve_opts::fast);\n }\n\n }\n\n };\n \n struct gradient_descent{\n\n constexpr gradient_descent() noexcept = default;\n constexpr gradient_descent(gradient_descent const& other) noexcept = default;\n constexpr gradient_descent(gradient_descent && other) noexcept = default;\n constexpr gradient_descent& operator=(gradient_descent const& other) noexcept = default;\n constexpr gradient_descent& operator=(gradient_descent && other) noexcept = default;\n ~gradient_descent() = default;\n \n constexpr gradient_descent(double alpha, std::size_t iter)\n : alpha(alpha)\n , iteration(iter)\n {}\n\n auto operator()(arma::Mat& beta, arma::Mat const& x, arma::Mat const& y, double lm) const {\n beta.resize(x.n_cols, 1ul);\n beta.randu();\n if( lm == 0.0 )\n eval(beta,x,y,lm);\n else\n eval(beta,x,y);\n }\n\n // double compute_cost(arma::Mat const& beta, arma::Mat const& x, arma::Mat const& y){\n // auto temp = ( x * beta ) - y;\n // auto m = 2 * x.n_rows;\n // auto J = ( temp * temp.t() ) / static_cast(m);\n // return J[0];\n // }\n\n void eval(arma::Mat& beta, arma::Mat const& x, arma::Mat const& y, double lm) const{\n auto m = alpha / static_cast(x.n_rows);\n auto reg_coef = m * lm;\n\n auto x_t = x.t();\n for( auto i = 0u; i < iteration; ++i ){\n auto p = ( x * beta ) - y;\n auto temp = m * (x_t * p);\n beta -= ( temp + ( reg_coef * beta ) );\n }\n }\n\n void eval(arma::Mat& beta, arma::Mat const& x, arma::Mat const& y) const{\n auto m = alpha / static_cast(x.n_rows);\n auto x_t = x.t();\n for( auto i = 0u; i < iteration; ++i ){\n auto p = ( x * beta ) - y;\n auto temp = m * (x_t * p);\n beta -= temp;\n }\n }\n\n\n double alpha{0.01};\n std::size_t iteration{1500};\n };\n\n template\n inline static constexpr bool is_default_opt_v = std::is_same_v;\n\n template\n inline static constexpr bool is_gradient_descent_v = std::is_same_v;\n\n} // namespace amt::regression\n\n\n#endif\n", "meta": {"hexsha": "34b798080edf779b24025bffc4cd793fdbc1a044", "size": 3488, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/model/LinearRegression/optimizer.hpp", "max_stars_repo_name": "amitsingh19975/ML-v2", "max_stars_repo_head_hexsha": "0201ff66a25635d8d165f0299a18b3843bdbbc97", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-13T07:59:05.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T07:59:05.000Z", "max_issues_repo_path": "include/model/LinearRegression/optimizer.hpp", "max_issues_repo_name": "amitsingh19975/ML-v2", "max_issues_repo_head_hexsha": "0201ff66a25635d8d165f0299a18b3843bdbbc97", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/model/LinearRegression/optimizer.hpp", "max_forks_repo_name": "amitsingh19975/ML-v2", "max_forks_repo_head_hexsha": "0201ff66a25635d8d165f0299a18b3843bdbbc97", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9056603774, "max_line_length": 123, "alphanum_fraction": 0.5126146789, "num_tokens": 899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894520743981, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6831572232738374}} {"text": "/**\n * @file eigen.cpp\n * @author Wei Du\n *\n * @version 0.1\n * @date 2021-08-18\n */\n\n// STL include\n#include \n#include \n#include \n\n// external include\n#include \n#include \n\n/*\n * int main() {\n * // x, y, z, w\n * std::array arr{0.3, 0.27, 0, 1.0};\n * Eigen::Vector4d vct{0.3, 0.27, 0, 1};\n *\n * // Eigen::Quaterniond quat1(vct(0), vct(1), vct(2), vct(3));\n * // Eigen::Quaterniond quat2(arr[0], arr[1], arr[2], arr[3]);\n * Eigen::Quaterniond quat1(vct.data());\n * Eigen::Quaterniond quat2(arr.data());\n *\n * printf(\"should be: %.2f %.2f %.2f %.2f\\n\", arr[0], arr[1], arr[2], arr[3]);\n * printf(\"%.2f %.2f %.2f %.2f\\n\", quat1.x(), quat1.y(), quat1.z(),\n * quat1.w()); printf(\"%.2f %.2f %.2f %.2f\\n\", quat2.x(), quat2.y(), quat2.z(),\n * quat2.w()); return 0;\n * }\n */\n\n/*\n * int main() {\n * Eigen::VectorXd v1(4);\n * Eigen::Vector3d v2{0.1, 0.2, 0.3};\n *\n * v1.head(3) = v2;\n * v1(3) = 0.8;\n * std::cout << v1 << std::endl;\n * return 0;\n * }\n */\n\n/*\nint main() {\n Eigen::Vector2d tran{0.2, 0.3};\n Eigen::Rotation2Dd ori(0.785398);\n\n Eigen::Affine2d pose;\n pose.setIdentity();\n pose.translate(tran);\n pose.rotate(ori);\n\n Eigen::Vector2d origin{0.1, 0.0};\n Eigen::Vector2d newpt = pose * origin;\n std::cout << newpt << std::endl;\n return 0;\n}\n*/\n\n/*\nint main() {\n Eigen::Vector3d vct1;\n Eigen::VectorXd vct2;\n if (vct1.isApprox(vct2)) {\n printf(\"they are the same\\n\");\n } else {\n printf(\"they are not the same\\n\");\n }\n std::cout << vct1 << std::endl;\n\n return 0;\n}\n*/\n\n/*\n * int main() {\n * Eigen::MatrixXd mt;\n * mt.resize(1000, 1000);\n * mt.fill(-1);\n * std::cout << mt;\n * return 0;\n * }\n */\n\n/*\n * int main() {\n * Eigen::MatrixXd mat(5, 4);\n * mat << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,\n * 20;\n *\n * std::cout << mat.rows() << std::endl;\n * mat.conservativeResize(mat.rows() - 2, 3);\n * std::cout << mat << std::endl;\n * std::cout << mat.rows() << std::endl;\n *\n * return 0;\n * }\n */\n\n/*\n * int main() {\n * const Eigen::Vector3d vec{0, 1, 0};\n * std::cout << vec << std::endl;\n * return 0;\n * }\n */\n\nint main() {\n Eigen::MatrixXd mt(2, 2);\n mt << 0, 1, 2, 3;\n\n Eigen::MatrixXd new_mt = mt;\n mt(1, 1) = 8;\n std::cout << mt << std::endl;\n std::cout << new_mt << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "6410a7c081b8f672e717ab25458f9e14c40dbc7b", "size": 2371, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen.cpp", "max_stars_repo_name": "SushiStar/Doubts", "max_stars_repo_head_hexsha": "18933aa380d8c47281dcae0c094b6eb485ce9ac2", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/eigen.cpp", "max_issues_repo_name": "SushiStar/Doubts", "max_issues_repo_head_hexsha": "18933aa380d8c47281dcae0c094b6eb485ce9ac2", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/eigen.cpp", "max_forks_repo_name": "SushiStar/Doubts", "max_forks_repo_head_hexsha": "18933aa380d8c47281dcae0c094b6eb485ce9ac2", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.1209677419, "max_line_length": 80, "alphanum_fraction": 0.5221425559, "num_tokens": 932, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677468516187, "lm_q2_score": 0.8056321983146848, "lm_q1q2_score": 0.6831501199960197}} {"text": "//============================================================================\n// Daniel J. Greenhoe\n// normed linear space R^2\n//============================================================================\n//=====================================\n// headers\n//=====================================\n#include \n#include \n#include \n#include \n#include \n#include \"r1.h\"\n#include \"r3.h\"\n\n\n//=====================================\n// VectR3\n//=====================================*/\n//-----------------------------------------------------------------------------\n//! \\brief Calculate magnitude of vector\n//-----------------------------------------------------------------------------\ndouble vectR3::mag(void) const \n{\n const double x = getx();\n const double y = gety();\n const double z = getz();\n const double magSq = x*x + y*y + z*z;\n const double magVal = sqrt( magSq );\n return magVal;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Convert polar (r, theta, phi) coordinate to rectangular (x,y,z) coordinate\n//-----------------------------------------------------------------------------\nvoid vectR3::polartoxyz(const double r, const double theta, const double phi)\n{\n const double x = r*cos(phi)*cos(theta);\n const double y = r*cos(phi)*sin(theta);\n const double z = r*sin(phi);\n otriple::put( x, y, z );\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Add vector q to vectR3 vector\n//-----------------------------------------------------------------------------\nvoid vectR3::operator+=(const vectR3 q)\n{\n Eigen::Map< Eigen::Vector3d > a( getdataa() );\n const Eigen::Map< const Eigen::Vector3d > b( q.getdata() );\n a += b;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Subtract vector q from vectR3 vector\n//-----------------------------------------------------------------------------\nvoid vectR3::operator-=(const vectR3 q)\n{\n Eigen::Map< Eigen::Vector3d > a( getdataa() );\n const Eigen::Map< const Eigen::Vector3d > b( q.getdata() );\n a -= b;\n}\n\n//=====================================\n// seqR3\n//=====================================*/\n//-----------------------------------------------------------------------------\n//! \\brief Constructor initializing seqR3 to 0\n//-----------------------------------------------------------------------------\nseqR3::seqR3(long M)\n{\n N=M;\n seqr3 = new vectR3[N];\n clear();\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Constructor initializing seqR3 to \n//-----------------------------------------------------------------------------\nseqR3::seqR3(long M, double u)\n{\n N = M;\n seqr3 = new vectR3[N];\n fill( u );\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Fill the seqR3 with a value 0\n//-----------------------------------------------------------------------------\nvoid seqR3::clear(void)\n{\n for( long n=0; n\n//-----------------------------------------------------------------------------\nvoid seqR3::fill(double u)\n{\n long n;\n for(n=0; n into the seqR3 x at location n\n//-----------------------------------------------------------------------------\nint seqR3::put(long n, double u, double v, double w)\n{\n if(n into the seqR3 x at location n\n//-----------------------------------------------------------------------------\nint seqR3::put(long n, vectR3 abc)\n{\n if(n0) fprintf(ptr,\"%s\",str1);\n for(n=start,m=1; n<=end; n++,m++){\n fprintf(ptr,\"(%6.3lf,%6.3lf,%6.3lf) \", seqr3[n].getx(), seqr3[n].gety(), seqr3[n].getz() );\n if(m%3==0)fprintf(ptr,\"\\n\");\n }\n if(strlen(str2)>0)fprintf(ptr,\"%s\",str2);\n }\n }\n\n//-----------------------------------------------------------------------------\n//! \\brief list contents of seqR3 using 1 digit per element\n//-----------------------------------------------------------------------------\nvoid seqR3::list1(void){\n long n,m;\n for(n=0,m=1; n a( p.getdataa() );\n const Eigen::Map< const Eigen::Vector3d > b( q.getdataa() );\n const Eigen::Vector3d c = a + b;\n const vectR3 r( c(0), c(1), c(2) );\n return r;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief operator: return p-q\n//-----------------------------------------------------------------------------\nvectR3 operator-(vectR3 p, vectR3 q){\n const Eigen::Map< const Eigen::Vector3d > a( p.getdataa() );\n const Eigen::Map< const Eigen::Vector3d > b( q.getdataa() );\n const Eigen::Vector3d c = a - b;\n const vectR3 r( c(0), c(1), c(2) );\n return r;\n }\n\n//-----------------------------------------------------------------------------\n//! \\brief operator: return -p\n//-----------------------------------------------------------------------------\nvectR3 operator-(vectR3 p)\n{\n const Eigen::Map< const Eigen::Vector3d > a( p.getdataa() );\n const Eigen::Vector3d b = -a;\n const vectR3 q( b(0), b(1), b(2) );\n return q;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief return the angle theta in radians between the two vectors induced by \n//! the points

and in the space R^3.\n//! \\returns On SUCCESS return theta in the closed interval [0:PI];\n//! On ERROR return negative value or exit with value EXIT_FAILURE\n//-----------------------------------------------------------------------------\ndouble pqtheta(const vectR3 p, const vectR3 q)\n{\n const double rp=p.mag();\n const double rq=q.mag();\n if(rp==0) return -1;\n if(rq==0) return -2;\n const double y = (p^q)/(rp*rq);\n if(y>+1) {fprintf(stderr,\"\\nERROR using pqtheta(vectR3 p, vectR3 q): (p^q)/(rp*rq)=%lf>+1\\n\",y); exit(EXIT_FAILURE);}\n if(y<-1) {fprintf(stderr,\"\\nERROR using pqtheta(vectR3 p, vectR3 q): (p^q)/(rp*rq)=%lf<-1\\n\",y); exit(EXIT_FAILURE);}\n const double theta = acos(y);\n return theta;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Return the minimum element of the tupple\n//-----------------------------------------------------------------------------\ndouble otriple::min(void) const\n{\n const Eigen::Map< const Eigen::Vector3d > abc( getdata() );\n int row, col;\n const double min = abc.minCoeff( &row, &col );\n return min;\n}\n\n//-----------------------------------------------------------------------------\n//! \\brief Return the maximum element of the tupple\n//-----------------------------------------------------------------------------\ndouble otriple::max(void) const\n{\n const Eigen::Map< const Eigen::Vector3d > abc( getdata() );\n int row, col;\n const double max = abc.maxCoeff( &row, &col );\n return max;\n}\n", "meta": {"hexsha": "e02f71aa55cedf70ee89416605de83bf735aac52", "size": 10023, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "r3.cpp", "max_stars_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_stars_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "r3.cpp", "max_issues_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_issues_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "r3.cpp", "max_forks_repo_name": "dgreenhoe/symbolic-sequence-processing", "max_forks_repo_head_hexsha": "8e9f5a40dbddf44fd0fde0a461d7ed73208c9598", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9233449477, "max_line_length": 120, "alphanum_fraction": 0.3711463634, "num_tokens": 2146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.855851143290548, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6831290621791717}} {"text": "#ifndef MATHTOOLBOX_STRONG_WOLFE_CONDITIONS_LINE_SEARCH_HPP\n#define MATHTOOLBOX_STRONG_WOLFE_CONDITIONS_LINE_SEARCH_HPP\n\n#include \n#include \n#include \n#include \n\n#define MATHTOOLBOX_VERBOSE_LINE_SEARCH_WARNINGS\n\nnamespace mathtoolbox\n{\n namespace optimization\n {\n // Algorithm 3.5: Line Search Algorithm\n //\n // This algoritmh tries to find an appropriate step size that satisfies the strong Wolfe conditions (i.e., both\n // the safficient decreasing condition and the curvature condition).\n inline double\n RunStrongWolfeConditionsLineSearch(const std::function& f,\n const std::function& g,\n const Eigen::VectorXd& x,\n const Eigen::VectorXd& p,\n const double alpha_init,\n const double alpha_max = 50.0,\n const double c_1 = 1e-04,\n const double c_2 = 0.9)\n {\n auto phi = [&](const double alpha) { return f(x + alpha * p); };\n auto phi_grad = [&](const double alpha) { return static_cast(g(x + alpha * p).transpose() * p); };\n\n const double phi_zero = phi(0.0);\n const double phi_grad_zero = phi_grad(0.0);\n\n double alpha_prev = 0.0;\n double alpha = alpha_init;\n double phi_alpha_prev = phi_zero;\n\n bool is_first = true;\n\n // Algorithm 3.6: Zoom\n auto zoom = [&](double alpha_l, double alpha_h) {\n constexpr unsigned int max_num_iterations = 50;\n for (unsigned int i = 0; i < max_num_iterations; ++i)\n {\n const double alpha_j = 0.5 * (alpha_l + alpha_h); // TODO: Use a better strategy\n const double phi_alpha_j = phi(alpha_j);\n\n if (phi_alpha_j > phi_zero + c_1 * alpha_j * phi_grad_zero || phi_alpha_j >= phi(alpha_l))\n {\n alpha_h = alpha_j;\n }\n else\n {\n const double phi_grad_alpha_j = phi_grad(alpha_j);\n if (std::abs(phi_grad_alpha_j) <= -c_2 * phi_grad_zero)\n {\n return alpha_j;\n }\n if (phi_grad_alpha_j * (alpha_h - alpha_l) >= 0.0)\n {\n alpha_h = alpha_l;\n }\n alpha_l = alpha_j;\n }\n }\n#ifdef MATHTOOLBOX_VERBOSE_LINE_SEARCH_WARNINGS\n std::cerr << \"Warning: The line search did not converge.\" << std::endl;\n#endif\n return 0.5 * (alpha_l + alpha_h);\n };\n\n constexpr unsigned int max_num_iterations = 50;\n for (int i = 0; i < max_num_iterations; ++i)\n {\n const double phi_alpha = phi(alpha);\n\n if (phi_alpha > phi_zero + c_1 * alpha * phi_grad_zero || (!is_first && (phi_alpha >= phi_alpha_prev)))\n {\n return zoom(alpha_prev, alpha);\n }\n\n const double phi_grad_alpha = phi_grad(alpha);\n\n if (std::abs(phi_grad_alpha) <= -c_2 * phi_grad_zero)\n {\n return alpha;\n }\n\n if (phi_grad_alpha >= 0.0)\n {\n return zoom(alpha, alpha_prev);\n }\n\n alpha_prev = alpha;\n phi_alpha_prev = phi_alpha;\n\n alpha = 0.5 * (alpha + alpha_max); // TODO: Use a better strategy\n }\n#ifdef MATHTOOLBOX_VERBOSE_LINE_SEARCH_WARNINGS\n std::cerr << \"Warning: The line search did not converge.\" << std::endl;\n#endif\n return alpha_init;\n }\n } // namespace optimization\n} // namespace mathtoolbox\n\n#endif // MATHTOOLBOX_STRONG_WOLFE_CONDITIONS_LINE_SEARCH_HPP\n", "meta": {"hexsha": "be3ae4d67db88d693fe8c1296ea37839282f2da5", "size": 4444, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mathtoolbox/strong-wolfe-conditions-line-search.hpp", "max_stars_repo_name": "yuki-koyama/mathtoolbox", "max_stars_repo_head_hexsha": "eb7449c3c489f465849a74405e72aff016a296f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 195.0, "max_stars_repo_stars_event_min_datetime": "2018-04-28T16:12:06.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:52:56.000Z", "max_issues_repo_path": "include/mathtoolbox/strong-wolfe-conditions-line-search.hpp", "max_issues_repo_name": "amazing89/mathtoolbox", "max_issues_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 52.0, "max_issues_repo_issues_event_min_datetime": "2018-04-15T01:24:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:14:23.000Z", "max_forks_repo_path": "include/mathtoolbox/strong-wolfe-conditions-line-search.hpp", "max_forks_repo_name": "amazing89/mathtoolbox", "max_forks_repo_head_hexsha": "8904bb06ced2ac501594f9574ef1ba3454b8e38e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 21.0, "max_forks_repo_forks_event_min_datetime": "2018-06-05T04:11:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-17T13:28:12.000Z", "avg_line_length": 40.7706422018, "max_line_length": 119, "alphanum_fraction": 0.4774977498, "num_tokens": 878, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422645, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6829342556950038}} {"text": "// Copyright Louis Dionne 2015\n// Distributed under the Boost Software License, Version 1.0.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \nnamespace hana = boost::hana;\n\n\ntemplate ()\n>>\nconstexpr T sqrt(T x) {\n T inf = 0, sup = (x == 1 ? 1 : x/2);\n while (!((sup - inf) <= 1 || ((sup*sup <= x) && ((sup+1)*(sup+1) > x)))) {\n T mid = (inf + sup) / 2;\n bool take_inf = mid*mid > x ? 1 : 0;\n inf = take_inf ? inf : mid;\n sup = take_inf ? mid : sup;\n }\n\n return sup*sup <= x ? sup : inf;\n}\n\ntemplate ()\n>>\nconstexpr auto sqrt(T const&) {\n return hana::integral_constant;\n}\n\n\nnamespace then {\nusing namespace boost::mpl;\n\ntemplate \nstruct sqrt\n : integral_c\n{ };\n\ntemplate \nstruct point {\n using x = X;\n using y = Y;\n};\n\n// sample(arithmetic-then)\ntemplate \nstruct distance {\n using xs = typename minus::type;\n using ys = typename minus::type;\n using type = typename sqrt<\n typename plus<\n typename multiplies::type,\n typename multiplies::type\n >::type\n >::type;\n};\n\nstatic_assert(equal_to<\n distance, int_<5>>, point, int_<2>>>::type,\n int_<5>\n>::value, \"\");\n// end-sample\n}\n\n\nnamespace now {\nusing namespace boost::hana;\nusing namespace boost::hana::literals;\n\ntemplate \nstruct _point {\n X x;\n Y y;\n};\ntemplate \nconstexpr _point point(X x, Y y) { return {x, y}; }\n\n// sample(arithmetic-now)\ntemplate \nconstexpr auto distance(P1 p1, P2 p2) {\n auto xs = p1.x - p2.x;\n auto ys = p1.y - p2.y;\n return sqrt(xs*xs + ys*ys);\n}\n\nstatic_assert(distance(point(3_c, 5_c), point(7_c, 2_c)) == 5_c, \"\");\n// end-sample\n\nvoid test() {\n\n// sample(arithmetic-now-dynamic)\nauto p1 = point(3, 5); // dynamic values now\nauto p2 = point(7, 2); //\nassert(distance(p1, p2) == 5); // same function works!\n// end-sample\n\n}\n}\n\n\nint main() {\n now::test();\n}\n", "meta": {"hexsha": "961239f0746344e4a133696a552a7a8d43cab14e", "size": 2682, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/arithmetic.cpp", "max_stars_repo_name": "ldionne/cppnow-2015-hana", "max_stars_repo_head_hexsha": "2f9e86996b61b11e19486741f59ef217ea9125a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-02T22:23:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T19:44:15.000Z", "max_issues_repo_path": "code/arithmetic.cpp", "max_issues_repo_name": "ldionne/cppnow-2015-hana", "max_issues_repo_head_hexsha": "2f9e86996b61b11e19486741f59ef217ea9125a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/arithmetic.cpp", "max_forks_repo_name": "ldionne/cppnow-2015-hana", "max_forks_repo_head_hexsha": "2f9e86996b61b11e19486741f59ef217ea9125a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.35, "max_line_length": 76, "alphanum_fraction": 0.6387024609, "num_tokens": 792, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711908591638, "lm_q2_score": 0.8031738034238806, "lm_q1q2_score": 0.6826745941630797}} {"text": "\n// solving A * X = B\n// A hermitian\n// driver function hesv()\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 cmplx_t; \n\ntypedef ublas::matrix cm_t;\ntypedef ublas::hermitian_adaptor cherml_t; \ntypedef ublas::hermitian_adaptor chermu_t; \n\nint main() {\n\n cm_t cal (3, 3), cau (3, 3); // matrices (storage)\n cherml_t hcal (cal); // hermitian adaptor \n chermu_t hcau (cau); // hermitian adaptor \n cm_t cx (3, 1);\n cm_t cbl (3, 1), cbu (3, 1); // RHS\n\n hcal (0, 0) = cmplx_t (3, 0);\n hcal (1, 0) = cmplx_t (4, -2);\n hcal (1, 1) = cmplx_t (5, 0);\n hcal (2, 0) = cmplx_t (-7, -5);\n hcal (2, 1) = cmplx_t (0, 3);\n hcal (2, 2) = cmplx_t (2, 0);\n\n hcau (0, 0) = cmplx_t (3, 0);\n hcau (0, 1) = cmplx_t (4, 2);\n hcau (0, 2) = cmplx_t (-7, 5);\n hcau (1, 1) = cmplx_t (5, 0);\n hcau (1, 2) = cmplx_t (0, -3);\n hcau (2, 2) = cmplx_t (2, 0);\n\n print_m (cal, \"cal\"); \n cout << endl; \n print_m (cau, \"cau\"); \n cout << endl; \n\n for (int i = 0; i < cx.size1(); ++i) \n cx (i, 0) = cmplx_t (1, -1); \n print_m (cx, \"cx\"); \n cout << endl; \n cbl = prod (hcal, cx);\n cbu = prod (hcau, cx);\n print_m (cbl, \"cbl\"); \n cout << endl; \n print_m (cbu, \"cbu\"); \n cout << endl; \n\n cm_t cal2 (hcal), cau2 (hcau); // for part 2\n cm_t cbl2 (cbl), cbu2 (cbu); \n\n int ierr = lapack::hesv (hcal, cbl); \n if (ierr == 0)\n print_m (cbl, \"cxl\"); \n else \n cout << \"matrix is not regular: ierr = \" \n << ierr << endl;\n cout << endl; \n\n std::vector ipiv (3); \n std::vector cwork (3*64); \n // 3*64 -- optimal size\n\n ierr = lapack::hesv (hcau, ipiv, cbu, cwork); \n if (ierr == 0) {\n print_v (ipiv, \"ipiv\"); \n cout << endl; \n print_m (cbu, \"cxu\"); \n }\n else \n cout << \"matrix is not regular: ierr = \" \n << ierr << endl;\n cout << endl; \n\n // part 2\n\n swap (row (cal2, 0), row (cal2, 2));\n swap (column (cal2, 0), column (cal2, 2));\n\n swap (row (cau2, 1), row (cau2, 2));\n swap (column (cau2, 1), column (cau2, 2));\n\n print_m (cal2, \"cal2\"); \n cout << endl; \n print_m (cau2, \"cau2\"); \n cout << endl; \n\n cbl2 = prod (cal2, cx);\n cbu2 = prod (cau2, cx);\n print_m (cbl2, \"cbl2\"); \n cout << endl; \n print_m (cbu2, \"cbu2\"); \n cout << endl; \n\n ierr = lapack::hesv ('L', cal2, cbl2); \n if (ierr == 0)\n print_m (cbl2, \"cxl2\"); \n else \n cout << \"matrix is not regular: ierr = \" \n << ierr << endl;\n cout << endl; \n\n ierr = lapack::hesv ('U', cau2, ipiv, cbu2, cwork); \n if (ierr == 0) {\n print_v (ipiv, \"ipiv\"); \n cout << endl; \n print_m (cbu2, \"cxu\"); \n }\n else \n cout << \"matrix is not regular: ierr = \" \n << ierr << endl;\n cout << endl; \n\n}\n\n", "meta": {"hexsha": "f3bf14879d2404f0c0165129ce299133a91dacca", "size": 3242, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_hesv.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_hesv.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_hesv.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.8382352941, "max_line_length": 63, "alphanum_fraction": 0.5687847008, "num_tokens": 1321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929797, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.682643272116696}} {"text": "#include \r\n#include \r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n// Returns n!\r\ncpp_int factorial(cpp_int n) {\r\n\tif(n == 0) {\r\n\t\treturn 1;\r\n\t}\r\n\treturn n * factorial(n - 1);\r\n}\r\n\r\n// Returns the sum of the factorials of the digits of a number.\r\ncpp_int sumDigitsFactorial(cpp_int n) {\r\n\tcpp_int sum = 0;\r\n\twhile(n) {\r\n\t\tsum += factorial(n % 10);\r\n\t\tn /= 10;\r\n\t}\r\n\treturn sum;\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n\tcpp_int sum = 0;\r\n\t// Randomly decided to put limit as 100,000 for now.\r\n\tfor(cpp_int i = 3; i <= 100'000; i++) {\r\n\t\tsum = (i == sumDigitsFactorial(i)) ? sum + i : sum;\r\n\t}\r\n\tcout << sum << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "907e306534eac9aa2427b983c9d8d096e631fea2", "size": 695, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/1-50/34/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/1-50/34/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/1-50/34/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 21.0606060606, "max_line_length": 64, "alphanum_fraction": 0.6115107914, "num_tokens": 209, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9458012762876287, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6826256513290021}} {"text": "#pragma once\n#include \n#include \n#include \n#include \n#include \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 . At the end:\n//! u(index) = g(vertices(index)) for each boundary index.\n//!\n//! @param[out] interiorVertexIndices the list of vertices that are not on\n//! the boundary.\n//!\n//! @param[in] vertices a list of vertices for the mesh\n//!\n//! @param[in] triangles the elements represented as triangles\n//!\n//! @param[in] g the boundary value function g.\nvoid setDirichletBoundary(Eigen::VectorXd & u,\n Eigen::VectorXi & interiorVertexIndices,\n const Eigen::MatrixXd &vertices,\n const Eigen::MatrixXi &triangles,\n const std::function &g) {\n\t// Find boundary edges\n\tEigen::MatrixXi boundaryEdgeIndices;\n\tigl::boundary_facets(triangles, boundaryEdgeIndices);\n\n\t// Find boundary vertices\n\tEigen::VectorXi boundaryVertexIndices, IA, IC;\n\tigl::unique(boundaryEdgeIndices, boundaryVertexIndices, IA, IC);\n\n\tfor (int i = 0; i < boundaryVertexIndices.size(); ++i) {\n\t\tconst int index = boundaryVertexIndices(i);\n\t\tconst auto &x = vertices.row(index);\n\t\tu(index) = g(x(0), x(1));\n\t}\n\n\tEigen::VectorXi allIndices;\n\tigl::colon(0, vertices.rows() - 1, allIndices);\n\tigl::setdiff(allIndices, boundaryVertexIndices, interiorVertexIndices, IA);\n}\n", "meta": {"hexsha": "b484ee592bf425876396c61e67125c7f8c6ea4f3", "size": 1633, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2_warmup/2d-poissonlFEM/dirichlet_boundary.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series2_warmup/2d-poissonlFEM/dirichlet_boundary.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series2_warmup/2d-poissonlFEM/dirichlet_boundary.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2888888889, "max_line_length": 76, "alphanum_fraction": 0.6466625842, "num_tokens": 391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.6825923007220569}} {"text": "//\n// Created by philipp on 22.12.19.\n//\n\n#ifndef FUNNELS_CPP_LYAPUNOV_HH\n#define FUNNELS_CPP_LYAPUNOV_HH\n\n#include \n\n#include \n#include \n#include \n\nnamespace lyapunov{\n \n \n template \n inline double projected_max_radius(const Eigen::MatrixBase & C0,\n const Eigen::MatrixBase & C1){\n // todo optimize for usage of triangular shape\n // use spezialised version to compute smallest eigenvalue only\n auto Cinv = C0.inverse();\n auto P1_prime = (Cinv.transpose()*(C1.transpose()*C1)*Cinv);\n double max_rad = 1./P1_prime.eigenvalues().real().array().minCoeff();\n return std::sqrt(max_rad);\n }\n \n struct lyap_zone_t{};\n \n class lyapunov_t{\n public:\n virtual bool intersect(const lyap_zone_t & other);\n virtual bool covers(const lyap_zone_t & other);\n virtual bool is_covered(const lyap_zone_t & other);\n };\n \n struct fixed_ellipsoidal_zone_t{\n virtual const Eigen::VectorXd & x0() const {\n throw std::runtime_error(\"Virtual\");\n return Eigen::Vector2d::Zero();\n };\n virtual const Eigen::MatrixXd & C() const {\n throw std::runtime_error(\"Virtual\");\n return Eigen::Matrix2d::Zero();\n };\n };\n \n struct fixed_ellipsoidal_zone_copied_t: public fixed_ellipsoidal_zone_t{\n public:\n fixed_ellipsoidal_zone_copied_t( const Eigen::VectorXd & x0,\n const Eigen::MatrixXd & C);\n const Eigen::VectorXd & x0() const {\n return _x0;\n }\n const Eigen::MatrixXd & C() const {\n return _C;\n }\n // (x-x0)^T.P.(x-x0) <= 1\n // ||C.(x-x0)||_2^2 <= 1\n Eigen::VectorXd _x0;\n Eigen::MatrixXd _C;\n };\n \n struct fixed_ellipsoidal_zone_ref_t: public fixed_ellipsoidal_zone_t{\n public:\n fixed_ellipsoidal_zone_ref_t( const Eigen::VectorXd & x0,\n const Eigen::MatrixXd & C);\n const Eigen::VectorXd & x0() const {\n return _x0;\n }\n const Eigen::MatrixXd & C() const {\n return _C;\n }\n // (x-x0)^T.P.(x-x0) <= 1\n // ||C.(x-x0)||_2^2 <= 1\n const Eigen::VectorXd &_x0;\n const Eigen::MatrixXd &_C;\n };\n \n // Does zone0 cover zone1\n template\n bool covers_helper(const fixed_ellipsoidal_zone_t &zone0,\n const fixed_ellipsoidal_zone_t &zone1,\n DIST &dist){\n \n \n // First compute the projected distance\n auto dy = zone0.C()*(dist.cp_vv(zone1.x0(), zone0.x0()));\n double dy_norm = dy.norm(); //l2 norm\n // center out of bounds\n if (dy_norm>=1.){\n return false;\n }\n \n // Compute radius\n return dy_norm+projected_max_radius(zone0.C(), zone1.C())<=1.;\n }\n \n template\n class fixed_ellipsoidal_lyap_t:public lyapunov_t{\n public:\n using dist_t = DIST;\n \n fixed_ellipsoidal_lyap_t(const Eigen::MatrixXd &P,\n double gamma, DIST &dist):\n _gamma(gamma), _dist(dist){\n // Compute cholesky\n Eigen::LLT llt_pre_comp;\n llt_pre_comp.compute(P);\n _C = llt_pre_comp.matrixU();\n }\n \n const Eigen::MatrixXd &C() const {\n return _C;\n }\n double gamma() const {\n return _gamma;\n }\n \n // Conservative intersect\n // If true, the zone may intersect with this\n // If false, the zone does definitively not intersect\n template\n bool intersect(const Eigen::MatrixBase &x0,\n const fixed_ellipsoidal_zone_t &zone) {\n // First compute the projected distance\n auto dy = _C*(_dist.cp_vv(zone.x0(), x0));\n double dy_norm = dy.norm(); //l2 norm\n \n if (dy_norm <= 1.){\n return true;\n }\n \n return dy_norm>=1.+projected_max_radius(_C, zone.C());\n }\n \n // Conservative cover\n // If true, zone is definitively covered by this\n // If false, it may not be covered\n template\n bool covers(const Eigen::MatrixBase &x0, const fixed_ellipsoidal_zone_t &zone) {\n fixed_ellipsoidal_zone_ref_t this_zone(x0, _C);\n return covers_helper(this_zone, zone, _dist);\n }\n \n // Conservative cover\n // If true, this is definitively covered by zone\n // If false, it may not be covered\n template\n bool is_covered(const Eigen::MatrixBase &x0, const fixed_ellipsoidal_zone_t &zone) {\n fixed_ellipsoidal_zone_ref_t this_zone(x0, _C);\n return covers_helper(zone, this_zone, _dist);\n }\n \n dist_t & dist(){\n return _dist;\n }\n \n protected:\n Eigen::MatrixXd _C;\n double _gamma;\n DIST &_dist;\n };\n \n}\n\n#endif //FUNNELS_CPP_LYAPUNOV_HH\n", "meta": {"hexsha": "c0acd88409b5ccbc27ec090b6b63e8a314d9403c", "size": 4642, "ext": "hh", "lang": "C++", "max_stars_repo_path": "include/funnels/lyapunov.hh", "max_stars_repo_name": "schlepil/funnels_cpp", "max_stars_repo_head_hexsha": "fa1f9084a168abfbdf594c4eca6b0f26d33b9258", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/funnels/lyapunov.hh", "max_issues_repo_name": "schlepil/funnels_cpp", "max_issues_repo_head_hexsha": "fa1f9084a168abfbdf594c4eca6b0f26d33b9258", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/funnels/lyapunov.hh", "max_forks_repo_name": "schlepil/funnels_cpp", "max_forks_repo_head_hexsha": "fa1f9084a168abfbdf594c4eca6b0f26d33b9258", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.630952381, "max_line_length": 97, "alphanum_fraction": 0.6296854804, "num_tokens": 1290, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.743168019989179, "lm_q1q2_score": 0.6825851443514461}} {"text": "//StandardDeviation_StandardError.hpp\n//purpose: header file for standard deriation\n//author: bondxue\n//version: 1.0 11/22/2017\n\n#ifndef STANDARDDEVIATION_STANDARDERROR_HPP\n#define STANDARDDEVIATION_STANDARDERROR_HPP\n\n#include \n#include \n#include \n\n#include // include tuple class\n#include // include I/O for tuple\n\nusing namespace std;\nusing boost::tuple;\n\n// function to obtain standard deviation and standard error\nboost::tuple get_SD_SE(vector price_vec, double r, double T)\n{\n\tint price_size = price_vec.size();\n\tdouble sum_price = 0.0;\n\tdouble square_sum_price = 0.0;\n\n\tfor (int i = 0; i < price_size; i++)\n\t{\n\t\tsum_price += price_vec[i];\n\t\tsquare_sum_price += pow(price_vec[i], 2);\n\t}\n\n\tdouble temp = sqrt((square_sum_price - pow(sum_price, 2)/double(price_size))/(double(price_size)-1.0)); // use temp to store the square root part in SD formula \n\tdouble SD = temp * exp(-r*T);\n\tdouble SE = SD / sqrt(double(price_size));\n\n\treturn boost::tuple(SD, SE);\n}\n\n#endif", "meta": {"hexsha": "464d02acc2bdd9b65a557cc620adcf90a3ee4752", "size": 1087, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/StandardDeviation_StandardError.hpp", "max_stars_repo_name": "bondxue/Option-Pricing-Model", "max_stars_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/StandardDeviation_StandardError.hpp", "max_issues_repo_name": "bondxue/Option-Pricing-Model", "max_issues_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/StandardDeviation_StandardError.hpp", "max_forks_repo_name": "bondxue/Option-Pricing-Model", "max_forks_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8717948718, "max_line_length": 161, "alphanum_fraction": 0.7322907084, "num_tokens": 288, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802350995702, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6825851272688712}} {"text": "#include \n\n#include \n\n#include \n\nusing namespace Ubpa;\n\nusing namespace std;\nusing namespace Eigen;\n\nvoid DeformRBF::Clear() {\n\ttriMesh = nullptr;\n\torigPos.clear();\n}\n\nbool DeformRBF::Init(Ptr triMesh) {\n\tif (triMesh == this->triMesh)\n\t\treturn true;\n\n\tif (triMesh->GetType() == TriMesh::INVALID) {\n\t\tprintf(\"ERROR::DeformRBF::Init\\n\"\n\t\t\t\"\\t\"\"triMesh->GetType() == TriMesh::INVALID\\n\");\n\t\treturn false;\n\t}\n\n\tthis->triMesh = triMesh;\n\torigPos = triMesh->GetPositions();\n\treturn true;\n}\n\nbool DeformRBF::Run(const std::vector & constraints, const vector & updateIndice) {\n\tif (!triMesh) {\n\t\tprintf(\"ERROR::DeformRBF::Run\\n\"\n\t\t\t\"\\t\"\"!triMesh\\n\");\n\t\treturn false;\n\t}\n\n\tfor (auto constraint : constraints) {\n\t\tif (constraint.id >= origPos.size()) {\n\t\t\tprintf(\"ERROR::DeformRBF::Run\\n\"\n\t\t\t\t\"\\t\"\"constraint.id >= origPos.size()\\n\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t// compute RBF matrix\n\tauto phi = [](float r) -> float {return r*r*r; }; // basis function\n\tsize_t m = constraints.size();\n\tsize_t k = 10;\n\t\n\t// A = - -\n\t// | G P |\n\t// | |\n\t// | t |\n\t// | P 0 |\n\t// - -\n\tMatrixXf A(m + k, m + k);\n\t\n\t// G : m x m\n\t// Gij = gj(ci) = basicFunc(||ci-cj||)\n\tfor (size_t i = 0; i < m; i++) {\n\t\tfor (size_t j = 0; j < m; j++) {\n\t\t\tauto ci = origPos[constraints[i].id];\n\t\t\tauto cj = origPos[constraints[j].id];\n\t\t\tfloat norm = pointf3::distance(ci, cj);\n\t\t\tA(i, j) = phi(norm);\n\t\t}\n\t}\n\n\t// P : m x k\n\t// Pij = pj(ci)\n\t// [p0, p1, ..., p9] is a basis of the space of trivariate quadratic polunomials\n\t// e[1]. [1, xx, xy, xz, yx, yy, yz, zx, zy, zz]\n\tfor (size_t i = 0; i < m; i++) {\n\t\tauto ci = origPos[constraints[i].id];\n\t\tA(m + 0, i) = A(i, m + 0) = 1.f;\n\t\tA(m + 1, i) = A(i, m + 1) = ci[0] * ci[0];\n\t\tA(m + 2, i) = A(i, m + 2) = ci[0] * ci[1];\n\t\tA(m + 3, i) = A(i, m + 3) = ci[0] * ci[2];\n\t\tA(m + 4, i) = A(i, m + 4) = ci[1] * ci[0];\n\t\tA(m + 5, i) = A(i, m + 5) = ci[1] * ci[1];\n\t\tA(m + 6, i) = A(i, m + 6) = ci[1] * ci[2];\n\t\tA(m + 7, i) = A(i, m + 7) = ci[2] * ci[0];\n\t\tA(m + 8, i) = A(i, m + 8) = ci[2] * ci[1];\n\t\tA(m + 9, i) = A(i, m + 9) = ci[2] * ci[2];\n\t}\n\n\t// 0 : k x k\n\tfor (size_t i = 0; i < k; i++) {\n\t\tfor (size_t j = 0; j < k; j++) {\n\t\t\tA(m + i, m + j) = 0.f;\n\t\t}\n\t}\n\n\tMatrixXf b(m + k, 3);\n\tfor (int i = 0; i < k; i++)\n\t\tb(m + i,0) = b(m + i, 1) = b(m + i, 2) = 0;\n\tfor (int i = 0; i < m; i++) {\n\t\tauto bi = constraints[i].pos;\n\t\tb(i, 0) = bi[0];\n\t\tb(i, 1) = bi[1];\n\t\tb(i, 2) = bi[2];\n\t}\n\n\tMatrixXf RBF = A.colPivHouseholderQr().solve(b);\n\n\t// compute target pos of vertex\n\tvector qVec;\n\tfor (auto id : updateIndice) {\n\t\tauto pos = origPos[id];\n\t\t// compute p\n\t\tMatrixXf p(1, m + k);\n\t\tfor (size_t i = 0; i < m; i++) {\n\t\t\tauto ci = origPos[constraints[i].id];\n\t\t\tp(i) = phi(pointf3::distance(ci, pos));\n\t\t}\n\t\tp(0, m + 0) = 1;\n\t\tp(0, m + 1) = pos[0] * pos[0];\n\t\tp(0, m + 2) = pos[0] * pos[1];\n\t\tp(0, m + 3) = pos[0] * pos[2];\n\t\tp(0, m + 4) = pos[1] * pos[0];\n\t\tp(0, m + 5) = pos[1] * pos[1];\n\t\tp(0, m + 6) = pos[1] * pos[2];\n\t\tp(0, m + 7) = pos[2] * pos[0];\n\t\tp(0, m + 8) = pos[2] * pos[1];\n\t\tp(0, m + 9) = pos[2] * pos[2];\n\n\t\t// compute q\n\t\tMatrixXf q = p * RBF;\n\t\ttriMesh->GetPositions()[id] = { q(0,0),q(0,1),q(0,2) };\n\t}\n\n\treturn true;\n}\n\nvoid DeformRBF::Restore() {\n\tif (triMesh == nullptr)\n\t\treturn;\n\n\ttriMesh->Update(origPos);\n}\n", "meta": {"hexsha": "cd1035bb4d8edcc2dc2415a4f48060c54d0b5531", "size": 3383, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Engine/MeshEdit/DeformRBF.cpp", "max_stars_repo_name": "Ubpa/DGP", "max_stars_repo_head_hexsha": "5dcf6413126888fb2556bd7eddf4b899b23babed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 594.0, "max_stars_repo_stars_event_min_datetime": "2019-02-19T01:09:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T07:47:11.000Z", "max_issues_repo_path": "src/Engine/MeshEdit/DeformRBF.cpp", "max_issues_repo_name": "xmlandroid/RenderLab", "max_issues_repo_head_hexsha": "71db49aa03de4fb258f9171691c8d570216e5e05", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-05-08T07:52:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T01:04:30.000Z", "max_forks_repo_path": "src/Engine/MeshEdit/DeformRBF.cpp", "max_forks_repo_name": "xmlandroid/RenderLab", "max_forks_repo_head_hexsha": "71db49aa03de4fb258f9171691c8d570216e5e05", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 107.0, "max_forks_repo_forks_event_min_datetime": "2019-03-26T20:18:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T23:41:18.000Z", "avg_line_length": 23.6573426573, "max_line_length": 103, "alphanum_fraction": 0.5063553059, "num_tokens": 1446, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802417938535, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.682585127019212}} {"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \n#include \n#include \n#include \n\nnamespace fluid {\nnamespace algorithm {\n\nclass WindowFuncs\n{\npublic:\n enum class WindowTypes {\n kHann,\n kHannD,\n kHamming,\n kBlackmanHarris,\n kGaussian\n };\n using WindowFuncsMap =\n std::map)>>;\n\n static WindowFuncsMap& map()\n {\n using namespace std;\n static WindowFuncsMap _funcs = {\n {WindowTypes::kHann,\n [](index size, Eigen::Ref out) {\n for (index i = 0; i < size; i++)\n { out(i) = 0.5 - 0.5 * cos((pi * 2 * i) / size); }\n }},\n {WindowTypes::kHannD,\n [](index size, Eigen::Ref out) {\n double norm = pi / size;\n for (index i = 0; i < size; i++)\n { out(i) = norm * sin((2 * pi * i) / size); }\n }},\n {WindowTypes::kHamming,\n [](index size, Eigen::Ref out) {\n for (index i = 0; i < size; i++)\n { out(i) = 0.54 - 0.46 * cos((pi * 2 * i) / size); }\n }},\n {WindowTypes::kBlackmanHarris,\n [](index size, Eigen::Ref out) {\n for (index i = 0; i < size; i++)\n {\n out(i) = 0.35875 - 0.48829 * cos((pi * 2 * i) / size) +\n 0.14128 * cos((pi * 2 * i) / size) +\n 0.01168 * cos((pi * 2 * i) / size);\n }\n }},\n {WindowTypes::kGaussian,\n [](index size, Eigen::Ref out) {\n double sigma = size / 3; // TODO: should be argument\n assert(size % 2);\n index h = (size - 1) / 2;\n for (index i = -h; i <= h; i++)\n { out(i + h) = exp(-i * i / (2 * sigma * sigma)); }\n }}};\n return _funcs;\n }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "d11eb2cecce78f63e2ef5f305923e51751470ccb", "size": 2402, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/WindowFuncs.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/public/WindowFuncs.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/public/WindowFuncs.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 30.4050632911, "max_line_length": 74, "alphanum_fraction": 0.5395503747, "num_tokens": 689, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.682553062708704}} {"text": "#include \n#include \n#include \n#include \n\nnamespace ub = boost::numeric::ublas;\n\n// f: R->R\nkv::autodif testfunc1(const kv::autodif& x) {\n\tkv::autodif tmp;\n\n\ttmp = x * x - 1.;\n\treturn cos(tmp + sin(tmp));\n}\n\n// f: R->R (use template)\ntemplate T testfunc2(const T& x) {\n\tT tmp;\n\n\ttmp = x * x - 1.;\n\treturn cos(tmp + sin(tmp));\n}\n\n// f: R^n->R\ntemplate T testfunc3(const ub::vector& x) {\n\treturn atan(x(0) * x(0) + 2. * x(1) * x(1) - 1.);\n}\n\n// f: R->R^n\ntemplate ub::vector testfunc4(const T& x) {\n\tub::vector y(2);\n\n\ty(0) = sin(x);\n\ty(1) = cos(x);\n\n\treturn y;\n}\n\n// f: R^n->R^n\ntemplate ub::vector testfunc5(const ub::vector& x) {\n\tub::vector y(2);\n\n\ty(0) = 2. * x(0) * x(0) * x(1) - 1.;\n\ty(1) = x(0) + 0.5 * x(1) * x(1) - 2.;\n\n\treturn y;\n}\n\n\nint main()\n{\n\tdouble d1, d2;\n\tkv::autodif a1, a2, a3;\n\tub::vector v1, v2;\n\tub::vector< kv::autodif > va1, va2, va3, va4, va5;\n\tub::matrix m;\n\tint i;\n\n\t//\n\t// f: R->R (testfunc1)\n\t//\n\n\t// helper function to initialize autodif variable with single variable\n\t// same as \" a1.v = 1.5; a1.d(0) = 1.; \"\n\ta1 = kv::autodif::init(1.5);\n\n\ta2 = testfunc1(a1);\n\n\t// helper function to separate autodif variable into value and gradient\n\t// same as \" d1 = a2.v; d2 = a2.d(0); \"\n\tkv::autodif::split(a2, d1, d2);\n\n\tstd::cout << \"testfunc1\\n\";\n\tstd::cout << d1 << \"\\n\"; // f(1.5)\n\tstd::cout << d2 << \"\\n\"; // f'(1.5)\n\n\t//\n\t// f: R->R (testfunc2: use template)\n\t//\n\n\ta1 = kv::autodif::init(1.5);\n\ta2 = testfunc2(a1);\n\n\tkv::autodif::split(a2, d1, d2);\n\n\tstd::cout << \"testfunc2\\n\";\n\tstd::cout << d1 << \"\\n\"; // f(1.5)\n\tstd::cout << d2 << \"\\n\"; // f'(1.5)\n\n\td1 = 1.5;\n\td2 = testfunc2(d1); // double can be also passed\n\tstd::cout << d2 << \"\\n\"; // f(1.5)\n\n\t//\n\t// f: R^n->R\n\t//\n\n\tv1.resize(2);\n\tv1(0) = 5.; v1(1) = 6.;\n\n\t// helper function to initialize autodif vector with vector variable\n\t// same as \" va1(0).v = 5.; va1(0).d(0) = 1.; va1(0).d(1) = 0,; \"\n\t// \" va1(1).v = 6.; va1(1).d(0) = 0.; va1(1).d(1) = 1,; \"\n\tva1 = kv::autodif::init(v1);\n\n\ta1 = testfunc3(va1);\n\n\t// helper function to separate autodif variable into value and gradient\n\t// same as \" y = a1.v; v2(0) = a1.d(0); v2(1) = a1.d(1) \"\n\tkv::autodif::split(a1, d1, v2);\n\n\tstd::cout << \"testfunc3\\n\";\n\tstd::cout << d1 << \"\\n\"; // f(5, 6)\n\tstd::cout << v2 << \"\\n\"; // gradient\n\n\t//\n\t// f: R->R^n\n\t//\n\n\ta1 = kv::autodif::init(1.5);\n\n\tva1 = testfunc4(a1);\n\n\t// helper function to separate autodif variable into value and gradient\n\t// same as \" v1(0) = va1(0).v; v1(1) = va1(1).v; \"\n\t// \" v2(0) = va1(0).d(0); v2(1) = va1(1).d(0); \"\n\tkv::autodif::split(va1, v1, v2);\n\n\tstd::cout << \"testfunc4\\n\";\n\tstd::cout << v1 << \"\\n\"; // f(1.5)\n\tstd::cout << v2 << \"\\n\"; // f'(1.5)\n\n\t//\n\t// f: R^n->R^m\n\t//\n\n\tv1(0) = 5.; v1(1) = 6.;\n\n\tva1 = kv::autodif::init(v1);\n\n\tva2 = testfunc5(va1);\n\n\t// helper function to separate autodif vector into vector value and jacobian\n\t// same as \" v2(0) = va2(0).v; m(0)(0) = va2(0).d(0); m(0)(1) = va2(0).d(1); \"\n\t// \" v2(1) = va2(1).v; m(1)(0) = va2(1).d(0); m(1)(1) = va2(1).d(1); \"\n\tkv::autodif::split(va2, v2, m);\n\n\tstd::cout << \"testfunc5\\n\";\n\tstd::cout << v2 << \"\\n\"; // f(5, 6)\n\tstd::cout << m << \"\\n\"; // Jacobian matrix\n\n\t//\n\t// operations for autodif\n\t//\n\n\tv1(0) = 0.7; v1(1) = 0.8;\n\tva1 = kv::autodif::init(v1);\n\ta1 = va1(0);\n\ta2 = va1(1);\n\n\tstd::cout << \"autodif operations\\n\";\n\n\tstd::cout << a1 << \"\\n\";\n\tstd::cout << a2 << \"\\n\";\n\n\ta3 = a1 + a2; std::cout << a3 << \"\\n\";\n\ta3 = a1 - a2; std::cout << a3 << \"\\n\";\n\ta3 = a1 * a2; std::cout << a3 << \"\\n\";\n\ta3 = a1 / a2; std::cout << a3 << \"\\n\";\n\ta3 = pow(a1, 3); std::cout << a3 << \"\\n\";\n\ta3 = pow(a1, a2); std::cout << a3 << \"\\n\";\n\ta2 = sqrt(a1); std::cout << a2 << \"\\n\";\n\ta2 = exp(a1); std::cout << a2 << \"\\n\";\n\ta2 = log(a1); std::cout << a2 << \"\\n\";\n\ta2 = sin(a1); std::cout << a2 << \"\\n\";\n\ta2 = cos(a1); std::cout << a2 << \"\\n\";\n\ta2 = tan(a1); std::cout << a2 << \"\\n\";\n\ta2 = sinh(a1); std::cout << a2 << \"\\n\";\n\ta2 = cosh(a1); std::cout << a2 << \"\\n\";\n\ta2 = tanh(a1); std::cout << a2 << \"\\n\";\n\ta2 = asin(a1); std::cout << a2 << \"\\n\";\n\ta2 = acos(a1); std::cout << a2 << \"\\n\";\n\ta2 = atan(a1); std::cout << a2 << \"\\n\";\n\t// asinh, acosh, atanh may not compile for autodif\n\t// because c++03 does not have asinh, acosh, atanh\n\t// a2 = asinh(a1); std::cout << a2 << \"\\n\";\n\t// a2 = acosh(a1+1.); std::cout << a2 << \"\\n\";\n\t// a2 = atanh(a1); std::cout << a2 << \"\\n\";\n\n\t//\n\t// compress / expand\n\t//\n\n\tv1.resize(20);\n\tfor (i=0; i<20; i++) v1(i) = i + 2.;\n\tva1 = kv::autodif::init(v1);\n\t// use only a few of the many variables\n\tva2.resize(2);\n\tva2(0) = va1(10);\n\tva2(1) = va1(11);\n\n\t// usual way\n\tstd::cout << \"usual input\\n\";\n\tstd::cout << va2 << \"\\n\";\n\tva3 = testfunc5(va2);\n\tstd::cout << \"usual output\\n\";\n\tstd::cout << va3 << \"\\n\";\n\n\t// using compress/expand to save calculation time\n\tub::matrix save;\n\tva3 = kv::autodif::compress(va2, save);\n\tstd::cout << \"compressed input\\n\";\n\tstd::cout << va3 << \"\\n\";\n\tva4 = testfunc5(va3);\n\tstd::cout << \"compressed output\\n\";\n\tstd::cout << va4 << \"\\n\";\n\tva5 = kv::autodif::expand(va4, save);\n\tstd::cout << \"expanded output\\n\";\n\tstd::cout << va5 << \"\\n\";\n}\n", "meta": {"hexsha": "9a76939dbf5a14ed55dc71e0500e51542837a1ce", "size": 5427, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test-autodif.cc", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "test/test-autodif.cc", "max_issues_repo_name": "soonho-tri/kv", "max_issues_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "test/test-autodif.cc", "max_forks_repo_name": "soonho-tri/kv", "max_forks_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 24.556561086, "max_line_length": 79, "alphanum_fraction": 0.5295743505, "num_tokens": 2237, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7956580903722561, "lm_q1q2_score": 0.6824901323986547}} {"text": "#include \n#include \n#include \n\nEigen::VectorXd poly(int const n, double & x){\n\tEigen::VectorXd v(n);\n\tv(0)=1;\n\tif(n>1) v(1)=x;\n\tfor (int i=2; i < n;i++){\n\t\tv(i)=2*x*v(i-1)-v(i-2);\n\t}\n\treturn v;\n}\n\nEigen::VectorXd zeroes(const int n){\n\tEigen::VectorXd v(n);\n\tfor (int i=0;i\nvoid bestpolchebnodes (const Function&f, Eigen::VectorXd &alpha){\n\t\tsize_t n= alpha.size();\n\t\tEigen::VectorXd v;\n\t\tEigen::VectorXd fn(n+1);\n\t\tfor (int i=0; i V=poly(n,x);\n for (int k=0; k, Randi Cabezas \n * Licensed under the MIT license. See the license file LICENSE. \n */\n\n#pragma once\n\n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\nusing namespace Eigen;\nusing std::endl;\nusing std::cout;\n\ntemplate\nclass IW : public Distribution\n{\npublic:\n Matrix Delta_;\n T nu_;\n uint32_t D_;\n\n IW(const Matrix& Delta, T nu, boost::mt19937 *pRndGen);\n IW(const Matrix& Delta, T nu, const Matrix& scatter, \n\t const Matrix& mean, T counts, boost::mt19937 *pRndGen);\n IW(const IW& iw);\n ~IW();\n\n IW* copy();\n\n IW posterior(const Matrix& x, const VectorXu& z,\n uint32_t k, uint32_t zDivider=1);\n IW posterior(const Matrix& outer, T count) const;\n IW posterior() const ;\n void resetSufficientStatistics();\n\n Matrix sample();\n// Normal sample();\n T logPdf(const Matrix& Sigma) const;\n T logPdf(const Normal& normal) const;\n T logLikelihoodMarginalized() const; // log pdf of SS under NIW prior\n T logLikelihoodMarginalized(const Matrix& Scatter, \n T count) const;\n\n Matrix mode() const;\n\n const Matrix& scatter() const {return scatter_;};\n Matrix& scatter() {return scatter_;};\n const Matrix& mean() const {return mean_;};\n Matrix& mean() {return mean_;};\n T count() const {return count_;};\n T& count() {return count_;};\n\nprivate:\n boost::random::normal_distribution<> gauss_;\n\n // sufficient statistics\n Matrix scatter_;\n Matrix mean_;\n T count_;\n};\n\ntypedef IW IWd;\ntypedef IW IWf;\n\n/* prior for spherical covariances (i.e. \\Sigma = \\sigma^2 I) */\ntemplate\nclass IW_spherical : public Distribution\n{\npublic:\n T delta_;\n T nu_;\n uint32_t D_;\n\n IW_spherical(T delta, T nu, uint32_t D, boost::mt19937 *pRndGen);\n IW_spherical(const IW_spherical& iw);\n ~IW_spherical();\n\n IW_spherical* copy();\n\n IW_spherical posterior(const Matrix& x, \n const VectorXu& z, uint32_t k, uint32_t zDivider=1);\n// T sample();\n// T logPdf(T sigma);\n//// T logPdf(const Normal& normal);\n\nprivate:\n boost::random::normal_distribution<> gauss_;\n};\n\n// ----------------------------------------------------------------------------\n", "meta": {"hexsha": "b83a487ba789e3a4228f72373702eaea971b29ea", "size": 2805, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dpMM/iw.hpp", "max_stars_repo_name": "jstraub/dpMM", "max_stars_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_stars_repo_licenses": ["MIT-feh"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2015-04-27T15:14:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-18T00:19:18.000Z", "max_issues_repo_path": "include/dpMM/iw.hpp", "max_issues_repo_name": "jstraub/dpMM", "max_issues_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_issues_repo_licenses": ["MIT-feh"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dpMM/iw.hpp", "max_forks_repo_name": "jstraub/dpMM", "max_forks_repo_head_hexsha": "538c432d5f98c040d5c1adb072e545e38f97fc69", "max_forks_repo_licenses": ["MIT-feh"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-02T12:46:20.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T04:39:30.000Z", "avg_line_length": 28.3333333333, "max_line_length": 120, "alphanum_fraction": 0.6802139037, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.682339985445466}} {"text": "/*\n * Copyright (c) 2013, Christian Gehring, Hannes Sommer, Paul Furgale, Remo Diethelm\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * * Neither the name of the Autonomous Systems Lab, ETH Zurich nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL Christian Gehring, Hannes Sommer, Paul Furgale,\n * Remo Diethelm BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\n * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n*/\n#pragma once\n\n#include \n\nnamespace kindr {\n\n\n/*!\n * \\brief Gets a skew-symmetric matrix from a (column) vector\n * \\param vec 3x1-matrix (column vector)\n * \\return skew 3x3-matrix\n */\ntemplate\ninline static Eigen::Matrix getSkewMatrixFromVector(const Eigen::Matrix& vec) {\n Eigen::Matrix 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\ninline static Eigen::Matrix getVectorFromSkewMatrix(const Eigen::Matrix& matrix) {\n return Eigen::Matrix (matrix(2,1), matrix(0,2), matrix(1,0));\n}\n\n/*!\n * \\brief Computes the Moore–Penrose pseudoinverse\n * info: http://eigen.tuxfamily.org/bz/show_bug.cgi?id=257\n * \\param a: Matrix to invert\n * \\param result: Result is written here\n * \\param epsilon: Numerical precision (for example 1e-6)\n * \\return true if successful\n */\ntemplate\nbool static pseudoInverse(const _Matrix_TypeA_ &a, _Matrix_TypeB_ &result,\n double epsilon = std::numeric_limits::epsilon())\n{\n // Shorthands\n constexpr auto rowsA = static_cast(_Matrix_TypeA_::RowsAtCompileTime);\n constexpr auto colsA = static_cast(_Matrix_TypeA_::ColsAtCompileTime);\n constexpr auto rowsB = static_cast(_Matrix_TypeB_::RowsAtCompileTime);\n constexpr auto colsB = static_cast(_Matrix_TypeB_::ColsAtCompileTime);\n\n // Assert wrong matrix types\n static_assert(std::is_same::value,\n \"[kindr::pseudoInverse] Matrices must be of the same Scalar type!\");\n static_assert(rowsA == colsB && colsA == rowsB, \"[kindr::pseudoInverse] Result type has wrong size!\");\n\n // If one dimension is dynamic, compute everything as dynamic size\n constexpr auto m = Eigen::JacobiSVD< _Matrix_TypeA_ >::DiagSizeAtCompileTime;\n\n // JacobiSVD needs to be computed on dynamic size if we need ComputeThinU, ComputeThinV, see:\n // https://eigen.tuxfamily.org/dox/classEigen_1_1JacobiSVD.html\n Eigen::JacobiSVD< Eigen::Matrix > svd(a, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n typename _Matrix_TypeA_::Scalar tolerance =\n epsilon * std::max(a.cols(), a.rows()) * svd.singularValues().array().abs().maxCoeff();\n\n // Sigma for ThinU and ThinV\n Eigen::Matrix sigmaThin = Eigen::Matrix(\n (svd.singularValues().array().abs() > tolerance).select(svd.singularValues().array().inverse(), 0)).asDiagonal();\n\n result = svd.matrixV() * sigmaThin * svd.matrixU().transpose();\n\n return true;\n}\n\n\n} // end namespace kindr\n", "meta": {"hexsha": "336840d06ad4ea9a07660ca7a83c11573e7f00aa", "size": 4680, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/kindr/math/LinearAlgebra.hpp", "max_stars_repo_name": "mcx/kindr", "max_stars_repo_head_hexsha": "761303a6d82780b3e476473ba66a0c2abc623179", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 289.0, "max_stars_repo_stars_event_min_datetime": "2018-08-06T15:57:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:52:43.000Z", "max_issues_repo_path": "include/kindr/math/LinearAlgebra.hpp", "max_issues_repo_name": "mcx/kindr", "max_issues_repo_head_hexsha": "761303a6d82780b3e476473ba66a0c2abc623179", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T10:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-31T13:24:52.000Z", "max_forks_repo_path": "include/kindr/math/LinearAlgebra.hpp", "max_forks_repo_name": "mcx/kindr", "max_forks_repo_head_hexsha": "761303a6d82780b3e476473ba66a0c2abc623179", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 106.0, "max_forks_repo_forks_event_min_datetime": "2018-08-24T08:39:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T15:17:37.000Z", "avg_line_length": 46.3366336634, "max_line_length": 151, "alphanum_fraction": 0.7333333333, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392725805823, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.6823399643757079}} {"text": "/*\n * Using Sundaram' sieve, print the first 2,000,000 numbers\n * darkturo 2014\n */\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define TIMEDIFF(start, stop) 1000.0 * (stop - start)/CLOCKS_PER_SEC\n#define MAX 32452843\n#define MAXPRIMES 2000000\n#define BUFFER_SIZE 8l * MAX\n\nclass SundaramSieve\n{\n std::bitset N;\n std::ofstream output;\n int counter; \n char * buffer;\n char * p_input;\n\n public:\n SundaramSieve() : \n output(\"primesEveryWhere.txt\", std::ios::out | std::ios::trunc),\n counter(0)\n {\n buffer = new char[BUFFER_SIZE];\n p_input = buffer;\n N.set();\n }\n\n ~SundaramSieve()\n {\n if (p_input != buffer)\n output.write(buffer, p_input - buffer); // flush\n output.close();\n }\n\n void sieve()\n {\n // Given i,j ∈ ℕ, 1 ≤ i ≤ j\n // Sieve all the x ∈ ℕ, x = i + j + 2ij ≤ MAX\n for (long i = 1; (2*i + 2*(i^2)) <= 2*sqrt(MAX); i++)\n {\n for (long j = i; (i + j + 2*i*j) <= (MAX - 2)/2; j++)\n {\n N.set((i + j + 2*i*j) - 1, false);\n }\n }\n\n // Generate the primes from the sieved list.\n print( 2 );\n for (int i = 1; counter < MAXPRIMES; i++)\n {\n if (N[i-1]) \n {\n print( 2*i + 1 );\n }\n }\n }\n\n int printedPrimes()\n {\n return counter;\n }\n\n private:\n inline void print(int number)\n {\n doPrint(number);\n counter ++;\n }\n\n inline void doPrint(int number)\n {\n boost::spirit::karma::generate(p_input, boost::spirit::int_, number);\n *p_input++ = '\\n';\n }\n};\n\nint main(int argc, char ** argv)\n{\n clock_t t1, t2;\n\n t1 = std::clock();\n\n SundaramSieve siever;\n siever.sieve();\n\n t2 = std::clock();\n\n // Summary\n std::cout.precision(std::numeric_limits::digits10);\n std::cerr << \"Used \" << std::fixed << TIMEDIFF(t1, t2)\n << \" msecs to calculate \" << siever.printedPrimes()\n << \" primes.\" << std::endl;\n}\n", "meta": {"hexsha": "370465eae636c81d89a851c6fc09e72df8914830", "size": 2071, "ext": "cc", "lang": "C++", "max_stars_repo_path": "c++/sundaram.cc", "max_stars_repo_name": "darkturo/primo", "max_stars_repo_head_hexsha": "055d564ecb1106c23e2327f4e8921d111472492f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-02-07T16:35:32.000Z", "max_stars_repo_stars_event_max_datetime": "2015-02-07T16:35:32.000Z", "max_issues_repo_path": "c++/sundaram.cc", "max_issues_repo_name": "darkturo/primo", "max_issues_repo_head_hexsha": "055d564ecb1106c23e2327f4e8921d111472492f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/sundaram.cc", "max_forks_repo_name": "darkturo/primo", "max_forks_repo_head_hexsha": "055d564ecb1106c23e2327f4e8921d111472492f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.504950495, "max_line_length": 75, "alphanum_fraction": 0.5287300821, "num_tokens": 630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6823315145704235}} {"text": "#pragma once\n\n#include \"modprop/compo/Interfaces.h\"\n#include \"modprop/compo/Parametric.hpp\"\n#include \n\nnamespace percepto\n{\n\n// TODO Support matrix inputs?\n/*! \\brief A simple linear regression class. Outputs Weights matrix * input. \n * The matrix and input are dynamically-sized. Assumes row-major ordering\n * for vectorizing the weights matrix. */\nclass LinearRegressor\n: public Source\n{\npublic:\n\t\n\ttypedef VectorType InputType;\n\ttypedef VectorType OutputType;\n\ttypedef Source SourceType;\n\n\tLinearRegressor( unsigned int inputDim, unsigned int outputDim )\n\t: _inputDim( inputDim ), _outputDim( outputDim ), _W( nullptr, 0, 0 ),\n\t_inputPort( this ) {}\n\n\tLinearRegressor( const LinearRegressor& other )\n\t: _inputDim( other._inputDim ), _outputDim( other._outputDim ),\n\t_params( other._params ), _W( other._W ), _inputPort( this ) {}\n\n\tvoid SetSource( SourceType* b ) { b->RegisterConsumer( &_inputPort ); }\n\n\tunsigned int InputDim() const { return _inputDim; }\n\tunsigned int OutputDim() const { return _outputDim; }\n\n\tParameters::Ptr CreateParameters()\n\t{\n\t\tParameters::Ptr params = std::make_shared();\n\t\tparams->Initialize( (_inputDim + 1) * _outputDim );\n\t\tSetParameters( params );\n\t\treturn params;\n\t}\n\n\tvoid SetParameters( Parameters::Ptr params )\n\t{\n\t\tif( params->ParamDim() != (_inputDim+1) * _outputDim )\n\t\t{\n\t\t\tthrow std::runtime_error( \"LinearRegressor: Invalid parameter dimension.\" );\n\t\t}\n\t\t_params = params;\n\t\tnew (&_W) Eigen::Map( params->GetParamsVec().data(),\n\t\t _outputDim, _inputDim + 1 );\n\t}\n\n\tvoid SetOffsets( const VectorType& off )\n\t{\n\t\tRowMatrixType p( _W );\n\t\tif( off.size() != p.rows() )\n\t\t{\n\t\t\tthrow std::runtime_error( \"LinearRegressor: Offsets invalid dimension.\" );\n\t\t}\n\t\tp.col( p.cols() - 1 ) = off;\n\t\tEigen::Map v( p.data(), p.size(), 1 );\n\t\t_params->SetParamsVec( v );\n\t\tnew (&_W) Eigen::Map( _params->GetParamsVec().data(),\n\t\t _outputDim, _inputDim + 1 );\n\t}\n\n\tvirtual void Foreprop()\n\t{\n\t\tVectorType out = _W * _inputPort.GetInput().homogeneous();\n\t\tSourceType::SetOutput( out );\n\t\tSourceType::Foreprop();\n\t}\n\t\n\tvirtual void BackpropImplementation( const MatrixType& nextDodx )\n\t{\n\t\tMatrixType nDodx;\n\t\tif( nextDodx.size() == 0 )\n\t\t{\n\t\t\tnDodx = MatrixType::Identity( OutputDim(), OutputDim() );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tnDodx = nextDodx;\n\t\t}\n\n\t\tif( nDodx.cols() != OutputDim() )\n\t\t{\n\t\t\tthrow std::runtime_error( \"LinearRegressor: Backprop dim error!\" );\n\t\t}\n\n\t\tconst VectorType& input = _inputPort.GetInput();\n\t\tMatrixType thisDodw = MatrixType::Zero( nDodx.rows(), ParamDim() );\n\t\tfor( unsigned int i = 0; i < nDodx.rows(); i++ )\n\t\t{\n\t\t\tfor( unsigned int j = 0; j < OutputDim(); j++ )\n\t\t\t{\n\t\t\t\tthisDodw.block(i, j*(InputDim()+1), 1, InputDim()+1) =\n\t\t\t\t\tnDodx(i,j) * input.homogeneous().transpose();\n\t\t\t}\n\t\t}\n\t\tMatrixType thisDodx = nDodx * _W;\n\n\t\tif( !SourceType::modName.empty() )\n\t\t{\n\t\t\tstd::cout << SourceType::modName << \" dodx: \" << nDodx << std::endl << \"dodw: \" << thisDodw << std::endl;\n\t\t\tstd::cout << \"acc dodw: \" << _params->GetDerivs() << std::endl;\n\t\t\tstd::cout << \"input: \" << input.transpose() << std::endl;\n\t\t\tstd::cout << \"param dim: \" << ParamDim() << std::endl;\n\t\t}\n\n\t\t_params->AccumulateDerivs( thisDodw );\n\t\t_inputPort.Backprop( thisDodx );\n\t}\n\n\tvirtual unsigned int ParamDim() const { return _W.size(); }\n\n\tconst Eigen::Map& GetWeights() const { return _W; }\n\nprivate:\n\n\tfriend std::ostream& operator<<( std::ostream& os, const LinearRegressor& lreg );\n\t\n\tunsigned int _inputDim;\n\tunsigned int _outputDim;\n\tParameters::Ptr _params;\n\tEigen::Map _W; // The weight vector\n\tSink _inputPort;\n\t\n};\n\ninline\nstd::ostream& operator<<( std::ostream& os, const LinearRegressor& lreg )\n{\n\tos << lreg._W;\n\treturn os;\n}\n\n}", "meta": {"hexsha": "0cb14f0cc8ca402f43acc519aeb552c621854fb5", "size": 3898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/modprop/compo/LinearRegressor.hpp", "max_stars_repo_name": "Humhu/modprop", "max_stars_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_stars_repo_licenses": ["AFL-3.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-11-10T00:54:53.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-10T00:54:53.000Z", "max_issues_repo_path": "include/modprop/compo/LinearRegressor.hpp", "max_issues_repo_name": "Humhu/modprop", "max_issues_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_issues_repo_licenses": ["AFL-3.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/modprop/compo/LinearRegressor.hpp", "max_forks_repo_name": "Humhu/modprop", "max_forks_repo_head_hexsha": "0cff8240d5e1522f620de8004c22a74491a0c9fb", "max_forks_repo_licenses": ["AFL-3.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8428571429, "max_line_length": 108, "alphanum_fraction": 0.6570035916, "num_tokens": 1119, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6823102107592398}} {"text": "/***********************************************************************\nThis file is part of the librjmcmc project source files.\n\nCopyright : Institut Geographique National (2008-2012)\nContributors : Mathieu Brédif, Olivier Tournaire, Didier Boldo\nemail : librjmcmc@ign.fr\n\nThis software is a generic C++ library for stochastic optimization.\n\nThis software is governed by the CeCILL license under French law and\nabiding by the rules of distribution of free software. You can use,\nmodify and/or redistribute the software under the terms of the CeCILL\nlicense as circulated by CEA, CNRS and INRIA at the following URL\n\"http://www.cecill.info\".\n\nAs a counterpart to the access to the source code and rights to copy,\nmodify and redistribute granted by the license, users are provided only\nwith a limited warranty and the software's author, the holder of the\neconomic rights, and the successive licensors have only limited liability.\n\nIn this respect, the user's attention is drawn to the risks associated\nwith loading, using, modifying and/or developing or reproducing the\nsoftware by the user in light of its specific status of free software,\nthat may mean that it is complicated to manipulate, and that also\ntherefore means that it is reserved for developers and experienced\nprofessionals having in-depth computer knowledge. Users are therefore\nencouraged to load and test the software's suitability as regards their\nrequirements in conditions enabling the security of their systems and/or\ndata to be ensured and, more generally, to use and operate it in the\nsame conditions as regards security.\n\nThe fact that you are presently reading this means that you have had\nknowledge of the CeCILL license and that you accept its terms.\n\n***********************************************************************/\n\n#ifndef EVEN_NUMBERED_ORDER_STATISTICS_UNIFORM_DISTRIBUTION_HPP\n#define EVEN_NUMBERED_ORDER_STATISTICS_UNIFORM_DISTRIBUTION_HPP\n\n#include \n// boost::math::uniform is not used as it is linked to real values rather than discrete integral values\n\nnamespace rjmcmc {\n\n // 1_(n\\in[a,b])/(b-a+1)\n class even_numbered_order_statistics_uniform_distribution {\n public:\n typedef double real_type;\n typedef int int_type;\n typedef boost::random::uniform_real_distribution rand_distribution_type;\n\n even_numbered_order_statistics_uniform_distribution(int_type k , real_type a, real_type b)\n : m_rand(a,b)\n , m_size(k) {}\n\n // new/old\n template real_type pdf_ratio(Iterator begin0, Iterator end0, Iterator begin1, Iterator end1) const\n {\n return pdf(begin1,end1)/pdf(begin0,end0);\n }\n\n template real_type pdf(Iterator begin, Iterator end) const\n {\n typedef typename std::iterator_traits::value_type T;\n const T a = m_rand.min();\n const T b = m_rand.max();\n const T s = b - a;\n T x = a;\n T res(1);\n int i = 2;\n for(Iterator it=begin; it != end; ++it, i+=2)\n {\n const T y = *it;\n if(y\n inline void operator()(Engine& e, Iterator out) const {\n std::vector v(2*m_size+1);\n for(std::vector::iterator it = v.begin(); it!=v.end(); ++it)\n *it = m_rand(e);\n std::sort(v.begin(),v.end());\n for(std::vector::iterator it = ++v.begin(); it!=v.end(); it+=2)\n *out++ = *it;\n }\n\n private:\n mutable rand_distribution_type m_rand;\n int_type m_size;\n };\n\n}; // namespace rjmcmc\n\n#endif // EVEN_NUMBERED_ORDER_STATISTICS_UNIFORM_DISTRIBUTION_HPP\n", "meta": {"hexsha": "c50958037098cf1d33f32ff7006be1d66bee394f", "size": 4043, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rjmcmc/rjmcmc/distribution/even_numbered_order_statistics_uniform_distribution.hpp", "max_stars_repo_name": "qc2105/librjmcmc", "max_stars_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-02-17T17:07:31.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-02T16:49:02.000Z", "max_issues_repo_path": "include/rjmcmc/rjmcmc/distribution/even_numbered_order_statistics_uniform_distribution.hpp", "max_issues_repo_name": "qc2105/librjmcmc", "max_issues_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-09-24T09:39:33.000Z", "max_issues_repo_issues_event_max_datetime": "2016-01-03T13:22:49.000Z", "max_forks_repo_path": "include/rjmcmc/rjmcmc/distribution/even_numbered_order_statistics_uniform_distribution.hpp", "max_forks_repo_name": "qc2105/librjmcmc", "max_forks_repo_head_hexsha": "6e031a9f6f3612394f8918c745700ae41d2aa586", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2015-03-18T17:32:26.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-04T21:38:16.000Z", "avg_line_length": 40.0297029703, "max_line_length": 125, "alphanum_fraction": 0.652733119, "num_tokens": 882, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.682226805953445}} {"text": "#ifndef FVMSCALAR1D_RECONSTRUCTION_HPP\n#define FVMSCALAR1D_RECONSTRUCTION_HPP\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\ninline double sign(double a) { return copysign(1.0, a); }\n\n//// ANCSE_CUT_START_TEMPLATE\n//----------------SlopeLimiterABegin----------------\ninline double minmod(double a, double b) {\n return 0.5 * (sign(a) + sign(b)) * std::min(std::abs(a), std::abs(b));\n}\n\ninline double maxmod(double a, double b) {\n return 0.5 * (sign(a) + sign(b)) * std::max(std::abs(a), std::abs(b));\n}\n\ninline double minmod(double a, double b, double c) {\n return minmod(a, minmod(b, c));\n}\n\ninline double minabs(double a, double b) {\n double tolerance = 1e-10;\n if (std::abs( std::abs(a) - std::abs(b) ) < tolerance)\n return 0.5*(a+b);\n return std::abs(a) < std::abs(b) ? a : b;\n}\n//----------------SlopeLimiterAEnd----------------\n\n//----------------SlopeLimiterBBegin----------------\nstruct MinMod {\n inline double operator()(double sL, double sR) const {\n return minmod(sL, sR);\n }\n};\n//----------------SlopeLimiterBEnd----------------\n\n//----------------SlopeLimiterCBegin----------------\nstruct MinAbs {\n inline double operator()(double sL, double sR) const {\n return minabs(sL, sR);\n }\n};\n\nstruct SuperBee {\n inline double operator()(double sL, double sR) const {\n double A = minmod(2.0 * sL, sR);\n double B = minmod(sL, 2.0 * sR);\n\n return maxmod(A, B);\n }\n};\n\nstruct VanLeer {\n inline double operator()(double sL, double sR) const {\n double r = sL / (sR + eps);\n return (r + std::abs(r)) / (1 + std::abs(r)) * sR;\n }\n\n private:\n double eps = 1e-10;\n};\n\nstruct MonotonizedCentral {\n inline double operator()(double sL, double sR) const {\n return minmod(2.0 * sL, 0.5 * (sL + sR), 2.0 * sR);\n }\n};\n\nstruct Unlimited {\n inline double operator()(double a, double b) const { return 0.5 * (a + b); }\n};\n//----------------SlopeLimiterCEnd----------------\n//// ANCSE_END_TEMPLATE\n\nclass PWConstantReconstruction {\n public:\n /// Compute the left and right trace at the interface i + 1/2.\n /** Note: This API is agnostic to the number of cell-averages required\n * by the method. Therefore, reconstructions with different stencil\n * sizes can implement this API; and this call can be used in parts\n * of the code that do not need to know about the details of the\n * reconstruction.\n */\n inline std::pair operator()(const Eigen::VectorXd &u,\n int i) const {\n return (*this)(u[i], u[i + 1]);\n }\n\n /// Compute the left and right trace at the interface.\n /** Piecewise constant reconstruction of the left and right trace only\n * requires the cell-average to the left and right of the interface.\n *\n * Note: Compared to the other overload this reduces the assumption on\n * how the cell-averages are stored. This is useful when testing and\n * generally makes the function useful in more situations.\n */\n inline std::pair operator()(double ua, double ub) const {\n return {ua, ub};\n }\n};\n\n//// ANCSE_CUT_START_TEMPLATE\n//----------------LinearRCBegin----------------\ntemplate \nclass PWLinearReconstruction {\n public:\n explicit PWLinearReconstruction(const SlopeLimiter &slope_limiter)\n : slope_limiter(slope_limiter) {}\n\n std::pair operator()(const Eigen::VectorXd &u,\n int i) const {\n return (*this)(u[i - 1], u[i], u[i + 1], u[i + 2]);\n }\n\n std::pair\n operator()(double ua, double ub, double uc, double ud) const {\n double sL = ub - ua;\n double sM = uc - ub;\n double sR = ud - uc;\n\n double uL = ub + 0.5 * slope_limiter(sL, sM);\n double uR = uc - 0.5 * slope_limiter(sM, sR);\n\n return {uL, uR};\n }\n\n private:\n SlopeLimiter slope_limiter;\n};\n//----------------LinearRCEnd----------------\n//// ANCSE_END_TEMPLATE\n\n#endif // FVMSCALAR1D_RATE_OF_CHANGE_HPP\n", "meta": {"hexsha": "49d5eb7246308ed547a71d5ed24a4e431121bdc3", "size": 4280, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series1_solution/fvm_scalar_1d/include/ancse/reconstruction.hpp", "max_stars_repo_name": "BeatHubmann/19H-AdvNCSE", "max_stars_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-01-05T22:38:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-05T22:38:47.000Z", "max_issues_repo_path": "series1_solution/fvm_scalar_1d/include/ancse/reconstruction.hpp", "max_issues_repo_name": "BeatHubmann/19H-AdvNCSE", "max_issues_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "series1_solution/fvm_scalar_1d/include/ancse/reconstruction.hpp", "max_forks_repo_name": "BeatHubmann/19H-AdvNCSE", "max_forks_repo_head_hexsha": "3979f768da933de82bd6ab29bbf31ea9fc31e501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-08T20:43:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-08T20:43:27.000Z", "avg_line_length": 30.1408450704, "max_line_length": 80, "alphanum_fraction": 0.5820093458, "num_tokens": 1144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.682226796450036}} {"text": "#include\n#include\n#include\n#include\n#include\n#include\n#include\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"Integrate.hpp\"\n\nusing namespace std;\nnamespace po = boost::program_options;\n\n\nvoid print_version()\n{\n cout<<\"integrate-cli - linked against libIntegrate version \"<< libIntegrate_VERSION_FULL << endl;\n}\n\nvoid print_usage(char prog_name[])\n{\n\n cout<<\"usage: \"<&,std::vector&)> create(std::string type)\n{\n if( boost::starts_with(\"riemann\",type) )\n return _1D::RiemannRule();\n\n if( boost::starts_with(\"trapezoid\",type) )\n return _1D::TrapezoidRule();\n\n if( boost::starts_with(\"simpson\",type) )\n return [](std::vector& x, std::vector& y){\n // create an interpolator to pass to the integrator\n _1D::CubicSplineInterpolator interp(x,y);\n\n double min = *std::min_element( x.begin(), x.end() );\n double max = *std::max_element( x.begin(), x.end() );\n\n _1D::SimpsonRule integ;\n\n return integ( interp, min, max, x.size() );\n };\n\n if( boost::starts_with(\"gauss-legendre\",type) )\n return [](std::vector& x, std::vector& y){\n // create an interpolator to pass to the integrator\n _1D::CubicSplineInterpolator interp(x,y);\n\n double min = *std::min_element( x.begin(), x.end() );\n double max = *std::max_element( x.begin(), x.end() );\n\n // we have quadratures of order\n // 8, 16, 32, and 64.\n if( x.size() <= 8 )\n {\n _1D::GQ::GaussLegendreQuadrature integ;\n return integ( interp, min, max );\n }\n if( x.size() <= 16 )\n {\n _1D::GQ::GaussLegendreQuadrature integ;\n return integ( interp, min, max );\n }\n if( x.size() <= 32 )\n {\n _1D::GQ::GaussLegendreQuadrature integ;\n return integ( interp, min, max );\n }\n\n _1D::GQ::GaussLegendreQuadrature integ;\n return integ( interp, min, max );\n };\n\n return nullptr;\n}\n\nvoid ReadFunction(std::istream &_in, double *&_x, double *&_y, int &_n, int _dimensions = 1, int _multiplicity = 1);\n\n\nint main( int argc, char* argv[])\n{\n po::options_description options(\"Allowed options\");\n options.add_options()\n (\"help,h\" , \"print help message\")\n (\"batch,b\" , \"output in 'batch' mode\")\n (\"method,m\" , po::value()->default_value(\"riemann\"), \"integration method.\")\n (\"list,l\" , \"list available integration methods.\")\n (\"integrate-data\" , \"file containing data to be integrated.\")\n ;\n\n po::positional_options_description args;\n args.add(\"integrate-data\", 1);\n\n po::variables_map vm;\n po::store(po::command_line_parser(argc, argv).options(options).positional(args).run(), vm);\n po::notify(vm);\n\n\n if (argc == 1 || vm.count(\"help\"))\n {\n print_version();\n print_usage( argv[0] );\n cout<<\"\\n\";\n cout << options<< \"\\n\";\n cout<<\"\\n\";\n print_documentation();\n cout<<\"\\n\";\n return 1;\n }\n\n if (vm.count(\"list\"))\n {\n print_version();\n cout<<\"\\t'riemann' : simple riemann sum\\n\";\n cout<<\"\\t'trapezoid' : trapezoid rule\\n\";\n cout<<\"\\t'simpson' : simposon's rule (uses interpolation)\\n\";\n cout<<\"\\t'gauss-legendre' : Gauss-Legendre interpolation (uses interpolation)\\n\";\n return 1;\n }\n\n\n ifstream in;\n double *x, *y, sum;\n int n;\n\n // load data\n in.open( vm[\"integrate-data\"].as().c_str() );\n if( !in.is_open() )\n {\n cerr << \"ERROR: could not open file: \"<()<< endl;\n return 0;\n }\n\n ReadFunction( in, x, y, n );\n in.close();\n\n std::function&,std::vector&)> interp;\n interp = create(vm[\"method\"].as());\n if( !interp )\n {\n delete[] x;\n delete[] y;\n cerr << \"ERROR: Unrecognized interpolation method (\" << vm[\"method\"].as()<< \").\" << endl;\n return 0;\n }\n \n std::vector X(x,x+n),Y(y,y+n);\n\n delete[] x;\n delete[] y;\n\n sum = interp(X,Y);\n\n std::cout << sum << std::endl;\n \n return 0;\n}\n\n\n\n\n\nvoid ReadFunction(std::istream &_in, double *&_x, double *&_y, int *&_n, int _dimensions, int _multiplicity)\n{\n\n double *xbuffer1, *xbuffer2;\n double *ybuffer1, *ybuffer2;\n\n //////////////////////////////\n // READ IN DATA FROM FILE //\n //////////////////////////////\n\n const int chunck = 1000;\n int buffsize,buffsize_old;\n int i,j;\n int n;\n\n std::string line;\n \n\n buffsize = chunck;\n\n xbuffer1 = new double[buffsize*_dimensions ];\n ybuffer1 = new double[buffsize*_multiplicity];\n\n i = 0;\n while( getline( _in, line ) )\n {\n // if line is blank, skip it\n if( line == \"\" )\n continue;\n std::vector columns;\n boost::char_separator sep(\" \\t\");\n boost::tokenizer> toks(line,sep);\n for( auto it = toks.begin(); it != toks.end(); ++it )\n columns.push_back( *it );\n\n // if first column starts with a #, this line is a comment\n // and we should skip it.\n if( columns.size() > 0 && columns[0].find('#') == 0 )\n continue;\n\n if(i == buffsize - 1) // this \"grows\" the buffer\n {\n buffsize_old = buffsize;\n buffsize = buffsize + chunck;\n\n xbuffer2 = new double[buffsize*_dimensions ];\n std::copy( xbuffer1, xbuffer1 + buffsize_old*_dimensions, xbuffer2);\n delete[] xbuffer1;\n\n ybuffer2 = new double[buffsize*_multiplicity];\n std::copy( ybuffer1, ybuffer1 + buffsize_old*_multiplicity, ybuffer2);\n delete[] ybuffer1;\n\n xbuffer1 = xbuffer2;\n ybuffer1 = ybuffer2;\n }\n\n for(j = 0; j < _dimensions; j++)\n xbuffer1[i*_dimensions + j] = boost::lexical_cast(columns[j]);\n for(j = 0; j < _multiplicity; j++)\n ybuffer1[i*_multiplicity + j] = boost::lexical_cast(columns[j+_dimensions]);\n\n i++;\n }\n\n n = i;\n\n\n /** \\todo add actual multi-coordinate support */\n\n _n = new int[_dimensions];\n _x = new double[n * _dimensions ];\n _y = new double[n * _multiplicity];\n\n for(j = 0; j < n * _dimensions ; j++)\n _x[j] = xbuffer1[j];\n for(j = 0; j < n * _multiplicity; j++)\n _y[j] = ybuffer1[j];\n for(j = 0; j < _dimensions; j++)\n _n[j] = n;\n\n delete[] xbuffer1;\n delete[] ybuffer1;\n\n}\n\nvoid ReadFunction(std::istream &_in, double *&_x, double *&_y, int &_n, int _dimensions, int _multiplicity)\n{\n int *n;\n ReadFunction(_in, _x, _y, n, _dimensions, _multiplicity);\n _n = n[0];\n delete[] n;\n}\n\n\n", "meta": {"hexsha": "c2db531ec687d43d36321ffbd1a6c9a04beb85ae", "size": 7163, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/integrate-cli.cpp", "max_stars_repo_name": "CD3/libIntegrate", "max_stars_repo_head_hexsha": "44067c9c579b79efa20fc4320ffaafa11224ec9f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2019-05-20T00:46:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-10T14:29:46.000Z", "max_issues_repo_path": "applications/integrate-cli.cpp", "max_issues_repo_name": "CD3/libIntegrate", "max_issues_repo_head_hexsha": "44067c9c579b79efa20fc4320ffaafa11224ec9f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-09-27T02:00:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T04:28:02.000Z", "max_forks_repo_path": "applications/integrate-cli.cpp", "max_forks_repo_name": "CD3/libIntegrate", "max_forks_repo_head_hexsha": "44067c9c579b79efa20fc4320ffaafa11224ec9f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-04-30T02:28:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-03T02:43:05.000Z", "avg_line_length": 25.8592057762, "max_line_length": 121, "alphanum_fraction": 0.5881613849, "num_tokens": 2026, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6820272321602517}} {"text": "//\n// Created by yongqi on 17-12-4.\n//\n\n#ifndef VFORCE_MATHUTILS_HPP\n#define VFORCE_MATHUTILS_HPP\n\n#include \n#include \n\nnamespace VForce {\nnamespace Utils {\n/**\n * make angle between [-pi, pi)\n * @param x input angle in radius\n * @return normalized angle\n */\ninline double normalize_angle(double x) {\n x = fmod(x + M_PI, 2 * M_PI);\n return x < 0 ? x += 2 * M_PI : x - M_PI;\n}\n\ninline float normalize_anlge(float x) {\n x = fmod(x + M_PI, 2 * M_PI);\n return x < 0 ? x += 2 * M_PI : x - M_PI;\n}\n\n/**\n * radian to degree\n * @tparam T\n * @param x\n * @return\n */\ntemplate\ninline T rad2deg(T x) {\n return x / M_PI * 180.;\n}\n\n/**\n * degree to radian\n * @tparam T\n * @param x\n * @return\n */\ntemplate\ninline T deg2rad(T x) {\n return x * M_PI / 180.;\n}\n\n/**\n * Convert pose(in Rz(yaw)Ry(pitch)Rx(roll) order) into transformation matrix\n * @tparam T\n * @param x\n * @param y\n * @param z\n * @param roll\n * @param pitch\n * @param yaw\n * @param tf\n */\ntemplate\nvoid pose2matrix(const T &x, const T &y, const T &z,\n const T &roll, const T &pitch, const T &yaw,\n Eigen::Matrix &t) {\n T A = cos(yaw), B = sin(yaw), C = cos(pitch), D = sin (pitch),\n E = cos(roll), F = sin(roll), DE = D*E, DF = D*F;\n\n t(0, 0) = A*C; t(0, 1) = A*DF - B*E; t(0, 2) = B*F + A*DE; t(0, 3) = x;\n t(1, 0) = B*C; t(1, 1) = A*E + B*DF; t(1, 2) = B*DE - A*F; t(1, 3) = y;\n t(2, 0) = -D; t(2, 1) = C*F; t(2, 2) = C*E; t(2, 3) = z;\n t(3, 0) = 0; t(3, 1) = 0; t(3, 2) = 0; t(3, 3) = 1;\n}\n\n/**\n * Convert transformation matrix into pose\n * @tparam T\n * @param matrix\n * @param x\n * @param y\n * @param z\n * @param roll\n * @param pitch\n * @param yaw\n */\ntemplate\nvoid matrix2pose(const Eigen::Matrix &t,\n T &x, T &y, T &z,\n T &roll, T &pitch, T &yaw) {\n x = t(0, 3);\n y = t(1, 3);\n z = t(2, 3);\n roll = atan2(t(2, 1), t(2, 2));\n pitch = atan2(-t(2, 0), sqrt(t(2, 1) * t(2, 1) + t(2, 2) * t(2, 2)));\n yaw = atan2(t(1, 0), t(0, 0));\n}\n\n}\n}\n\n#endif //VFORCE_MATHUTILS_HPP\n", "meta": {"hexsha": "9723786bf60c0ec7622abf655d045c2e738844fc", "size": 2145, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/MathUtils.hpp", "max_stars_repo_name": "eagleeye1105/VForce", "max_stars_repo_head_hexsha": "8a0b80ff633ccabff4410eaf7c368de2cfb0f15c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2018-05-04T04:55:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-03T06:56:23.000Z", "max_issues_repo_path": "src/utils/MathUtils.hpp", "max_issues_repo_name": "eagleeye1105/VForce", "max_issues_repo_head_hexsha": "8a0b80ff633ccabff4410eaf7c368de2cfb0f15c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-06T06:22:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-06T06:22:58.000Z", "max_forks_repo_path": "src/utils/MathUtils.hpp", "max_forks_repo_name": "freealong/VForce", "max_forks_repo_head_hexsha": "8a0b80ff633ccabff4410eaf7c368de2cfb0f15c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2018-05-04T04:53:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-28T15:51:33.000Z", "avg_line_length": 21.2376237624, "max_line_length": 77, "alphanum_fraction": 0.5198135198, "num_tokens": 870, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.7549149978955811, "lm_q1q2_score": 0.6819103500488627}} {"text": "/**\n * gaussian.hpp v1.0.0\n *\n * Contains methods related to Gaussian distributions and smoothing.\n * Methods for curve fitting are in gaussianfit.cpp.\n */\n\n#pragma once\n\n#define SQRT2PI 2.506628275\n\n#include \n\n#define ARMA_DONT_USE_WRAPPER\n#define ARMA_USE_LAPACK\n#define ARMA_DONT_PRINT_ERRORS\n#include \n\nnamespace bib {\n\n namespace gaussian {\n\n const double M_SQRT_2OVERPI = std::sqrt(2.0 / M_PI);\n const double M_SQRT_2OVERPI_CUBED = std::pow(M_SQRT_2OVERPI, 3.0);\n \n /**\n * Represents a Gaussian distribution. Comparison functions only\n * compare amplitude (used for sorting from most to least important\n * when curve fitting).\n *\n * amplitude: suqare root of the amplitude of the distribution.\n * mean: center point of the distribution.\n * stdev: standard deviation of the distribution.\n */\n struct Parameters {\n \n double amplitude;\n double mean;\n double stdev;\n\n bool operator >(const Parameters& a) const {\n\treturn amplitude * amplitude / stdev > a.amplitude * a.amplitude / a.stdev;\n }\n \n bool operator <(const Parameters& a) const {\n\treturn amplitude * amplitude / stdev < a.amplitude * a.amplitude / a.stdev;\n }\n \n };\n\n /**\n * Represents a Gaussian distribution with shape (adds skewness).\n * Comparison functions only compare amplitude (used for sorting\n * from most to least important when curve fitting).\n *\n * shape: shape parameter (alpha) capturing skewness.\n * amplitude: suqare root of the amplitude of the distribution.\n * mean: center point of the distribution.\n * stdev: standard deviation of the distribution.\n */\n struct SkewParameters {\n \n double amplitude;\n double mean;\n double stdev;\n double shape;\n\n bool operator >(const SkewParameters& a) const {\n\treturn amplitude * amplitude / stdev > a.amplitude * a.amplitude / a.stdev;\n }\n \n bool operator <(const SkewParameters& a) const {\n\treturn amplitude * amplitude / stdev < a.amplitude * a.amplitude / a.stdev;\n }\n \n };\n\n /**\n * Returns the value of a Gaussian distribution at a given point x.\n *\n * amplitude: suqare root of the amplitude of the distribution.\n * mean: center point of the distribution.\n * stdev: standard deviation of the distribution.\n * x: the point at which to sample the distribution.\n */\n inline double curveValue(double amplitude, double mean, double stdev, double x) {\n return amplitude * amplitude / stdev * std::exp( -(x - mean) * (x - mean) / stdev / stdev / 2.0 );\n }\n\n /**\n * Returns the value of a Gaussian distribution with shape at a given point x.\n *\n * amplitude: suqare root of the amplitude of the distribution.\n * mean: center point of the distribution.\n * stdev: standard deviation of the distribution.\n * shape: shape parameter (alpha) capturing skewness.\n * x: the point at which to sample the distribution.\n */\n inline double curveValue(double amplitude, double mean, double stdev, double shape, double x) {\n return amplitude * amplitude / stdev * std::exp( -(x - mean) * (x - mean) / stdev / stdev / 2.0 )\n\t* (1.0 + std::erf(shape * (x - mean) / (stdev * M_SQRT2)));\n }\n \n /**\n * Returns the value of a Gaussian distribution with shape at a given point x.\n *\n * distribution: the distribution to sample.\n * x: the point at which to sample the distribution.\n */\n inline double curveValue(Parameters distribution, double x) {\n return curveValue(distribution.amplitude, distribution.mean, distribution.stdev, x);\n }\n\n /**\n * Returns the value of a Gaussian distribution with shape at a given point x.\n *\n * distribution: the distribution to sample.\n * x: the point at which to sample the distribution.\n */\n inline double curveValue(SkewParameters distribution, double x) {\n return curveValue(distribution.amplitude, distribution.mean, distribution.stdev,\n\t\t\tdistribution.shape, x);\n }\n \n /**\n * Smooths the input vector using a Gaussian distribution of the given width.\n *\n * input: the input vector to smooth.\n * kernelWidth: standard deviation of the distribution to use for smoothing.\n */\n arma::Col smooth(const arma::Col& input, double kernelWidth);\n\n /**\n * Smooths the input vector using the second derivative of a Gaussian distribution\n * of the given width.\n *\n * input: the input vector to smooth.\n * kernelWidth: standard deviation of the distribution to use for smoothing.\n */\n arma::Col scaleSpaceSmooth(const arma::Col& input, double kernelWidth);\n\n std::vector getDistribution(double A, double x, double u, size_t length);\n\n inline int sgn(double val) {\n return (0.0 < val) - (val < 0.0);\n }\n \n inline double skewMode(SkewParameters gaussian) {\n double delta = gaussian.shape / std::sqrt(1.0 + gaussian.shape * gaussian.shape);\n double uz = M_SQRT_2OVERPI * delta;\n double oz = std::sqrt(1.0 - uz * uz);\n double skewness = ((4.0 - M_PI) / 2.0)\n\t* ((M_SQRT_2OVERPI_CUBED * delta * delta * delta) / std::pow(1.0 - 2.0 * delta * delta / M_PI, 1.5));\n return (uz - skewness * oz / 2.0 - sgn(gaussian.shape) / 2.0 * std::exp(-2.0 * M_PI / std::abs(gaussian.shape)))\n\t* gaussian.stdev + gaussian.mean;\n }\n \n }\n\n} // namespace bib::gaussian\n", "meta": {"hexsha": "8f1dd3d98374bc1921d8d0544728d441f3a0854f", "size": 5477, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "tasks/signal/src/lib/gaussian.hpp", "max_stars_repo_name": "genome-almanac/mnase-workflow", "max_stars_repo_head_hexsha": "3f75c469dd31294549f68ea413af24575be7ef1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tasks/signal/src/lib/gaussian.hpp", "max_issues_repo_name": "genome-almanac/mnase-workflow", "max_issues_repo_head_hexsha": "3f75c469dd31294549f68ea413af24575be7ef1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tasks/signal/src/lib/gaussian.hpp", "max_forks_repo_name": "genome-almanac/mnase-workflow", "max_forks_repo_head_hexsha": "3f75c469dd31294549f68ea413af24575be7ef1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0186335404, "max_line_length": 118, "alphanum_fraction": 0.6558334855, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942014971871, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6819103302608538}} {"text": "#include \"Gaussian.h\"\n#include \n#include \n#include \n#include \"../Utils.h\"\n//#include \n\nnamespace DNest4\n{\n\nGaussian::Gaussian(double center, double width)\n:center(center)\n,width(width)\n{\n if(width <= 0.0)\n throw std::domain_error(\"Gaussian distribution must have positive width.\");\n}\n\ndouble Gaussian::cdf(double x) const\n{\n return normal_cdf((x-center)/width);\n}\n\ndouble Gaussian::cdf_inverse(double x) const\n{\n if(x < 0.0 || x > 1.0)\n throw std::domain_error(\"Input to cdf_inverse must be in [0, 1].\");\n return center + width*normal_inverse_cdf(x);\n //return center + width * sqrt(2) * boost::math::erf_inv(2*x - 1);\n}\n\ndouble Gaussian::log_pdf(double x) const\n{\n\tdouble r = (x - center)/width;\n return -0.5*r*r - _norm_pdf_logC;\n}\n\n\n\nTruncatedGaussian::TruncatedGaussian(double center, double width, double lower, double upper)\n:center(center)\n,width(width)\n,lower(lower)\n,upper(upper)\n{\n if(width <= 0.0)\n throw std::domain_error(\"TruncatedGaussian distribution must have positive width.\");\n if(lower >= upper)\n throw std::domain_error(\"TruncatedGaussian: lower bound should be less than upper bound.\");\n // the original, untruncated, Gaussian distribution\n unG = Gaussian(center, width);\n c = unG.cdf(upper) - unG.cdf(lower);\n}\n\ndouble TruncatedGaussian::cdf(double x) const\n{\n double up = std::max(std::min(x,upper), lower);\n return (unG.cdf(up) - unG.cdf(lower)) / c;\n}\n\ndouble TruncatedGaussian::cdf_inverse(double x) const\n{\n if(x < 0.0 || x > 1.0)\n throw std::domain_error(\"Input to cdf_inverse must be in [0, 1].\");\n double xx = unG.cdf(lower) + x * c;\n return unG.cdf_inverse(xx);\n}\n\ndouble TruncatedGaussian::log_pdf(double x) const\n{\n if(xupper) return -std::numeric_limits::infinity();\n return unG.log_pdf(x) - log(c);\n}\n\n\n\n} // namespace DNest4", "meta": {"hexsha": "568d45c676bf76850dee23e48f544c092e9b31e5", "size": 1935, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/Distributions/Gaussian.cpp", "max_stars_repo_name": "j-faria/DNest4", "max_stars_repo_head_hexsha": "a8b2f6b133c7106db495c9cede8a7927cdaff46d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/Distributions/Gaussian.cpp", "max_issues_repo_name": "j-faria/DNest4", "max_issues_repo_head_hexsha": "a8b2f6b133c7106db495c9cede8a7927cdaff46d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/Distributions/Gaussian.cpp", "max_forks_repo_name": "j-faria/DNest4", "max_forks_repo_head_hexsha": "a8b2f6b133c7106db495c9cede8a7927cdaff46d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-13T09:58:15.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-13T09:58:15.000Z", "avg_line_length": 25.1298701299, "max_line_length": 99, "alphanum_fraction": 0.6733850129, "num_tokens": 540, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6818044387953641}} {"text": "/*\nMIT License\n\nCopyright (c) 2020 kyawakyawa\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n#include \n#include \n\n#include \"macros.h\"\n\nIGNORE_STRICT_WARNING_PUSH\n\n#include \n\nIGNORE_STRICT_WARNING_POP\n\n// reference http://takashiijiri.com/study/miscs/QRfactorization.htm\n\ntemplate \nEigen::Matrix HouseholderTransformation(\n const Eigen::Matrix& x, const Eigen::Matrix& y) {\n static_assert(N >= 1);\n const auto aux = x - y;\n const Eigen::Matrix u = aux.normalized();\n\n return Eigen::Matrix::Identity() - 2 * u * u.transpose();\n}\n\ntemplate \nEigen::Matrix HouseholderTransformation(\n const Eigen::Matrix& x,\n const Eigen::Matrix& y) {\n assert(x.rows() >= 1 && x.rows() == y.rows());\n const auto aux = x - y;\n const Eigen::Matrix u = aux.normalized();\n\n return Eigen::Matrix::Identity(\n x.rows(), x.rows()) -\n 2 * u * u.transpose();\n}\n\ntemplate \nstd::pair, Eigen::Matrix>\nQRDecompositionWithHouseholderTransformation(\n const Eigen::Matrix& input) {\n static_assert(M >= 1 && N >= M);\n Eigen::Matrix R = input;\n Eigen::Matrix Q = Eigen::Matrix::Identity();\n\n for (int k = 0; k < M - 1; ++k) {\n const Real sign = (R(k, k) >= Real(0) ? Real(1) : Real(-1));\n const int Mmk = M - k;\n\n const Eigen::Matrix x = R.block(k, k, Mmk, 1);\n // グラフィック用途(ローテーションとスケールの分離)の場合、\n // y(0,0)の符号は+で固定したほうがいい(この値がRの対角要素になる)\n Eigen::Matrix y =\n Eigen::Matrix::Zero(Mmk, 1);\n const Real norm = x.norm();\n // uが0 vectorになる場合\n // この場合はそもそも計算する必要がない\n if (std::abs(norm - std::abs(x[0])) <\n std::numeric_limits::epsilon()) {\n continue;\n }\n y[0] = -sign * x.norm();\n\n const Eigen::Matrix u = (x - y).normalized();\n\n R.bottomRightCorner(Mmk, Mmk) -=\n Real(2) * u * (u.transpose() * R.bottomRightCorner(Mmk, Mmk));\n //////////////////// Rのみ欲しい場合はここまでの計算で良い\n ///////////////////////\n\n if (k > 0) {\n Q.topRightCorner(k, Mmk) -=\n Real(2) * (Q.topRightCorner(k, Mmk) * u) * u.transpose();\n }\n Q.bottomRightCorner(Mmk, Mmk) -=\n Real(2) * (Q.bottomRightCorner(Mmk, Mmk) * u) * u.transpose();\n }\n\n return std::make_pair(Q, R);\n}\n\n#ifdef USE_STACK_TRACE_LOGGER\n#include \n#endif\n\nint main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) {\n#ifdef USE_STACK_TRACE_LOGGER\n (void)argc;\n google::InitGoogleLogging(argv[0]);\n google::InstallFailureSignalHandler();\n#endif\n\n const Eigen::Vector3d x = {1, 2, 3};\n const Eigen::Vector3d y = {3, 2, 1};\n\n std::cout << \"----------HouseholderTransformation----------\" << std::endl;\n\n std::cout << \" x = (\" << x.transpose() << \")^T\\n y = (\" << y.transpose()\n << \")^T\\n\"\n << std::endl;\n\n const Eigen::Matrix3d H = HouseholderTransformation(x, y);\n std::cout << \" H = \\n\" << H << \"\\n\" << std::endl;\n\n const Eigen::Vector3d Hx = H * x;\n const Eigen::Vector3d Hy = H * y;\n\n std::cout << \" (Hx)^T = (\" << Hx.transpose() << \")\\n\" << std::endl;\n std::cout << \" (Hy)^T = (\" << Hy.transpose() << \")\\n\" << std::endl;\n\n std::cout << \" H*H^T = \\n\" << H * H.transpose() << \"\\n\" << std::endl;\n\n std::cout << \"---------- ----------\" << std::endl;\n\n std::cout\n << \"----------QRDecompositionWithHouseholderTransformation----------\"\n << std::endl;\n Eigen::Matrix3d A;\n\n A(0, 0) = 1.;\n A(0, 1) = 4.;\n A(0, 2) = 9.;\n\n A(1, 0) = 16.;\n A(1, 1) = 25.;\n A(1, 2) = 36.;\n\n A(2, 0) = 49.;\n A(2, 1) = 64.;\n A(2, 2) = 81.;\n\n const auto result = QRDecompositionWithHouseholderTransformation(A);\n\n std::cout << \" Q = \\n\" << result.first << \"\\n\" << std::endl;\n std::cout << \" R = \\n\" << result.second << \"\\n\" << std::endl;\n\n std::cout << \" QR = \\n\" << result.first * result.second << \"\\n\" << std::endl;\n\n std::cout << \" QQ^T = \\n\"\n << result.first * result.first.transpose() << \"\\n\"\n << std::endl;\n\n std::cout << \"---------- ----------\" << std::endl;\n return 0;\n}\n", "meta": {"hexsha": "55539df7fa78f7fceaf60d03934df20d6b12d96b", "size": 5366, "ext": "cc", "lang": "C++", "max_stars_repo_path": "pc/qr-decomposition.cc", "max_stars_repo_name": "kyawakyawa/cpp-junk-parts", "max_stars_repo_head_hexsha": "f56432e9a097d4b151803164cd6847ef152b8e16", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "pc/qr-decomposition.cc", "max_issues_repo_name": "kyawakyawa/cpp-junk-parts", "max_issues_repo_head_hexsha": "f56432e9a097d4b151803164cd6847ef152b8e16", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pc/qr-decomposition.cc", "max_forks_repo_name": "kyawakyawa/cpp-junk-parts", "max_forks_repo_head_hexsha": "f56432e9a097d4b151803164cd6847ef152b8e16", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7514792899, "max_line_length": 79, "alphanum_fraction": 0.6082743198, "num_tokens": 1680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.7879311856832191, "lm_q1q2_score": 0.6817370454814721}} {"text": "/**\n * @file Interpolation.hpp\n * @author bwu\n * @brief Interpolation method implementation\n * @version 0.1\n * @date 2022-02-22\n */\n#ifndef GENERIC_MATH_INTERPOLATION_HPP\n#define GENERIC_MATH_INTERPOLATION_HPP\n#include \n#include \n#include \n#include \"generic/common/Traits.hpp\"\n#include \"MathUtility.hpp\"\n#include \nnamespace generic {\nnamespace math {\nusing generic::common::float_type;\ntemplate \nclass Interpolation\n{\n using float_t = float_type;\n using vector_t = boost::numeric::ublas::vector;\n using band_matrix_t = boost::numeric::ublas::banded_matrix;\npublic:\n enum class Method { Linear = 1, Cubic = 2};\n enum class BCType { FirstDeriv = 1, SecondDeriv = 2, NotAKnot = 3 };\n\n ///@brief constructs an interpolation object with method\n Interpolation(Method method = Method::Linear);\n /**\n * @brief constructs an interpolation object with parameters\n * @param x input samples of x\n * @param y input samples of y\n * @param method interpolation method\n * @note if Cubic method failed with input x, y samples, it will decay to Linear method\n * @param monotonic set whether curve monotonic when interpolation\n * @param left left boundary condition type\n * @param lValue left boundary condition initial value\n * @param right right boundary condition type\n * @param rValue right boundary condition inital value\n */\n Interpolation(const std::vector & x, const std::vector & y,\n Method method, bool monotonic = false,\n BCType left = BCType::SecondDeriv, float_t lValue = 0,\n BCType right = BCType::SecondDeriv, float_t rValue = 0);\n\n ///@brief sets boundary conditions and inital values\n void SetBoundary(BCType left, BCType right, float_t lVal, float_t rVal);\n ///@brief sets input samples of x and y\n void SetSamples(const std::vector & x, const std::vector & y);\n\n ///@brief gets interpolated value of input x\n num_type operator() (num_type x) const { return Interpolate(x); }\n\nprivate:\n void UpdateCoefficients();\n bool makeMonotonic();\n size_t FindClosest(num_type x) const;\n num_type Interpolate(num_type x) const;\n num_type Interpolate(num_type x, const num_integer_tag) const;\n float_t Interpolate(num_type x, const num_floating_tag) const;\n\nprivate:\n Method m_method;\n bool m_monotonic;\n BCType m_left, m_right;\n float_t m_lVal, m_rVal;\n std::vector m_x, m_y;\n float_t m_coef0 = 0;\n std::vector m_coef1, m_coef2, m_coef3;\n};\n\ntemplate \ninline Interpolation::Interpolation(Method method)\n : m_method(method), m_monotonic(false), m_left(BCType::SecondDeriv), m_right(BCType::SecondDeriv), m_lVal(0), m_rVal(0)\n{\n}\n\ntemplate \ninline Interpolation::Interpolation(const std::vector & x, const std::vector & y,\n Method method, bool monotonic,\n BCType left, float_t lValue, BCType right, float_t rValue)\n : m_method(method), m_monotonic(monotonic), m_left(left), m_right(right), m_lVal(lValue), m_rVal(rValue)\n{\n SetSamples(x, y);\n}\n\ntemplate \ninline void Interpolation::SetBoundary(BCType left, BCType right, float_t lVal, float_t rVal)\n{\n assert(m_x.size() == 0 && \"should set boundary type before setting samples\");\n m_left = left; m_right = right;\n m_lVal = lVal; m_rVal = rVal;\n}\n\ntemplate \ninline void Interpolation::SetSamples(const std::vector & x, const std::vector & y)\n{\n const size_t size = x.size();\n assert(size > 0 && size == y.size());\n m_x = x; m_y = y;\n m_coef1.assign(size, 0); m_coef2.assign(size, 0), m_coef3.assign(size, 0);\n if(size < 2) return;\n if(size < 3) m_method = Method::Linear;\n if(Method::Linear == m_method){\n for(size_t i = 0, j = 1; i < size - 1; ++i, ++j)\n m_coef1[i] = float_t(m_y[j] - m_y[i]) / float_t(m_x[j] - m_x[i]);\n m_coef1[size - 1] = m_coef1[size - 2];\n }\n else if(Method::Cubic == m_method){\n size_t lower = (m_right == BCType::NotAKnot) ? 2 : 1;\n size_t upper = (m_left == BCType::NotAKnot) ? 2 : 1;\n band_matrix_t m(size, size, lower, upper);\n vector_t rhs(size);\n for(size_t i = 0, j = 1, k = 2; k < size; ++i, ++j, ++k){\n m(j, i) = 1.0 / 3.0 * (m_x[j] - m_x[i]);\n m(j, j) = 2.0 / 3.0 * (m_x[k] - m_x[i]);\n m(j, k) = 1.0 / 3.0 * (m_x[k] - m_x[j]);\n rhs[j] = (m_y[k] - m_y[j]) / (m_x[k] - m_x[j]) - (m_y[j] - m_y[i]) / (m_x[j] - m_x[i]);\n }\n //BC\n if(m_left == BCType::FirstDeriv){\n m(0, 0) = 2.0 * (m_x[1] - m_x[0]);\n m(0, 1) = 1.0 * (m_x[1] - m_x[0]);\n rhs[0] = 3.0 * ((m_y[1] - m_y[0]) / (m_x[1] - m_x[0]) - m_lVal);\n }\n else if(m_left == BCType::SecondDeriv){\n m(0, 0) = 2.0;\n m(0, 1) = 0.0;\n rhs[0] = m_lVal;\n }\n else if(m_left == BCType::NotAKnot){\n m(0, 0) = - m_x[2] + m_x[1];\n m(0, 1) = m_x[2] - m_x[0];\n m(0, 2) = - m_x[1] + m_x[0];\n rhs[0] = 0.0;\n }\n else { assert(false); }\n\n if(m_right == BCType::FirstDeriv){\n m(size - 1, size - 1) = 2.0 * (m_x[size - 1] - m_x[size - 2]);\n m(size - 1, size - 2) = 1.0 * (m_x[size - 1] - m_x[size - 2]);\n rhs[size - 1] = 3.0 * (m_rVal - (m_y[size - 1] - m_y[size - 2]) / (m_x[size - 1] - m_x[size - 2]));\n }\n else if(m_right == BCType::SecondDeriv){\n m(size - 1, size - 1) = 2.0;\n m(size - 1, size - 2) = 0.0;\n rhs[size - 1] = m_rVal;\n }\n else if(m_right == BCType::NotAKnot){\n m(size - 1, size - 3) = - m_x[size - 1] + m_x[size - 2];\n m(size - 1, size - 2) = m_x[size - 1] - m_x[size - 3];\n m(size - 1, size - 1) = - m_x[size - 2] + m_x[size - 3]; \n }\n else { assert(false); }\n\n boost::numeric::ublas::permutation_matrix pm(size);\n\n //decay to linear method if fail at LU factorization \n try {\n lu_factorize(m, pm);\n lu_substitute(m, pm, rhs);\n }\n catch (...) {\n m_method = Method::Linear;\n SetSamples(x, y);\n return;\n }\n\n for(size_t i = 0; i < size; ++i)\n m_coef2[i] = rhs[i];\n \n for(size_t i = 0, j = 1; j < size; ++i, ++j) {\n m_coef1[i] = (m_y[j] - m_y[i]) / (m_x[j] - m_x[i]) - 1.0 / 3.0 * (2.0 * m_coef2[i] + m_coef2[j]) * (m_x[j] - m_x[i]);\n m_coef3[i] = 1.0 / 3.0 * (m_coef2[j] - m_coef2[i]) / (m_x[j] - m_x[i]);\n }\n\n float_t h = x[size - 1] - x[size - 2];\n m_coef3[size - 1] = 0.0;\n m_coef1[size - 1] = 3.0 * m_coef3[size - 2] * h * h + 2.0 * m_coef2[size - 2] * h + m_coef1[size - 2];\n if(m_right == BCType::FirstDeriv) m_coef2[size - 1] = 0.0;\n }\n m_coef0 = (m_left == BCType::FirstDeriv) ? 0 : m_coef3[0];\n \n if(!m_monotonic && size > 2) makeMonotonic();\n}\n\ntemplate \ninline void Interpolation::UpdateCoefficients()\n{\n size_t size = m_coef1.size();\n for(size_t i = 0; i < size - 1; ++i){\n const float_t h = m_x[i + 1] - m_x[i];\n m_coef2[i] = (3.0 * (m_y[i + 1] - m_y[i]) / h - (2.0 * m_coef1[i] + m_coef1[i + 1])) / h;\n m_coef3[i] = ((m_coef1[i + 1] - m_coef1[i]) / (3.0 * h) - 2.0 / 3.0 * m_coef2[i]) / h;\n }\n m_coef0 = (m_left == BCType::FirstDeriv) ? 0 : m_coef3[0];\n}\n\ntemplate \ninline bool Interpolation::makeMonotonic()\n{\n assert(m_x.size() > 2);\n bool modified = false;\n for(size_t i = 0; i < m_x.size(); ++i){\n size_t im1 = std::max(i - 1, size_t(0));\n size_t ip1 = std::min(i + 1, m_x.size() - 1);\n if((m_y[im1] <= m_y[i] && m_y[i] <= m_y[ip1] && m_coef1[i] < 0) ||\n (m_y[im1] >= m_y[i] && m_y[i] >= m_y[ip1] && m_coef1[i] > 0)) {\n modified = true;\n m_coef1[i] = 0;\n }\n }\n\n for(size_t i = 0; i < m_x.size() - 1; ++i){\n float_t avg = float_t(m_y[i + 1] - m_y[i]) / float_t(m_x[i + 1] - m_x[i]);\n if(EQ(avg, 0.0) && (!EQ(m_coef1[i], 0.0) || !EQ(m_coef1[i], 0.0))){\n modified = true;\n m_coef1[i] = 0;\n m_coef1[i + 1] = 0;\n }\n else if((GE(m_coef1[i], 0.0) && GE(m_coef1[i + 1], 0.0) && GE(avg, 0.0)) ||\n (LE(m_coef1[i], 0.0) && LE(m_coef1[i + 1], 0.0) && LE(avg, 0.0))) {\n float_t r = std::sqrt(m_coef1[i] * m_coef1[i] + m_coef1[i + 1] * m_coef1[i + 1]) / std::fabs(avg);\n if(r > 3.0){\n modified = true;\n m_coef1[i] *= (3.0 / r);\n m_coef1[i + 1] *= (3.0 / r);\n }\n }\n }\n\n if(modified == true){\n UpdateCoefficients();\n m_monotonic = true;\n }\n return modified;\n}\n\ntemplate \ninline size_t Interpolation::FindClosest(num_type x) const\n{\n typename std::vector::const_iterator iter;\n iter = std::upper_bound(m_x.begin(), m_x.end(), x);\n size_t index = std::max(int(iter - m_x.begin() - 1), 0);\n return index;\n}\n\ntemplate \ninline num_type Interpolation::Interpolate(num_type x) const\n{\n return Interpolate(x, typename num_traits_float_or_int::tag());\n}\n\ntemplate \ninline num_type Interpolation::Interpolate(num_type x, const num_integer_tag) const\n{\n return num_type(std::round(Interpolate(x, num_floating_tag())));\n}\n\ntemplate \ninline float_type Interpolation::Interpolate(num_type x, const num_floating_tag) const\n{\n size_t n = m_x.size();\n size_t idx = FindClosest(x);\n float_t h = x - m_x[idx];\n if(x < m_x[0]) return (m_coef0 * h + m_coef1[0]) * h + m_y[0];\n else if(x > m_x[n - 1]) return (m_coef2[n-1] * h + m_coef1[n - 1]) * h + m_y[n - 1];\n else return ((m_coef3[idx] * h + m_coef2[idx]) * h + m_coef1[idx]) * h + m_y[idx]; \n}\n\n}//namespace math\n}//namespace generic\n#endif//GENERIC_MATH_INTERPOLATION_HPP", "meta": {"hexsha": "70d467b7378f3d45d8e17c49f723ad4d786dd957", "size": 10481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "math/Interpolation.hpp", "max_stars_repo_name": "Draaaaaaven/generic", "max_stars_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-01-05T02:34:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-19T13:51:50.000Z", "max_issues_repo_path": "math/Interpolation.hpp", "max_issues_repo_name": "Draaaaaaven/generic", "max_issues_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/Interpolation.hpp", "max_forks_repo_name": "Draaaaaaven/generic", "max_forks_repo_head_hexsha": "f72a1896058486ef865cb2a0a722d70b2398a7af", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1127272727, "max_line_length": 129, "alphanum_fraction": 0.5646407786, "num_tokens": 3402, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513648201266, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.6817341856133396}} {"text": "#include \"Tetrahedron.h\"\n#include \n#include \n\nnamespace ZIRAN {\n\ntemplate \nvoid barycentricWeights(\n const Vector& p,\n const Vector& a,\n const Vector& b,\n const Vector& c,\n const Vector& d,\n Vector& weights)\n{\n Matrix Dm;\n Dm.col(0) = a - d;\n Dm.col(1) = b - d;\n Dm.col(2) = c - d;\n\n Vector weights_for_abc = Dm.partialPivLu().solve(p - d);\n weights.template head<3>() = weights_for_abc;\n weights(3) = (T)1 - weights_for_abc.array().sum();\n ZIRAN_ASSERT((weights.array() >= (T)0).all(), weights.transpose());\n ZIRAN_ASSERT((weights.array() <= (T)1).all(), weights.transpose());\n ZIRAN_ASSERT(std::abs(weights.array().sum() - (T)1) < 1e-7, weights.transpose());\n\n Vector test_p = Vector::Constant((T)0);\n test_p += weights(0) * a;\n test_p += weights(1) * b;\n test_p += weights(2) * c;\n test_p += weights(3) * d;\n ZIRAN_ASSERT((p - test_p).squaredNorm() < 1e-7);\n}\n\ntemplate void barycentricWeights(Eigen::Matrix const&, Eigen::Matrix const&, Eigen::Matrix const&, Eigen::Matrix const&, Eigen::Matrix const&, Eigen::Matrix&);\ntemplate void barycentricWeights(Eigen::Matrix const&, Eigen::Matrix const&, Eigen::Matrix const&, Eigen::Matrix const&, Eigen::Matrix const&, Eigen::Matrix&);\n} // namespace ZIRAN\n", "meta": {"hexsha": "9e2082496f919a12937dcc43fd9110b84e83ff9e", "size": 1664, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lib/Ziran/Math/Geometry/Tetrahedron.cpp", "max_stars_repo_name": "NTForked/ziran2019", "max_stars_repo_head_hexsha": "35742ac3ab1ae42cf2bbe8761fd7c8e630a638c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 73.0, "max_stars_repo_stars_event_min_datetime": "2019-11-06T13:33:46.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-06T15:54:50.000Z", "max_issues_repo_path": "Lib/Ziran/Math/Geometry/Tetrahedron.cpp", "max_issues_repo_name": "NTForked/ziran2019", "max_issues_repo_head_hexsha": "35742ac3ab1ae42cf2bbe8761fd7c8e630a638c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-06-24T21:19:33.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-15T19:37:53.000Z", "max_forks_repo_path": "Lib/Ziran/Math/Geometry/Tetrahedron.cpp", "max_forks_repo_name": "NTForked/ziran2019", "max_forks_repo_head_hexsha": "35742ac3ab1ae42cf2bbe8761fd7c8e630a638c4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2019-11-07T07:15:45.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-06T10:40:39.000Z", "avg_line_length": 42.6666666667, "max_line_length": 305, "alphanum_fraction": 0.6033653846, "num_tokens": 654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070109242131, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6815997019099154}} {"text": "// Copyright Christopher Kormanyos 2021.\n// Distributed under the Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#include \n#include \n#include \n#include \n\n// cd C:\\Users\\User\\Documents\\Ks\\PC_Software\\NumericalPrograms\\ExtendedNumberTypes\\e_float\\libs\\e_float\\build\n\n// g++ -Wall -Wextra -m64 -O3 -std=gnu++11 -DE_FLOAT_TYPE_EFX -I../../../libs/e_float/src -IC:/boost/modular_boost/boost/libs/multiprecision/include -IC:/boost/modular_boost/boost/libs/math/include -IC:/boost/boost_1_75_0 ../src/e_float/efx/e_float_efx.cpp ../src/e_float/e_float.cpp ../src/e_float/e_float_base.cpp ../src/functions/constants/constants.cpp ../src/functions/elementary/elementary_complex.cpp ../src/functions/elementary/elementary_hyper_g.cpp ../src/functions/elementary/elementary_math.cpp ../src/functions/elementary/elementary_trans.cpp ../src/functions/elementary/elementary_trig.cpp ../test_boost/test_boost.cpp -o test_boost.exe\n\nnamespace local\n{\n using big_float_type = boost::multiprecision::number;\n\n template\n FloatingPointType hypergeometric_2f1(const FloatingPointType& a,\n const FloatingPointType& b,\n const FloatingPointType& c,\n const FloatingPointType& x)\n {\n // Compute the series representation of hypergeometric_2f1\n // taken from Abramowitz and Stegun 15.1.1.\n // There are no checks on input range or parameter boundaries.\n\n FloatingPointType x_pow_n_div_n_fact(x);\n FloatingPointType pochham_a (a);\n FloatingPointType pochham_b (b);\n FloatingPointType pochham_c (c);\n FloatingPointType ap (a);\n FloatingPointType bp (b);\n FloatingPointType cp (c);\n\n FloatingPointType h2f1 = 1 + (((pochham_a * pochham_b) / pochham_c) * x_pow_n_div_n_fact);\n\n const FloatingPointType tol = std::numeric_limits::epsilon() * x;\n\n // Series expansion of hyperg_2f1(a, b; c; x).\n for(std::int32_t n = INT32_C(2); n < INT32_C(100000); ++n)\n {\n x_pow_n_div_n_fact *= x;\n x_pow_n_div_n_fact /= n;\n\n pochham_a *= ++ap;\n pochham_b *= ++bp;\n pochham_c *= ++cp;\n\n const FloatingPointType term = ((pochham_a * pochham_b) / pochham_c) * x_pow_n_div_n_fact;\n\n using std::fabs;\n\n if((n > 11) && (fabs(term) < tol))\n {\n break;\n }\n\n h2f1 += term;\n }\n\n return h2f1;\n }\n\n template\n FloatingPointType hypergeometric_2f1_regularized(const FloatingPointType& a,\n const FloatingPointType& b,\n const FloatingPointType& c,\n const FloatingPointType& x)\n {\n return hypergeometric_2f1(a, b, c, x) / boost::math::tgamma(c);\n }\n\n template\n FloatingPointType pochhammer(const FloatingPointType& x,\n const FloatingPointType& a)\n {\n return boost::math::tgamma(x + a) / boost::math::tgamma(x);\n }\n\n template\n FloatingPointType legendre_pvu(const FloatingPointType& v,\n const FloatingPointType& u,\n const FloatingPointType& x)\n {\n using std::pow;\n\n // See also the third series representation provided in:\n // https://functions.wolfram.com/HypergeometricFunctions/LegendreP2General/06/01/04/\n\n const FloatingPointType u_half = u / 2U;\n const FloatingPointType one_minus_x = 1U - x;\n const FloatingPointType one_minus_mu = 1U - u;\n\n const FloatingPointType tgamma_term = boost::math::tgamma(one_minus_mu);\n const FloatingPointType h2f1_reg_term = hypergeometric_2f1_regularized(FloatingPointType(-v),\n FloatingPointType(1U + v),\n one_minus_mu,\n FloatingPointType(one_minus_x / 2U));\n\n return (pow(1U + x, u_half) * h2f1_reg_term) / pow(one_minus_x, u_half);\n }\n\n template\n FloatingPointType legendre_qvu(const FloatingPointType& v,\n const FloatingPointType& u,\n const FloatingPointType& x)\n {\n using std::cos;\n using std::pow;\n using std::sin;\n\n // See also the third series representation provided in:\n // https://functions.wolfram.com/HypergeometricFunctions/LegendreQ2General/06/01/02/\n\n const FloatingPointType u_pi = u * boost::math::constants::pi();\n const FloatingPointType sin_u_pi = sin(u_pi);\n const FloatingPointType cos_u_pi = cos(u_pi);\n\n const FloatingPointType one_minus_x = 1U - x;\n const FloatingPointType one_plus_x = 1U + x;\n const FloatingPointType u_half = u / 2U;\n const FloatingPointType one_minus_x_over_two = one_minus_x / 2U;\n\n const FloatingPointType one_plus_x_over_one_minus_x_pow_u_half = pow(one_plus_x / one_minus_x, u_half);\n\n const FloatingPointType v_plus_one = v + 1U;\n\n const FloatingPointType h2f1_1 = hypergeometric_2f1_regularized(FloatingPointType(-v), v_plus_one, FloatingPointType(1U - u), one_minus_x_over_two);\n const FloatingPointType h2f1_2 = hypergeometric_2f1_regularized(FloatingPointType(-v), v_plus_one, FloatingPointType(1U + u), one_minus_x_over_two);\n\n const FloatingPointType term1 = (h2f1_1 * one_plus_x_over_one_minus_x_pow_u_half) * cos_u_pi;\n const FloatingPointType term2 = (h2f1_2 / one_plus_x_over_one_minus_x_pow_u_half) * pochhammer(FloatingPointType(v_plus_one - u), FloatingPointType(u * 2U));\n\n return (boost::math::constants::half_pi() * (term1 - term2)) / sin_u_pi;\n }\n}\n\nbool test___tgamma()\n{\n const local::big_float_type x(0.5F);\n\n const local::big_float_type g = boost::math::tgamma(x);\n const local::big_float_type sqrt_pi = boost::math::constants::root_pi();\n\n std::cout << std::setprecision(std::numeric_limits::digits10) << g << std::endl;\n std::cout << std::setprecision(std::numeric_limits::digits10) << sqrt_pi << std::endl;\n\n const local::big_float_type ratio = g / sqrt_pi;\n const local::big_float_type delta = fabs(1 - ratio);\n\n const bool result_is_ok = delta < std::numeric_limits::epsilon() * 10U;\n\n return result_is_ok;\n}\n\nbool test_legendre()\n{\n const local::big_float_type x = local::big_float_type(UINT32_C(789)) / 1000U;\n\n // Compute some values of the Legendre function of the second kind\n // on the real axis within the unit circle.\n\n const local::big_float_type lpvu = local::legendre_pvu(local::big_float_type(local::big_float_type(1U) / 3),\n local::big_float_type(local::big_float_type(1U) / 7),\n x);\n\n const local::big_float_type lqvu = local::legendre_qvu(local::big_float_type(local::big_float_type(1U) / 3),\n local::big_float_type(local::big_float_type(1U) / 7),\n x);\n\n // N[LegendreP[1/3, 1/7, 2, 789/1000], 104]\n const local::big_float_type control_lpvu\n {\n \"0.99315918549340645725680897933376572969241094126736434178747245976770375217673830111149222182128969080027\"\n };\n\n // N[LegendreQ[1/3, 1/7, 2, 789/1000], 104]\n const local::big_float_type control_lqvu\n {\n \"0.18027013586354735033576549475861160812128148962186378344662781978695122523958952227406954299821460356031\"\n };\n\n std::cout << std::setprecision(std::numeric_limits::digits10) << lpvu << std::endl;\n std::cout << std::setprecision(std::numeric_limits::digits10) << control_lpvu << std::endl;\n std::cout << std::setprecision(std::numeric_limits::digits10) << lqvu << std::endl;\n std::cout << std::setprecision(std::numeric_limits::digits10) << control_lqvu << std::endl;\n\n using std::fabs;\n\n const local::big_float_type closeness_lpvu = fabs(1 - (lpvu / control_lpvu));\n const local::big_float_type closeness_lqvu = fabs(1 - (lqvu / control_lqvu));\n\n const bool result_lpvu_is_ok = (closeness_lpvu < (std::numeric_limits::epsilon() * UINT32_C(10000000)));\n const bool result_lqvu_is_ok = (closeness_lqvu < (std::numeric_limits::epsilon() * UINT32_C(10000000)));\n\n const bool result_is_ok = (result_lpvu_is_ok && result_lqvu_is_ok);\n\n return result_is_ok;\n}\n\nbool test_boost_sf()\n{\n const bool test_tgamma___is_ok = test___tgamma();\n const bool test_legendre_is_ok = test_legendre();\n\n std::cout << \"test_tgamma___is_ok: \" << std::boolalpha << test_tgamma___is_ok << std::endl;\n std::cout << \"test_legendre_is_ok: \" << std::boolalpha << test_legendre_is_ok << std::endl;\n\n const bool result_is_ok = (test_tgamma___is_ok && test_legendre_is_ok);\n\n return result_is_ok;\n}\n", "meta": {"hexsha": "076a948786206c397c4192a870b0c8dc3a7a66b0", "size": 9603, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/e_float/test_boost/test_boost_sf.cpp", "max_stars_repo_name": "ckormanyos/e_float-2021", "max_stars_repo_head_hexsha": "fac3eef3aa15cc5b74fb19135d6474396cbc6fa8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "libs/e_float/test_boost/test_boost_sf.cpp", "max_issues_repo_name": "ckormanyos/e_float-2021", "max_issues_repo_head_hexsha": "fac3eef3aa15cc5b74fb19135d6474396cbc6fa8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2021-02-08T14:43:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T15:12:27.000Z", "max_forks_repo_path": "libs/e_float/test_boost/test_boost_sf.cpp", "max_forks_repo_name": "ckormanyos/e_float-2021", "max_forks_repo_head_hexsha": "fac3eef3aa15cc5b74fb19135d6474396cbc6fa8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.6651162791, "max_line_length": 650, "alphanum_fraction": 0.6593772779, "num_tokens": 2526, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907001151883, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6815996945895881}} {"text": "/*\n * FileName: main.cpp\n * Description: Main program.\n * Copyright (C) 2014 K M Masum Habib \n * Created: 02 Nov 2014.\n */\n\n#include \"main.h\"\n#include \"config.h\"\n\n#include \n#include \n#include \n\n#include \n\n\n\nusing namespace std;\nusing namespace arma;\n\n/*\n * The main function\n */\nint main(int argc, char** argv) {\n\n cout << \"Armadillo Minimum Project v\" << ARMAMIN_VERSION << endl;\n\n mat A = randu(3,3); // construct a random 3x3 matrix.\n mat B;\n B << 1 << 2 << 3 << endr // B = | 1 2 3 |\n << 4 << 5 << 6 << endr // | 4 5 6 |\n << 7 << 8 << 9 << endr;// | 7 8 8 |\n\n // print A and B\n cout << \"A = \" << endl << A << endl;\n cout << \"B = \" << endl << B << endl;\n \n // compute A*B\n mat C = A*B;\n // show A*B\n cout << \"A*B = \" << endl << C << endl;\n \n // compute A+B\n C = A+B;\n // show A+B\n cout << \"A+B = \" << endl << C << endl;\n\n // compute inverse\n C = solve(A, B);\n cout << \"A\\\\B = \" << endl << C << endl;\n\n // Eigenvalue solver\n cx_vec E = eig_gen(A);\n cout << \"Eigen values of (A): \" << endl << E << endl;\n\n \n return MAIN_SUCCESS;\n}\n\n", "meta": {"hexsha": "a531023debdcd91e13a44b96e9fc97ea8b03d674", "size": 1213, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "masumhabib/armamin", "max_stars_repo_head_hexsha": "676182a0a8f7f0e7dfa957bcae457943688a12a1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "masumhabib/armamin", "max_issues_repo_head_hexsha": "676182a0a8f7f0e7dfa957bcae457943688a12a1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "masumhabib/armamin", "max_forks_repo_head_hexsha": "676182a0a8f7f0e7dfa957bcae457943688a12a1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8852459016, "max_line_length": 69, "alphanum_fraction": 0.4921681781, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583168, "lm_q2_score": 0.8198933381139645, "lm_q1q2_score": 0.6814486479587699}} {"text": "//\n// Created by moriya on 02/10/17.\n//\n\n#ifndef LIBSCAPI_MATRIX_H\n#define LIBSCAPI_MATRIX_H\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include <../../include/primitives/Mersenne.hpp>\n\n\nusing namespace NTL;\n\n/**\n * A hyper-invertible matrix is a matrix of which every (non-trivial) square sub-matrix is invertible. Given\n * a hyper-invertible matrix M and vectors x and y satisfying y = M x, then given any |x| components of x\n * and y (any mixture is fine!), one can compute all other components of x and y as a linear function from\n * the given components.\n * Such matrices provide very good diversion and concentration properties: Given a vector x with random-ness in some components;\n * then this very same randomness can be observed in any components of y.\n * Similarly, given a vector x with up to k non-zero elements, then either y will have a non-zero element in\n * each subset of k components, or x is the zero-vector.\n * We present a construction of hyper-invertible matrices and a bunch of applications.\n */\n\nusing namespace std;\nusing namespace NTL;\n\ntemplate \nclass HIM {\nprivate:\n int m_n,m_m;\n FieldType** m_matrix;\n TemplateField *field;\npublic:\n\n /**\n * This method allocate m-by-n matrix.\n * m rows, n columns.\n */\n HIM(int m, int n, TemplateField *field);\n\n HIM();\n\n /**\n * This method is a construction of a hyper-invertible m-by-n matrix M over a finite field F with |F| ≥ 2n.\n * Let α1,...,αn , β1,...,βm denote fixed distinct elements in F according the vectors alpha and beta,\n * and consider the function f:Fn → Fm,\n * mapping (x1,...,xn) to (y1,...,ym) such that the points (β1,y1),...,(βm,ym) lie on the polynomial g(·)\n * of degree n−1 defined by the points (α1,x1),...,(αn,xn).\n * Due to the linearity of Lagrange interpolation, f is linear and can be expressed as a matrix:\n * M = {λi,j} j=1,...n i=1,...,m\n * where λ i,j = {multiplication}k=1,..n (βi−αk)/(αj−αk)\n */\n FieldType** InitHIMByVectors(vector &alpha, vector &beta);\n\n FieldType** InitHIMVectorAndsizes(vector &alpha, int n, int m);\n\n /**\n * This method create vectors alpha and beta,\n * and init the matrix by the method InitHIMByVectors(alpha, beta).\n */\n FieldType** InitHIM();\n\n /**\n * This method print the matrix\n */\n void Print();\n\n /**\n * matrix/vector multiplication.\n * The result is the answer vector.\n */\n void MatrixMult(std::vector &vector, std::vector &answer);\n\n void allocate(int m, int n, TemplateField *field);\n\n virtual ~HIM();\n};\n\n\n\ntemplate \nHIM::HIM(){}\n\ntemplate \nHIM::HIM(int m, int n, TemplateField *field) {\n // m rows, n columns\n this->m_m = m;\n this->m_n = n;\n this->field = field;\n this->m_matrix = new FieldType*[m_m];\n\n for (int i = 0; i < m_m; i++)\n {\n m_matrix[i] = new FieldType[m_n];\n }\n}\n\ntemplate \nFieldType** HIM::InitHIMByVectors(vector &alpha, vector &beta)\n{\n FieldType lambda;\n\n\n int m = beta.size();\n int n = alpha.size();\n for (int i = 0; i < m; i++)\n {\n for (int j = 0; j < n; j++)\n {\n // lambda = 1\n lambda = *(field->GetOne());\n\n // compute value for matrix[i,j]\n for (int k = 0; k < n; k++)\n {\n if (k == j)\n {\n continue;\n }\n\n lambda *= ((beta[i]) - (alpha[k])) / ((alpha[j]) - (alpha[k]));\n }\n\n // set the matrix\n (m_matrix[i][j]) = lambda;\n }\n }\n return m_matrix;\n}\n\n\ntemplate \nFieldType** HIM::InitHIMVectorAndsizes(vector &alpha, int n, int m)\n{\n FieldType lambda;\n\n for (int i = 0; i < m; i++)\n {\n for (int j = 0; j < n; j++)\n {\n // lambda = 1\n lambda = *(field->GetOne());\n\n // compute value for matrix[i,j]\n for (int k = 0; k < n; k++)\n {\n if (k == j)\n {\n continue;\n }\n\n lambda *= ((alpha[n+i]) - (alpha[k])) / ((alpha[j]) - (alpha[k]));\n }\n\n // set the matrix\n (m_matrix[i][j]) = lambda;\n }\n }\n return m_matrix;\n}\n\n\n\ntemplate \nvoid HIM::allocate(int m, int n, TemplateField *field)\n{\n // m rows, n columns\n this->m_m = m;\n this->m_n = n;\n this->field = field;\n this->m_matrix = new FieldType*[m_m];\n for (int i = 0; i < m_m; i++)\n {\n m_matrix[i] = new FieldType[m_n];\n }\n}\n\ntemplate \nFieldType** HIM::InitHIM()\n{\n int i;\n vector alpha(m_n);\n vector beta(m_m);\n\n // check if valid\n if (256 <= m_m+m_n)\n {\n cout << \"error\";\n }\n\n // Let alpha_j and beta_i be arbitrary field elements\n for (i = 0; i < m_n; i++)\n {\n alpha[i] = field->GetElement(i);\n }\n\n for (i = 0; i < m_m; i++)\n {\n beta[i] = field->GetElement(m_n+i);\n }\n\n return(InitHIMByVectors(alpha,beta));\n}\n\ntemplate \nvoid HIM::Print()\n{\n for (int i = 0; i < m_m; i++) {\n for (int j = 0; j < m_n; j++) {\n cout << (m_matrix[i][j]) << \" \";\n }\n\n cout << \" \" << '\\n';\n }\n\n}\n\ntemplate \nvoid HIM::MatrixMult(std::vector &vector, std::vector &answer)\n{\n FieldType temp1;\n for(int i = 0; i < m_m; i++)\n {\n // answer[i] = 0\n answer[i] = *(field->GetZero());\n\n for(int j=0; j < m_n; j++)\n {\n temp1 = m_matrix[i][j] * vector[j];\n //answer[i] = answer[i] + temp1;\n answer[i] += temp1;\n }\n }\n}\n\ntemplate \nHIM::~HIM() {\n for (int i = 0; i < m_m; i++)\n {\n delete[] m_matrix[i];\n }\n delete[] m_matrix;\n}\n\ntemplate\nclass VDM {\nprivate:\n int m_n,m_m;\n FieldType** m_matrix;\n TemplateField *field;\npublic:\n VDM(int n, int m, TemplateField *field);\n VDM() {};\n ~VDM();\n void InitVDM();\n void Print();\n void MatrixMult(std::vector &vector, std::vector &answer, int length);\n\n void allocate(int n, int m, TemplateField *field);\n};\n\n\ntemplate\nVDM::VDM(int n, int m, TemplateField *field) {\n this->m_m = m;\n this->m_n = n;\n this->field = field;\n this->m_matrix = new FieldType*[m_n];\n for (int i = 0; i < m_n; i++)\n {\n m_matrix[i] = new FieldType[m_m];\n }\n}\n\ntemplate\nvoid VDM::allocate(int n, int m, TemplateField *field) {\n\n this->m_m = m;\n this->m_n = n;\n this->field = field;\n this->m_matrix = new FieldType*[m_n];\n for (int i = 0; i < m_n; i++)\n {\n m_matrix[i] = new FieldType[m_m];\n }\n}\n\ntemplate\nvoid VDM::InitVDM() {\n vector alpha(m_n);\n for (int i = 0; i < m_n; i++) {\n alpha[i] = field->GetElement(i + 1);\n }\n\n for (int i = 0; i < m_n; i++) {\n m_matrix[i][0] = *(field->GetOne());\n for (int k = 1; k < m_m; k++) {\n m_matrix[i][k] = m_matrix[i][k - 1] * (alpha[i]);\n }\n }\n}\n\n/**\n * the function print the matrix\n */\ntemplate\nvoid VDM::Print()\n{\n for (int i = 0; i < m_n; i++)\n {\n for(int j = 0; j < m_m; j++)\n {\n cout << (m_matrix[i][j]) << \" \";\n\n }\n cout << \" \" << '\\n';\n }\n\n}\n\ntemplate\nvoid VDM::MatrixMult(std::vector &vector, std::vector &answer, int length)\n{\n for(int i = 0; i < m_n; i++)\n {\n // answer[i] = 0\n answer[i] = *(field->GetZero());\n\n for(int j=0; j < length; j++)\n {\n answer[i] += (m_matrix[i][j] * vector[j]);\n }\n }\n\n}\n//\ntemplate\nVDM::~VDM() {\n for (int i = 0; i < m_n; i++) {\n delete[] m_matrix[i];\n }\n delete[] m_matrix;\n}\n\ntemplate\nclass VDMTranspose {\nprivate:\n int m_n,m_m;\n FieldType** m_matrix;\n TemplateField *field;\npublic:\n VDMTranspose(int n, int m, TemplateField *field);\n VDMTranspose() {};\n ~VDMTranspose();\n void InitVDMTranspose();\n void Print();\n void MatrixMult(std::vector &vector, std::vector &answer, int length);\n\n void allocate(int n, int m, TemplateField *field);\n};\n\n\ntemplate\nVDMTranspose::VDMTranspose(int n, int m, TemplateField *field) {\n this->m_m = m;\n this->m_n = n;\n this->field = field;\n this->m_matrix = new FieldType*[m_n];\n for (int i = 0; i < m_n; i++)\n {\n m_matrix[i] = new FieldType[m_m];\n }\n}\n\ntemplate\nvoid VDMTranspose::allocate(int n, int m, TemplateField *field) {\n\n this->m_m = m;\n this->m_n = n;\n this->field = field;\n this->m_matrix = new FieldType*[m_n];\n for (int i = 0; i < m_n; i++)\n {\n m_matrix[i] = new FieldType[m_m];\n }\n}\n\ntemplate\nvoid VDMTranspose::InitVDMTranspose() {\n vector alpha(m_m);\n for (int i = 0; i < m_m; i++) {\n alpha[i] = field->GetElement(i + 1);\n }\n\n for (int i = 0; i < m_m; i++) {\n m_matrix[0][i] = *(field->GetOne());\n for (int k = 1; k < m_n; k++) {\n m_matrix[k][i] = m_matrix[k-1][i] * (alpha[k]);\n }\n }\n}\n\n/**\n * the function print the matrix\n */\ntemplate\nvoid VDMTranspose::Print()\n{\n for (int i = 0; i < m_m; i++)\n {\n for(int j = 0; j < m_n; j++)\n {\n cout << (m_matrix[i][j]) << \" \";\n\n }\n cout << \" \" << '\\n';\n }\n\n}\n\ntemplate\nvoid VDMTranspose::MatrixMult(std::vector &vector, std::vector &answer, int length)\n{\n for(int i = 0; i < length; i++)\n {\n // answer[i] = 0\n answer[i] = *(field->GetZero());\n\n for(int j=0; j < m_m; j++)\n {\n answer[i] += (m_matrix[i][j] * vector[j]);\n }\n }\n\n}\n\n\n//\ntemplate\nVDMTranspose::~VDMTranspose() {\n for (int i = 0; i < m_n; i++) {\n delete[] m_matrix[i];\n }\n delete[] m_matrix;\n}\n\n\n\n#endif //LIBSCAPI_MATRIX_H\n", "meta": {"hexsha": "715038688ee5c30d64b491c7cd27d5b8d56316fd", "size": 10904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/primitives/Matrix.hpp", "max_stars_repo_name": "manel1874/libscapi", "max_stars_repo_head_hexsha": "8cf705162af170c04c8e2299213f52888193cabe", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 160.0, "max_stars_repo_stars_event_min_datetime": "2016-05-11T09:45:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T09:32:19.000Z", "max_issues_repo_path": "include/primitives/Matrix.hpp", "max_issues_repo_name": "cryptobiu/libscapi", "max_issues_repo_head_hexsha": "49eee7aee9eb3544a7facb199d0a6e98097b058a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 57.0, "max_issues_repo_issues_event_min_datetime": "2016-12-26T07:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T16:34:31.000Z", "max_forks_repo_path": "include/primitives/Matrix.hpp", "max_forks_repo_name": "manel1874/libscapi", "max_forks_repo_head_hexsha": "8cf705162af170c04c8e2299213f52888193cabe", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 67.0, "max_forks_repo_forks_event_min_datetime": "2016-10-10T17:56:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T22:56:39.000Z", "avg_line_length": 23.7559912854, "max_line_length": 128, "alphanum_fraction": 0.5586023478, "num_tokens": 3104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.7577943658046608, "lm_q1q2_score": 0.681349120014949}} {"text": "#include \n#include \n#include \n\n#include \n\n\n// https://stackoverflow.com/a/24519913\ntemplate \nstd::vector full_convolve(const std::vector &f, const std::vector &g) {\n const int nf = f.size();\n const int ng = g.size();\n const int n = nf + ng - 1;\n std::vector ret(n, T());\n for (int i = 0; i < n; ++i) {\n const int jmin = (i >= ng - 1)? i - (ng - 1) : 0;\n const int jmax = (i < nf - 1)? i : nf - 1;\n for(int j = jmin; j <= jmax; ++j) {\n ret[i] += (f[j] * g[i - j]);\n }\n }\n return ret;\n}\n\n\ntemplate \nclass Lagrange {\npublic:\n Lagrange(const std::vector &x, const std::vector &w) :\n coefficients()\n {\n assert(x.size() == w.size());\n std::vector p;\n p.push_back(0.0);\n for (std::size_t j = 0; j < x.size(); ++j) {\n std::vector pt;\n pt.push_back(w[j]);\n for (std::size_t k = 0; k < x.size(); ++k) {\n if (k == j) {\n continue;\n }\n T fac = x[j] - x[k];\n std::vector poly;\n poly.push_back(1.0 / fac);\n poly.push_back(-x[k] / fac);\n pt = full_convolve(pt, poly);\n }\n p = add(p, pt);\n }\n coefficients = p;\n }\n\n T operator ()(const T &x) const {\n assert(coefficients.size() > 0);\n T result = 0.0;\n std::size_t d = coefficients.size() - 1;\n for (std::size_t i = 0; i < d; ++i) {\n // result += std::pow(x, d) * coefficients[i];\n result += coefficients[i];\n result *= x;\n }\n result += coefficients[d];\n return result;\n }\n\n std::vector add(const std::vector &a, const std::vector &b) const {\n int diff = a.size() - b.size();\n if ( diff == 0 ) {\n std::vector result;\n for (std::size_t i = 0; i < a.size(); ++i) {\n result.push_back(a[i] + b[i]);\n }\n return result;\n } else if ( diff > 0 ) {\n std::vector new_b(diff, 0);\n new_b.reserve(diff + b.size());\n new_b.insert(new_b.end(), b.begin(), b.end());\n return add(a, new_b);\n } else {\n std::vector new_a(-diff, 0);\n new_a.reserve(-diff + a.size());\n new_a.insert(new_a.end(), a.begin(), a.end());\n return add(new_a, b);\n }\n }\n\n std::vector coefficients;\n\n static T fast(T x, const std::vector &xs, const std::vector &ws) {\n assert(xs.size() == ws.size());\n T result = 0.0;\n for (std::size_t j = 0; j < xs.size(); ++j) {\n T n = 1.0, d = 1.0;\n for (std::size_t k = 0; k < xs.size(); ++k) {\n if ( j == k ) {\n continue;\n }\n n *= x - xs[k];\n d *= xs[j] - xs[k];\n }\n result += ws[j] * (n / d);\n }\n return result;\n }\n\n};\n\n\ntemplate \nclass DeltaLagrange {\npublic:\n DeltaLagrange(const std::vector &x, const std::vector &w) :\n x0(x[0]),\n w0(w[0]),\n coefficients()\n {\n assert(x.size() == w.size());\n std::vector p;\n p.push_back(0.0);\n for (std::size_t j = 0; j < x.size(); ++j) {\n std::vector pt;\n pt.push_back(w[j] - w0);\n auto xj = x[j] - x0;\n for (std::size_t k = 0; k < x.size(); ++k) {\n if (k == j) {\n continue;\n }\n auto xk = x[k] - x0;\n T fac = xj - xk;\n std::vector poly;\n poly.push_back(1.0 / fac);\n poly.push_back(-xk / fac);\n pt = full_convolve(pt, poly);\n }\n p = add(p, pt);\n }\n coefficients = p;\n }\n\n T operator ()(const T &x) const {\n assert(coefficients.size() > 0);\n T result = 0.0;\n auto xd = x - x0;\n std::size_t d = coefficients.size() - 1;\n for (std::size_t i = 0; i < d; ++i) {\n // result += std::pow(x, d) * coefficients[i];\n result += coefficients[i];\n result *= xd;\n }\n result += coefficients[d];\n return result + w0;\n }\n\n std::vector add(const std::vector &a, const std::vector &b) const {\n int diff = a.size() - b.size();\n if ( diff == 0 ) {\n std::vector result;\n for (std::size_t i = 0; i < a.size(); ++i) {\n result.push_back(a[i] + b[i]);\n }\n return result;\n } else if ( diff > 0 ) {\n std::vector new_b(diff, 0);\n new_b.reserve(diff + b.size());\n new_b.insert(new_b.end(), b.begin(), b.end());\n return add(a, new_b);\n } else {\n std::vector new_a(-diff, 0);\n new_a.reserve(-diff + a.size());\n new_a.insert(new_a.end(), a.begin(), a.end());\n return add(new_a, b);\n }\n }\n\n T x0;\n T w0;\n std::vector coefficients;\n\n};\n\n", "meta": {"hexsha": "1ccb02e326c05f984534817bc2b0ac8a8e3eb76a", "size": 5277, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/lagrange.hpp", "max_stars_repo_name": "mugwort-rc/boost_python_lagrange", "max_stars_repo_head_hexsha": "ae7cc35b1f650e63de91fd7c25996dc6abc550c4", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/lagrange.hpp", "max_issues_repo_name": "mugwort-rc/boost_python_lagrange", "max_issues_repo_head_hexsha": "ae7cc35b1f650e63de91fd7c25996dc6abc550c4", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/lagrange.hpp", "max_forks_repo_name": "mugwort-rc/boost_python_lagrange", "max_forks_repo_head_hexsha": "ae7cc35b1f650e63de91fd7c25996dc6abc550c4", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1546961326, "max_line_length": 80, "alphanum_fraction": 0.4223990904, "num_tokens": 1474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793452, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.681349115096773}} {"text": "///2\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 Vb;\ntypedef CGAL::Triangulation_face_base_2 Fb;\ntypedef CGAL::Triangulation_data_structure_2 Tds;\ntypedef CGAL::Delaunay_triangulation_2 Delaunay;\n\n// BGL Graph definitions\n// =====================\n// Graph Type, OutEdgeList Type, VertexList Type, (un)directedS\ntypedef boost::adjacency_list graph;\ntypedef boost::graph_traits::vertex_descriptor vertex_desc; // Vertex Descriptor: with vecS vertex list, this is really just an int in the range [0, num_vertices(G)). \ntypedef boost::graph_traits::edge_iterator edge_it; // to iterate over all edges\ntypedef boost::graph_traits::out_edge_iterator out_edge_it;\n// Coloring definitions\ntypedef std::vector< boost::default_color_type > partition_t;\n\n\n\nvoid testcase() {\n Index n, m;\n double r;\n std::cin >> n >> m >> r;\n \n // read points: first, we read all points and store them into a vector,\n // together with their indices\n typedef std::pair IPoint;\n std::vector points;\n points.reserve(n);\n for (Index i = 0; i < n; ++i) {\n int x, y;\n std::cin >> x >> y;\n points.emplace_back(K::Point_2(x, y), i);\n }\n \n Delaunay t;\n t.insert(points.begin(), points.end());\n \n graph G(n);\n for (auto e = t.finite_edges_begin(); e != t.finite_edges_end(); ++e) {\n Index i1 = e->first->vertex((e->second+1)%3)->info();\n Index i2 = e->first->vertex((e->second+2)%3)->info();\n if(t.segment(e).squared_length() <= r * r) {\n boost::add_edge(int(i1), int(i2), G);\n }\n }\n \n // check for bipartiteness of the graph with *only* the delaunay edges\n partition_t partition(n); \n bool without_interference = boost::is_bipartite(G, boost::get(boost::vertex_index, G), \n boost::make_iterator_property_map(partition.begin(), boost::get(boost::vertex_index, G)));\n if(without_interference) {\n // if bipartite only with delaunay edges, we can use the coloring found by BGL\n // to create one triangulation for each color. Since same colored points should\n // not be closer than r to each other, this new triangulation should not include small edges \n std::vector points_1;\n std::vector points_2;\n for(auto v = t.finite_vertices_begin(); v != t.finite_vertices_end(); ++v) {\n Index i = v->info();\n if(partition[i] == boost::color_traits::white()) {\n points_1.push_back(v->point());\n } else {\n points_2.push_back(v->point());\n }\n }\n\n for(int i = 0; i < 2; i++) {\n if(!without_interference) break;\n Delaunay ti;\n if(i == 0) ti.insert(points_1.begin(), points_1.end());\n else ti.insert(points_2.begin(), points_2.end());\n // loop through edges\n for (auto e = ti.finite_edges_begin(); e != ti.finite_edges_end(); ++e) {\n if(t.segment(e).squared_length() <= r * r) {\n without_interference = false;\n break;\n }\n }\n }\n }\n \n \n std::vector component_map(n);\t// We MUST use such a vector as an Exterior Property Map: Vertex -> Component\n boost::connected_components(G,\n boost::make_iterator_property_map(component_map.begin(), boost::get(boost::vertex_index, G))); \n\n\n for(Index i = 0; i < m; i++) {\n int a0, a1, b0, b1;\n std::cin >> a0 >> a1 >> b0 >> b1;\n if(!without_interference) {\n std::cout << \"n\";\n continue;\n }\n K::Point_2 a = K::Point_2(a0, a1);\n K::Point_2 b = K::Point_2(b0, b1);\n \n if(CGAL::squared_distance(a, b) <= r * r) {\n std::cout << \"y\";\n continue;\n }\n auto vertex_a = t.nearest_vertex(a);\n auto vertex_b = t.nearest_vertex(b);\n \n if(CGAL::squared_distance(a, vertex_a->point()) > r * r || CGAL::squared_distance(b, vertex_b->point()) > r * r) {\n std::cout << \"n\";\n continue;\n }\n \n int va = vertex_a->info();\n int vb = vertex_b->info();\n if(component_map[va] == component_map[vb]) {\n std::cout << \"y\";\n continue;\n } else {\n std::cout << \"n\";\n continue;\n }\n }\n \n std::cout << \"\\n\";\n \n}\n\nint main() \n{\n std::ios_base::sync_with_stdio(false);\n std::size_t t;\n for (std::cin >> t; t > 0; --t) testcase();\n return 0;\n}\n", "meta": {"hexsha": "443ceacba38897ab5908b9513251a91540523ea4", "size": 5202, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problems/week13-potw-clues/src/algorithm.cpp", "max_stars_repo_name": "haeggee/algolab", "max_stars_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "problems/week13-potw-clues/src/algorithm.cpp", "max_issues_repo_name": "haeggee/algolab", "max_issues_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problems/week13-potw-clues/src/algorithm.cpp", "max_forks_repo_name": "haeggee/algolab", "max_forks_repo_head_hexsha": "176a7d4efbbfb2842f46e93250be00d3b59e0ec3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1486486486, "max_line_length": 181, "alphanum_fraction": 0.6259131103, "num_tokens": 1444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418262465169, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6812386906441984}} {"text": "/*\n * Author: Jonathan Bober\n * Version: .6\n *\n * This program computes p(n), the number of integer partitions of n, using Rademacher's\n * formula. (See Hans Rademacher, On the Partition Function p(n),\n * Proceedings of the London Mathematical Society 1938 s2-43(4):241-254; doi:10.1112/plms/s2-43.4.241,\n * currently at\n *\n * http://plms.oxfordjournals.org/cgi/content/citation/s2-43/4/241\n *\n * if you have access.)\n *\n * We use the following notation:\n *\n * p(n) = lim_{n --> oo} t(n,N)\n *\n * where\n *\n * t(n,N) = sum_{k=1}^N a(n,k) f_n(k),\n *\n * where\n *\n * a(n,k) = sum_{h=1, (h,k) = 1}^k exp(\\pi i s(h,k) - 2 \\pi i h n / k)\n *\n * and\n *\n * f_n(k) = \\pi sqrt{2} cosh(A_n/(sqrt{3}*k))/(B_n*k) - sinh(C_n/k)/D_n;\n *\n * where\n *\n * s(h,k) = \\sum_{j=1}^{k-1}(j/k)((hj/k))\n *\n * A_n = sqrt{2} \\pi * sqrt{n - 1/24}\n * B_n = 2 * sqrt{3} * (n - 1/24)\n * C_n = sqrt{2} * \\pi * sqrt{n - 1.0/24.0} / sqrt{3}\n * D_n = 2 * (n - 1/24) * sqrt{n - 1.0/24.0}\n *\n * and, finally, where ((x)) is the sawtooth function ((x)) = {x} - 1/2 if x is not an integer, 0 otherwise.\n *\n * Some clever tricks are used in the computation of s(h,k), and perhaps at least\n * some of these are due to Apostol. (I don't know a reference for this.)\n *\n * TODO:\n *\n * -- Search source code for other TODO comments.\n *\n * OTHER CREDITS:\n *\n * I looked source code written by Ralf Stephan, currently available at\n *\n * http://www.ark.in-berlin.de/part.c\n *\n * while writing this code, but didn't really make use of it.\n * Maybe we could use the function cospi() instead of mpfr_cos()\n * but there seems to be no gain in doing that.\n *\n * More useful were notes currently available at\n *\n * http://www.ark.in-berlin.de/part.pdf\n *\n * and others at\n *\n * http://www.math.uwaterloo.ca/~dmjackso/CO630/ptnform1.pdf\n *\n * Also, Bill Hart made some comments about ways to speed up this computation on the SAGE\n * mailing list.\n *\n * A big clean up of this file was done by Jeroen Demeyer in\n * https://trac.sagemath.org/ticket/24667\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see .\n */\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace std;\nusing NTL::GCD;\n\n\n/*****************************************************************************\n *\n * We begin be declaring all the constant global variables.\n *\n ****************************************************************************/\n\n// First, some variables that can be set to have the program\n// output some information that might be useful for debugging.\n\nconst bool debug = false; // If true, output some random stuff\n\nconst bool debug_precision = false; // If true, output information that might be useful for\n // debugging the precision setting code.\n\nconst bool debugf = false; // Same for the f() functions.\nconst bool debuga = false; // Same for the a() functions.\nconst bool debugt = false; // Same for the t() functions.\n\n#if FLT_RADIX != 2\n#error \"I don't know what to do when the float radix is not 2\"\n#endif\n// Note - it might be unreasonable to not support a float radix other than\n// 2, but apparently gcc doesn't either. See http://gcc.gnu.org/ml/fortran/2006-12/msg00032.html\n\n\nconst unsigned int min_precision = DBL_MANT_DIG; // The minimum precision that we will ever use.\nconst unsigned int double_precision = DBL_MANT_DIG; // The assumed precision of a double.\n\n\n#if defined(__sparc) || defined(__CYGWIN__) || defined(__FreeBSD__)\n// On sparc solaris long double is bad/broken/different, etc. E.g.,\n// LDBL_MANT_DIG is 113 rather than 106, which causes all kinds of trouble.\n// So we only use double_precision.\nconst unsigned int long_double_precision = double_precision;\n#else\nconst unsigned int long_double_precision = (LDBL_MANT_DIG == 106) ? double_precision : LDBL_MANT_DIG;\n#endif\n // The assumed precision of a long double.\n // Note: On many systems double_precision = long_double_precision. This is OK, as\n // the long double stage of the computation will just be skipped.\n\n// Second, some constants that control the precision at which we compute.\n\n// When we compute the terms of the Rademacher series, we start by computing with\n// mpfr_t variables. But for efficiency we switch to special purpose code when\n// we don't need as much precision. These constants control the various\n// precision levels at which we switch to different special\n// purpose functions.\nconst unsigned int level_two_precision = long_double_precision;\nconst unsigned int level_five_precision = double_precision;\n\n// Third, the rounding mode for mpfr.\nconst mpfr_rnd_t round_mode = MPFR_RNDN;\n\n/*****************************************************************************\n *\n * We are finished declaring constants, and next declare semi-constant\n * variables. These are all set just once per call to part(n).\n *\n * All of these are set in initialize_globals(), and\n * cleared in clear_globals().\n *\n ****************************************************************************/\n\nmpfr_t mp_sqrt2, mp_sqrt3, mp_pi; // These need to be set at run time\n // because we don't know how much precision we will need\n // until we know for what n we are computing p(n).\n\nmpfr_t mp_A, mp_B, mp_C, mp_D; // These \"constants\" all depend on n\ndouble d_pi, d_A, d_B, d_C, d_D;\nlong double ld_pi, ld_A, ld_B, ld_C, ld_D;\n\n\n/*****************************************************************************\n *\n * We next declare the variables that actually vary. It is cumbersome to have\n * so many global variables, but it is somewhat necessary since we want to call\n * the functions mpz_init(), mpq_init(), mpfr_init(), and the corresponding\n * clear() functions as little as possible.\n *\n ****************************************************************************/\n\n// These are initialized in the function initialize_globals()\n// and cleared in clear_globals().\nmpq_t qtemps, qtempa, qtempa2;\nmpfr_t mptemp;\n\n\n/*****************************************************************************\n *\n * End of Global Variables, beginning of function declarations\n *\n ****************************************************************************/\n\n// A listing of the main functions, in \"conceptual\" order.\nvoid part(mpz_t answer, unsigned int n);\n\nstatic void mp_t(mpfr_t result, unsigned int n); // Compute t(n,N) for an N large enough, and with a high enough precision, so that\n // |p(n) - t(n,N)| < .5\n\nstatic unsigned int compute_initial_precision(unsigned int n); // computes the precision required to accurately compute p(n)\n\nstatic void initialize_globals(mp_prec_t prec, unsigned int n); // Once we know the precision that we will need, we precompute\n // some commonly used constants.\n\nstatic unsigned int compute_current_precision(unsigned int n, unsigned int N, unsigned int extra); // Computed the precision required to\n // accurately compute the tail of the rademacher series\n // assuming that N terms have already been computed.\n // This is called after computing each summand, unless\n // we have already reached the minimum precision.\n\n // Reducing the precision as fast as possible is key to\n // fast performance.\n\nstatic double compute_remainder(unsigned int n, unsigned int N); // Gives an upper bound on the error that occurs\n // when only N terms of the Rademacher series have been\n // computed.\n\n // This should only be called when we know that compute_current_precision\n // will return min_precision. Otherwise the error will be too large for\n // it to compute.\n\nstatic void mp_f(mpfr_t result, unsigned int k); // See introduction for an explanation of these functions.\nstatic void q_s(mpq_t result, unsigned int h, unsigned int k);\nstatic void mp_a(mpfr_t result, unsigned int n, unsigned int k);\n\ntemplate static inline T a(unsigned int n, unsigned int k); // Template versions of the above functions for computing with\ntemplate static inline T f(unsigned int k); // low precision. Currently used for computing with\ntemplate static inline T s(unsigned int h, unsigned int k); // long double, and double.\n\n\n// The following are a bunch of \"fancy macros\" designed so that in the templated code\n// for a, for example, when we need to use pi, we just call pi() to get pi to\n// the proper precision. The compiler should inline these, so using one of these\n// functions is just as good as using a constant, and since these functions are static\n// they shouldn't even appear in the object code generated.\ntemplate static inline T sqrt2() {return sqrt(T(2));}\ntemplate static inline T sqrt3() {return sqrt(T(3));}\n\ntemplate static inline T pi() {return T(d_pi);}\ntemplate <> inline long double pi() {return ld_pi;}\n\ntemplate static inline T A() {return T(d_A);}\ntemplate <> inline long double A() {return ld_A;}\n\ntemplate static inline T B() {return T(d_B);}\ntemplate <> inline long double B() {return ld_B;}\n\ntemplate static inline T C() {return T(d_C);}\ntemplate <> inline long double C() {return ld_C;}\n\ntemplate static inline T D() {return T(d_D);}\ntemplate <> inline long double D() {return ld_D;}\n\ntemplate static inline T pi_sqrt2() {return pi() * sqrt(T(2));}\n\ntemplate static inline T one_over_12() {return T(1)/T(12);}\n\n// A few utility functions...\n\nint test(bool longtest = false, bool forever = false); // Runs a bunch of tests to make sure\n // that we are getting the right answers.\n // Tests are based on a few \"known\" values that\n // have been verified by other programs, and\n // also on known congruences for p(n)\n\nstatic int grab_last_digits(char * output, int n, mpfr_t x); // Might be useful for debugging, but\n // don't use it for anything else.\n // (See function definition for more information.)\n\n/***********************************************************************\n *\n * That should be the end of both function and variable definitions.\n *\n **********************************************************************/\n\n// The following function can be useful for debugging in come circumstances, but should not be used for anything else\n// unless it is rewritten.\nstatic int grab_last_digits(char * output, int n, mpfr_t x) {\n // fill output with the n digits of x that occur\n // just before the decimal point\n // Note: this assumes that x has enough digits and enough\n // precision -- otherwise bad things can happen\n\n // returns: the number of digits to the right of the decimal point\n\n char * temp;\n mp_exp_t e;\n\n temp = mpfr_get_str(NULL, &e, 10, 0, x, MPFR_RNDN);\n\n int retval;\n\n if (e > 0) {\n strncpy(output, temp + e - n, n);\n retval = strlen(temp + e);\n }\n else {\n for (int i = 0; i < n; i++)\n output[i] = '0';\n retval = strlen(temp);\n }\n output[n] = '\\0';\n\n mpfr_free_str(temp);\n\n return retval;\n}\n\n\nstatic unsigned int compute_initial_precision(unsigned int n) {\n // We just want to know how many bits we will need to\n // compute to get an accurate answer.\n\n // We know that\n\n // p(n) ~ exp(pi * sqrt(2n/3))/(4n sqrt(3)),\n\n // so for now we are assuming that p(n) < exp(pi * sqrt(2n/3))/n,\n // so we need pi*sqrt(2n/3)/log(2) - log(n)/log(2) + EXTRA bits.\n\n // EXTRA should depend on n, and should be something that ensures\n // that the TOTAL ERROR in all computations is < (something small).\n // This needs to be worked out carefully. EXTRA = log(n)/log(2) + 3\n // is probably good enough, and is convenient...\n\n // but we really need:\n\n // p(n) < something\n\n // to be sure that we compute the correct answer\n\n unsigned int result = (unsigned int)(ceil(3.1415926535897931 * sqrt(2.0 * double(n)/ 3.0) / log(2))) + 3;\n if (debug) cout << \"Using initial precision of \" << result << \" bits.\" << endl;\n\n if (result <= min_precision)\n result = min_precision;\n\n return result;\n}\n\n\nstatic unsigned int compute_current_precision(unsigned int n, unsigned int N, unsigned int extra = 0) {\n // Roughly, we compute\n\n // log(A/sqrt(N) + B*sqrt(N/(n-1))*sinh(C * sqrt(n) / N) / log(2)\n\n // where A, B, and C are the constants listed below. These error bounds\n // are given in the paper by Rademacher listed at the top of this file.\n // We then return this + extra, if extra != 0. If extra == 0, return with\n // what is probably way more extra precision than is needed.\n\n // extra should probably have been set by a call to compute_extra_precision()\n // before this function was called.\n\n // n = the number for which we are computing p(n)\n // N = the number of terms that have been computed so far\n\n // if N is 0, then we can't use the above formula (because we would be\n // dividing by 0).\n if (N == 0) return compute_initial_precision(n) + extra;\n\n mpfr_t A, B, C;\n mpfr_init2(A, 32);\n mpfr_init2(B, 32);\n mpfr_init2(C, 32);\n\n mpfr_set_d(A, 1.11431833485164, MPFR_RNDN);\n mpfr_set_d(B, 0.059238439175445, MPFR_RNDN);\n mpfr_set_d(C, 2.5650996603238, MPFR_RNDN);\n\n mpfr_t error, t1, t2;\n mpfr_init2(error, 32); // we shouldn't need much precision here since we just need the most significant bit\n mpfr_init2(t1, 32);\n mpfr_init2(t2, 32);\n\n mpfr_set(error, A, MPFR_RNDF); // error = A\n mpfr_sqrt_ui(t1, N, MPFR_RNDF); // t1 = sqrt(N)\n mpfr_div(error, error, t1, MPFR_RNDF); // error = A/sqrt(N)\n\n mpfr_sqrt_ui(t1, n, MPFR_RNDF); // t1 = sqrt(n)\n mpfr_mul(t1, t1, C, MPFR_RNDF); // t1 = C * sqrt(n)\n mpfr_div_ui(t1, t1, N, MPFR_RNDF); // t1 = C * sqrt(n) / N\n mpfr_sinh(t1, t1, MPFR_RNDF); // t1 = sinh( ditto )\n mpfr_mul(t1, t1, B, MPFR_RNDF); // t1 = B * sinh( ditto )\n\n mpfr_set_ui(t2, N, MPFR_RNDF); // t2 = N\n mpfr_div_ui(t2, t2, n-1, MPFR_RNDF); // t2 = N/(n-1)\n mpfr_sqrt(t2, t2, MPFR_RNDF); // t2 = sqrt( ditto )\n\n mpfr_fma(error, t1, t2, error, MPFR_RNDF); // error += t1 * t2 (= ERROR ESTIMATE)\n\n // the number of bits required to hold the integer part of the error\n unsigned int p = mpfr_get_exp(error);\n\n if (extra == 0) {\n // Stupid fall back case\n extra = ceil(log(n)/log(2));\n }\n\n p += extra; // Recall that the extra precision should be\n // large enough so that the accumulated errors\n // in all of the computations that we make\n // are not big enough to matter.\n if (debug) {\n cout << \"Error seems to be: \";\n mpfr_out_str(stdout, 10, 0, error, round_mode);\n cout << endl;\n cout.flush();\n cout << \"Switching to precision of \" << p << \" bits. \" << endl;\n }\n\n mpfr_clear(error);\n mpfr_clear(t1);\n mpfr_clear(t2);\n mpfr_clear(A);\n mpfr_clear(B);\n mpfr_clear(C);\n\n if (p <= min_precision) // We don't want to return < min_precision.\n p = min_precision; // Note that when the code that calls this\n // function finds that the returned result\n // is min_precision, it should stop calling\n // this function, since the result won't change\n // after that. Also, it should probably switch\n // to computations with doubles, and should\n // start calling compute_remainder().\n return p;\n}\n\n\nstatic int compute_extra_precision(unsigned int n, double error = .25) {\n // Return the number of terms of the Rachemacher series that\n // we will need to compute to get a remainder of less than error\n // in absolute value, and then return the extra precision\n // that will guarantee that the accumulated error after computing\n // that number of steps will be less than .5 - error.\n\n // How this works:\n // We first need to figure out how many terms of the series we are going to\n // need to compute. That is, we need to know how large k needs to be\n // for compute_remainder(n,k) to return something smaller than error. There\n // might be a clever way to do this, but instead we just keep calling\n // compute_current_precision() until we know that the error will be\n // small enough to call compute_remainder(). Then we just call compute_remainder()\n // until the error is small enough.\n\n // Now that we know how many terms we will need to compute, k, we compute\n // the number of bits required to accurately store (.5 - error)/k. This ensures\n // that the total error introduced when we add up all k terms of the sum\n // will be less than (.5 - error). This way, if everything else works correctly,\n // then the sum will be within .5 of the correct (integer) answer, and we\n // can correctly find it by rounding.\n unsigned int k = 1;\n while (compute_current_precision(n, k, 0) > double_precision) k += 100;\n while (compute_remainder(n, k) > error) k += 100;\n\n if (debug_precision) {\n cout << \"To compute p(\" << n << \") we will add up approximately \" << k << \" terms from the Rachemacher series.\" << endl;\n }\n int bits = (int)((log(k/(.5 - error)))/log(2)) + 5; // NOTE: reducing the number of bits by 3 here is known to cause errors\n // Why the extra 5 bits? Anytime we call a function, eg mp_a(),\n // we end up doing a bunch of arithmetic operations, and if\n // we want the result of those operations to be accurate\n // within (.5 - error)/k, then we need that function to use\n // a slightly higher working precision, which should be\n // independent of n.\n // TODO:\n // Extensive trial and error has found 3 to be the smallest value\n // that doesn't seem to produce any wrong answers. Thus, to\n // be safe, we use 5 extra bits.\n // (Extensive trial and error means compiling this file to get\n // a.out and then running './a.out testforever' for a few hours.)\n return bits;\n}\n\n\nstatic double compute_remainder(unsigned int n, unsigned int N) {\n // This computes the remainder left after N terms have been computed.\n // The formula is exactly the same as the one used to compute the required\n // precision, but once we know the necessary precision is small, we can\n // call this function to determine the actual error (rather than the precision).\n\n // Generally, this is only called once we know that the necessary\n // precision is <= min_precision, because then the error is small\n // enough to fit into a double, and also, we know that we are\n // getting close to the correct answer.\n\n double A = 1.11431833485164;\n double B = 0.059238439175445;\n double C = 2.5650996603238;\n double result;\n result = A/sqrt(N) + B * sqrt(double(N)/double(n-1))*sinh(C * sqrt(double(n))/double(N));\n return result;\n}\n\n\nstatic void initialize_globals(mp_prec_t prec, unsigned int n) {\n // The variables mp_A, mp_B, mp_C, and mp_D are used for\n // A_n, B_n, C_n, and D_n listed at the top of this file.\n\n // They depend only on n, so we compute them just once in this function,\n // and then use them many times elsewhere.\n\n // Also, we precompute some extra constants that we use a lot, such as\n // sqrt2, sqrt3, pi\n\n // NOTE: Calls to this function must be paired with calls to clear_globals()\n\n // To ensure that we compute a good approximation of these\n // constants, we use a larger precision than needed and then round\n // to a lower precision after we are done. Working at a larger\n // precision also means that we can use MPFR_RNDF safely (this\n // corresponds roughly to losing 1 bit of precision).\n mpfr_prec_t p = prec;\n if (p < long_double_precision) p = long_double_precision;\n p += 10;\n\n // Global constants\n mpfr_init2(mp_sqrt2, p);\n mpfr_init2(mp_sqrt3, p);\n mpfr_init2(mp_pi, p);\n mpfr_init2(mp_A, p);\n mpfr_init2(mp_B, p);\n mpfr_init2(mp_C, p);\n mpfr_init2(mp_D, p);\n\n // Global temporary variables\n mpq_init(qtemps);\n mpq_init(qtempa);\n mpq_init(qtempa2);\n mpfr_init2(mptemp, prec);\n\n // Temporary variables only used in this function to compute\n // the constants\n mpfr_t n_minus;\n mpfr_t sqrt_n_minus;\n mpfr_init2(n_minus, p);\n mpfr_init2(sqrt_n_minus, p);\n\n mpfr_set_si(n_minus, -1, MPFR_RNDF);\n mpfr_div_ui(n_minus, n_minus, 24, MPFR_RNDF); // n_minus = -1/24\n mpfr_add_ui(n_minus, n_minus, n, MPFR_RNDF); // n_minus = n - 1/24\n\n mpfr_sqrt(sqrt_n_minus, n_minus, MPFR_RNDF); // sqrt_n_minus = sqrt(n - 1/24)\n\n mpfr_sqrt_ui(mp_sqrt2, 2, MPFR_RNDF); // mp_sqrt2 = sqrt(2)\n mpfr_sqrt_ui(mp_sqrt3, 3, MPFR_RNDF); // mp_sqrt3 = sqrt(3)\n mpfr_const_pi(mp_pi, MPFR_RNDF); // mp_pi = π\n\n // mp_A = sqrt(2) * π * sqrt(n - 1/24)\n mpfr_set(mp_A, mp_sqrt2, MPFR_RNDF); // mp_A = sqrt(2)\n mpfr_mul(mp_A, mp_A, mp_pi, MPFR_RNDF); // mp_A = sqrt(2) * π\n mpfr_mul(mp_A, mp_A, sqrt_n_minus, MPFR_RNDF); // mp_A = sqrt(2) * π * sqrt(n - 1/24)\n\n // mp_B = 2 * sqrt(3) * (n - 1/24)\n mpfr_set_ui(mp_B, 2, MPFR_RNDF); // mp_A = 2\n mpfr_mul(mp_B, mp_B, mp_sqrt3, MPFR_RNDF); // mp_A = 2 * sqrt(3)\n mpfr_mul(mp_B, mp_B, n_minus, MPFR_RNDF); // mp_A = 2 * sqrt(3) * (n - 1/24)\n\n // mp_C = sqrt(2) * π * sqrt(n - 1/24) / sqrt(3)\n mpfr_set(mp_C, mp_sqrt2, MPFR_RNDF); // mp_C = sqrt(2)\n mpfr_mul(mp_C, mp_C, mp_pi, MPFR_RNDF); // mp_C = sqrt(2) * π\n mpfr_mul(mp_C, mp_C, sqrt_n_minus, MPFR_RNDF); // mp_C = sqrt(2) * π * sqrt(n - 1/24)\n mpfr_div(mp_C, mp_C, mp_sqrt3, MPFR_RNDF); // mp_C = sqrt(2) * π * sqrt(n - 1/24) / sqrt3\n\n // mp_D = 2 * (n - 1/24) * sqrt(n - 1/24)\n mpfr_set_ui(mp_D, 2, MPFR_RNDF); // mp_D = 2\n mpfr_mul(mp_D, mp_D, n_minus, MPFR_RNDF); // mp_D = 2 * (n - 1/24)\n mpfr_mul(mp_D, mp_D, sqrt_n_minus, MPFR_RNDF); // mp_D = 2 * (n - 1/24) * sqrt(n - 1/24)\n\n // Convert these to double and long double\n d_pi = mpfr_get_d(mp_pi, MPFR_RNDN);\n d_A = mpfr_get_d(mp_A, MPFR_RNDN);\n d_B = mpfr_get_d(mp_B, MPFR_RNDN);\n d_C = mpfr_get_d(mp_C, MPFR_RNDN);\n d_D = mpfr_get_d(mp_D, MPFR_RNDN);\n\n ld_pi = mpfr_get_ld(mp_pi, MPFR_RNDN);\n ld_A = mpfr_get_ld(mp_A, MPFR_RNDN);\n ld_B = mpfr_get_ld(mp_B, MPFR_RNDN);\n ld_C = mpfr_get_ld(mp_C, MPFR_RNDN);\n ld_D = mpfr_get_ld(mp_D, MPFR_RNDN);\n\n // Drop the precision of the computed constants\n mpfr_prec_round(mp_pi, prec, MPFR_RNDN);\n mpfr_prec_round(mp_sqrt2, prec, MPFR_RNDN);\n mpfr_prec_round(mp_sqrt3, prec, MPFR_RNDN);\n mpfr_prec_round(mp_A, prec, MPFR_RNDN);\n mpfr_prec_round(mp_B, prec, MPFR_RNDN);\n mpfr_prec_round(mp_C, prec, MPFR_RNDN);\n mpfr_prec_round(mp_D, prec, MPFR_RNDN);\n\n mpfr_clear(n_minus);\n mpfr_clear(sqrt_n_minus);\n}\n\n\nstatic void clear_globals() {\n mpq_clear(qtemps);\n mpq_clear(qtempa);\n mpq_clear(qtempa2);\n mpfr_clear(mptemp);\n mpfr_clear(mp_sqrt2);\n mpfr_clear(mp_sqrt3);\n mpfr_clear(mp_pi);\n mpfr_clear(mp_A);\n mpfr_clear(mp_B);\n mpfr_clear(mp_C);\n mpfr_clear(mp_D);\n}\n\n\nstatic void set_temp_precision(mp_prec_t prec) {\n // Set the precision of the temporary MPFR variables to \"prec\".\n // This requires that the temporary variables have already been\n // initialized by initialize_globals().\n mpfr_set_prec(mptemp, prec);\n}\n\n\nstatic void mp_f(mpfr_t result, unsigned int k) {\n // compute f_n(k) as described in the introduction\n\n // notice that this doesn't use n - the \"constants\"\n // A, B, C, and D depend on n, but they are precomputed\n // once before this function is called.\n\n //result = pi * sqrt(2) * cosh(A/(sqrt(3)*k))/(B*k) - sinh(C/k)/D;\n\n mpfr_set(result, mp_pi, round_mode); // result = pi\n\n mpfr_mul(result, result, mp_sqrt2, round_mode); // result = sqrt(2) * pi\n\n mpfr_div(mptemp, mp_A, mp_sqrt3, round_mode); // temp = mp_A/sqrt(3)\n mpfr_div_ui(mptemp, mptemp, k, round_mode); // temp = mp_A/(sqrt(3) * k)\n mpfr_cosh(mptemp, mptemp, round_mode); // temp = cosh(mp_A/(sqrt(3) * k))\n mpfr_div(mptemp, mptemp, mp_B, round_mode); // temp = cosh(mp_A/(sqrt(3) * k))/mp_B\n mpfr_div_ui(mptemp, mptemp, k, round_mode); // temp = cosh(mp_A/(sqrt(3) * k))/(mp_B*k)\n\n mpfr_mul(result, result, mptemp, round_mode); // result = sqrt(2) * pi * cosh(mp_A/(sqrt(3) * k))/(mp_B*k)\n\n mpfr_div_ui(mptemp, mp_C, k, round_mode); // temp = mp_C/k\n mpfr_sinh(mptemp, mptemp, round_mode); // temp = sinh(mp_C/k)\n mpfr_div(mptemp, mptemp, mp_D, round_mode); // temp = sinh(mp_C/k)/D\n\n mpfr_sub(result, result, mptemp, round_mode); // result = RESULT!\n}\n\n\n// call the following when 4k < sqrt(UINT_MAX)\n\n// TODO: maybe a faster version of this can be written without using mpq_t,\n// or maybe this version can be smarter.\n\n// The actual value of the cosine that we compute using s(h,k)\n// only depends on {s(h,k)/2}, that is, the fractional\n// part of s(h,k)/2. It may be possible to make use of this somehow.\nstatic void q_s(mpq_t result, unsigned int h, unsigned int k) {\n if (k < 3) {\n mpq_set_ui(result, 0, 1);\n return;\n }\n\n if (h == 1) {\n unsigned int d = GCD( (k-1)*(k-2), 12*k);\n if (d > 1) {\n mpq_set_ui(result, ((k-1)*(k-2))/d, (12*k)/d);\n }\n else {\n mpq_set_ui(result, (k-1)*(k-2), 12*k);\n }\n return;\n }\n // TODO:\n // It may be advantageous to implement some of the special forms in the comments below,\n // and also some more listed in some of the links mentioned in the introduction, but\n // it seems like there might not be much speed benefit to this, and putting in too\n // many seems to slow things down a little.\n\n // if h = 2 and k is odd, we have\n // s(h,k) = (k-1)*(k-5)/24k\n //if(h == 2 && k > 5 && k % 2 == 1) {\n // unsigned int d = GCD( (k-1)*(k-5), 24*k);\n // if(d > 1) {\n // mpq_set_ui(result, ((k-1)*(k-5))/d, (24*k)/d);\n // }\n // else {\n // mpq_set_ui(result, (k-1)*(k-5), 24*k);\n // }\n // return;\n //}\n\n/*\n\n // if k % h == 1, then\n\n // s(h,k) = (k-1)(k - h^2 - 1)/(12hk)\n\n\n // We need to be a little careful here because k - h^2 - 1 can be negative.\n if(k % h == 1) {\n int num = (k-1)*(k - h*h - 1);\n int den = 12*k*h;\n int d = GCD(num, den);\n if(d > 1) {\n mpq_set_si(result, num/d, den/d);\n }\n else {\n mpq_set_si(result, num, den);\n }\n return;\n }\n\n // if k % h == 2, then\n\n // s(h,k) = (k-2)[k - .5(h^2 + 1)]/(12hk)\n\n\n //if(k % h == 2) {\n //}\n*/\n\n mpq_set_ui(result, 0, 1); // result = 0\n\n int r1 = k;\n int r2 = h;\n\n int n = 0;\n int temp3;\n while(r1 > 0 && r2 > 0) {\n unsigned int d = GCD(r1 * r1 + r2 * r2 + 1, r1 * r2);\n if (d > 1) {\n mpq_set_ui(qtemps, (r1 * r1 + r2 * r2 + 1)/d, (r1 * r2)/d);\n }\n else{\n mpq_set_ui(qtemps, r1 * r1 + r2 * r2 + 1, r1 * r2);\n }\n\n if (n % 2 == 0){\n mpq_add(result, result, qtemps); // result += temp;\n }\n else {\n mpq_sub(result, result, qtemps); // result -= temp;\n }\n temp3 = r1 % r2;\n r1 = r2;\n r2 = temp3;\n n++;\n }\n\n mpq_set_ui(qtemps, 1, 12);\n mpq_mul(result, result, qtemps); // result = result * 1.0/12.0;\n\n if (n % 2 == 1) {\n mpq_set_ui(qtemps, 1, 4);\n mpq_sub(result, result, qtemps); // result = result - .25;\n }\n}\n\n\nstatic void mp_a(mpfr_t result, unsigned int n, unsigned int k) {\n // compute a(n,k)\n\n if (k == 1) {\n mpfr_set_ui(result, 1, round_mode); //result = 1\n return;\n }\n\n mpfr_set_ui(result, 0, round_mode);\n\n unsigned int h;\n for (h = 1; h < k+1; h++) {\n if (GCD(h,k) == 1) {\n\n // Note that we compute each term of the summand as\n // result += cos(pi * ( s(h,k) - (2.0 * h * n)/k) );\n\n // This is the real part of the exponential that was written\n // down in the introduction, and we don't need to compute\n // the imaginary part because we know that, in the end, the\n // imaginary part will be 0, as we are computing an integer.\n\n q_s(qtempa, h, k);\n\n unsigned int r = n % k; // here we make use of the fact that the\n unsigned int d = GCD(r,k); // cos() term written above only depends\n unsigned int K; // on {hn/k}.\n if (d > 1) {\n r = r/d;\n K = k/d;\n }\n else {\n K = k;\n }\n if (K % 2 == 0) {\n K = K/2;\n }\n else {\n r = r * 2;\n }\n mpq_set_ui(qtempa2, h*r, K);\n mpq_sub(qtempa, qtempa, qtempa2);\n\n mpfr_mul_q(mptemp, mp_pi, qtempa, round_mode);\n mpfr_cos(mptemp, mptemp, round_mode);\n mpfr_add(result, result, mptemp, round_mode);\n }\n }\n}\n\n\ntemplate \ninline T partial_sum_of_t(unsigned int n, unsigned int &k, unsigned int exit_precision, unsigned int extra_precision, double error = 0) {\n unsigned int current_precision = compute_current_precision(n, k - 1, extra_precision);\n T result = 0;\n if (error == 0) {\n for (; current_precision > exit_precision; k++) { // (don't change k -- it is already the right value)\n result += sqrt(T(k)) * a(n,k) * f(k);\n current_precision = compute_current_precision(n,k,extra_precision); // The only reason that we compute the new precision\n // now is so that we know when we can change to using just doubles.\n // (There should be a 'long double' version of the compute_current_precision function.\n }\n }\n else {\n double remainder = 1;\n for (; remainder > error; k++) { // (don't change k -- it is already the right value)\n result += sqrt(T(k)) * a(n,k) * f(k);\n remainder = compute_remainder(n,k);\n }\n }\n return result;\n}\n\n\nstatic void mp_t(mpfr_t result, unsigned int n) {\n // This is the function that actually computes p(n).\n\n // More specifically, it computes t(n,N) to within 1/2 of p(n), and then\n // we can find p(n) by rounding.\n\n // NOTE: result should NOT have been initialized when this is called,\n // as we initialize it to the proper precision in this function.\n double error = .25;\n int extra = compute_extra_precision(n, error);\n\n unsigned int initial_precision = compute_initial_precision(n); // We begin by computing the precision necessary to hold the final answer.\n // and then initialize both the result and some temporary variables to that\n // precision.\n mpfr_t t1, t2;\n mpfr_init2(t1, initial_precision);\n mpfr_init2(t2, initial_precision);\n mpfr_init2(result, initial_precision);\n mpfr_set_ui(result, 0, round_mode);\n\n initialize_globals(initial_precision, n); // Now that we have the precision information, we initialize some constants\n // that will be used throughout, and also set the precision of the \"temp\"\n // variables that are used in individual functions.\n unsigned int current_precision = initial_precision;\n unsigned int new_precision;\n\n // We start by computing with high precision arithmetic, until\n // we are sure enough that we don't need that much precision\n // anymore. Once current_precision == min_precision, we drop\n // out of this loop and switch to a computation\n // that only involves doubles.\n unsigned int k = 1; // (k holds the index of the summand that we are computing.)\n for (k = 1; current_precision > level_two_precision; k++) {\n mpfr_sqrt_ui(t1, k, round_mode); // t1 = sqrt(k)\n\n mp_a(t2, n, k); // t2 = A_k(n)\n\n if (debuga) {\n cout << \"a(\" << k << \") = \";\n mpfr_out_str(stdout, 10, 10, t2, round_mode);\n cout << endl;\n }\n\n mpfr_mul(t1, t1, t2, round_mode); // t1 = sqrt(k)*A_k(n)\n\n mp_f(t2, k); // t2 = f_k(n)\n\n if (debugf) {\n cout << \"f(\" << n << \",\" << k << \") = \";\n mpfr_out_str(stdout, 10, 0, t2, round_mode);\n cout << endl;\n }\n\n mpfr_mul(t1, t1, t2, round_mode); // t1 = sqrt(k)*A_k(n)*f_k(n)\n\n mpfr_add(result, result, t1, round_mode); // result += summand\n\n if (debugt) {\n int num_digits = 20;\n int num_extra_digits;\n char digits[num_digits + 1];\n num_extra_digits = grab_last_digits(digits, 5, t1);\n grab_last_digits(digits, num_digits, result);\n\n mpfr_out_str(stdout, 10, 10, t1, round_mode);\n cout << endl;\n\n cout << k << \": current precision:\" << current_precision << \". 20 last digits of partial result: \" << digits << \". Number of extra digits: \" << num_extra_digits << endl;\n cout.flush();\n\n }\n\n new_precision = compute_current_precision(n,k,extra); // After computing one summand, check what the new precision should be.\n if (new_precision != current_precision) { // If the precision changes, we need to fix the\n current_precision = new_precision; // precision of all \"temp\" variables.\n set_temp_precision(current_precision);\n mpfr_set_prec(t1, current_precision);\n mpfr_set_prec(t2, current_precision);\n }\n }\n\n long double ld_partial_sum = partial_sum_of_t(n, k, level_five_precision, extra, 0);\n mpfr_set_prec(t1, long_double_precision);\n mpfr_set_ld(t1, ld_partial_sum, round_mode);\n mpfr_add(result, result, t1, round_mode);\n\n double d_partial_sum = partial_sum_of_t(n, k, 0, extra, error);\n mpfr_add_d(result, result, d_partial_sum, round_mode); // We add together the main result and the tail ends'\n\n mpfr_div(result, result, mp_pi, round_mode); // The actual result is the sum that we have computed\n mpfr_div(result, result, mp_sqrt2, round_mode); // divided by pi*sqrt(2).\n\n clear_globals();\n mpfr_clear(t1);\n mpfr_clear(t2);\n}\n\n\ntemplate \nT f(unsigned int k) {\n return pi_sqrt2() * cosh(A()/(sqrt3()*k))/(B() * k) - sinh(C()/k)/D();\n}\n\n\ntemplate \nT a(unsigned int n, unsigned int k) {\n if (k == 1) {\n return 1;\n }\n T result = 0;\n\n unsigned int h = 0;\n for (h = 1; h < k+1; h++) {\n if (GCD(h,k) == 1) {\n result += cos( pi() * ( s(h,k) - T(2.0 * double(h) * n)/T(k)) ); // be careful to promote 2 and h to Ts\n // because the result 2 * h * n could\n // be too large.\n }\n }\n return result;\n}\n\n\ntemplate \nT s(unsigned int h, unsigned int k) {\n if (k < 3) {\n return T(0);\n }\n\n if (h == 1) {\n return T((k-1) * (k-2))/T(12 * k);\n }\n // TODO: In the function mp_s() there are a few special cases for special forms of h and k.\n // (And there are more special cases listed in one of the references listed in the introduction.)\n\n // It may be advantageous to implement some here, but I'm not sure\n // if there is any real speed benefit to this.\n\n // In the mpfr_t version of this function, the speedups didn't seem to help too much, but\n // they might make more of a difference here.\n\n // Update to the above comments:\n // Actually, a few tests seem to indicate that putting in too many special\n // cases slows things down a little bit.\n\n // if h = 2 and k is odd, we have\n // s(h,k) = (k-1)*(k-5)/24k\n if (h == 2 && k > 5 && k % 2 == 1) {\n return T((k-1)*(k-5))/ T(24 * k);\n }\n\n int r1 = k;\n int r2 = h;\n\n int n = 1;\n int temp3;\n\n T result = T(0);\n T temp;\n while(r2 > 0) // Note that we maintain the invariant r1 >= r2, so\n // we only need to make sure that r2 > 0\n {\n temp = T(r1 * r1 + r2 * r2 + 1)/(n * r1 * r2);\n temp3 = r1 % r2;\n r1 = r2;\n r2 = temp3;\n\n result += temp;\n\n n = -n;\n }\n\n result *= one_over_12();\n\n if (n < 0) {\n result -= T(.25);\n }\n return result;\n}\n\n\n// answer must have already been mpz_init'd.\nvoid part(mpz_t answer, unsigned int n){\n if (n <= 1) {\n mpz_set_ui(answer, 1);\n return;\n }\n mpfr_t result;\n\n mp_t(result, n);\n\n mpfr_get_z(answer, result, MPFR_RNDN);\n\n mpfr_clear(result);\n}\n\n\n// This program is mainly meant for inclusion in SageMath (or any other\n// program, if anyone feels like it). We include a main() function\n// anyway, because it is useful to compile this as a standalone program\n// for testing purposes.\nint main(int argc, char *argv[]){\n unsigned int n = 10;\n\n if (argc > 1)\n if (strcmp(argv[1], \"test\") == 0) {\n n = test(true);\n if (n == 0) {\n cout << \"All Tests Passed\" << endl;\n }\n else {\n cout << \"Error computing p(\" << n << \")\" << endl;\n }\n return 0;\n }\n else if (strcmp(argv[1], \"testforever\") == 0) {\n n = test(false, true);\n if (n == 0) {\n cout << \"All Tests Passed\" << endl;\n }\n else {\n cout << \"Error computing p(\" << n << \")\" << endl;\n }\n return 0;\n }\n else {\n n = atoi(argv[1]);\n }\n else {\n n = test(false);\n if (n == 0) {\n cout << \"All short tests passed. Run '\" << argv[0] << \" test' to run all tests. (This may take some time, but it gives updates as it progresses, and can be interrupted.)\" << endl;\n cout << \"Run with the argument 'testforever' to run tests until a failure is found (or, hopefully, to run tests forever.)\" << endl;\n }\n else {\n cout << \"Error computing p(\" << n << \")\" << endl;\n }\n return 0;\n }\n //mpfr_t result;\n\n //mp_t(result, n);\n\n mpz_t answer;\n mpz_init(answer);\n part(answer, n);\n\n //mpfr_get_z(answer, result, round_mode);\n\n mpz_out_str (stdout, 10, answer);\n\n cout << endl;\n\n return 0;\n}\n\n\nint test(bool longtest, bool forever) {\n // The exact values given below are confirmed by multiple sources, so are probably correct.\n // Other tests rely on known congruences.\n // If longtest is true, then we run some tests that probably take on the order\n // of 10 minutes.\n // If forever is true, then we just do randomized tests until a failure\n // is found. Ideally, this should mean that we test forever, of course.\n\n int n;\n\n mpz_t expected_value;\n mpz_t actual_value;\n\n mpz_init(expected_value);\n mpz_init(actual_value);\n\n n= 1;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n mpz_set_str(expected_value, \"1\", 10);\n part(actual_value, n);\n\n if (mpz_cmp(expected_value, actual_value) != 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 10;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n mpz_set_str(expected_value, \"42\", 10);\n part(actual_value, n);\n\n if (mpz_cmp(expected_value, actual_value) != 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 100;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n mpz_set_str(expected_value, \"190569292\", 10);\n part(actual_value, n);\n\n if (mpz_cmp(expected_value, actual_value) != 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 1000;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n mpz_set_str(expected_value, \"24061467864032622473692149727991\", 10);\n part(actual_value, n);\n\n if (mpz_cmp(expected_value, actual_value) != 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 10000;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n mpz_set_str(expected_value, \"36167251325636293988820471890953695495016030339315650422081868605887952568754066420592310556052906916435144\", 10);\n part(actual_value, n);\n\n if (mpz_cmp(expected_value, actual_value) != 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 100000;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n mpz_set_str(expected_value, \"27493510569775696512677516320986352688173429315980054758203125984302147328114964173055050741660736621590157844774296248940493063070200461792764493033510116079342457190155718943509725312466108452006369558934464248716828789832182345009262853831404597021307130674510624419227311238999702284408609370935531629697851569569892196108480158600569421098519\", 10);\n part(actual_value, n);\n\n if (mpz_cmp(expected_value, actual_value) != 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 1000000;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n mpz_set_str(expected_value, \"1471684986358223398631004760609895943484030484439142125334612747351666117418918618276330148873983597555842015374130600288095929387347128232270327849578001932784396072064228659048713020170971840761025676479860846908142829356706929785991290519899445490672219997823452874982974022288229850136767566294781887494687879003824699988197729200632068668735996662273816798266213482417208446631027428001918132198177180646511234542595026728424452592296781193448139994664730105742564359154794989181485285351370551399476719981691459022015599101959601417474075715430750022184895815209339012481734469448319323280150665384042994054179587751761294916248142479998802936507195257074485047571662771763903391442495113823298195263008336489826045837712202455304996382144601028531832004519046591968302787537418118486000612016852593542741980215046267245473237321845833427512524227465399130174076941280847400831542217999286071108336303316298289102444649696805395416791875480010852636774022023128467646919775022348562520747741843343657801534130704761975530375169707999287040285677841619347472368171772154046664303121315630003467104673818\", 10);\n part(actual_value, n);\n\n if (mpz_cmp(expected_value, actual_value) != 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n\n // We now run some tests based on the fact that if n = 369 (mod 385) then p(n) = 0 (mod 385).\n\n n = 369 + 10*385;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 369 + 10*385;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 369 + 100*385;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 369 + 110*385;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 369 + 120*385;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 369 + 130*385;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n // Randomized testing\n\n srand( time(NULL) );\n\n for (int i = 0; i < 100; i++) {\n n = int(100000 * double(rand())/double(RAND_MAX) + 1);\n n = n - (n % 385) + 369;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n return n;\n }\n cout << \" OK.\" << endl;\n\n }\n\n if (longtest) {\n n = 369 + 1000*385;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 369 + 10000*385;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n n = 369 + 100000*385;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n for (int i = 0; i < 20; i++) {\n n = int(100000 * double(rand())/double(RAND_MAX) + 1) + 100000;\n n = n - (n % 385) + 369;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n return n;\n }\n cout << \" OK.\" << endl;\n }\n\n for (int i = 0; i < 20; i++) {\n n = int(100000 * double(rand())/double(RAND_MAX) + 1) + 500000;\n n = n - (n % 385) + 369;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n return n;\n }\n cout << \" OK.\" << endl;\n }\n\n for (int i = 0; i < 20; i++) {\n n = int(100000 * double(rand())/double(RAND_MAX) + 1) + 1000000;\n n = n - (n % 385) + 369;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n return n;\n }\n cout << \" OK.\" << endl;\n }\n\n for (int i = 0; i < 10; i++) {\n n = int(100000 * double(rand())/double(RAND_MAX) + 1) + 10000000;\n n = n - (n % 385) + 369;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n return n;\n }\n cout << \" OK.\" << endl;\n }\n\n n = 369 + 1000000*385;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n for (int i = 0; i < 10; i++) {\n n = int(100000000 * double(rand())/double(RAND_MAX) + 1) + 100000000;\n n = n - (n % 385) + 369;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n return n;\n }\n cout << \" OK.\" << endl;\n }\n\n n = 1000000000 + 139;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0)\n return n;\n\n cout << \" OK.\" << endl;\n\n for (int i = 0; i < 10; i++) {\n n = int(100000000 * double(rand())/double(RAND_MAX) + 1) + 1000000000;\n n = n - (n % 385) + 369;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n return n;\n }\n cout << \" OK.\" << endl;\n }\n }\n\n while (forever) {\n for (int i = 0; i < 100; i++) {\n n = int(900000 * double(rand())/double(RAND_MAX) + 1) + 100000;\n n = n - (n % 385) + 369;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n return n;\n }\n cout << \" OK.\" << endl;\n }\n\n for (int i = 0; i < 50; i++) {\n n = int(9000000 * double(rand())/double(RAND_MAX) + 1) + 1000000;\n n = n - (n % 385) + 369;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n return n;\n }\n cout << \" OK.\" << endl;\n }\n\n for (int i = 0; i < 50; i++) {\n n = int(90000000 * double(rand())/double(RAND_MAX) + 1) + 10000000;\n n = n - (n % 385) + 369;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n return n;\n }\n cout << \" OK.\" << endl;\n }\n\n for (int i = 0; i < 10; i++) {\n n = int(900000000 * double(rand())/double(RAND_MAX) + 1) + 100000000;\n n = n - (n % 385) + 369;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n return n;\n }\n cout << \" OK.\" << endl;\n }\n for (int i = 0; i < 5; i++) {\n n = int(100000000 * double(rand())/double(RAND_MAX) + 1) + 1000000000;\n n = n - (n % 385) + 369;\n cout << \"Computing p(\" << n << \")...\";\n cout.flush();\n part(actual_value, n);\n if (mpz_divisible_ui_p(actual_value, 385) == 0) {\n return n;\n }\n cout << \" OK.\" << endl;\n }\n }\n\n mpz_clear(expected_value);\n mpz_clear(actual_value);\n return 0;\n}\n", "meta": {"hexsha": "b432107241916495e748f9efc632c77bf3b3a5bd", "size": 56324, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/sage/combinat/partitions_c.cc", "max_stars_repo_name": "fchapoton/sage", "max_stars_repo_head_hexsha": "765c5cb3e24dd134708eca97e4c52e0221cd94ba", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-07-17T04:49:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-29T06:33:51.000Z", "max_issues_repo_path": "src/sage/combinat/partitions_c.cc", "max_issues_repo_name": "Ivo-Maffei/sage", "max_issues_repo_head_hexsha": "467fbc70a08b552b3de33d9065204ee9cbfb02c7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sage/combinat/partitions_c.cc", "max_forks_repo_name": "Ivo-Maffei/sage", "max_forks_repo_head_hexsha": "467fbc70a08b552b3de33d9065204ee9cbfb02c7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-03-29T17:13:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T18:11:28.000Z", "avg_line_length": 38.8709454796, "max_line_length": 1148, "alphanum_fraction": 0.5280697394, "num_tokens": 14279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418199787566, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6812386806875225}} {"text": "// (C) Copyright Nick Thompson 2020.\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0. (See accompanying file\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#include \n#include \n#include \n#include \n\nusing boost::math::tools::cohen_acceleration;\nusing boost::math::constants::pi;\n\ntemplate\nclass G {\npublic:\n G(){\n k_ = 0;\n }\n \n Real operator()() {\n k_ += 1;\n return 1/(k_*k_);\n }\n\nprivate:\n Real k_;\n};\n\nint main() {\n using Real = float;\n auto g = G();\n Real computed = cohen_acceleration(g);\n Real expected = pi()*pi()/12;\n std::cout << std::setprecision(std::numeric_limits::max_digits10);\n\n std::cout << \"Computed = \" << computed << \" = \" << std::hexfloat << computed << \"\\n\";\n std::cout << std::defaultfloat;\n std::cout << \"Expected = \" << expected << \" = \" << std::hexfloat << expected << \"\\n\";\n\n // Compute with a specified number of terms:\n // Make sure to reset g:\n g = G();\n computed = cohen_acceleration(g, 5);\n std::cout << std::defaultfloat;\n std::cout << \"Computed = \" << computed << \" = \" << std::hexfloat << computed << \" using 5 terms.\\n\";\n}\n", "meta": {"hexsha": "e16357d132a2af62e33c5a005b6e36b6b604e658", "size": 1352, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cohen_acceleration.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "example/cohen_acceleration.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "Libs/boost_1_76_0/libs/math/example/cohen_acceleration.cpp", "max_forks_repo_name": "Antd23rus/S2DE", "max_forks_repo_head_hexsha": "47cc7151c2934cd8f0399a9856c1e54894571553", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 28.7659574468, "max_line_length": 104, "alphanum_fraction": 0.6109467456, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314798554444, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6811216731719669}} {"text": "//\n// eigen_geometry_util.cpp\n// PointLineReloc\n//\n// Created by jimmy on 2017-05-05.\n// Copyright (c) 2017 Nowhere Planet. All rights reserved.\n//\n\n#include \"eigen_geometry_util.h\"\n#include \n#include \n#include \n\nusing Eigen::Vector2f;\nusing Eigen::Vector3f;\nusing std::cout;\nusing std::endl;\n\nEigen::Matrix3d EigenGeometryUtil::vector2SkewSymmetricMatrix(const Eigen::Vector3d & v)\n{\n // https://en.wikipedia.org/wiki/Skew-symmetric_matrix\n Eigen::Matrix3d m = Eigen::Matrix3d::Zero();\n double a = v.x();\n double b = v.y();\n double c = v.z();\n m << 0, -c, b,\n c, 0, -a,\n -b, a, 0;\n \n return m;\n}\n\n\nnamespace EigenX {\n \n // @brief internal function. RPE report 2015 summer\n static bool focalLengthEstimation(const double a, const double b,\n const double c, const double d,\n double& fl,\n bool verbose = true)\n {\n double delta = (d*d *(a+b) - 2.0*c)*(d*d *(a+b) - 2.0*c) - 4.0 *(d*d*a*b-c*c)*(d*d-1.0);\n if (delta < 0.0) {\n if (verbose) {\n printf(\"Error: sqrt a negative number.\\n\");\n printf(\"delta is %f\\n\", delta);\n }\n return false;\n }\n \n double numerator = 2.0 * (d*d*a*b - c*c);\n double denominator = 2.0*c - d*d *(a+b) + sqrt(delta);\n if (denominator == 0.0) {\n if (verbose) {\n printf(\"Error: denominator is zero.\\n\");\n }\n \n return false;\n }\n double fl_2 = numerator/denominator;\n if (fl_2 <= 0.0) {\n if (verbose) {\n printf(\"Error: focal length is not a real number. f^2 is %f\\n\", fl_2);\n printf(\"numerator, denominator is %f %f\\n\", numerator, denominator);\n }\n return false;\n }\n fl = sqrt(fl_2);\n return true;\n }\n \n void pointPanTilt(const Eigen::Vector2f& pp,\n const Eigen::Vector3f& ptz,\n const Eigen::Vector2f& point,\n Eigen::Vector2f& point_pan_tilt)\n {\n double dx = point.x() - pp.x();\n double dy = point.y() - pp.y();\n double fl = ptz.z();\n double delta_pan = atan2(dx, fl) * 180.0/M_PI;\n double delta_tilt = atan2(dy, fl) * 180.0/M_PI;\n point_pan_tilt[0] = ptz[0] + delta_pan;\n point_pan_tilt[1] = ptz[1] - delta_tilt; // oppositive direction of y\n }\n \n void pointPanTilt(const Eigen::Vector2d& pp,\n const Eigen::Vector3d& ptz,\n const Eigen::Vector2d& point,\n Eigen::Vector2d& point_pan_tilt)\n {\n double dx = point.x() - pp.x();\n double dy = point.y() - pp.y();\n double fl = ptz.z();\n double delta_pan = atan2(dx, fl) * 180.0/M_PI;\n double delta_tilt = atan2(dy, fl) * 180.0/M_PI;\n point_pan_tilt[0] = ptz[0] + delta_pan;\n point_pan_tilt[1] = ptz[1] - delta_tilt; // oppositive direction of y \n }\n\n static Eigen::Matrix3f matrixFromPanYTiltX(double pan, double tilt)\n {\n Eigen::Matrix3f m;\n \n pan *= M_PI / 180.0;\n tilt *= M_PI / 180.0;\n \n Eigen::Matrix3f R_tilt;\n R_tilt(0 ,0) = 1; R_tilt(0, 1) = 0; R_tilt(0, 2) = 0;\n R_tilt(1, 0) = 0; R_tilt(1, 1) = cos(tilt); R_tilt(1, 2) = sin(tilt);\n R_tilt(2, 0) = 0; R_tilt(2, 1) = -sin(tilt); R_tilt(2, 2) = cos(tilt);\n \n Eigen::Matrix3f R_pan;\n R_pan(0, 0) = cos(pan); R_pan(0, 1) = 0; R_pan(0, 2) = -sin(pan);\n R_pan(1, 0) = 0; R_pan(1, 1) = 1; R_pan(1, 2) = 0;\n R_pan(2, 0) = sin(pan); R_pan(2, 1) = 0; R_pan(2, 2) = cos(pan);\n \n m = R_tilt * R_pan;\n return m;\n }\n\n \n \n bool ptzFromTwoPoints(const Eigen::Vector2f& pan_tilt1,\n const Eigen::Vector2f& pan_tilt2,\n const Eigen::Vector2f& point1,\n const Eigen::Vector2f& point2,\n const Eigen::Vector2f& pp,\n Eigen::Vector3f& ptz)\n {\n Eigen::Vector2f p1 = point1 - pp;\n Eigen::Vector2f p2 = point2 - pp;\n \n // Step 1. focal length\n double pan1 = pan_tilt1[0];\n double tilt1 = pan_tilt1[1];\n double pan2 = pan_tilt2[0];\n double tilt2 = pan_tilt2[1];\n \n double a = p1.dot(p1);\n double b = p2.dot(p2);\n double c = p1.dot(p2);\n Eigen::Vector3f z_axis = Eigen::Vector3f::Zero(3, 1);\n z_axis[2] = 1.0f;\n // rotate matrix of axis z\n Eigen::Vector3f rotated_axis_z = matrixFromPanYTiltX(pan2 - pan1, tilt2 - tilt1) * z_axis;\n double d = z_axis.dot(rotated_axis_z); // angular difference of two angles\n double fl = 0;\n bool is_estimated = focalLengthEstimation(a, b, c, d, fl, false);\n if (!is_estimated) {\n return false;\n }\n \n // Step 2. pan and tilt\n double theta1 = pan1 - atan2(p1(0), fl)*180.0/M_PI;\n double theta2 = pan2 - atan2(p2(0), fl)*180.0/M_PI;\n ptz[0] = (theta1 + theta2)/2.0;\n \n double phi1 = tilt1 + atan2(p1(1), fl)*180.0/M_PI; // oppositive direction as y is from top to down in image\n double phi2 = tilt2 + atan2(p2(1), fl)*180.0/M_PI;\n ptz[1] = (phi1 + phi2)/2.0;\n ptz[2] = fl;\n \n return true;\n }\n \n bool ptzFromTwoPoints(const Eigen::Vector2d& pan_tilt1,\n const Eigen::Vector2d& pan_tilt2,\n const Eigen::Vector2d& point1,\n const Eigen::Vector2d& point2,\n const Eigen::Vector2d& pp,\n Eigen::Vector3d& ptz)\n {\n Eigen::Vector3f ptz_temp;\n bool is_ok = ptzFromTwoPoints(Eigen::Vector2f(pan_tilt1.x(), pan_tilt1.y()),\n Eigen::Vector2f(pan_tilt2.x(), pan_tilt2.y()),\n Eigen::Vector2f(point1.x(), point1.y()),\n Eigen::Vector2f(point2.x(), point2.y()),\n Eigen::Vector2f(pp.x(), pp.y()),\n ptz_temp);\n ptz[0] = ptz_temp[0];\n ptz[1] = ptz_temp[1];\n ptz[2] = ptz_temp[2];\n return is_ok; \n }\n\n \n}; // namespace EigenX", "meta": {"hexsha": "57785010b5eff4262e62008cad6c404df15b5ff1", "size": 6569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pan_tilt_forest/util/eigen_geometry_util.cpp", "max_stars_repo_name": "lood339/two_point_calib", "max_stars_repo_head_hexsha": "b4b861429c92368e8e4accecc986272070fb19bc", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2018-04-22T10:12:52.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T07:35:07.000Z", "max_issues_repo_path": "src/pan_tilt_forest/util/eigen_geometry_util.cpp", "max_issues_repo_name": "lood339/two_point_calib", "max_issues_repo_head_hexsha": "b4b861429c92368e8e4accecc986272070fb19bc", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-01-18T06:33:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-02T06:11:14.000Z", "max_forks_repo_path": "src/pan_tilt_forest/util/eigen_geometry_util.cpp", "max_forks_repo_name": "lood339/two_point_calib", "max_forks_repo_head_hexsha": "b4b861429c92368e8e4accecc986272070fb19bc", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2018-03-07T07:25:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T06:16:42.000Z", "avg_line_length": 35.128342246, "max_line_length": 117, "alphanum_fraction": 0.4903333841, "num_tokens": 1952, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.885631470799559, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6811216615198226}} {"text": "#pragma once\n#include \n#include \n\n// Returns in the inverse of a 4x4 homogeneous transform\nEigen::Matrix4d get_inverse_tf(Eigen::Matrix4d T);\n\n/*!\n \\brief Enforce orthogonality conditions on the given rotation matrix such that det(R) == 1 and R.tranpose() * R = I\n \\param R The input rotation matrix either 2x2 or 3x3, will be overwritten with a slightly modified matrix to\n satisfy orthogonality conditions.\n*/\nvoid enforce_orthogonality(Eigen::MatrixXd &R);\n\n/*!\n \\brief Returns the output of the cross operator.\n For 3 x 1 input, cross(x) * y is equivalent to cross_product(x, y)\n For 6 x 1 input, x = [rho, phi]^T. out = [cross(phi), rho; 0 0 0 1]\n \\param x Input vector which can be 3 x 1 or 6 x 1.\n \\return If the input if 3 x 1, the output is 3 x 3, if the input is 6 x 1, the output is 4 x 4.\n*/\nEigen::MatrixXd cross(Eigen::VectorXd x);\n\n/*!\n \\brief This function converts from a lie vector to a 4 x 4 SE(3) transform.\n Lie Vector xi = [rho, phi]^T (6 x 1) --> SE(3) T = [C, R; 0 0 0 1] (4 x 4)\n \\param x Input vector is 6 x 1\n \\return Output is 4 x SE(3) transform\n*/\nEigen::Matrix4d se3ToSE3(Eigen::MatrixXd xi);\n\n/*!\n \\brief Removes motion distortion from a pointcloud.\n Given a pointcloud, a timestamp for each point, a transform from the sensor to the origin,\n and a ground truth data vector, this function adjusts the position of each point so as to remove\n the motion distortion.\n \\param pc input/output pointcloud, the position of points will be modified to remove distortion.\n \\param times vector of timestamps for each point\n \\param T_enu_sensor Global transform from the sensor frame to ENU at timestamp times[0].\n \\param gt Vector of ground truth associated with this pointcloud:\n GPSTime,x,y,z,vel_x,vel_y,vel_z,roll,pitch,heading,ang_vel_z\n*/\nvoid removeMotionDistortion(Eigen::MatrixXd &pc, std::vector ×, Eigen::Matrix4d T_enu_sensor,\n std::vector gt);\n\n/*!\n \\brief Get the K closest keyframes to the specified location.\n \\param loc [x, y] location of the query frame.\n \\param frame_locs Vector specifying the location of the candidate keyframes.\n \\param K The number of keyframes to retrieve. If frame_locs.size() < K, then less will be returned.\n \\param closestK output vector of indices specifying the closest K keyframes, not in any particular order.\n*/\nvoid getClosestKFrames(std::vector loc, std::vector> &frame_locs, uint K,\n std::vector & closestK);\n\n/*!\n \\brief Calculates the translation and rotation difference between two 4x4 homogeneous transformations.\n The two transformations should be doing the same thing, ex: T_map_sensor.\n*/\nvoid poseError(Eigen::Matrix4d T1, Eigen::Matrix4d T2, double &trans_error, double &rot_error);\n\n/*!\n \\brief Given a 3x3 rotation matrix, this function extracts 3-2-1 yaw-pitch-roll angles.\n*/\nvoid rotToYawPitchRoll(Eigen::Matrix3d C, double &yaw, double &pitch, double &roll);\n\nvoid filterPointCloud(Eigen::MatrixXd &pc, double xmin, double xmax, double ymin, double ymax, double zmin,\n double zmax);\n", "meta": {"hexsha": "40d49da9b21f7b4a76a3b426eae035f46e5d16e0", "size": 3151, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/estimation.hpp", "max_stars_repo_name": "keenan-burnett/leslie_lidar_mapping", "max_stars_repo_head_hexsha": "004f3b552c27aa87931b3e3a851a836d703682e7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-01-05T01:17:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T21:51:30.000Z", "max_issues_repo_path": "include/estimation.hpp", "max_issues_repo_name": "keenan-burnett/leslie_lidar_mapping", "max_issues_repo_head_hexsha": "004f3b552c27aa87931b3e3a851a836d703682e7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/estimation.hpp", "max_forks_repo_name": "keenan-burnett/leslie_lidar_mapping", "max_forks_repo_head_hexsha": "004f3b552c27aa87931b3e3a851a836d703682e7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-02-02T15:42:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T16:59:35.000Z", "avg_line_length": 45.6666666667, "max_line_length": 118, "alphanum_fraction": 0.7197715011, "num_tokens": 862, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7690802317779601, "lm_q1q2_score": 0.6811216545108129}} {"text": "//\n// Copyright (c) 2016-2020 CNRS INRIA\n//\n\n#ifndef __pinocchio_math_rpy_hpp__\n#define __pinocchio_math_rpy_hpp__\n\n#include \"pinocchio/math/fwd.hpp\"\n#include \"pinocchio/math/comparison-operators.hpp\"\n\n#include \n\nnamespace pinocchio\n{\n namespace rpy\n {\n ///\n /// \\brief Convert from Roll, Pitch, Yaw to rotation Matrix\n ///\n /// Given \\f$r, p, y\\f$, the rotation is given as \\f$ R = R_z(y)R_y(p)R_x(r) \\f$,\n /// where \\f$R_{\\alpha}(\\theta)\\f$ denotes the rotation of \\f$\\theta\\f$ degrees\n /// around axis \\f$\\alpha\\f$.\n ///\n template\n Eigen::Matrix rpyToMatrix(const Scalar r,\n const Scalar p,\n const Scalar y)\n {\n typedef Eigen::AngleAxis AngleAxis;\n typedef Eigen::Matrix Vector3s;\n return (AngleAxis(y, Vector3s::UnitZ())\n * AngleAxis(p, Vector3s::UnitY())\n * AngleAxis(r, Vector3s::UnitX())\n ).toRotationMatrix();\n }\n\n ///\n /// \\brief Convert from Roll, Pitch, Yaw to rotation Matrix\n ///\n /// Given a vector \\f$(r, p, y)\\f$, the rotation is given as \\f$ R = R_z(y)R_y(p)R_x(r) \\f$,\n /// where \\f$R_{\\alpha}(\\theta)\\f$ denotes the rotation of \\f$\\theta\\f$ degrees\n /// around axis \\f$\\alpha\\f$.\n ///\n template\n Eigen::Matrix\n rpyToMatrix(const Eigen::MatrixBase & rpy)\n {\n PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE(Vector3Like, rpy, 3, 1);\n return rpyToMatrix(rpy[0], rpy[1], rpy[2]);\n }\n\n ///\n /// \\brief Convert from Transformation Matrix to Roll, Pitch, Yaw\n ///\n /// Given a rotation matrix \\f$R\\f$, the angles \\f$r, p, y\\f$ are given\n /// so that \\f$ R = R_z(y)R_y(p)R_x(r) \\f$,\n /// where \\f$R_{\\alpha}(\\theta)\\f$ denotes the rotation of \\f$\\theta\\f$ degrees\n /// around axis \\f$\\alpha\\f$.\n /// The angles are guaranteed to be in the ranges \\f$r\\in[-\\pi,\\pi]\\f$\n /// \\f$p\\in[-\\frac{\\pi}{2},\\frac{\\pi}{2}]\\f$ \\f$y\\in[-\\pi,\\pi]\\f$,\n /// unlike Eigen's eulerAngles() function\n ///\n /// \\warning the method assumes \\f$R\\f$ is a rotation matrix. If it is not, the result is undefined.\n ///\n template\n Eigen::Matrix\n matrixToRpy(const Eigen::MatrixBase & R)\n {\n PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE(Matrix3Like, R, 3, 3);\n assert(R.isUnitary() && \"R is not a unitary matrix\");\n\n typedef typename Matrix3Like::Scalar Scalar;\n typedef Eigen::Matrix ReturnType;\n static const Scalar pi = PI();\n\n ReturnType res = R.eulerAngles(2,1,0).reverse();\n\n if(res[1] < -pi/2)\n res[1] += 2*pi;\n\n if(res[1] > pi/2)\n {\n res[1] = pi - res[1];\n if(res[0] < Scalar(0))\n res[0] += pi;\n else\n res[0] -= pi;\n // res[2] > 0 according to Eigen's eulerAngles doc, no need to check its sign\n res[2] -= pi;\n }\n\n return res;\n }\n } // namespace rpy\n}\n#endif //#ifndef __pinocchio_math_rpy_hpp__\n", "meta": {"hexsha": "798b9e1237c9269a8913cc09de7c440a275f2aae", "size": 3323, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/rpy.hpp", "max_stars_repo_name": "ikalevatykh/pinocchio", "max_stars_repo_head_hexsha": "2c22ca240e78e5a6c20e7b2cb6c44e7a45658d38", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-05-10T08:06:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-22T14:26:57.000Z", "max_issues_repo_path": "src/math/rpy.hpp", "max_issues_repo_name": "dengs08/pinocchio", "max_issues_repo_head_hexsha": "4dcea71b112fcceff43326c824353bcf5f05038a", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/rpy.hpp", "max_forks_repo_name": "dengs08/pinocchio", "max_forks_repo_head_hexsha": "4dcea71b112fcceff43326c824353bcf5f05038a", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-21T01:20:41.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-12T18:59:35.000Z", "avg_line_length": 34.2577319588, "max_line_length": 104, "alphanum_fraction": 0.5973517906, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382200964034, "lm_q2_score": 0.7905303162021596, "lm_q1q2_score": 0.6810720815530555}} {"text": "/*\n * Copyright (c) 2013-2015 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef VLEQ_HPP\n#define VLEQ_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n// verified linear equation solver\n// for matrix-rhs\n// set r if you already have approximate inverse of a\n\ntemplate \nbool vleq(\n\tconst ub::matrix< interval >& a,\n\tconst ub::matrix< interval >& b,\n\tub::matrix >& x,\n\tconst ub::matrix* r = NULL )\n{\n\tint i, j;\n\tint s1 = b.size1();\n\tint s2 = b.size2();\n\tub::matrix R, E;\n\tub::matrix< interval > EmRA;\n\tub::vector< interval > xtmp(s1), btmp(s1), rtmp(s1);\n\tbool bo;\n\tT norm1, norm2, norm3, err;\n\n\tif (r == NULL) {\n\t\tbo = invert(mid(a), R);\n\t\tif (bo == false) return false;\n\t} else {\n\t\tR = *r;\n\t}\n\n\tE = ub::identity_matrix(s1);\n\n\tEmRA = E - prod(R, a);\n\tnorm1 = max_norm(EmRA);\n\trop::begin();\n\tnorm1 = rop::sub_down(T(1.), norm1);\n\trop::end();\n\n\tif (norm1 <= 0.) return false;\n\n\tx = prod(R, mid(b));\n\n\tnorm2 = max_norm(R);\n\n\tfor (i=0; i::begin();\n\t\terr = rop::div_up(rop::mul_up(norm2, norm3), norm1);\n\t\trop::end();\n\t\tfor (j=0; j(-err, err);\n\t\t}\n\t}\n\n\treturn true;\n}\n\n// verified linear equation solver\n// for vector-rhs\n// set r if you already have approximate inverse of a\n\ntemplate \nbool vleq(\n\tconst ub::matrix< interval >& a,\n\tconst ub::vector< interval >& b,\n\tub::vector >& x,\n\tconst ub::matrix* r = NULL )\n{\n\tint s = b.size();\n\tint i;\n\tub::matrix< interval > b1, x1;\n\tbool bo;\n\n\tb1.resize(s, 1);\n\tx1.resize(s, 1);\n\tx.resize(s);\n\n\tfor (i=0; i\n#include \n#include \n#include \n#include \"quicksvg/graph_fn.hpp\"\n#include \"quicksvg/plot_time_series.hpp\"\n\n\nusing boost::math::hypergeometric_1F1;\nusing boost::math::hypergeometric_2F0;\n\nint main() {\n\n double a = -3.14159;\n double b = 3.14159;\n std::string title = \"sin(𝑥) and cos(𝑥)\";\n std::string filename = \"examples/sine_and_cosine.svg\";\n auto f = [](double x)->double { return std::sin(x); };\n auto g = [](double x)->double { return std::cos(x); };\n quicksvg::graph_fn sin_graph(a, b, title, filename);\n\n sin_graph.add_fn(f);\n sin_graph.add_fn(g, \"green\");\n\n sin_graph.write_all();\n\n auto onef1_1 = [](double x)->double { return hypergeometric_1F1(3, 7, x); };\n a = -3;\n b = 2;\n title = \"\\u2081F\\u2081(3, 7, 𝑥)\";\n filename = \"examples/1F1_1.svg\";\n quicksvg::graph_fn onef1_1graph(a, b, title, filename);\n onef1_1graph.add_fn(onef1_1);\n onef1_1graph.write_all();\n\n auto onef1_2 = [](double x)->double { return hypergeometric_1F1(-2, 3, x); };\n a = -3;\n b = 2;\n title = \"\\u2081F\\u2081(-2, 3, 𝑥)\";\n filename = \"examples/1F1_2.svg\";\n quicksvg::graph_fn onef1_2graph(a, b, title, filename);\n onef1_2graph.add_fn(onef1_2);\n onef1_2graph.write_all();\n\n auto onef1_3 = [](double x)->double { return hypergeometric_1F1(2, -2.5, x); };\n a = -2;\n b = 1;\n title = \"\\u2081F\\u2081(2, -2.5, 𝑥)\";\n filename = \"examples/1F1_3.svg\";\n\n quicksvg::graph_fn onef1_3graph(a, b, title, filename);\n onef1_3graph.add_fn(onef1_3);\n onef1_3graph.write_all();\n\n auto onef1_4 = [](double x)->double { return hypergeometric_1F1(-2, -2.5, x); };\n a = -4;\n b = 1;\n title = \"\\u2081F\\u2081(-2, -2.5, 𝑥)\";\n filename = \"examples/1F1_4.svg\";\n quicksvg::graph_fn onef1_4graph(a, b, title, filename);\n onef1_4graph.add_fn(onef1_4);\n onef1_4graph.write_all();\n\n\n\n std::vector v(50);\n std::vector u(50);\n double start_time = 0;\n double time_step = 0.25;\n for (size_t i = 0; i < v.size(); ++i) {\n v[i] = std::sin(start_time + i*time_step);\n u[i] = std::cos(start_time + i*time_step);\n }\n\n title = \"sine and cosine time series\";\n filename = \"examples/sin_cos_time_series.svg\";\n\n quicksvg::plot_time_series pts(start_time, time_step, title, filename);\n pts.add_dataset(v);\n pts.add_dataset(u, false, \"lime\", \"lightgreen\");\n pts.write_all();\n\n}\n", "meta": {"hexsha": "edadd32614fc4cb6894866a6015a901a2b774199", "size": 2523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "NAThompson/quicksvg", "max_stars_repo_head_hexsha": "2089e0bef304a4409f237b250117d8f29e8ac949", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-27T00:07:53.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-27T00:07:53.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "NAThompson/quicksvg", "max_issues_repo_head_hexsha": "2089e0bef304a4409f237b250117d8f29e8ac949", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "NAThompson/quicksvg", "max_forks_repo_head_hexsha": "2089e0bef304a4409f237b250117d8f29e8ac949", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-14T13:26:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-14T11:30:58.000Z", "avg_line_length": 30.0357142857, "max_line_length": 84, "alphanum_fraction": 0.6341656758, "num_tokens": 871, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.6809093077367313}} {"text": "#include \n\n#ifdef HAS_EIGEN\n#include \n#endif\n\n/*\n * Fit vertices to a plane defined by a set of points with normals as described in\n * Ju, Tao, et al. \"Dual contouring of hermite data.\" Proceedings of the 29th annual conference on Computer graphics and interactive techniques. 2002.\n * and\n * Lindstrom, P. (2000, July). Out-of-core simplification of large polygonal models. In Proceedings of the 27th annual conference on Computer graphics and interactive techniques (pp. 259-262).\n */\n\nnamespace MishMesh {\n\tnamespace Meshing {\n\t\tenum SVDCutoffType {\n\t\t\tRELATIVE,\n\t\t\tABSOLUTE\n\t\t};\n\t\tconstexpr double SVD_CUTOFF_FACTOR = 0.1;\n\n\t\t/**\n\t\t * Fit a point to the average of a set of points and clip it to a bounding box.\n\t\t * @param The mesh.\n\t\t * @param vh The vertex handle for the point to fit.\n\t\t * @param points a set of points, that is used to calculcate the average.\n\t\t */\n\t\tvoid fit_vertex_average(MishMesh::PolyMesh &mesh,\n\t\t const MishMesh::PolyMesh::VertexHandle vh,\n\t\t const MishMesh::BBox &bbox,\n\t\t const std::vector &points) {\n\t\t\tOpenMesh::Vec3d x = std::accumulate(points.begin(), points.end(), OpenMesh::Vec3d{0, 0, 0}) / points.size();\n\t\t\tmesh.set_point(vh, OpenMesh::Vec3d(x.data()));\n\t\t}\n\n#ifdef HAS_EIGEN\n\t\t/**\n\t\t * Fit a point to a plane defined by a set of points with normals.\n\t\t * @param The mesh.\n\t\t * @param vh The vertex handle for the point to fit.\n\t\t * @param bbox a bounding box that is used to clip the point when it lies outside.\n\t\t * @param points a set of points, that is used to calculcate the average.\n\t\t * @param normals The normals at the points in the points array.\n\t\t * @param clip If clip is true, the result will be clipped on the bounding box.\n\t\t * @param svd_cutoff_type For absolute cutoff, singular values smaller than svd_cutoff_factor\n\t\t * are truncated and for relative cutoff singular values S_i with S_i/S_0 smaller than\n\t\t * svd_cutoff_factor are truncated.\n\t\t * @param svd_cutoff_factor Threshold which singular values are truncated to avoid instable results,\n\t\t * when determining the plane of the points.\n\t\t */\n\t\tvoid fit_vertex_svd(MishMesh::PolyMesh &mesh,\n\t\t const MishMesh::PolyMesh::VertexHandle vh,\n\t\t const MishMesh::BBox &bbox,\n\t\t const std::vector &points,\n\t\t const std::vector &normals,\n\t\t const bool clip,\n\t\t const SVDCutoffType svd_cutoff_type,\n\t\t const double svd_cutoff_factor) {\n\t\t\tEigen::Matrix3d ATA;\n\t\t\tEigen::Vector3d ATb;\n\t\t\tATA.setZero();\n\t\t\tATb.setZero();\n\t\t\tassert(points.size() == normals.size());\n\t\t\tMishMesh::BBox cube_bbox_eigen{Eigen::Vector3d(bbox.ltf.data()), Eigen::Vector3d(bbox.rbn.data())};\n\t\t\tfor(int i = 0; i < points.size(); i++) {\n\t\t\t\tEigen::Vector3d p_i(points[i].data());\n\t\t\t\tEigen::Matrix n_i(normals[i].data());\n\t\t\t\tassert(1.0 - n_i.norm() < FLT_EPSILON);\n\t\t\t\tATA += n_i * n_i.transpose();\n\t\t\t\tassert(cube_bbox_eigen.contains(p_i));\n\t\t\t\tATb += n_i * (n_i.transpose().dot(p_i));\n\t\t\t}\n\n\t\t\tEigen::Vector3d cell_center = (cube_bbox_eigen.rbn + cube_bbox_eigen.ltf) / 2.0;\n\t\t\tEigen::JacobiSVD svd(ATA, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\t\t\tsvd.compute(ATA);\n\t\t\tEigen::MatrixXd S = svd.singularValues().asDiagonal();\n\t\t\t// Invert the singular values diagonal matrix to calculate the pseudo inverse,\n\t\t\t// but cut off small singular values.\n\t\t\tfor(short j = 0; j < 3; j++) {\n\t\t\t\tif(svd_cutoff_type == SVDCutoffType::RELATIVE && S(j, j) / S(0, 0) < svd_cutoff_factor) {\n\t\t\t\t\t// Relative cutoff like in Lindstrom 2000\n\t\t\t\t\tS(j, j) = 0.0;\n\t\t\t\t} else if(svd_cutoff_type == SVDCutoffType::ABSOLUTE && S(j, j) < svd_cutoff_factor) {\n\t\t\t\t\t// Absolute cutoff like in Ju et al. 2002\n\t\t\t\t\tS(j, j) = 0.0;\n\t\t\t\t} else {\n\t\t\t\t\tS(j, j) = 1.0 / S(j, j);\n\t\t\t\t}\n\t\t\t}\n\t\t\tEigen::MatrixXd ATA_pinv = svd.matrixV() * S * svd.matrixU().transpose();\n\t\t\tEigen::Vector3d x = cell_center + ATA_pinv * (ATb - ATA * cell_center);\n\t\t\tif(clip) {\n\t\t\t\tx = cube_bbox_eigen.clip(x, 0.2);\n\t\t\t}\n\n\t\t\tmesh.set_point(vh, OpenMesh::Vec3d(x.data()));\n\t\t}\n#endif\n\t}\n}", "meta": {"hexsha": "97c9c8fcd42c4acf9b638965c5cec280c05b0e5f", "size": 4316, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/meshing/vertexfit.hpp", "max_stars_repo_name": "aschier/MishMesh", "max_stars_repo_head_hexsha": "6128e33501935b57c80c7e0816aa1b2229907990", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-15T11:10:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-27T02:30:47.000Z", "max_issues_repo_path": "src/meshing/vertexfit.hpp", "max_issues_repo_name": "aschier/MishMesh", "max_issues_repo_head_hexsha": "6128e33501935b57c80c7e0816aa1b2229907990", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/meshing/vertexfit.hpp", "max_forks_repo_name": "aschier/MishMesh", "max_forks_repo_head_hexsha": "6128e33501935b57c80c7e0816aa1b2229907990", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-26T13:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-26T13:25:28.000Z", "avg_line_length": 42.7326732673, "max_line_length": 192, "alphanum_fraction": 0.6501390176, "num_tokens": 1233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206870747658, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6808734386655196}} {"text": "// Copyright © 2016-2019 Thomas Nagler and Thibault Vatter\n//\n// This file is part of the vinecopulib library and licensed under the terms of\n// the MIT license. For a copy, see the LICENSE file in the root directory of\n// vinecopulib or https://vinecopulib.github.io/vinecopulib/.\n\n#pragma once\n\n#include \n#include \n\nnamespace vinecopulib {\n\nnamespace tools_stats {\n\n\n//! @brief Density function of the Standard normal distribution.\n//!\n//! @param x evaluation points.\n//!\n//! @return An \\f$ n \\times d \\f$ matrix of evaluated densities.\ninline Eigen::MatrixXd dnorm(const Eigen::MatrixXd &x)\n{\n boost::math::normal dist;\n auto f = [&dist](double y) { return boost::math::pdf(dist, y); };\n return tools_eigen::unaryExpr_or_nan(x, f);\n}\n\n//! @brief Distribution function of the Standard normal distribution.\n//!\n//! @param x evaluation points.\n//!\n//! @return An \\f$ n \\times d \\f$ matrix of evaluated probabilities.\ninline Eigen::MatrixXd pnorm(const Eigen::MatrixXd &x)\n{\n boost::math::normal dist;\n auto f = [&dist](double y) { return boost::math::cdf(dist, y); };\n return tools_eigen::unaryExpr_or_nan(x, f);\n}\n\n//! @brief Quantile function of the Standard normal distribution.\n//!\n//! @param x evaluation points.\n//!\n//! @return An \\f$ n \\times d \\f$ matrix of evaluated quantiles.\ninline Eigen::MatrixXd qnorm(const Eigen::MatrixXd &x)\n{\n boost::math::normal dist;\n auto f = [&dist](double y) { return boost::math::quantile(dist, y); };\n return tools_eigen::unaryExpr_or_nan(x, f);\n}\n\n//! @brief Density function of the Student t distribution.\n//!\n//! @param x evaluation points.\n//! @param nu degrees of freedom parameter.\n//!\n//! @return An \\f$ n \\times d \\f$ matrix of evaluated densities.\ninline Eigen::MatrixXd dt(const Eigen::MatrixXd &x, double nu)\n{\n boost::math::students_t dist(nu);\n auto f = [&dist](double y) { return boost::math::pdf(dist, y); };\n return tools_eigen::unaryExpr_or_nan(x, f);\n}\n\n//! @brief Distribution function of the Student t distribution.\n//!\n//! @param x evaluation points.\n//! @param nu degrees of freedom parameter.\n//!\n//! @return An \\f$ n \\times d \\f$ matrix of evaluated probabilities.\ninline Eigen::MatrixXd pt(const Eigen::MatrixXd &x, double nu)\n{\n boost::math::students_t dist(nu);\n auto f = [&dist](double y) { return boost::math::cdf(dist, y); };\n return tools_eigen::unaryExpr_or_nan(x, f);\n}\n\n//! @brief Quantile function of the Student t distribution.\n//!\n//! @param x evaluation points.\n//! @param nu degrees of freedom parameter.\n//!\n//! @return An \\f$ n \\times d \\f$ matrix of evaluated quantiles.\ninline Eigen::MatrixXd qt(const Eigen::MatrixXd &x, double nu)\n{\n boost::math::students_t dist(nu);\n auto f = [&dist](double y) { return boost::math::quantile(dist, y); };\n return tools_eigen::unaryExpr_or_nan(x, f);\n}\n\nEigen::MatrixXd simulate_uniform(const size_t& n, const size_t& d,\n std::vector seeds = std::vector());\n\nEigen::MatrixXd simulate_uniform(const size_t& n, const size_t& d, bool qrng,\n std::vector seeds = std::vector());\n\nEigen::VectorXd to_pseudo_obs_1d(Eigen::VectorXd x,\n std::string ties_method = \"average\");\n\nEigen::MatrixXd to_pseudo_obs(Eigen::MatrixXd x,\n std::string ties_method = \"average\");\n\ndouble pairwise_mcor(const Eigen::Matrix& x,\n const Eigen::VectorXd &weights = Eigen::VectorXd());\n\nEigen::MatrixXd dependence_matrix(const Eigen::MatrixXd &x,\n const std::string &measure);\n\nEigen::MatrixXd ghalton(const size_t& n, const size_t& d,\n std::vector seeds = std::vector());\n\nEigen::MatrixXd sobol(const size_t& n, const size_t& d,\n std::vector seeds = std::vector());\n\nEigen::VectorXd pbvt(const Eigen::Matrix &z,\n int nu, double rho);\n\nEigen::VectorXd pbvnorm(const Eigen::Matrix &z,\n double rho);\n}\n\n}\n\n#include \n", "meta": {"hexsha": "1fd66d50a375c306936e00b8d586c90a513acb40", "size": 4258, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "4.CalculatePairCopulas/include/vinecopulib/misc/tools_stats.hpp", "max_stars_repo_name": "covit2019/analysis_codes", "max_stars_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "4.CalculatePairCopulas/include/vinecopulib/misc/tools_stats.hpp", "max_issues_repo_name": "covit2019/analysis_codes", "max_issues_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.CalculatePairCopulas/include/vinecopulib/misc/tools_stats.hpp", "max_forks_repo_name": "covit2019/analysis_codes", "max_forks_repo_head_hexsha": "0c580c51f790723390676eef85422055007e2354", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-04-09T12:59:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-09T12:59:17.000Z", "avg_line_length": 33.7936507937, "max_line_length": 79, "alphanum_fraction": 0.6538280883, "num_tokens": 1048, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6808734307047707}} {"text": "#pragma once\n\n#include \n\nnamespace random_sinks {\n arma::mat fwht(arma::mat X, bool apply_to_rows=true);\n\n template inline T randchi(double df, uint m, uint n) { // T must be an armadillo Row, Col, or Mat type\n return arma::sqrt(arma::chi2rnd(df, m, n));\n }\n\n template inline T randchi(double df, uint n) { // T must be an armadillow Row or Col type\n return arma::sqrt(arma::chi2rnd(df, n));\n }\n\n inline double randchi(double df) {\n return std::sqrt(arma::chi2rnd(df));\n }\n \n class RFF {\n private:\n arma::mat _w;\n arma::rowvec _b;\n double _gamma;\n int _nfs, _dim;\n\n public:\n const arma::mat& weights;\n const arma::rowvec& bias;\n\n RFF(double gamma=1, int n_feats=100, int seed=-1);\n void fit(const arma::mat& X);\n arma::mat get_features(const arma::mat& X);\n };\n\n class fastfood {\n private:\n arma::rowvec _B, _G, _S, _b;\n arma::uvec _P;\n int _dim, _nfs, _d;\n double _gamma;\n\n public:\n fastfood(double gamma=1, int n_feats=128, int seed=-1);\n void fit(const arma::mat& X);\n arma::mat get_features(arma::mat X);\n };\n\n class SORF {\n private:\n arma::rowvec _B1, _B2, _B3, _b;\n int _dim, _d, _nfs;\n double _gamma;\n\n public:\n SORF(double gamma=1, int n_feats=128, int seed=-1);\n void fit(const arma::mat& X);\n arma::mat get_features(arma::mat X);\n };\n\n void rSVD(arma::mat& U, arma::vec& s, arma::mat& V, const arma::mat& X, uint n_comps);\n double powerSVD(arma::mat& U, arma::vec& s, arma::mat& V, const arma::mat& X, uint n_comps, uint max_iter=10, double tol=1e-8);\n\n class tPCA {\n private:\n arma::mat _V;\n arma::vec _s;\n arma::rowvec _means;\n int _dim, _n_comps;\n bool _use_rSVD;\n\n public:\n const arma::mat& components;\n const arma::vec& cov_eigenvals;\n const int& n_components;\n\n tPCA(uint n_components, std::string method=\"rSVD\");\n void fit(arma::mat X, uint max_iter=10, double tol=1e-8, bool zero_mean=false);\n arma::mat get_features(arma::mat X);\n arma::mat get_projection(arma::mat X);\n arma::mat inv_features(arma::mat X);\n };\n\n class gauss_nystrom {\n private:\n arma::mat _data, _V, _U;\n arma::vec _s;\n arma::rowvec _stds, _means;\n double _gamma;\n int _dim, _nfs;\n arma::mat _eval_kernel(arma::mat X);\n arma::mat _eval_kernel();\n\n public:\n const arma::vec& kernel_singular_vals;\n const arma::mat& kernel_left_vecs;\n const arma::mat& kernel_right_vecs;\n const int& n_features;\n gauss_nystrom(uint n_feats=128, double gamma=1, int seed=-1);\n void fit(arma::mat X, std::string method=\"powerSVD\", uint max_iter=20, double tol=1e-10);\n arma::mat get_features(arma::mat X);\n };\n}", "meta": {"hexsha": "d8fe211617aefea476a7dc7be74b050f6d4802b2", "size": 3015, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/random_kitchen_sinks.hpp", "max_stars_repo_name": "arotem3/random-kitchen-sinks", "max_stars_repo_head_hexsha": "f85073456a5f4a13904e73c3c4706c205e5396ba", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T18:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-18T04:15:08.000Z", "max_issues_repo_path": "include/random_kitchen_sinks.hpp", "max_issues_repo_name": "arotem3/random-kitchen-sinks", "max_issues_repo_head_hexsha": "f85073456a5f4a13904e73c3c4706c205e5396ba", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/random_kitchen_sinks.hpp", "max_forks_repo_name": "arotem3/random-kitchen-sinks", "max_forks_repo_head_hexsha": "f85073456a5f4a13904e73c3c4706c205e5396ba", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-02T09:55:33.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-02T09:55:33.000Z", "avg_line_length": 29.2718446602, "max_line_length": 131, "alphanum_fraction": 0.5751243781, "num_tokens": 886, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096090086367, "lm_q2_score": 0.7431680199891789, "lm_q1q2_score": 0.6808233642200094}} {"text": "#include \n\n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nint main() {\n\tMatrixXf A(4, 4);\n\n\tfloat data[4][4] = {\n\t\t{1, 0, 0, 0},\n\t\t{0, 1, 0, 0},\n\t\t{0, 0, 1, 0},\n\t\t{0, 0, 0, 1}\n\t};\n\n\tfor (size_t row = 0; row < 4; row++) {\n\t\tfor (size_t col = 0; col < 4; col++)\n\t\t\tA(row, col) = data[row][col];\n\t}\n\n\tMatrixXf b(4, 2);\n\tfor (size_t row = 0; row < 4; row++) {\n\t\tb(row, 0) = 1;\n\t\tb(row, 1) = 2;\n\t}\n\n\tMatrixXf x = A.colPivHouseholderQr().solve(b);\n\n\tcout << x << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "a3234011b8db958b748fdf73d58b10a242a8106d", "size": 509, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homeworks/2_ImageWarping/documents/eigen_example/src/test/00_LinearEquation/main.cpp", "max_stars_repo_name": "CieloNeet/CG-project", "max_stars_repo_head_hexsha": "664747c7599636f46d2ff9758f38283658c85c08", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 289.0, "max_stars_repo_stars_event_min_datetime": "2020-01-28T09:07:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-25T09:00:25.000Z", "max_issues_repo_path": "Homeworks/2_ImageWarping/documents/eigen_example/src/test/00_LinearEquation/main.cpp", "max_issues_repo_name": "CieloNeet/CG-project", "max_issues_repo_head_hexsha": "664747c7599636f46d2ff9758f38283658c85c08", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-19T07:11:14.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-07T06:41:27.000Z", "max_forks_repo_path": "Homeworks/2_ImageWarping/documents/eigen_example/src/test/00_LinearEquation/main.cpp", "max_forks_repo_name": "CieloNeet/CG-project", "max_forks_repo_head_hexsha": "664747c7599636f46d2ff9758f38283658c85c08", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 249.0, "max_forks_repo_forks_event_min_datetime": "2020-02-01T08:14:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T14:52:58.000Z", "avg_line_length": 14.5428571429, "max_line_length": 47, "alphanum_fraction": 0.5186640472, "num_tokens": 226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096135894201, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6808233467796964}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nstruct Point {\n double x;\n double y;\n string word;\n};\n\nsize_t read_file(string filename, MatrixXd& points, vector& words)\n{\n vector output;\n Point tmp;\n string line;\n ifstream infile(filename);\n assert(infile.is_open());\n\n while(getline(infile, line)) {\n // read line in\n\n // read parts of line\n istringstream iss(line);\n iss >> tmp.x >> tmp.y >> tmp.word;\n\n // add point to list\n output.push_back(tmp);\n }\n\n\n points.resize(2, output.size());\n words.resize(output.size());\n for(unsigned int ii=0; ii svd(inmat, ComputeThinU | ComputeThinV);\n\n VectorXd s_inv = svd.singularValues();\n cerr << endl << s_inv << endl;\n for(unsigned int ii = 0; ii < s_inv.rows(); ii++) {\n if(s_inv[ii] > pinvtoler) {\n s_inv[ii] = 1.0/s_inv[ii];\n } else {\n s_inv[ii] = 0;\n }\n }\n return svd.matrixV()*s_inv.asDiagonal()*svd.matrixU().transpose();\n}\n\n/**\n * @brief Solves\n *\n * YW = AXW\n * A = YW (XW)^1\n *\n * where columns of R are points in the reference (fixed) point set, A is an\n * affine matrix (2x3, where column 3 is the shift), M is an augmented matrix\n * with 1' in the bottom row and the top two rows containing coordinates in the\n * moving dataset -- one point per column and W being a correspondance matrix\n * such that correponding points in the R and M matrixes 1 is\n *\n * @param ref\n * @param moving\n * @param weights\n *\n * @return\n */\nvoid solve(const MatrixXd& ref_y, const MatrixXd& mov_x,\n const VectorXd& weights, Matrix& affine)\n{\n // Create augmented moving matrix, with lowest row of 1s\n MatrixXd aug_mov_x = MatrixXd::Ones(mov_x.rows() + 1, mov_x.cols());\n aug_mov_x.topRows(2) = mov_x;\n\n MatrixXd tmp = aug_mov_x*weights.asDiagonal();\n MatrixXd pinv = pseudo_inverse(tmp);\n affine = ref_y*weights.asDiagonal()*pinv;\n\n // enforce rigid + scaling ???\n\n}\n\nint main(int argc, char** argv)\n{\n if(argc != 3) {\n cerr << \"Need to provide two input files!\" << endl;\n return -1;\n }\n\n vector ref_words;\n MatrixXd ref_points;\n read_file(argv[1], ref_points, ref_words);\n\n vector move_words;\n MatrixXd move_points;\n read_file(argv[2], move_points, move_words);\n\n map word_counts;\n for(auto& word: ref_words) {\n auto ret = word_counts.insert(pair(word,0));\n if(ret.second) {\n // element not inserted, so it exists, already existed so just\n // increment the old count\n ret.first->second++;\n }\n }\n\n for(auto& v: word_counts) {\n cerr << v.first << \":\" << v.second << endl;\n }\n\n // Reorder points / duplicate / remove points that don't match. Also\n // initialize weights to down-weight repeated matches\n VectorXd weights = VectorXd::Ones(ref_points.cols());\n MatrixXd matches(move_points.cols(), ref_points.cols());\n for(unsigned int cc = 0; cc < ref_words.size(); cc++) {\n for(unsigned int rr = 0; rr< move_words.size(); rr++) {\n cerr << ref_words[cc] << \" vs \" << move_words[cc] << endl;\n if(ref_words[cc] == move_words[rr]) {\n matches(rr, cc) = 1;\n //weights[cc] /= 2.;\n } else {\n matches(rr, cc) = 0;\n }\n }\n }\n MatrixXd move_points_match = move_points*matches;\n MatrixXd err(ref_points.rows(), ref_points.cols());\n\n cerr << \"Ref\" << endl << ref_points << endl;\n cerr << \"Moving\" << endl << move_points_match << endl;\n cerr << \"Matching\" << endl << matches << endl;\n cerr << \"Weights\" << endl << weights << endl;\n\n Matrix affine(2, 3);\n affine << 1, 0, 0,\n 0, 1, 0;\n\n for(int ii = 0; ii < 10; ii++) {\n MatrixXd adjusted = affine.leftCols(2)*move_points +\n affine.col(2)*MatrixXd::Ones(1, move_points.cols());\n cerr << \"Adjusted \" << endl << adjusted << endl;\n\n // Re-weight based on norms\n err = ref_points - adjusted;\n for(size_t rr = 0; rr < weights.rows(); rr++) {\n weights[rr] = 1./max(0.0001, err.col(rr).norm());\n }\n cerr << \"Weights\" << endl << weights << endl;\n\n cerr << \"Affine\" << endl << affine << endl;\n solve(ref_points, move_points_match, weights, affine);\n\n }\n}\n", "meta": {"hexsha": "213d9c2ce949d3ef7cb70d5fb0080f806a4795a6", "size": 4971, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "point_match.cpp", "max_stars_repo_name": "micahcc/ctest", "max_stars_repo_head_hexsha": "af2a789a8c610f83a7e6ef55c371c64a41492e85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "point_match.cpp", "max_issues_repo_name": "micahcc/ctest", "max_issues_repo_head_hexsha": "af2a789a8c610f83a7e6ef55c371c64a41492e85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "point_match.cpp", "max_forks_repo_name": "micahcc/ctest", "max_forks_repo_head_hexsha": "af2a789a8c610f83a7e6ef55c371c64a41492e85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.4640883978, "max_line_length": 79, "alphanum_fraction": 0.5853952927, "num_tokens": 1331, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361676202372, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.680804208463726}} {"text": "/*!=======================================================\n | |\n | tensor.cpp |\n | |\n -------------------------------------------------------\n | The source file for a class definition that allows |\n | n-dimensional tensors. The data for the tensor is |\n | stored in a 2 dimensional array and there is logic |\n | which allows referencing to the correct indices to |\n | occur. |\n =======================================================\n | Dependencies: |\n | Eigen: An implementation of various matrix |\n | commands. The implementation of the data |\n | matrix uses such a matrix. |\n =======================================================*/\n \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace tensor{\n //!==\n //!|\n //!| Functions\n //!|\n //!==\n \n Tensor23 eye(){\n /*!Return the second order identity tensor\n \n Populate the second order identity tensor.\n This function is useful so that a consistent identity tensor can be used \n with different storage schemes.*/\n \n //Initialize the matrix\n \n Tensor23 I({3,3});\n \n for(int i=0; i<3; i++){\n I(i,i) = 1.;\n }\n return I;\n }\n Tensor43 FOT_eye(){\n /*!Return the fourth order identity tensor\n \n Populate the fourth order identity tensor.\n This function is useful so that a consistent identity tensor can be used\n with different storage schemes.*/\n \n //Initialize the tensor\n Tensor43 FOTI({3,3,3,3});\n Tensor23 I = eye(); //Get the second order identity tensor\n \n for(int i=0; i<3; i++){\n for(int j=0; j<3; j++){\n for(int k=0; k<3; k++){\n for(int l=0; l<3; l++){\n FOTI(i,j,k,l) = I(i,k)*I(j,l);\n }\n }\n }\n }\n \n return FOTI;\n }\n}", "meta": {"hexsha": "f868113e9289c45bb0578d5c838359a1ebc959a6", "size": 2293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/tensor.cpp", "max_stars_repo_name": "lanl/tardigrade-micromorphic-element", "max_stars_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cpp/tensor.cpp", "max_issues_repo_name": "lanl/tardigrade-micromorphic-element", "max_issues_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cpp/tensor.cpp", "max_forks_repo_name": "lanl/tardigrade-micromorphic-element", "max_forks_repo_head_hexsha": "dafc66df8a308e9fef8af4907de902464b84302b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2957746479, "max_line_length": 81, "alphanum_fraction": 0.4077627562, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6808041910557547}} {"text": "#include \n#include \n#include \n#include \n#include \nusing namespace std;\nusing namespace arma;\n\nvoid RHO_A_FILL(vec &rho, mat &A, int N,double rhoN); //rho, kind of like a linespace\n //A, Tridiagonal matrix\nvoid Maxoff(mat &A, int N,int &k, int &l, double &max); //Finds the max element of a matrix\n\nint main(){\n int N = 100; //matrix size; N x N\n double rhoN = 6;\n double max;\n int k,l;\n\n mat A = mat(N,N,fill::zeros); //indexes go from (0) to (N-1)\n mat S = mat(N,N,fill::eye);\n vec rho = vec(N,fill::zeros);\n fvec eigen = fvec(N);\n\n\n RHO_A_FILL(rho,A,N,rhoN);\n Maxoff(A,N,k,l,max);\n //A.print();\n int iterations = 0;\n\n double eps = 1E-10;\n\n double tau, t, s, c, il, ik, kk, ll, s_ik, s_il;\n double start, finish;\n\n start = clock(); //clock value before eigen solve\n while(max > eps){\n tau = (A(l,l)-A(k,k))/(2.*A(k,l));\n if(tau>0){\n t = 1.0/(tau + sqrt(1.0 + tau*tau));}\n else{t = -1.0/( -tau + sqrt(1.0 + tau*tau));}\n \n //cosine and sine\n c = 1./sqrt(1.+t*t);\n s = t*c;\n \n //Jacobi rotating A round theta in N-dim space\n for(int i = 0; i max){\n max =A(i,j)*A(i,j);\n k = i; \n l = j;\n }\n }\n }\n \n }\n", "meta": {"hexsha": "9c798c917391b6df4d18c0a37658f5312fb350e9", "size": 3408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project2/code-joseph/jacobi.cpp", "max_stars_repo_name": "frxstrem/fys3150", "max_stars_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "project2/code-joseph/jacobi.cpp", "max_issues_repo_name": "frxstrem/fys3150", "max_issues_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project2/code-joseph/jacobi.cpp", "max_forks_repo_name": "frxstrem/fys3150", "max_forks_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8759124088, "max_line_length": 98, "alphanum_fraction": 0.4137323944, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.680695823818469}} {"text": "//---------------------------------Spheral++----------------------------------//\n// QuadraticInterpolator\n//\n// Encapsulates the algorithm and data for parabolic interpolation in 1D\n// Assumes the results is interpolated as y_interp = a + b*x + c*x^2\n//\n// Created by JMO, Fri Dec 4 14:28:08 PST 2020\n//----------------------------------------------------------------------------//\n#include \"QuadraticInterpolator.hh\"\n\n#include \n\nnamespace Spheral {\n\n//------------------------------------------------------------------------------\n// Default constructor\n//------------------------------------------------------------------------------\nQuadraticInterpolator::QuadraticInterpolator():\n mN1(),\n mXmin(),\n mXmax(),\n mXstep(),\n mcoeffs() {\n}\n\n//------------------------------------------------------------------------------\n// Construct with tabulated data\n//------------------------------------------------------------------------------\nQuadraticInterpolator::QuadraticInterpolator(const double xmin,\n const double xmax,\n const std::vector& yvals):\n mN1(),\n mXmin(),\n mXmax(),\n mXstep(),\n mcoeffs() {\n this->initialize(xmin, xmax, yvals);\n}\n\n//------------------------------------------------------------------------------\n// Initialize the interpolation to fit the given data\n// Note, because we're doing a parabolic fit there are 2 fewer sets of coeficients\n// than the size of the table we're fitting.\n//------------------------------------------------------------------------------\nvoid\nQuadraticInterpolator::initialize(const double xmin,\n const double xmax,\n const std::vector& yvals) {\n const auto n = yvals.size();\n REQUIRE(n > 2); // Need at least 3 points to fit a parabola\n REQUIRE(xmax > xmin);\n\n mN1 = n - 3; // Maximum index into arrays\n mXmin = xmin;\n mXmax = xmax;\n mXstep = (xmax - xmin)/(n - 1);\n mcoeffs.resize(3*(n - 2));\n\n typedef Eigen::Matrix EMatrix;\n typedef Eigen::Matrix EVector;\n\n // We use simple least squares fitting for each 3-point interval, giving us an\n // exact parabolic fit for those three points.\n // Find the coefficient fits.\n double x0, x1, x2;\n EMatrix A;\n EVector B, C;\n for (auto i0 = 0u; i0 < n - 2; ++i0) {\n const auto i1 = i0 + 1u;\n const auto i2 = i0 + 2u;\n CHECK(i2 < n);\n x0 = xmin + i0*mXstep;\n x1 = x0 + mXstep;\n x2 = x1 + mXstep;\n A << 1.0, x0, x0*x0,\n 1.0, x1, x1*x1,\n 1.0, x2, x2*x2;\n B << yvals[i0], yvals[i1], yvals[i2];\n C = A.inverse()*B;\n mcoeffs[3*i0 ] = C(0);\n mcoeffs[3*i0 + 1] = C(1);\n mcoeffs[3*i0 + 2] = C(2);\n }\n}\n\n//------------------------------------------------------------------------------\n// Destructor\n//------------------------------------------------------------------------------\nQuadraticInterpolator::~QuadraticInterpolator() {\n}\n\n}\n", "meta": {"hexsha": "8dbc227f2789387c70df50d0214db377335b17c9", "size": 3030, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/Utilities/QuadraticInterpolator.cc", "max_stars_repo_name": "jmikeowen/Spheral", "max_stars_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_stars_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2018-07-31T21:38:22.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-29T08:58:33.000Z", "max_issues_repo_path": "src/Utilities/QuadraticInterpolator.cc", "max_issues_repo_name": "jmikeowen/Spheral", "max_issues_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_issues_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_issues_count": 41.0, "max_issues_repo_issues_event_min_datetime": "2020-09-28T23:14:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T17:01:33.000Z", "max_forks_repo_path": "src/Utilities/QuadraticInterpolator.cc", "max_forks_repo_name": "jmikeowen/Spheral", "max_forks_repo_head_hexsha": "3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4", "max_forks_repo_licenses": ["BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T07:00:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-15T21:12:39.000Z", "avg_line_length": 32.5806451613, "max_line_length": 82, "alphanum_fraction": 0.4409240924, "num_tokens": 704, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7606506635289836, "lm_q1q2_score": 0.6806221989755404}} {"text": "/*\n * Copyright (C) 2009 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n#include \n#include \"HelloEigen.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\n\nstd::string helloMatrix(){\n std::stringstream ss;\n ss << __PRETTY_FUNCTION__ << std::endl;\n MatrixXd m(2,2);\n m(0,0) = 3;\n m(1,0) = 2.5;\n m(0,1) = -1;\n m(1,1) = m(1,0) + m(0,1);\n ss << \"Here is the matrix m:\\n\" << m << std::endl;\n VectorXd v(2);\n v(0) = 4;\n v(1) = v(0) - 1;\n ss << \"Here is the vector v:\\n\" << v << std::endl;\n return ss.str();\n}\nJNIEXPORT jstring JNICALL Java_com_theveganrobot_cmake_HelloEigen_helloMatrix\n (JNIEnv * env, jobject)\n{\n return env->NewStringUTF( helloMatrix().c_str());\n}\n\n", "meta": {"hexsha": "f69c9975956d7af2833af2b93589663143e77c62", "size": 1293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake/android-cmake/samples/hello-eigen/hello-eigen.cpp", "max_stars_repo_name": "liangpengcheng/tng", "max_stars_repo_head_hexsha": "01c6517f734d5db01f7d59bf95b225f6d1642b6e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-04-16T06:24:20.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-29T13:36:51.000Z", "max_issues_repo_path": "cmake/android-cmake/samples/hello-eigen/hello-eigen.cpp", "max_issues_repo_name": "liangpengcheng/tng", "max_issues_repo_head_hexsha": "01c6517f734d5db01f7d59bf95b225f6d1642b6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake/android-cmake/samples/hello-eigen/hello-eigen.cpp", "max_forks_repo_name": "liangpengcheng/tng", "max_forks_repo_head_hexsha": "01c6517f734d5db01f7d59bf95b225f6d1642b6e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-04-29T11:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2019-09-16T03:27:30.000Z", "avg_line_length": 26.9375, "max_line_length": 77, "alphanum_fraction": 0.6744006187, "num_tokens": 375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256393148982, "lm_q2_score": 0.8080672204860316, "lm_q1q2_score": 0.6802517044950663}} {"text": "/*\n * EigenDecomposition.hpp\n *\n * Created on: 11/01/2011\n * Author: jimali\n */\n\n#ifndef EIGENDECOMPOSITION_HPP_\n#define EIGENDECOMPOSITION_HPP_\n\n#if !defined(SWIG)\n#include \n#include \n#endif\nnamespace rw { namespace math {\n //! @brief Type representing a set of eigen values and eigen vectors.\n template< class T = double > class EigenDecomposition\n {\n public:\n /**\n * @brief Construct new decomposition.\n * @param vectors [in] the eigen vectors as columns in a matrix.\n * @param values [in] the corresponding eigen values.\n */\n EigenDecomposition (Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > vectors,\n Eigen::Matrix< T, Eigen::Dynamic, 1 > values) :\n _vectors (vectors),\n _values (values)\n {}\n\n /**\n * @brief returns all eigenvectors as columns in a matrix\n * @return reference to the matrix.\n */\n const Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic >& getEigenVectors ()\n {\n return _vectors;\n }\n\n /**\n * @brief returns the i'th eigenvector\n * @return the eigen vector.\n */\n Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector (size_t i) { return _vectors.col (i); }\n\n /**\n * @brief return all eigenvalues\n * @return the eigen values.\n */\n const Eigen::Matrix< T, Eigen::Dynamic, 1 >& getEigenValues () { return _values; }\n\n /**\n * @brief returns the i'th eigenvalue\n * @return the eigenvalue.\n */\n T getEigenValue (size_t i) { return _values (i); }\n\n //! @brief Sort function for ordering of eigen values and vectors.\n struct MapSort\n {\n private:\n Eigen::Matrix< T, Eigen::Dynamic, 1 >& _values;\n\n public:\n /**\n * @brief Construct new sort function struct.\n * @param values [in] the eigen values.\n */\n MapSort (Eigen::Matrix< T, Eigen::Dynamic, 1 >& values) : _values (values) {}\n\n /**\n * @brief Compare the eigen values with the given indices.\n * @param i0 [in] index of first eigenvalue.\n * @param i1 [in] index of second eigenvalue.\n * @return true if first eigenvalue comes before the second (it is smaller), false\n * otherwise.\n */\n bool operator() (const int& i0, const int& i1)\n {\n using namespace rw::math;\n return _values (i0) < _values (i1);\n }\n };\n\n /**\n * @brief sorts the eigen vectors according to their eigen value. The vector with smallest\n * eigen value has index 0\n */\n void sort ()\n {\n std::vector< int > map (_values.size ());\n for (size_t i = 0; i < map.size (); i++)\n map[i] = (int) i;\n\n std::sort (map.begin (), map.end (), MapSort (_values));\n // now the mapping determines how the new vectors are to be layed out\n Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > vectors = _vectors;\n Eigen::Matrix< T, Eigen::Dynamic, 1 > values = _values;\n for (size_t i = 0; i < map.size (); i++) {\n _vectors.col (i) = vectors.col (map[i]);\n _values (i) = values (map[i]);\n }\n }\n\n private:\n Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > _vectors;\n Eigen::Matrix< T, Eigen::Dynamic, 1 > _values;\n };\n\n#if !defined(SWIG)\n using EigenDecompositiond = EigenDecomposition< double >;\n using EigenDecompositionf = EigenDecomposition< float >;\n#else\n#if SWIG_VERSION < 0x040000\n SWIG_DECLARE_TEMPLATE (EigenDecomposition_d, rw::math::EigenDecomposition< double >);\n ADD_DEFINITION (EigenDecomposition_d, EigenDecomposition)\n#else\n SWIG_DECLARE_TEMPLATE (EigenDecomposition, rw::math::EigenDecomposition< double >);\n#endif\n SWIG_DECLARE_TEMPLATE (EigenDecomposition_f, rw::math::EigenDecomposition< float >);\n#endif\n}} // namespace rw::math\n\n#endif /* EIGENDECOMPOSITION_HPP_ */\n", "meta": {"hexsha": "8a67d3f5ee4ffa4de263617e57e2f4302574ace8", "size": 4228, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/EigenDecomposition.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/EigenDecomposition.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/math/EigenDecomposition.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.824, "max_line_length": 100, "alphanum_fraction": 0.5593661306, "num_tokens": 1024, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528170040852, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.680017469700717}} {"text": "#include \n#include \n#include \n#include \n#include \n\nusing namespace mpp::hamiltonian;\nusing namespace mpp::chains;\nusing namespace boost::numeric::ublas;\n\ndouble log_posterior(vector const & q){\n double log_post_val(0);\n for(std::size_t i=0;i grad_log_posterior(vector const & q) {\n vector dq(q.size());\n for(std::size_t i=0;i inv_mass_mat(num_dims);\n for(std::size_t i=0;i const &)> lp = log_posterior;\n std::function<\n vector (vector const &) > glp = grad_log_posterior;\n\n hmc_sampler hmc_spr(\n lp,\n glp,\n num_dims,\n max_num_steps,\n max_eps,\n inv_mass_mat\n );\n\n std::size_t const num_samples(1000);\n std::mt19937 rng;\n std::normal_distribution nrm_dist;\n vector q_0(num_dims);\n for(size_t i=0;i chn = hmc_spr.run_sampler(num_samples,q_0);\n std::string chn_file_name(\"./eg_classic_hmc.chain\");\n chn.write_samples_to_csv(chn_file_name);\n\n return 0;\n}\n", "meta": {"hexsha": "57ec25a854d261caecf69ec52283d49a57a4519c", "size": 1560, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/quickstart/classic_hamiltonian.cpp", "max_stars_repo_name": "tbs1980/mpp", "max_stars_repo_head_hexsha": "5a704b48d5ab2386588c71987a7616a276380a99", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/quickstart/classic_hamiltonian.cpp", "max_issues_repo_name": "tbs1980/mpp", "max_issues_repo_head_hexsha": "5a704b48d5ab2386588c71987a7616a276380a99", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/quickstart/classic_hamiltonian.cpp", "max_forks_repo_name": "tbs1980/mpp", "max_forks_repo_head_hexsha": "5a704b48d5ab2386588c71987a7616a276380a99", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.1612903226, "max_line_length": 75, "alphanum_fraction": 0.6346153846, "num_tokens": 444, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6799981325967714}} {"text": "#include \n#include \n\n#define STB_IMAGE_IMPLEMENTATION\n#include \"stb_image.h\"\n\n#define STB_IMAGE_WRITE_IMPLEMENTATION\n#include \"stb_image_write.h\"\n\n#define VUL_DEFINE\n#include \"vul_timer.h\"\n\n#include \n\nusing namespace Eigen;\n\nint main( int argc, char **argv )\n{\n if( argc < 3 ) {\n printf( \"Usage: %s [path to image] [rank to reconstruct from] [iterations (optional)]\\n\", argv[ 0 ] );\n exit(1);\n }\n\n int w, h, n;\n unsigned char *data = stbi_load( argv[ 1 ], &w, &h, &n, 0 );\n \n // @TODO(thynn): Don't average into grayscale, do something useful (or each channel separately)\n\tMatrixXf A = MatrixXf( h, w );\n for( int y = 0; y < h; ++y ) {\n for( int x = 0; x < w; ++x ) {\n float v = ( float )data[ ( y * w + x ) * n ] / 255.f;\n for( int c = 1; c < n; ++c ) {\n v += ( float )data[ ( y * w + x ) * n + c ] / 255.f;\n }\n\t\t\tA( y, x ) = v / ( float )n;\n }\n }\n\n char *eptr;\n int rank = strtol( argv[ 2 ], &eptr, 10 );\n int wrank = rank;\n\n printf( \"Computing SVD of %s (%dx%d)\\n\", argv[ 1 ], w, h );\n vul_timer *t = vul_timer_create( );\n\tJacobiSVD< MatrixXf > svd( A, ComputeThinU | ComputeThinV );\n uint64_t mms = vul_timer_get_micros( t );\n printf( \"Completed in %lu.%lus\\n\", mms / 1000000, mms % 1000000 );\n\n\tVectorXf sigma = svd.singularValues();\n for( int i = 0; i < svd.rank(); ++i ) {\n printf( \"S[%d]: %f\\n\", i, sigma[i] );\n }\n\n printf( \"Rank of decomposition %d, wanted at most %d\\n\", svd.rank(), wrank );\n\n\tMatrixXf B = svd.matrixU() * svd.singularValues().asDiagonal() * svd.matrixV().transpose();\n\n unsigned char *odata = ( unsigned char* )malloc( sizeof( unsigned char ) * w * h * 3 );\n for( int y = 0; y < h; ++y ) {\n for( int x = 0; x < w; ++x ) {\n float v = B( y, x ) * 255.f;\n v = v < 0.f ? 0.f \n : v > 255.f ? 255.f \n : v;\n odata[ ( y * w + x ) * 3 ] = v;\n odata[ ( y * w + x ) * 3 + 1 ] = v;\n odata[ ( y * w + x ) * 3 + 2 ] = v;\n }\n }\n stbi_write_bmp( \"out.bmp\", w, h, 3, odata );\n printf( \"Wrote output to out.bmp.\\n\");\n for( int y = 0; y < h; ++y ) {\n for( int x = 0; x < w; ++x ) {\n float v = A( y, x ) * 255.f;\n v = v < 0.f ? 0.f \n : v > 255.f ? 255.f \n : v;\n odata[ ( y * w + x ) * 3 ] = v;\n odata[ ( y * w + x ) * 3 + 1 ] = v;\n odata[ ( y * w + x ) * 3 + 2 ] = v;\n }\n }\n stbi_write_bmp( \"source.bmp\", w, h, 3, odata );\n printf( \"Wrote input to source.bmp.\\n\");\n \n free( odata );\n free( data );\n}\n", "meta": {"hexsha": "ab4b1d3c6a9d1a1bb5e322e852b4c5430886151d", "size": 2610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Libraries/Tests/svd_image_eigen.cpp", "max_stars_repo_name": "thynnmas/vul", "max_stars_repo_head_hexsha": "4501e95cf20dde362a3b88d28fc9323c6c6f8725", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-03-07T22:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T11:53:26.000Z", "max_issues_repo_path": "Libraries/Tests/svd_image_eigen.cpp", "max_issues_repo_name": "thynnmas/vul", "max_issues_repo_head_hexsha": "4501e95cf20dde362a3b88d28fc9323c6c6f8725", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Libraries/Tests/svd_image_eigen.cpp", "max_forks_repo_name": "thynnmas/vul", "max_forks_repo_head_hexsha": "4501e95cf20dde362a3b88d28fc9323c6c6f8725", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3258426966, "max_line_length": 108, "alphanum_fraction": 0.4881226054, "num_tokens": 946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7690802370707283, "lm_q1q2_score": 0.6798971450843868}} {"text": "#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\ntypedef boost::adjacency_list > weighted_graph;\ntypedef boost::property_map::type weight_map;\ntypedef boost::graph_traits::edge_descriptor edge_desc;\ntypedef boost::graph_traits::vertex_descriptor vertex_desc;\n\nusing namespace std;\n\n// Essentially, the tasks asks for the cost of the second best spanning tree.\n// Leia performs Prims MST algorithm. We need at least one edge different to the MST,\n// therefore, the best we can do is computing the second best spanning tree.\nvoid solve() {\n // Tatooine is not needed for anything\n int n, tatooine;\n cin >> n >> tatooine;\n \n // Compute a MST (with any algorithm)\n weighted_graph G(n);\n\n int cost;\n vector> costs(n, vector(n));\n for (int j = 0; j < n - 1; ++j) {\n for (int k = 0; k < n - j - 1; ++k) {\n int u = j;\n int v = j + k + 1;\n cin >> cost;\n costs[u][v] = cost;\n costs[v][u] = cost;\n boost::add_edge(u, v, cost, G);\n }\n }\n \n // Use Kurskal (we could also use Prim...does not make any difference)\n std::vector mst;\n boost::kruskal_minimum_spanning_tree(G, std::back_inserter(mst));\n \n // Extract neighbors from MST and compute MST Value\n int mstValue = 0;\n vector> neighbors(n);\n vector> isMstEdge(n, vector(n, false));\n for (auto edge : mst) {\n int u = boost::source(edge, G);\n int v = boost::target(edge, G);\n mstValue += costs[u][v];\n neighbors[u].push_back(v);\n neighbors[v].push_back(u);\n isMstEdge[u][v] = true;\n isMstEdge[v][u] = true;\n }\n \n // Compute the most expensive edge for every u-v path in the MST\n vector> uvMaxEdge(n, vector(n, 0));\n \n for (int u = 0; u < n; ++u) {\n vector stack;\n stack.push_back(u);\n vector visited(n, false);\n visited[u] = true;\n \n while (!stack.empty()) {\n int v = *stack.rbegin();\n stack.pop_back();\n \n for (auto w : neighbors[v]) {\n if (!visited[w]) {\n visited[w] = true;\n uvMaxEdge[u][w] = max(costs[v][w], uvMaxEdge[u][v]);\n stack.push_back(w);\n }\n }\n }\n }\n \n // For all edges e = {u, v}, that are not in the MST, we will try adding e to the MST.\n // This will introduce a cycle. We remove the most expensive edge of the cycle that is \n // part of the MST. For this we can simply query the most expensive edge from u to v in the MST \n // and remove it. The cost of the MST changes by delta = cost[u][v] - cost[most expensive edge].\n // We simply find the best delta.\n int minVal = numeric_limits::max();\n for (int u = 0; u < n; ++u) {\n for (int v = u + 1; v < n; ++v) {\n if (!isMstEdge[u][v]) {\n int val = costs[u][v] - uvMaxEdge[u][v];\n minVal = min(val, minVal);\n }\n }\n }\n \n cout << mstValue + minVal << endl;\n}\n\n\nint main() {\n ios_base::sync_with_stdio(false);\n int t; cin >> t;\n while(t--) {\n solve();\n }\n}", "meta": {"hexsha": "72b3dc6b375da047d2487df012e830fb22463c36", "size": 3332, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/return_of_the_jedi.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/return_of_the_jedi.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/return_of_the_jedi.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 30.8518518519, "max_line_length": 98, "alphanum_fraction": 0.618847539, "num_tokens": 959, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460332, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6798971450640904}} {"text": "#pragma once\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"mpfr/import_std_math.hpp\"\n#include \"quadrature/qhermitew.hpp\"\n#include \"spectral/hermitenw.hpp\"\n#include \"spectral/lagrange_polynomial.hpp\"\n\n\nnamespace boltzmann {\n\n/**\n * @brief Nodal <-> Hermite transformation matrices in 1d.\n *\n * @remark\n * the nodal basis consists of Lagrange polynomials at Hermite quadrature nodes.\n * The underlying Lagrange polynomials satisfy:\n *\n * \\f$ l_i(x_j) = 0 \\quad \\textrm{for } i \\neq j \\f$\n *\n * and\n *\n * \\f$ l_i(x_i) = 1/sqrt(w_i) \\f$\n *\n * where \\f$w_i\\f$ are the Gauss-Hermite quadrature weights.\n *\n */\ntemplate \nclass H2N_1d\n{\n public:\n typedef NUMERIC_T numeric_t;\n // typedef Eigen::Matrix matrix_t;\n\n public:\n /**\n *\n *\n * @param H2N hermite to nodal matrix\n * @param N2H nodal to hermite matrix\n * @param K max. polynomial degree\n */\n template \n static void create(MATRIX& H2N, MATRIX& N2H, const int K);\n};\n\n// --------------------------------------------------------------------------------\ntemplate \ntemplate \nvoid\nH2N_1d::create(MATRIX& H2N, MATRIX& N2H, const int K)\n{\n N2H.resize(K, K);\n H2N.resize(K, K);\n // N2H_.resize(K,K);\n QHermiteW quad(1, K);\n HermiteNW hermw(K);\n hermw.compute(quad.pts());\n\n for (int i = 0; i < K; ++i) {\n for (int j = 0; j < K; ++j) {\n const double wi = quad.wts(i);\n H2N(i, j) = hermw.get(j)[i] * ::math::sqrt(wi);\n }\n }\n\n N2H = H2N.transpose();\n}\n\n// -------------------------------------------------------------------------------------\n// -------------------------------------------------------------------------------------\n// -------------------------------------------------------------------------------------\n/**\n * @brief Nodal <-> Hermite transformation matrices in 1d, nodes of the nodal basis can be\n * arbitrary.\n *\n * The nodes of the nodal basis are located at the nodes of the Gauss-Hermite quadrature rule\n * with weight function \\f$ exp(-\\alpha r^2) \\f$.\n *\n * @remark\n * ATTENTION: H2N(a=1) is orthonormal, but this is not the case when \\f$ a \\neq 1\\f$!\n *\n *\n * If this class is used together with @a Hermite2Nodal (and alpha!=1), the transformation\n * `N->H` will give wrong results! Only use H->N. TODO: update code such that BOTH forward AND\n * BACKWARD transformation works.\n *\n */\nclass H2NG_1d\n{\n public:\n template \n static void create(MATRIX& H2N, MATRIX& N2H, const int K, const double alpha)\n {\n typedef Eigen::VectorXd vec_t;\n\n H2N.resize(K, K);\n\n QHermiteW quad4nodes(alpha, K);\n QHermiteW quad(1, K);\n\n // Lagrange Poly\n vec_t xi = Eigen::Map(quad4nodes.points_data(), K);\n vec_t li(K); // lambda's (barycentric interpolation)\n vec_t yi(K);\n vec_t x = Eigen::Map(quad.points_data(), K);\n vec_t w = Eigen::Map(quad.weights_data(), K);\n vec_t y(K);\n // prepare barycentric interpol. weights\n LagrangePolynomial<>::compute_weights(li, xi);\n // evaluate hermite polynomials at quadrature points\n HermiteNW hermw(K);\n hermw.compute(quad.pts());\n const double ah4 = std::pow(alpha, 0.25);\n\n Eigen::MatrixXd T(K, K);\n for (int i = 0; i < K; ++i) {\n yi.setZero();\n yi[i] = 1.0;\n LagrangePolynomial<>::evaluate(y, x, xi, yi, li);\n const double sqrtwi = std::sqrt(w[i]);\n for (int j = 0; j < K; ++j) {\n double sum = 0;\n // quadrature\n for (int q = 0; q < K; ++q) {\n sum += hermw.get(j)[q] * std::exp((x[i] * x[i] - x[q] * x[q]) / 2) * ah4 * y[q] * w[q] /\n sqrtwi;\n }\n T(i, j) = sum;\n }\n }\n\n Eigen::MatrixXd M(K, K);\n vec_t y1(K);\n vec_t y2(K);\n const double ah2 = std::sqrt(alpha);\n // mass matrix (cf. notes in yellow notebook)\n for (int i = 0; i < K; ++i) {\n yi.setZero();\n yi[i] = 1.0;\n LagrangePolynomial<>::evaluate(y1, x, xi, yi, li);\n for (int j = 0; j < K; ++j) {\n yi.setZero();\n yi[j] = 1.0;\n LagrangePolynomial<>::evaluate(y2, x, xi, yi, li);\n double sum = 0;\n for (int q = 0; q < K; ++q) {\n sum += std::exp((x[i] * x[i] + x[j] * x[j]) / 2 - x[q] * x[q]) * y1[q] * y2[q] /\n std::sqrt(w[i] * w[j]) * w[q];\n }\n M(i, j) = ah2 * sum;\n }\n }\n H2N = M.inverse() * T;\n N2H = T.transpose();\n }\n};\n\n} // end namespace boltzmann\n", "meta": {"hexsha": "6e56dc50f51c63365bd6b75c7be1ee020bd9e344", "size": 4755, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/spectral/h2n_1d.hpp", "max_stars_repo_name": "simonpintarelli/2dBoltzmann", "max_stars_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/spectral/h2n_1d.hpp", "max_issues_repo_name": "simonpintarelli/2dBoltzmann", "max_issues_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/spectral/h2n_1d.hpp", "max_forks_repo_name": "simonpintarelli/2dBoltzmann", "max_forks_repo_head_hexsha": "bc6b7bbeffa242ce80937947444383b416ba3fc9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6453488372, "max_line_length": 98, "alphanum_fraction": 0.5509989485, "num_tokens": 1445, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6798667007557146}} {"text": "/*\n* Copyright (c) 2019 Nobuyuki Umetani\n*\n* This source code is licensed under the MIT license found in the\n* LICENSE file in the root directory of this source tree.\n*/\n\n/**\n * @brief demo for visualizing eigenmodes\n */\n\n#include \n#if defined(_WIN32) // windows\n# define NOMINMAX // to remove min,max macro\n# include // should put before glfw3.h\n#endif\n#define GL_SILENCE_DEPRECATION\n#include \n\n#include \"delfem2/eigen/ls_dense.h\"\n#include \"delfem2/lsitrsol.h\"\n#include \"delfem2/mshprimitive.h\"\n#include \"delfem2/mshuni.h\"\n#include \"delfem2/points.h\"\n#include \"delfem2/femsolidlinear.h\"\n#include \"delfem2/glfw/viewer3.h\"\n#include \"delfem2/glfw/util.h\"\n#include \"delfem2/opengl/old/mshuni.h\"\n\nnamespace dfm2 = delfem2;\n\nvoid ShowEigen_SolidLinear_MeshQuad2(\n const std::vector& aXY,\n const std::vector& aQuad,\n double elen)\n{\n const unsigned int np = aXY.size() / 2;\n Eigen::MatrixXd A(np * 2, np * 2);\n A.setZero();\n\n double emat[4][4][2][2];\n dfm2::EMat_SolidLinear2_QuadOrth_GaussInt(emat, elen, elen, 1.0, 1.0, 2);\n std::vector tmp_buffer;\n for (unsigned int iq = 0; iq < aQuad.size() / 4; ++iq) {\n const unsigned int aIp[4] = {\n aQuad[iq * 4 + 0], aQuad[iq * 4 + 1], aQuad[iq * 4 + 2], aQuad[iq * 4 + 3]};\n delfem2::Merge<4,4,2,2,double>(A,aIp,aIp,emat,tmp_buffer);\n }\n\n {\n auto B = A;\n B(0,0) += 1.0;\n B(1,1) += 1.0;\n B(2,2) += 1.0;\n B(3,3) += 1.0;\n Eigen::VectorXd r(np*2), u(np*2), Ap(np*2), p(np*2);\n r.setRandom();\n std::vector aConv = dfm2::Solve_CG(r,u,Ap,p,1.0e-5,300,B);\n std::cout << aConv.size() << std::endl;\n }\n\n Eigen::SelfAdjointEigenSolver s(A);\n const auto& evec = s.eigenvectors(); // somehow this takes time\n\n //\n delfem2::glfw::CViewer3 viewer;\n delfem2::glfw::InitGLOld();\n viewer.OpenWindow();\n\n std::vector aDisp(np*2,0.0);\n\n for(unsigned int iframe=0;iframe<10;++iframe){\n std::cout << s.eigenvalues()(iframe) << std::endl;\n for(unsigned int i=0;i& aXY,\n const std::vector& aTri)\n{\n const unsigned int np = aXY.size()/2;\n Eigen::MatrixXd A(np*2, np*2);\n A.setZero();\n\n std::vector aDisp(np*2,0.0);\n std::vector tmp_buffer;\n for(unsigned int it=0;it(disp,aIp,aDisp.data());\n double coord[3][2]; dfm2::FetchData<3,2>(coord,aIp,aXY.data());\n double emat[3][3][2][2], eres[3][2];\n dfm2::EMat_SolidStaticLinear_Tri2D(\n eres,emat,\n 1,1,0,0,0,\n disp,coord);\n delfem2::Merge<3,3,2,2,double>(A,aIp,aIp,emat,tmp_buffer);\n }\n\n Eigen::SelfAdjointEigenSolver s(A);\n const auto& evec = s.eigenvectors();\n //\n delfem2::glfw::CViewer3 viewer;\n delfem2::glfw::InitGLOld();\n viewer.OpenWindow();\n for(unsigned int iframe=0;iframe<10;++iframe){\n std::cout << s.eigenvalues()(iframe) << std::endl;\n for(unsigned int i=0;i aXY;\n std::vector aQuad;\n unsigned int nx = 10;\n unsigned int ny = 5;\n dfm2::MeshQuad2D_Grid(\n aXY,aQuad,\n nx,ny);\n const double elen = 0.1;\n {\n dfm2::Scale_Points(aXY.data(), aXY.size() / 2, 2, elen);\n dfm2::Translate_Points2(aXY,-0.5*nx*elen, -0.5*ny*elen);\n }\n ShowEigen_SolidLinear_MeshQuad2(aXY, aQuad, elen);\n //\n std::vector aTri;\n dfm2::convert2Tri_Quad(\n aTri,\n aQuad);\n ShowEigen_SolidLinear_MeshTri2(aXY,aTri);\n}\n", "meta": {"hexsha": "4bf13d036e974387525b549ace2c526889560e0e", "size": 4559, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples_oldgl_glfw_eigen/00_EigenModes/main.cpp", "max_stars_repo_name": "mmer547/delfem2", "max_stars_repo_head_hexsha": "4f4b28931c96467ac30948e6b3f83150ea530c92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-07-18T17:03:36.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-18T17:03:36.000Z", "max_issues_repo_path": "examples_oldgl_glfw_eigen/00_EigenModes/main.cpp", "max_issues_repo_name": "mmer547/delfem2", "max_issues_repo_head_hexsha": "4f4b28931c96467ac30948e6b3f83150ea530c92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples_oldgl_glfw_eigen/00_EigenModes/main.cpp", "max_forks_repo_name": "mmer547/delfem2", "max_forks_repo_head_hexsha": "4f4b28931c96467ac30948e6b3f83150ea530c92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1419753086, "max_line_length": 97, "alphanum_fraction": 0.6288659794, "num_tokens": 1596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.679859249752509}} {"text": "/* Copyright (c) 2021 Grumpy Cat Software S.L.\n *\n * This Source Code is licensed under the MIT 2.0 license.\n * the terms can be found in LICENSE.md at the root of\n * this project, or at http://mozilla.org/MPL/2.0/.\n */\n\n#include \n#include \n#include \n\n#include \n\nusing namespace Eigen;\n\nconstexpr auto EPSILON = 1e-8;\n\nnamespace {\n\naf::array vandermonde(const af::array &x, int order, bool ascending) {\n af::array result = af::array(x.dims(0), order, x.type());\n gfor(af::seq i, order) { result(af::span, i) = af::pow(x, i); }\n if (!ascending) {\n result = af::flip(result, 1);\n }\n return result;\n}\n\n} // namespace\n\naf::array gauss::polynomial::polyfit(const af::array &x, const af::array &y, int deg) {\n int order = deg + 1;\n af::array lhs = vandermonde(x, order, false);\n const af::array &rhs = y;\n\n af::array scale = af::max(af::sqrt(af::sum(lhs * lhs, 0)), EPSILON);\n\n lhs /= af::tile(scale, static_cast(lhs.dims(0)));\n\n af::array c = gauss::linalg::lls(lhs, rhs);\n c = af::transpose(c);\n c /= af::tile(scale, static_cast(c.dims(0)));\n c = af::transpose(c);\n\n return c;\n}\n\naf::array gauss::polynomial::roots(const af::array &pp) {\n af::array result = af::array(pp.dims(0) - 1, pp.dims(1), af::dtype::c32);\n for (int i = 0; i < pp.dims(1); i++) {\n af::array p = pp(af::span, i);\n // Strip leading and trailing zeros\n p = p(p != 0);\n\n p = (-1 * p(af::seq(1, static_cast(p.dims(0)) - 1), af::span)) /\n af::tile(p(0, af::span), static_cast(p.dims(0)) - 1);\n\n auto coeffs = gauss::utils::makeScopedHostPtr(p.as(af::dtype::f32).host());\n\n Eigen::VectorXf vec = Eigen::VectorXf::Ones(p.dims(0));\n Eigen::MatrixXf diag = vec.asDiagonal();\n\n Eigen::MatrixXf diag2(diag.rows(), diag.cols());\n int rest = static_cast(diag.rows()) - 1;\n diag2.topRows(1) = Eigen::Map(coeffs.get(), 1, p.dims(0));\n diag2.bottomRows(rest) = diag.topRows(rest);\n\n Eigen::VectorXcf eivals = diag2.eigenvalues();\n\n result(af::span, i) = af::array(p.dims(0), (af::cfloat *)eivals.data());\n }\n\n return result;\n}\n", "meta": {"hexsha": "037707ee2242b972cb1e5539aa44e21e1b19b627", "size": 2313, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/gauss/src/polynomial.cpp", "max_stars_repo_name": "shapelets/shapelets-compute", "max_stars_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T09:43:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:44:55.000Z", "max_issues_repo_path": "modules/gauss/src/polynomial.cpp", "max_issues_repo_name": "shapelets/shapelets-compute", "max_issues_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T11:48:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:30:34.000Z", "max_forks_repo_path": "modules/gauss/src/polynomial.cpp", "max_forks_repo_name": "shapelets/shapelets-compute", "max_forks_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.84, "max_line_length": 90, "alphanum_fraction": 0.5987894509, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.679859249752509}} {"text": "#ifndef RANDOMNUMBERGENERATOR_HPP_\n#define RANDOMNUMBERGENERATOR_HPP_\n\n// for random sampling\n#include \n#include \n#include \n#include \n#include \n#include \n\n\ntemplate\nclass RandomNumberGenerator {\n\n public:\n\n RandomNumberGenerator() {\n }\n\n ~RandomNumberGenerator() {\n }\n\n /* mean =0, std = 1*/\n Dtype sampleNormal() {\n auto dist = boost::random::normal_distribution(0.0, 1.0);\n return dist(rngGenerator);\n }\n\n /* from -1 to 1*/\n Dtype sampleUniform() {\n auto dist = boost::uniform_real(-1, 1);\n return dist(rngGenerator);\n }\n\n /* from 0 to 1*/\n Dtype sampleUniform01() {\n auto dist = boost::uniform_real(0, 1);\n return dist(rngGenerator);\n }\n\n bool forXPercent(float epsilon) {\n auto dist = boost::uniform_real(0, 1);\n return dist(rngGenerator) < epsilon;\n }\n\n int intRand(const int &min, const int &max) {\n {\n std::uniform_int_distribution distribution(min, max);\n return distribution(rngGenerator);\n }\n }\n\n /* weighted random sampling where the weights are given by 1, r, r^2, ... */\n int intWeightedRand (const int &max, Dtype weightDecayFtr) {\n Dtype sum = (Dtype(1) - std::pow(weightDecayFtr, max+1)) / (Dtype(1)-weightDecayFtr);\n return std::ceil(log(Dtype(1) - sampleUniform01() * sum * (Dtype(1) - weightDecayFtr)) / log(weightDecayFtr)) - 1;\n }\n\n template\n void sampleVectorInNormalUniform(Dtype *vector) {\n auto dist = boost::uniform_real(-1, 1);\n for (int i = 0; i < dim; i++)\n vector[i] = dist(rngGenerator);\n }\n\n template\n void sampleInUnitSphere(Dtype *vector) {\n sampleVectorInNormalUniform(vector);\n Dtype sum = 0.0f;\n\n for (int i = 0; i < dim; i++)\n sum += vector[i] * vector[i];\n\n Dtype amplitudeOverSum = pow(std::abs(sampleUniform()), Dtype(1.0) / Dtype(dim)) / sqrtf(sum);\n\n for (int i = 0; i < dim; i++)\n vector[i] = vector[i] * amplitudeOverSum;\n }\n\n template\n void sampleOnUnitSphere(Dtype *vector) {\n sampleVectorInNormalUniform(vector);\n Dtype sum = 0.0f;\n\n for (int i = 0; i < dim; i++)\n sum += vector[i] * vector[i];\n\n for (int i = 0; i < dim; i++)\n vector[i] = vector[i] / sqrtf(sum);\n }\n\n template\n void shuffleSTDVector(std::vector &order) {\n boost::variate_generator >\n random_number_shuffler(rngGenerator, boost::uniform_int<>());\n std::random_shuffle(order.begin(), order.end(), random_number_shuffler);\n }\n\n /* this method is opitmized for memory use. The column should be dynamic size */\n template\n void shuffleColumns(Eigen::Matrix &matrix) {\n int colSize = int(matrix.cols());\n\n /// sampling the order\n std::vector order;\n std::vector needSuffling(colSize, true);\n\n order.resize(colSize);\n for (int i = 0; i < colSize; i++) order[i] = i;\n shuffleSTDVector(order);\n Eigen::Matrix memoryCol(matrix.rows());\n\n int colID;\n\n for (int colStartID = 0; colStartID < colSize; colStartID++) {\n if (order[colStartID] == colStartID || !needSuffling[colStartID]) continue;\n\n colID = colStartID;\n memoryCol = matrix.col(colID);\n do {\n matrix.col(colID) = matrix.col(order[colID]);\n needSuffling[colID] = false;\n colID = order[colID];\n } while (colStartID != order[colID]);\n matrix.col(colID) = memoryCol;\n needSuffling[colID] = false;\n }\n }\n\n std::vector getNrandomSubsetIdx (unsigned nOfElem, unsigned nOfSubElem) {\n std::vector memoryIdx(nOfSubElem);\n ///// randomly sampling memory indeces\n for (unsigned i = 0; i < nOfSubElem; i++) {\n memoryIdx[i] = intRand(0, nOfElem - 1);\n for (unsigned j = 0; j < i; j++) {\n if (memoryIdx[i] == memoryIdx[j]) {\n i--;\n break;\n }\n }\n }\n return memoryIdx;\n }\n\n /*you can use this method to make the random samples the same*/\n void seed(uint32_t seed) {\n rngGenerator.seed(seed);\n }\n\n private:\n boost::random::mt19937 rngGenerator;\n\n};\n\n\n#endif /* RANDOMNUMBERGENERATOR_HPP_ */\n", "meta": {"hexsha": "f8b7d12fedfa0e14e002dca707db5c8525daac01", "size": 4331, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/common/RandomNumberGenerator.hpp", "max_stars_repo_name": "xdaNvidia/learning_quadrupedal_locomotion_over_challenging_terrain_supplementary", "max_stars_repo_head_hexsha": "2f94b13455ff16e26d1acd6a984f1f88f7824e31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 94.0, "max_stars_repo_stars_event_min_datetime": "2020-10-22T08:47:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:33:49.000Z", "max_issues_repo_path": "include/common/RandomNumberGenerator.hpp", "max_issues_repo_name": "lixuechuan123/learning_quadrupedal_locomotion_over_challenging_terrain_supplementary", "max_issues_repo_head_hexsha": "277d19b007fd3109956d1ea0cc9e0cd50d3ecb5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-10-25T09:41:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-04T06:58:11.000Z", "max_forks_repo_path": "include/common/RandomNumberGenerator.hpp", "max_forks_repo_name": "lixuechuan123/learning_quadrupedal_locomotion_over_challenging_terrain_supplementary", "max_forks_repo_head_hexsha": "277d19b007fd3109956d1ea0cc9e0cd50d3ecb5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2020-10-22T13:36:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T01:17:14.000Z", "avg_line_length": 27.4113924051, "max_line_length": 118, "alphanum_fraction": 0.640036943, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171067, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.6798592402820804}} {"text": "#pragma once\n#include \"shape.hpp\"\n#include \n#include \n\n//! The gradient of the shape function (on the reference element) for LINEAR FEM\n//!\n//! We have three shape functions\n//!\n//! @param i integer between 0 and 2 (inclusive). Decides which shape function to return.\n//! @param x x coordinate in the reference element.\n//! @param y y coordinate in the reference element.\ninline Eigen::Vector2d gradientLambda(const int i, double x, double y) {\n\tstd::ignore = x;\n\tstd::ignore = y;\n\n\treturn Eigen::Vector2d(-1 + (i > 0) + (i == 1),\n\t -1 + (i > 0) + (i == 2));\n\treturn Eigen::Vector2d(0, 0); //remove when implemented\n}\n\n//----------------gradshapefunBegin----------------\n//! The gradient of the shape function (on the reference element) for QUADRATIC FEM\n//!\n//! We have six shape functions\n//!\n//! @param i integer between 0 and 5 (inclusive). Decides which shape function to return.\n//! @param x x coordinate in the reference element.\n//! @param y y coordinate in the reference element.\ninline Eigen::Vector2d gradientShapefun(const int i, double x, double y) {\n\t// Eigen::Vector2d value;\n\t// (write your solution here)\n\tassert(0 <= i && i <= 5);\n\tswitch (i) {\n\t\tcase 0:\n\t\t\treturn Eigen::Vector2d(-3 + 4 * x + 4 * y, -3 + 4 * x + 4 * y);\n\t\tcase 1:\n\t\t\treturn Eigen::Vector2d(4 * x - 1, 0);\n\t\tcase 2:\n\t\t\treturn Eigen::Vector2d(0, 4 * y - 1);\n\t\tcase 3:\n\t\t\treturn Eigen::Vector2d(4 - 8 * x - 4 * y, -4 * x);\n\t\tcase 4:\n\t\t\treturn Eigen::Vector2d(4 * y, 4 * x);\n\t\tcase 5:\n\t\t\treturn Eigen::Vector2d(-4 * y, 4 - 4 * x - 8 * y);\n\t\tdefault:\n\t\t\tthrow std::domain_error(\"i not in {0,1,2,3,4,5}\");\n\t}\n\t//return value;\n}\n//----------------gradshapefunEnd----------------\n", "meta": {"hexsha": "aa0c289814ecdc85e257a0f81c3820a5536940e7", "size": 1699, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series3/2d-poissonqFEM/grad_shape.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series3/2d-poissonqFEM/grad_shape.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series3/2d-poissonqFEM/grad_shape.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0566037736, "max_line_length": 89, "alphanum_fraction": 0.6103590347, "num_tokens": 518, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6798374973452256}} {"text": "#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n\n\nusing s64 = int64_t;\n\nusing namespace std;\n\nusing boost::multiprecision::mpq_rational;\n\nQDebug operator<<(QDebug d, const mpq_rational& r) {\n d.nospace();\n d.noquote();\n stringstream s;\n s << r;\n d << QString::fromStdString(s.str());\n return d.resetFormat();\n}\n\nQMap rolls(int sides, int repetitions) {\n\n std::function*)> traverse = [&traverse, sides, repetitions](int sum, int rep, QMap* ret) {\n if (rep == repetitions) {\n if (ret->contains(sum) == false) {\n (*ret)[sum] = 0;\n }\n (*ret)[sum] += 1;\n return;\n }\n\n for (int i = 1; i <= sides; i += 1) {\n traverse(sum + i, rep + 1, ret);\n }\n };\n\n QMap ret;\n\n traverse(0, 0, &ret);\n\n return ret;\n}\n\nmpq_rational winProbability(int sides1, int reps1, int sides2, int reps2) {\n auto rolls1 = rolls(sides1, reps1);\n auto rolls2 = rolls(sides2, reps2);\n\n auto values1 = rolls1.values();\n auto values2 = rolls2.values();\n\n s64 sum1 = accumulate(begin(values1), end(values1), 0);\n s64 sum2 = accumulate(begin(values2), end(values2), 0);\n\n mpq_rational ret(0);\n\n QMap::const_iterator i = rolls2.constBegin();\n while (i != rolls2.constEnd()) {\n mpq_rational pickProbability(i.value(), sum1);\n\n s64 winNumerator = 0;\n\n QMap::const_iterator j = rolls1.constBegin();\n while (j != rolls1.constEnd()) {\n\n if (j.key() < i.key()) {\n winNumerator += j.value();\n //qDebug() << \" +\" << j.key() << j.value() << winNumerator;\n } else {\n //qDebug() << \" -\" << j.key();\n }\n\n ++j;\n }\n\n ret += pickProbability*mpq_rational(winNumerator, sum2);\n\n //qDebug() << \"sum\" << i.key() << \", pick\" << pickProbability << \", win this\" << mpq_rational(winNumerator, sum2) << \", total\" << ret;\n\n ++i;\n }\n\n return ret;\n}\n\nvoid testRolls();\nvoid test1();\n\nint main(int argc, char **args) {\n Q_UNUSED(argc); Q_UNUSED(args);\n\n testRolls();\n test1();\n\n return 0;\n}\n\nvoid testRolls() {\n\n auto a31 = rolls(3, 1);\n assert(a31.size() == 3);\n assert(a31[1] == 1);\n assert(a31[2] == 1);\n assert(a31[3] == 1);\n\n auto a22 = rolls(2, 2);\n assert(a22.size() == 3);\n assert(a22[2] == 1);\n assert(a22[3] == 2);\n assert(a22[4] == 1);\n\n auto a49 = rolls(4, 9).values(); assert(accumulate(begin(a49), end(a49), 0) == 262144);\n auto a66 = rolls(6, 6).values(); assert(accumulate(begin(a66), end(a66), 0) == 46656);\n}\n\nvoid test1() {\n qDebug() << winProbability(6, 6, 4, 9);\n}\n", "meta": {"hexsha": "d0082201219a366ebef5645dd13d7f9f37241af0", "size": 2919, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "project-euler/205/main.cpp", "max_stars_repo_name": "hydroo/coding-and-math-exercises", "max_stars_repo_head_hexsha": "c0c9b8ae48e043b0809e4c592444f3e4bc3222d8", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-05-29T21:03:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-11T02:10:53.000Z", "max_issues_repo_path": "project-euler/205/main.cpp", "max_issues_repo_name": "hydroo/coding-and-math-exercises", "max_issues_repo_head_hexsha": "c0c9b8ae48e043b0809e4c592444f3e4bc3222d8", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "project-euler/205/main.cpp", "max_forks_repo_name": "hydroo/coding-and-math-exercises", "max_forks_repo_head_hexsha": "c0c9b8ae48e043b0809e4c592444f3e4bc3222d8", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.352, "max_line_length": 142, "alphanum_fraction": 0.5344295992, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122263731811, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6796559819964845}} {"text": "#include \n#include \n#include \n#include \n#include \nusing namespace sf;\nusing namespace std;\nusing namespace Eigen;\ntypedef Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic > Mat;\n\nvoid reset(Mat& mat) {\n\t//initialize matrix to zero matrix\n\t//행렬을 영행렬로 초기화합니다.\n\tfor (int i = 0; i < mat.rows(); ++i)\n\t\tfor (int j = 0; j < mat.cols(); ++j)\n\t\t\tmat(i, j) = 0;\n}\n\nbool compare(pair a, pair b) {\n\t//compare function for sorting eigen values in descending order\n\t//고유값을 내림차순으로 정렬하기 위한 비교함수\n\treturn a.first * a.first > b.first * b.first;\n}\n\nclass RGB {\npublic:\n\tenum { R, G, B };\n\tRGB() {\n\t}\n\tRGB(Mat red, Mat green, Mat blue) {\n\t\tsize = red.rows();\n\t\tmat[R] = red;\tmat[G] = green;\tmat[B] = blue;\n\t\tempty = false;\n\t}\n\tMat mat[3];\n\tint size;\n\tbool empty = true;\n\n\n\tvector> lists[3];\n\tbool processed[3] = { false,false,false };\n\tint added[3] = { -1,-1,-1 };\n\tvoid getEVDColor(int color, int rate) {\n\t\tif (!processed[color]) {\n\t\t\tSelfAdjointEigenSolver eigensolver(mat[color]);\n\t\t\tif (eigensolver.info() != Success) abort();\n\t\t\tMat eigenValues = eigensolver.eigenvalues();\n\t\t\tMat eigenVectors = eigensolver.eigenvectors();\n\t\t\teigenVectors = eigenVectors.householderQr().householderQ();//정규직교화\n\t\t\tint num = eigenValues.rows();//고유값의 개수\n\n\t\t\tfor (int i = 0; i < num; ++i) {\n\t\t\t\tpair element;\n\t\t\t\telement.first = eigenValues(i);\n\t\t\t\telement.second = eigenVectors.col(i);\n\t\t\t\tlists[color].push_back(element);\n\t\t\t}\n\t\t\tsort(lists[color].begin(), lists[color].end(), compare);\n\t\t\tprocessed[color] = true;\n\t\t\tmat[color] = Mat(size, size);\n\t\t\treset(mat[color]);\n\t\t\tcout << endl;\n\t\t}\n\t\tif (added[color] <= rate) {\n\t\t\tfor (int i = added[color] + 1; i < rate; ++i) {\n\t\t\t\tmat[color] += (lists[color][i].first * (lists[color][i].second * lists[color][i].second.transpose()));\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tfor (int i = added[color]; i >= rate; --i) {\n\t\t\t\tmat[color] -= (lists[color][i].first * (lists[color][i].second * lists[color][i].second.transpose()));\n\t\t\t}\n\t\t}\n\t\tadded[color] = rate - 1;\n\t}\n};\n\nRGB getMatrixFromImage(Image& img) {\n\t//only square image available\n\t//it uses upper triangle part of the image only.\n\tif (img.getSize().x != img.getSize().y) return RGB();\n\tint size = img.getSize().x;\n\n\tMat red(size, size);\n\tMat green(size, size);\n\tMat blue(size, size);\n\tfor (int i = 0; i < size; ++i) {\n\t\tfor (int j = 0; j < size; ++j) {\n\t\t\tif (j < i) {\n\t\t\t\tred(i, j) = img.getPixel(i, j).r;\n\t\t\t\tgreen(i, j) = img.getPixel(i, j).g;\n\t\t\t\tblue(i, j) = img.getPixel(i, j).b;\n\t\t\t}\n\t\t\telse if (i == j) red(i, j) = 0;\n\t\t\telse {\n\t\t\t\tred(i, j) = img.getPixel(j, i).r;\n\t\t\t\tgreen(i, j) = img.getPixel(j, i).g;\n\t\t\t\tblue(i, j) = img.getPixel(j, i).b;\n\t\t\t}\n\t\t}\n\t}\n\treturn RGB(red, green, blue);\n}\n\nImage getImageFromRGB(RGB& rgb) {\n\tImage result;\n\tresult.create(rgb.size, rgb.size);\n\tfor (int i = 0; i < rgb.size; ++i) {\n\t\tfor (int j = 0; j < rgb.size; ++j) {\n\t\t\tColor color;\n\t\t\tcolor.r = rgb.mat[RGB::R](i, j);\n\t\t\tcolor.g = rgb.mat[RGB::G](i, j);\n\t\t\tcolor.b = rgb.mat[RGB::B](i, j);\n\t\t\tresult.setPixel(i, j, color.toInteger() < 0 ? Color(0) : color);\n\t\t}\n\t}\n\treturn result;\n}\n\nint main() {\n\n\tstring input;\n\tcout << \"input image file name including extension>\";\n\tcin >> input;\n\n\tImage original;\n\toriginal.loadFromFile(input);\n\tif (original.getSize().x != original.getSize().y) {\n\t\tcout << \"only square image available\";\n\t\treturn -1;\n\t}\n\n\tRenderWindow window(VideoMode(original.getSize().x, original.getSize().y), \"Math channel Ssootube Eigen Value Decomposition\");\n\tRGB mat;\n\tmat = getMatrixFromImage(original);\n\tImage applied = getImageFromRGB(mat);\n\tTexture t; t.loadFromImage(applied);\n\tSprite output(t);\n\tint k = 0;\n\tcout << \"only upper triangular part of the image will be used.\" << endl;\n\twhile (window.isOpen()) {\n\t\tEvent e;\n\t\twhile (window.pollEvent(e)) {\n\t\t\tif (e.type == Event::Closed)\n\t\t\t\twindow.close();\n\t\t\tif (e.type == Event::KeyPressed)\n\t\t\t\tif (e.key.code == Keyboard::Enter)\n\t\t\t\t{\n\t\t\t\t\twindow.clear();\n\t\t\t\t\twindow.draw(output);\n\t\t\t\t\twindow.display();\n\t\t\t\t\tif (k <= mat.size) {\n\t\t\t\t\t\tmat.getEVDColor(RGB::R, k);\n\t\t\t\t\t\tmat.getEVDColor(RGB::G, k);\n\t\t\t\t\t\tmat.getEVDColor(RGB::B, k++);\n\t\t\t\t\t}\n\t\t\t\t\tapplied = getImageFromRGB(mat);\n\t\t\t\t\tt.loadFromImage(applied);\n\t\t\t\t\toutput.setTexture(t);\n\t\t\t\t\tcout << \"press enter to continue. current rank:\" << ((k - 2 == -1) ? 0 : k - 2) << endl;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t}\n\t\t\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "a2ddcab95dde5553a3566cce88bf4903e4ffb3f9", "size": 4423, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "ssootube/image-compression-simulation-using-EVD-Eigen-Value-Decomposition-", "max_stars_repo_head_hexsha": "03af0a8a1aea4a1f95558fcd644e6324729da5e7", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-04-18T09:44:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-18T09:44:01.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "ssootube/image-compression-simulation-using-EVD-Eigen-Value-Decomposition-", "max_issues_repo_head_hexsha": "03af0a8a1aea4a1f95558fcd644e6324729da5e7", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-27T17:39:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-27T17:39:05.000Z", "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "ssootube/image-compression-simulation-using-EVD-Eigen-Value-Decomposition-", "max_forks_repo_head_hexsha": "03af0a8a1aea4a1f95558fcd644e6324729da5e7", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-18T09:42:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T09:42:45.000Z", "avg_line_length": 26.3273809524, "max_line_length": 127, "alphanum_fraction": 0.6079583993, "num_tokens": 1397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6796325046741426}} {"text": "/**\n * @file pfasst/quadrature/interface.hpp\n * @since v0.3.0\n */\n#ifndef _PFASST__QUADRATURE__INTERFACE_HPP_\n#define _PFASST__QUADRATURE__INTERFACE_HPP_\n\n#include \n#include \nusing namespace std;\n\n#include \ntemplate\nusing Matrix = Eigen::Matrix;\n\ntemplate\nusing Index = typename Matrix::Index;\n\n#include \"pfasst/globals.hpp\"\n#include \"pfasst/interfaces.hpp\"\n#include \"pfasst/quadrature/polynomial.hpp\"\n\n\nnamespace pfasst\n{\n namespace quadrature\n {\n /**\n * Quadrature type descriptors.\n * @since v0.3.0\n */\n enum class QuadratureType : int {\n GaussLegendre = 0 //!< @ref pfasst::quadrature::GaussLegendre \"Gauss-Legendre\" quadrature\n , GaussLobatto = 1 //!< @ref pfasst::quadrature::GaussLobatto \"Gauss-Lobatto\" quadrature\n , GaussRadau = 2 //!< @ref pfasst::quadrature::GaussRadau \"Gauss-Radau\" quadrature\n , ClenshawCurtis = 3 //!< @ref pfasst::quadrature::ClenshawCurtis \"Clenshaw-Curtis\" quadrature\n , Uniform = 4 //!< Uniform quadrature\n , UNDEFINED = -1\n };\n\n\n template\n static Polynomial build_polynomial(const size_t node, const vector& nodes)\n {\n const size_t num_nodes = nodes.size();\n Polynomial p(num_nodes + 1), p1(num_nodes + 1);\n p[0] = 1.0;\n\n for (size_t m = 0; m < num_nodes; ++m) {\n if (m == node) { continue; }\n\n // p_{m+1}(x) = (x - x_j) * p_m(x)\n p1[0] = scalar(0.0);\n for (size_t j = 0; j < num_nodes; ++j) { p1[j + 1] = p[j]; }\n for (size_t j = 0; j < num_nodes + 1; ++j) { p1[j] -= p[j] * nodes[m]; }\n for (size_t j = 0; j < num_nodes + 1; ++j) { p[j] = p1[j]; }\n }\n\n return p;\n }\n\n\n /**\n * Compute quadrature matrix \\\\( Q \\\\) between two sets of nodes.\n *\n * Computing the quadrature matrix \\\\( Q \\\\) for polynomial-based integration from one set of\n * quadrature nodes (@p from) to another set of quadrature nodes (@p to).\n *\n * @tparam scalar precision of quadrature (i.e. `double`)\n * @param[in] from first set of quadrature nodes\n * @param[in] to second set of quadrature nodes\n * @returns quadrature matrix \\\\( Q \\\\) with `to.size()` rows and `from.size()` colums\n *\n * @pre For correctness of the algorithm it is assumed, that both sets of nodes are in the range\n * \\\\( [0, 1] \\\\).\n *\n * @since v0.3.0\n */\n template\n static Matrix compute_q_matrix(const vector& from, const vector& to)\n {\n const size_t to_size = to.size();\n const size_t from_size = from.size();\n assert(to_size >= 1 && from_size >= 1);\n\n Matrix q_mat = Matrix::Zero(to_size, from_size);\n\n for (size_t m = 0; m < from_size; ++m) {\n Polynomial p = build_polynomial(m, from);\n // evaluate integrals\n auto den = p.evaluate(from[m]);\n auto P = p.integrate();\n for (size_t j = 0; j < to_size; ++j) {\n q_mat(j, m) = (P.evaluate(to[j]) - P.evaluate(scalar(0.0))) / den;\n }\n }\n\n return q_mat;\n }\n\n\n /**\n * Compute quadrature matrix \\\\( Q \\\\) for one set of nodes.\n *\n * @tparam scalar precision of quadrature (i.e. `double`)\n * @param[in] nodes quadrature nodes to compute \\\\( Q \\\\) matrix for\n *\n * @since v0.3.0\n *\n * @overload\n */\n template\n static Matrix compute_q_matrix(const vector& nodes)\n {\n return compute_q_matrix(nodes, nodes);\n }\n\n\n /**\n * Compute quadrature matrix \\\\( Q \\\\) from a given node-to-node quadrature matrix \\\\( S \\\\).\n *\n * @tparam scalar precision of quadrature (i.e. `double`)\n * @param[in] s_mat \\\\( S \\\\) matrix to compute \\\\( Q \\\\) from\n * @see pfasst::quadrature::compute_s_matrix\n *\n * @since v0.3.0\n *\n * @overload\n */\n template\n static Matrix compute_q_matrix(const Matrix& s_mat)\n {\n Matrix q_mat = Matrix::Zero(s_mat.rows(), s_mat.cols());\n q_mat.col(0) = s_mat.col(0);\n for (Index q_mat_col = 1; q_mat_col < q_mat.cols(); ++q_mat_col) {\n q_mat.col(q_mat_col) = q_mat.col(q_mat_col - 1) + s_mat.col(q_mat_col);\n }\n return q_mat;\n }\n\n\n /**\n * Compute node-to-node quadrature matrix \\\\( S \\\\) from a given quadrature matrix \\\\( Q \\\\).\n *\n * The \\\\( S \\\\) matrix provides a node-to-node quadrature where the \\\\( i \\\\)-th row of\n * \\\\( S \\\\) represents a quadrature from the \\\\( i-1 \\\\)-th node to the \\\\( i \\\\)-th node.\n *\n * The procedure is simply subtracting the \\\\( i-1 \\\\)-th row of \\\\( Q \\\\) from the\n * \\\\( i \\\\)-th row of \\\\( Q \\\\).\n *\n * @tparam scalar precision of quadrature (i.e. `double`)\n * @param[in] q_mat \\\\( Q \\\\) matrix to compute \\\\( S \\\\) of\n * @returns \\\\( S \\\\) matrix\n *\n * @since v0.3.0\n */\n template\n static Matrix compute_s_matrix(const Matrix& q_mat)\n {\n Matrix s_mat = Matrix::Zero(q_mat.rows(), q_mat.cols());\n s_mat.row(0) = q_mat.row(0);\n for (Index row = 1; row < s_mat.rows(); ++row) {\n s_mat.row(row) = q_mat.row(row) - q_mat.row(row - 1);\n }\n return s_mat;\n }\n\n\n /**\n * Compute node-to-node quadrature matrix \\\\( S \\\\) from two given sets of nodes\n *\n * @tparam scalar precision of quadrature (i.e. `double`)\n * @param[in] from first set of quadrature nodes\n * @param[in] to second set of quadrature nodes\n *\n * @since v0.3.0\n *\n * @overload\n */\n template\n static Matrix compute_s_matrix(const vector& from, const vector& to)\n {\n return compute_s_matrix(compute_q_matrix(from, to));\n }\n\n\n /**\n * Compute vector \\\\( q \\\\) for integration from \\\\( 0 \\\\) to \\\\( 1 \\\\) for given set of nodes.\n *\n * This equals to the last row of the quadrature matrix \\\\( Q \\\\) for the given set of nodes.\n *\n * @tparam scalar precision of quadrature (i.e. `double`)\n * @param[in] nodes quadrature nodes to compute \\\\( Q \\\\) matrix for\n * @pre For correctness of the algorithm it is assumed, that the nodes are in the range\n * \\\\( [0, 1] \\\\).\n *\n * @since v0.3.0\n */\n template\n static vector compute_q_vec(const vector& nodes)\n {\n const size_t num_nodes = nodes.size();\n assert(num_nodes >= 1);\n\n vector q_vec = vector(num_nodes, scalar(0.0));\n\n for (size_t m = 0; m < num_nodes; ++m) {\n Polynomial p = build_polynomial(m, nodes);\n // evaluate integrals\n auto den = p.evaluate(nodes[m]);\n auto P = p.integrate();\n q_vec[m] = (P.evaluate(scalar(1.0)) - P.evaluate(scalar(0.0))) / den;\n }\n\n return q_vec;\n }\n\n /**\n * Interface for quadrature handlers.\n *\n * Quadrature handlers provide \\\\( Q \\\\), \\\\( S \\\\) and \\\\( B \\\\) matrices respecting the left\n * and right nodes, i.e. whether \\\\( 0 \\\\) and \\\\( 1 \\\\) are part of the nodes or not.\n *\n * Computation of the quadrature nodes and matrices (i.e. quadrature weights) is done on\n * initialization.\n *\n * @tparam scalar precision of quadrature (i.e. `double`)\n *\n * @since v0.3.0\n */\n template\n class IQuadrature\n {\n protected:\n //! @{\n static const bool LEFT_IS_NODE = false;\n static const bool RIGHT_IS_NODE = false;\n\n size_t num_nodes;\n Matrix q_mat;\n Matrix s_mat;\n vector q_vec; // XXX: black spot\n Matrix b_mat;\n vector nodes;\n //! @}\n\n public:\n //! @{\n /**\n * @throws invalid_argument if number of nodes is invalid for quadrature type\n */\n explicit IQuadrature(const size_t num_nodes);\n /**\n * @throws invalid_argument if number of nodes is invalid for quadrature type\n */\n IQuadrature();\n virtual ~IQuadrature() = default;\n //! @}\n\n //! @{\n virtual const Matrix& get_q_mat() const;\n virtual const Matrix& get_s_mat() const;\n virtual const Matrix& get_b_mat() const;\n virtual const vector& get_q_vec() const;\n virtual const vector& get_nodes() const;\n virtual size_t get_num_nodes() const;\n\n /**\n * @throws pfasst::NotImplementedYet if not overwritten by implementation;\n * required for quadrature of any kind\n */\n virtual bool left_is_node() const;\n /**\n * @throws pfasst::NotImplementedYet if not overwritten by implementation;\n * required for quadrature of any kind\n */\n virtual bool right_is_node() const;\n //! @}\n\n /**\n * Compute a rough estimate of the numerical error... XXX\n */\n precision expected_error() const;\n\n protected:\n //! @{\n /**\n * @throws pfasst::NotImplementedYet if not overwritten by implementation;\n * required for quadrature of any kind\n */\n virtual void compute_nodes();\n virtual void compute_weights();\n //! @}\n };\n } // ::pfasst::quadrature\n} // ::pfasst\n\n#include \"pfasst/quadrature/interface_impl.hpp\"\n\n#endif // _PFASST__QUADRATURE__INTERFACE_HPP_\n", "meta": {"hexsha": "04b2f5c4be3e6e664ef8642dd46c4ec3d947a536", "size": 9758, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/pfasst/quadrature/interface.hpp", "max_stars_repo_name": "memmett/PFASST", "max_stars_repo_head_hexsha": "655085fae12b7cce8558484baefdac1bf3d84c2c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 28.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T11:25:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-09T01:09:52.000Z", "max_issues_repo_path": "include/pfasst/quadrature/interface.hpp", "max_issues_repo_name": "memmett/PFASST", "max_issues_repo_head_hexsha": "655085fae12b7cce8558484baefdac1bf3d84c2c", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 81.0, "max_issues_repo_issues_event_min_datetime": "2015-01-05T11:23:15.000Z", "max_issues_repo_issues_event_max_datetime": "2016-12-13T11:03:04.000Z", "max_forks_repo_path": "include/pfasst/quadrature/interface.hpp", "max_forks_repo_name": "memmett/PFASST", "max_forks_repo_head_hexsha": "655085fae12b7cce8558484baefdac1bf3d84c2c", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-02-03T07:59:40.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-25T20:26:08.000Z", "avg_line_length": 32.4186046512, "max_line_length": 103, "alphanum_fraction": 0.5833162533, "num_tokens": 2691, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430478583169, "lm_q2_score": 0.817574471748733, "lm_q1q2_score": 0.6795213383003954}} {"text": "/**\n * MIT License\n *\n * Copyright (c) 2019 Sean Crutchlow\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n/**\n * @file utils_test.cpp\n * @brief Unit tests using Google Test framework to validate class\n * implementation.\n * @author Sean Crutchlow \n * @version 1.0\n */\n\n/// System\n#include \n\n#include \n#include \n#include \n#include \n\n/// Library\n#include \n\n/// Project\n#include \"kalman_filter/utils.h\"\n\nnamespace kalman_filter {\nclass UtilsTest : public ::testing::Test {\n protected:\n double error;\n\n virtual void SetUp() {\n error = 1e-6;\n }\n\n virtual void TearDown() {}\n\n const bool Compare(const coord2D_t& _lhs,\n const coord2D_t& _rhs,\n const double _epsilon) {\n if (std::abs(std::get<0>(_lhs) - std::get<0>(_rhs)) > _epsilon)\n return false;\n if (std::abs(std::get<1>(_lhs) - std::get<1>(_rhs)) > _epsilon)\n return false;\n\n return true;\n }\n\n const bool Compare(const coord3D_t& _lhs,\n const coord3D_t& _rhs,\n const double _epsilon) {\n if (std::abs(std::get<0>(_lhs) - std::get<0>(_rhs)) > _epsilon)\n return false;\n if (std::abs(std::get<1>(_lhs) - std::get<1>(_rhs)) > _epsilon)\n return false;\n if (std::abs(std::get<2>(_lhs) - std::get<2>(_rhs)) > _epsilon)\n return false;\n\n return true;\n }\n};\n\nTEST_F(UtilsTest, Cartesian2Polar) {\n coord2D_t expected(5.0, 0.92729521800161); /// r, theta\n coord2D_t result = Cartesian2Polar(3.0, 4.0); /// x, y\n\n EXPECT_TRUE(Compare(result, expected, error));\n}\n\nTEST_F(UtilsTest, Polar2Cartesian) {\n coord2D_t expected(-2.0807341827357, 4.5464871341284); /// x, y\n coord2D_t result = Polar2Cartesian(5.0, 2.0); /// r, theta\n\n EXPECT_TRUE(Compare(result, expected, error));\n}\n\nTEST_F(UtilsTest, Cartesian2Spherical) {\n coord3D_t expected(7.6426435217142,\n 0.74847023342654,\n 0.90806681890191); /// rho, theta, phi\n coord3D_t result = Cartesian2Spherical(3.2, 4.1, 5.6); /// x, y, z\n\n EXPECT_TRUE(Compare(result, expected, error));\n}\n\nTEST_F(UtilsTest, Cartesian2Cylindrical) {\n coord3D_t expected(5.3413481444295,\n 0.90482708941579,\n 5.7); /// rho, theta, z\n coord3D_t result = Cartesian2Cylindrical(3.3, 4.2, 5.7); /// x, y, z\n\n EXPECT_TRUE(Compare(result, expected, error));\n}\n\nTEST_F(UtilsTest, Spherical2Cartesian) {\n coord3D_t expected(-6.352477916,\n 0.9055237668,\n 3.265892074); /// x, y, z\n coord3D_t result = Spherical2Cartesian(7.2, 3.0, 1.1); /// rho, theta, phi\n\n EXPECT_TRUE(Compare(result, expected, error));\n}\n\nTEST_F(UtilsTest, Cylindrical2Cartesian) {\n coord3D_t expected(-2.802096119,\n 2.566760086,\n 4.8); /// x, y, z\n coord3D_t result = Cylindrical2Cartesian(3.8, 2.4, 4.8); /// r, theta, z\n\n EXPECT_TRUE(Compare(result, expected, error));\n}\n\n\nTEST_F(UtilsTest, Deg2Rad) {\n double expected = 0.021537363; /// radians\n double result = Deg2Rad(1.234); /// degrees\n\n EXPECT_NEAR(result, expected, error);\n}\n\nTEST_F(UtilsTest, Rad2Deg) {\n double expected = 70.702992; /// degrees\n double result = Rad2Deg(1.234); /// radians\n\n EXPECT_NEAR(result, expected, error);\n}\n\nTEST_F(UtilsTest, Feet2Meters) {\n double expected = 0.3761232; /// meters\n double result = Feet2Meters(1.234); /// feet\n\n EXPECT_NEAR(result, expected, error);\n}\n\nTEST_F(UtilsTest, Meters2Feet) {\n double expected = 4.0485564; /// feet\n double result = Meters2Feet(1.234); /// meters\n\n EXPECT_NEAR(result, expected, error);\n}\n\nTEST_F(UtilsTest, CalcRMSE) {\n Eigen::VectorXd e1(2), e2(2), a1(2), a2(2);\n e1 << 0.00001234, 0.12340000;\n e2 << 0.00999900, 0.99990000;\n a1 << 0.00987600, 0.12000000;\n a2 << 0.00001200, 0.98760000;\n\n\n std::vector estimated = {e1, e2};\n std::vector actual = {a1, a2};\n\n Eigen::VectorXd expected(2);\n expected << 0.009925522,\n 0.00902358;\n\n Eigen::VectorXd result = CalcRMSE(estimated, actual); /// meters\n\n EXPECT_TRUE((result - expected).norm() < error);\n}\n} // namespace kalman_filter\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n", "meta": {"hexsha": "bd58014f18b515948d84388c096ad51b2c4dfff3", "size": 5509, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/utils_test.cpp", "max_stars_repo_name": "scr123/kalman_filter", "max_stars_repo_head_hexsha": "e282aef98d0ce0b4ec3e1307b292b35315468ccd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-05-25T18:44:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-25T18:44:17.000Z", "max_issues_repo_path": "test/utils_test.cpp", "max_issues_repo_name": "scr123/kalman_filter", "max_issues_repo_head_hexsha": "e282aef98d0ce0b4ec3e1307b292b35315468ccd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/utils_test.cpp", "max_forks_repo_name": "scr123/kalman_filter", "max_forks_repo_head_hexsha": "e282aef98d0ce0b4ec3e1307b292b35315468ccd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4598930481, "max_line_length": 81, "alphanum_fraction": 0.638772917, "num_tokens": 1603, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085146, "lm_q2_score": 0.8031737869342623, "lm_q1q2_score": 0.6794387909014795}} {"text": "//============================================================================\n//\n// This file is part of the Thea toolkit.\n//\n// This software is distributed under the BSD license, as detailed in the\n// accompanying LICENSE.txt file. Portions are derived from other works:\n// their respective licenses and copyright information are reproduced in\n// LICENSE.txt and/or in the relevant source files.\n//\n// Author: Siddhartha Chaudhuri\n// First version: 2011\n//\n//============================================================================\n\n#ifndef __Thea_Algorithms_Zernike2_hpp__\n#define __Thea_Algorithms_Zernike2_hpp__\n\n// Currently Visual Studio 2010 fails to compile Boost multi_array in Debug mode: https://svn.boost.org/trac/boost/ticket/4874\n#if defined(_MSC_VER) && _MSC_VER >= 1600\n# define THEA_NO_ZERNIKE\n#endif\n\n#ifndef THEA_NO_ZERNIKE\n\n#include \"../Common.hpp\"\n#include \"../IAddressableMatrix.hpp\"\n#include \"../MatVec.hpp\"\n#include \n#include \n\nnamespace Thea {\nnamespace Algorithms {\n\n/**\n * Compute Zernike moments of a 2D distribution, represented as a matrix of density values. The density values may be\n * multidimensional, i.e. the matrix elements may be vectors or colors.\n *\n * This class adapts code for the LightField Descriptor from Ding-Yun Chen et al.,\n * http://3d.csie.ntu.edu.tw/~dynamic/3DRetrieval/index.html .\n */\nclass THEA_API Zernike2\n{\n public:\n /** The matrix type storing N-dimensional moments. Each column is a moment. */\n template using MomentMatrix = Matrix< N, Eigen::Dynamic, std::complex >;\n\n /** %Options for generating Zernike moments. */\n struct THEA_API Options\n {\n int angular_steps; ///< Number of angular steps.\n int radial_steps; ///< Number of radial steps.\n int lut_radius; ///< Radius of Zernike basis function for lookup table.\n\n /** Constructor. */\n Options(int angular_steps_ = 12, int radial_steps_ = 3, int lut_radius_ = 50)\n : angular_steps(angular_steps_), radial_steps(radial_steps_), lut_radius(lut_radius_)\n {}\n\n /** Get the set of default options. */\n static Options const & defaults() { static Options const def; return def; }\n\n }; // struct Options\n\n /** Constructor. */\n Zernike2(Options const & opts_ = Options::defaults());\n\n /** Get the number of moments generated by a call to compute(). */\n intx numMoments() const { return opts.angular_steps * opts.radial_steps; }\n\n /**\n * Compute Zernike moments of a 2D distribution, represented as a matrix of single- or multi-dimensional density values\n * (such as reals, vectors or colors). If the density values have more than one dimension, they should allow array\n * addressing (operator[](intx i)). The template parameter N, inferred from the last argument, must be the same\n * as the number of dimensions of the input.\n *\n * @param distrib The distribution represented as an addressable matrix of density values.\n * @param center_x The x-coordinate (column) of the center of the non-zero region of the distribution, in matrix\n * coordinates.\n * @param center_y The y-coordinate (row) of the center of the non-zero region of the distribution, in matrix coordinates.\n * @param radius The radius of the non-zero region of the distribution, measured from the center, in matrix coordinates. All\n * zero elements can be ignored when specifying this number.\n * @param moments Used to return the Zernike moments, specified in \"angle-major, radius-minor\" order. Each moment is a\n * column of the matrix.\n *\n * @return The number of pixels that have non-zero values and were used to compute the moments.\n */\n template \n intx compute(IAddressableMatrix const & distrib, double center_x, double center_y, double radius,\n MomentMatrix & moments) const;\n\n private:\n /** Generate lookup table for moments. */\n void generateBasisLUT() const;\n\n /**\n * Check if an input element (type T) is zero. This is the generic implementation for multi-channel inputs. The\n * single-channel case is separately specialized.\n */\n template struct IsZero\n {\n template static bool check(T const & t)\n {\n for (int i = 0; i < N; ++i)\n if (t[i] != 0) return false;\n\n return true;\n }\n };\n\n /**\n * Add a scaled increment to a moment. This is the generic implementation for multi-channel inputs. The single-channel case\n * is separately specialized.\n */\n template struct Accum\n {\n template \n static void add(T const & t, std::complex const & x, typename MomentMatrix::ColXpr acc)\n {\n for (intx i = 0; i < acc.size(); ++i)\n {\n acc[i].real(acc[i].real() + static_cast(x.real() * t[i]));\n acc[i].imag(acc[i].imag() - static_cast(x.imag() * t[i]));\n }\n }\n };\n\n typedef boost::multi_array< std::complex, 4 > LUT; ///< Lookup table class.\n\n Options opts; ///< Set of options.\n mutable LUT lut; ///< Coefficient lookup table.\n mutable bool lut_generated; ///< Has the LUT been generated?\n\n}; // class Zernike2\n\n// Specializations for single-channel input.\ntemplate <>\nstruct Zernike2::IsZero<1>\n{\n template static bool check(T const & t)\n {\n return t != 0;\n }\n};\n\ntemplate \nstruct Zernike2::Accum<1, ScalarT>\n{\n template \n static void add(T const & t, std::complex const & x, typename MomentMatrix<1, ScalarT>::ColXpr & acc)\n {\n acc[0].real(acc[0].real() + static_cast(x.real() * t));\n acc[0].imag(acc[0].imag() - static_cast(x.imag() * t));\n }\n};\n\ntemplate \nintx\nZernike2::compute(IAddressableMatrix const & distrib, double center_x, double center_y, double radius,\n Zernike2::MomentMatrix & moments) const\n{\n alwaysAssertM(radius > 0, \"Zernike2: Radius must be greater than zero\");\n\n this->generateBasisLUT();\n\n moments.resize(Eigen::NoChange, numMoments());\n moments.setZero();\n\n intx ncols = distrib.cols();\n intx nrows = distrib.rows();\n\n // Don't go outside the specified radius\n intx min_x = std::max(0L, (intx)std::ceil (center_x - radius));\n intx max_x = std::min(ncols - 1, (intx)std::floor(center_x + radius));\n\n intx min_y = std::max(0L, (intx)std::ceil (center_y - radius));\n intx max_y = std::min(nrows - 1, (intx)std::floor(center_y + radius));\n\n double r_radius = opts.lut_radius / radius;\n\n std::complex x1, x2, x3;\n double dx, dy, tx, ty;\n intx ix, iy;\n intx count = 0;\n for (intx y = min_y; y <= max_y; ++y)\n {\n for (intx x = min_x; x <= max_x; ++x)\n {\n T const & density = distrib.at(y, x);\n if (!IsZero::check(density))\n {\n dx = x - center_x;\n dy = y - center_y;\n tx = dx * r_radius + opts.lut_radius;\n ty = dy * r_radius + opts.lut_radius;\n ix = (intx)tx;\n iy = (intx)ty;\n dx = tx - ix;\n dy = ty - iy;\n\n // Summation of basis function\n for (intx p = 0; p < opts.angular_steps; ++p)\n {\n for (intx r = 0; r < opts.radial_steps; ++r)\n {\n x1 = lut[p][r][ix][iy ] + (lut[p][r][ix + 1][iy ] - lut[p][r][ix][iy ]) * dx;\n x2 = lut[p][r][ix][iy + 1] + (lut[p][r][ix + 1][iy + 1] - lut[p][r][ix][iy + 1]) * dx;\n x3 = x1 + (x2 - x1) * dy;\n\n Accum::add(density, x3, moments.col(p * opts.radial_steps + r));\n }\n }\n\n count++;\n }\n }\n }\n\n if (count > 0)\n moments /= (ScalarT)count;\n\n return count;\n}\n\n} // namespace Algorithms\n} // namespace Thea\n\n#endif // !defined(THEA_NO_ZERNIKE)\n\n#endif\n", "meta": {"hexsha": "4eb706234803b1699b82eef3079cbb20cc4539b4", "size": 7993, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Code/Source/Algorithms/Zernike2.hpp", "max_stars_repo_name": "christinazavou/Thea", "max_stars_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T17:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:34.000Z", "max_issues_repo_path": "Code/Source/Algorithms/Zernike2.hpp", "max_issues_repo_name": "christinazavou/Thea", "max_issues_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-22T16:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-22T16:47:04.000Z", "max_forks_repo_path": "Code/Source/Algorithms/Zernike2.hpp", "max_forks_repo_name": "christinazavou/Thea", "max_forks_repo_head_hexsha": "f68293c4a4f5ddc3abda18e2e0b679bcf5163e93", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-10-17T20:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T09:56:27.000Z", "avg_line_length": 34.752173913, "max_line_length": 128, "alphanum_fraction": 0.6267984486, "num_tokens": 2100, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047847, "lm_q2_score": 0.7577943822145998, "lm_q1q2_score": 0.6791742577127514}} {"text": "//var_model.cpp\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"var_model.h\"\n\nusing namespace std;\nusing namespace boost::accumulators;\n\n//Define container for muliple criteria sorting\nstruct Container{\n double _return; //returns\n double _prob; //weighted prob,\n };\n\nbool sortByReturn(const Container &lhs, const Container &rhs) { return lhs._return < rhs._return; }\n\nVaR::VaR(double _alpha):alpha(_alpha){}\n\n//copy constructor implementation\nVaR::VaR(const VaR& other): \n\talpha(other.alpha)\n{}\n\ndouble VaR::getAlpha() const {return alpha;}\n\nvoid VaR::setAlpha(double _alpha) {alpha = _alpha;}\n\nParametricVaR::ParametricVaR(double _alpha, bool _logNormal):VaR(_alpha),logNormal(_logNormal)\n{}\n\n//copy constructor implementation\nParametricVaR::ParametricVaR(const ParametricVaR& other):\n\tVaR(other),logNormal(other.logNormal) \n{}\n\n\ndouble ParametricVaR::NormalVaR(double u, double sigma) const{\n\n\t\tdouble za;\n\n\t\tza = boost::math::quantile(snd, getAlpha());\n\n\t\treturn (u + sigma * za);\n}\n\ndouble ParametricVaR::LogNormalVaR(double u, double sigma) const {\n\n\t\tdouble za;\n\n\t\tza = boost::math::quantile(snd, getAlpha());\n\n\t\treturn -(1. - exp(u + sigma * za));\n}\n\nRiskMetricsVaR::RiskMetricsVaR(double _alpha, double _lambda, bool _logNormal)\n:ParametricVaR(_alpha, _logNormal), lambda(_lambda){}\n\n//copy constructor implementation\nRiskMetricsVaR::RiskMetricsVaR(const RiskMetricsVaR& other):\n\tParametricVaR(other), lambda(other.lambda)\n{}\n\ndouble RiskMetricsVaR::operator()(double _meanReturn,\n double _sigmatminus1, double _returnt) const{\n\n double sigmat = sqrt(lambda * _sigmatminus1 * _sigmatminus1 + (1. - lambda) * _returnt * _returnt);\n\n\tdouble tmp = logNormal ? LogNormalVaR(_meanReturn, sigmat) : NormalVaR(_meanReturn, sigmat);\n\n\treturn tmp >= 0 ? 0. : tmp;\n\n}\n\ndouble RiskMetricsVaR::operator()(double _meanReturn, const Vec& returns) const\n{\n\tdouble sigmaT = 0.;\n size_t T(returns.size());\n\n for(size_t i = 1; i < T;++i){\n sigmaT = sqrt(lambda * sigmaT * sigmaT + (1. - lambda) * returns[i] * returns[i]);\n }\n\n\tdouble tmp = logNormal ? LogNormalVaR(_meanReturn, sigmaT) : NormalVaR(_meanReturn, sigmaT);\n\n\treturn tmp >= 0 ? 0. : tmp;\n}\n\ndouble RiskMetricsVaR::operator()(const Vec& returns) const\n{\n double sigmaT = 0.;\n double _meanReturn =0;\n size_t T(returns.size());\n\n for(size_t i = 1; i < T;++i){\n sigmaT = sqrt(lambda * sigmaT * sigmaT + (1. - lambda) * returns[i] * returns[i]);\n _meanReturn += returns[i];\n }\n\n _meanReturn =_meanReturn/(T-1);\n\n double tmp = logNormal ? LogNormalVaR(_meanReturn, sigmaT) : NormalVaR(_meanReturn, sigmaT);\n\n\treturn tmp >= 0 ? 0. : tmp;\n}\n\nGarchVaR::GarchVaR(double _alpha, double _a, double _b, double _c,bool _logRtns)\n:ParametricVaR(_alpha, _logRtns), a(_a), b(_b), c(_c){}\n\n//copy constructor implementation\nGarchVaR::GarchVaR(const GarchVaR& other):\t\n\tParametricVaR(other), a(other.a), b(other.b),c(other.c)\n{}\n\ndouble GarchVaR::operator()(double _meanReturn,\n double _sigmatminus1, double _returntminus1) const{\n\n double sigmat = sqrt(a + c * _sigmatminus1 * _sigmatminus1 + b * _returntminus1 * _returntminus1);\n\n\tdouble tmp = logNormal ? LogNormalVaR(_meanReturn, sigmat) : NormalVaR(_meanReturn, sigmat);\n\n\treturn tmp >= 0 ? 0. : tmp;\n\n}\n\ndouble GarchVaR::operator()(double _meanReturn, const Vec& returns) const\n{\n\tdouble sigmaT = 0.;\n\n for(size_t i = 0; i < returns.size();++i)\n sigmaT += pow(c,static_cast(i)) * returns[i] * returns[i];\n\n sigmaT *= b;\n sigmaT += a/(1.-c);\n\n\tdouble tmp = logNormal ? LogNormalVaR(_meanReturn, sqrt(sigmaT)) : NormalVaR(_meanReturn, sqrt(sigmaT));\n\n\treturn tmp >= 0 ? 0. : tmp;\n}\n\ndouble GarchVaR::operator()(const Vec& returns) const\n{\n double sigmaT = 0.;\n double _meanReturn =0;\n size_t T(returns.size());\n\n for(size_t i = 0; i < T;++i){\n sigmaT += pow(c,static_cast(i)) * returns[i] * returns[i];\n _meanReturn += returns[i];\n }\n\n sigmaT *= b;\n sigmaT += a/(1.-c);\n _meanReturn =_meanReturn/(T-1);\n\n\tdouble tmp = logNormal ? LogNormalVaR(_meanReturn, sigmaT) : NormalVaR(_meanReturn, sigmaT);\n\n\treturn tmp >= 0 ? 0 : tmp;\n}\n\nNoneParametricVaR::NoneParametricVaR(double _alpha):VaR(_alpha){}\n\nNoneParametricVaR::NoneParametricVaR(const NoneParametricVaR& other)\n:VaR(other)\n{}\n\nHistoricalVaR::HistoricalVaR(double _alpha, double _lambda, WeightingScheme _ws)\n:NoneParametricVaR(_alpha), lambda(_lambda), ws(_ws){}\n\n//copy constructor implementation\nHistoricalVaR::HistoricalVaR(const HistoricalVaR& other):\t\n\tNoneParametricVaR(other), lambda(other.lambda), ws(other.ws)\n{}\n\ndouble HistoricalVaR::operator()(double _sigmatminus1,\n const Vec& returns) const\n{\n \tdouble T = returns.size();\n\n\tdouble alpha(getAlpha());\n\n\tunsigned int c(alpha * T);\n\tc == 0 ? c : c-= 1;\n\n\tdouble tmp;\n\n\tint input(ws);\n\n\tstd::vector _returns(returns);\n\n\tswitch(input){\n\n\tcase 0:\n {\n // sort returns find cth arg - Histogram method\n std::sort(_returns.begin(), _returns.end());\n\n tmp = _returns[c];\n }\n\n break;\n\n\tcase 1:\n {\n std::vector prob(T);\n\n double a = (1. - lambda)/(1. - pow(lambda, T));\n\n for(size_t i = 0; i < T; ++i){\n prob[i]._return = _returns[T -1 - i];\n prob[i]._prob = a * pow(lambda, i);\n }\n\n // Sort Container by return function\n std::sort(prob.begin(), prob.end(),sortByReturn);\n\n double sumProb(0);\n\n for(size_t i = 0; i < T; ++i){\n sumProb += prob[i]._prob;\n\n if(sumProb >= alpha){\n tmp = prob[i]._return;\n break;\n }\n }\n\n }\n\n\n break;\n\n case 2:\n\n {\n std::vector sigma;\n\n sigma.push_back(_sigmatminus1 * _sigmatminus1); \n\n for(size_t i = 1; i < T;++i)\n sigma.push_back(lambda * sigma[i - 1] + (1. - lambda) * returns[i - 1] * returns[i - 1]);\n\n double sigmaT(sigma.back()); \n\n std::vector _wgthRtns;\n\n for(size_t i = 0; i < T; ++i){\n\n if(sigma[i] <= 0) _wgthRtns.push_back(_returns[i]);\n else _wgthRtns.push_back(sqrt(sigmaT / sigma[i]) * _returns[i] );\n }\n\n\n // sort returns find cth arg - Histogram method\n std::sort(_wgthRtns.begin(), _wgthRtns.end());\n\n tmp = _wgthRtns[c];\n }\n\n break;\n\n default:\n break;\n\n\t}\n\n\treturn tmp >= 0 ? 0. : tmp;\n}\n\nExtremeValueVaR::ExtremeValueVaR(double _alpha):VaR(_alpha){}\n\n//copy constructor implementation\nExtremeValueVaR::ExtremeValueVaR(const ExtremeValueVaR& other): \n\tVaR(other)\n{}\n\nPoTVaR::PoTVaR(double _u,double _beta, double _xi,double _alpha)\n: ExtremeValueVaR(_alpha),xi(_xi),beta(_beta),u(_u){\n\n}\n\n//copy constructor implementation\nPoTVaR::PoTVaR(const PoTVaR& other): \n\tExtremeValueVaR(other), xi(other.xi), beta(other.beta), u(other.u)\n{}\n\ndouble PoTVaR::operator()(const double& ratio) const\n{\n\tdouble a = 1./ratio * getAlpha();\n\n\treturn -(u + beta * (pow(a,- xi) - 1.)/ xi );\n}\n\ndouble PoTVaR::expectedShortfall(const double& ratio) const\n{\n\treturn ((this->operator()(ratio) - (beta - xi * u)))/(1. - xi);\n\n}\n\ndouble PoTVaR::expectedShortfall(const Vec& returns) const{\n\n\tdouble ratio(0.);\n\n\tfor(size_t i =0;i < returns.size();++i){\n if(returns[i] < 0)\n if(-returns[i] > u) ratio +=1;\n\t}\n\n\tratio /= returns.size();\n if(ratio < .05) ratio = .05;\n\n\n\treturn this->expectedShortfall(ratio);\n}\n\ndouble PoTVaR::operator()(const Vec& returns) const{\n\n\tdouble ratio(0.);\n\n\tfor(size_t i =0;i < returns.size();++i){\n if(returns[i] < 0)\n if(-returns[i] > u) ratio +=1;\n\t}\n\n\tratio /= returns.size();\n if(ratio < .05) ratio = .05;\n\n\treturn this->operator()(ratio);\n}\n\n\n\n", "meta": {"hexsha": "b7b90050c0d16e2302d4314fcc73904d120fe31a", "size": 8137, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/var_model.cpp", "max_stars_repo_name": "calvin456/VaR", "max_stars_repo_head_hexsha": "ef70faf930b0dcae1725bca6cc9f205c3099324d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T08:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-23T04:26:16.000Z", "max_issues_repo_path": "src/var_model.cpp", "max_issues_repo_name": "calvin456/VaR", "max_issues_repo_head_hexsha": "ef70faf930b0dcae1725bca6cc9f205c3099324d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/var_model.cpp", "max_forks_repo_name": "calvin456/VaR", "max_forks_repo_head_hexsha": "ef70faf930b0dcae1725bca6cc9f205c3099324d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-19T18:21:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T04:26:17.000Z", "avg_line_length": 24.073964497, "max_line_length": 105, "alphanum_fraction": 0.6211134325, "num_tokens": 2308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624558, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.679174248610329}} {"text": "//\n// MathUtil.cpp\n// edgeRuntime\n//\n// Created by Abdelrahaman Aly on 04/02/14.\n//\n//\n\n//Library Headers\n#include \n#include \n\n//Custom Headers\n#include \"List.h\"\n#include \"MathUtil.h\"\nusing namespace NTL;\nnamespace Utilities\n{\n //less significative bit on the left always most significative bit on the right always\n int * MathUtil::obtainBits(long number, int size)\n {\n int * bits= new int[size];\n for (int i=0; i>=1;\n\n }\n return bits;\n };\n \n //Calculates the lagrangian interpolation. Currently optimized for 3 players\n long MathUtil::lagrangianInterpolation( long * values, int size)\n {\n //TODO: build the lagrangian interpolation\n\n ZZ_p result;\n result=2*conv(values[0]) -conv(values[1]);\n long resultLong =conv(result);\n return resultLong;\n };\n \n //calculates the complement 2 adding first aone and then decomposing into bits\n int* MathUtil::obtainComplementTwo(long value, int size)\n {\n value=~value;\n value++;\n return MathUtil::obtainBits(value, size);\n };\n \n //obtains the additive of 2 mod values\n long MathUtil::additionMod(long a, long b)\n {\n ZZ_p ap= conv(a);\n ZZ_p bp= conv(b);\n return conv(a+b);\n };\n \n //Obteins the multiplicative of 2 mod values\n long MathUtil::multiplyMod(long a, long b)\n {\n ZZ_p ap= conv(a);\n ZZ_p bp= conv(b);\n return conv(a*b);\n };\n \n //An specification on generic multiplier of polynomials\n ZZ_pX MathUtil::multiplyLagrangePolynomials(vec_ZZ_p x_v, ZZ_p x_j)\n {\n\n ZZ_p x_d= x_j-x_v[0];\n ZZ_p a= 1/x_d;\n ZZ_pX p;\n p.SetLength(2);\n p[0]= (-1)*x_v[0]*a;\n p[1]= a;\n \n for (int k=1; k< x_v.length(); k++)\n {\n ZZ_p x_k =x_v[k];\n x_d= x_j-x_k;\n a= 1/x_d;\n \n ZZ_pX auxP;\n auxP.SetLength(2);\n auxP[0]= (-1)*x_k*a;\n auxP[1]=a;\n \n p=p*auxP;\n }\n return p;\n };\n \n //Interpolations:\n ZZ_pX MathUtil::multiplyLagrangePolynomials(int x_s, int x_k,int x_j)\n {\n vec_ZZ_p values;\n values.SetLength((x_k+1)-x_s -1);\n int j=0;\n for (int i = x_s; i<=x_k; i++)\n {\n if (i!= x_j) {\n values[j]= conv(i);\n j++;\n }\n\n }\n return MathUtil::multiplyLagrangePolynomials(values, conv(x_j));\n };\n \n int MathUtil::pow2roundup (int value)\n {\n int x=value;\n if (x < 0)\n return 0;\n --x;\n x |= x >> 1;\n x |= x >> 2;\n x |= x >> 4;\n x |= x >> 8;\n x |= x >> 16;\n return x+1;\n }\n}\n", "meta": {"hexsha": "a60e3257d7026de63c741eb96507034c93853675", "size": 3087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "edgeRuntime/MathUtil.cpp", "max_stars_repo_name": "abdelrahamanaly/mpcToolkit", "max_stars_repo_head_hexsha": "fe656355cef77f9c40284339ba6d5e03dea03467", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-03-05T16:11:55.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T15:08:05.000Z", "max_issues_repo_path": "edgeRuntime/MathUtil.cpp", "max_issues_repo_name": "abdelrahamanaly/mpcToolkit", "max_issues_repo_head_hexsha": "fe656355cef77f9c40284339ba6d5e03dea03467", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "edgeRuntime/MathUtil.cpp", "max_forks_repo_name": "abdelrahamanaly/mpcToolkit", "max_forks_repo_head_hexsha": "fe656355cef77f9c40284339ba6d5e03dea03467", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-07T03:22:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-07T03:22:28.000Z", "avg_line_length": 22.8666666667, "max_line_length": 90, "alphanum_fraction": 0.4914156139, "num_tokens": 881, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6791742325054566}} {"text": "#include \n#include \n#include \n\n#include \"eigen-qp.hpp\"\n\nusing namespace std;\nusing namespace Eigen;\nusing namespace EigenQP;\n/*\n * min 0.5 x.Q.x + c.x\n *\n * Ax <= b\n * Ex = d\n *\n * See: http://etd.dtu.dk/thesis/220437/ep08_19.pdf\n */\n// #define NV_FIXED 8\n// #define NC_FIXED 16\n// #define NE_FIXED 3\n\n#define PROB_VARS 8\n#define PROB_INEQ 16\n#define PROB_EQ 3\n\n#define N_TEST (1<<16)\n\ntemplate\nvoid test()\n{\n\n typedef Eigen::Matrix MatrixXs;\n typedef Eigen::Matrix VectorXs;\n\n // Make a random problem\n int num_vars = NV_FIXED;\n int num_ineq = NC_FIXED;\n int num_eq = NE_FIXED;\n\n // Random matrices\n MatrixXs Q = MatrixXs::Random(num_vars,num_vars);\n Q *= Q.adjoint()/sqrt(num_vars); // Make it pos def\n\n VectorXs c = VectorXs::Random(num_vars);\n\n MatrixXs A = MatrixXs::Random(num_ineq,num_vars);\n VectorXs b = VectorXs::Random(num_ineq);\n\n MatrixXs E = MatrixXs::Random(num_eq,num_vars);\n VectorXs f = VectorXs::Random(num_eq);\n\n VectorXs x_unc;\n // Solve unconstrainted system\n cout << \"Unconstrained...\" << endl;\n {\n boost::timer::auto_cpu_timer t;\n for (int ii=0; ii < N_TEST; ii++)\n x_unc = -Q.ldlt().solve(c);\n }\n VectorXs x(num_vars);\n // Generate inequality constraints\n b.array() = (A*x_unc).array() - 0.15;\n // Inequality constrained problem\n cout << \"quadprog, dynamic code\" << endl;\n {\n boost::timer::auto_cpu_timer t;\n for (int ii=0; ii < N_TEST; ii++)\n quadprog(Q,c,A,b,x);\n }\n cout << \" error: \" << (x - x_unc).norm() << endl;\n {\n QPIneqSolver *solver;\n cout <<\"QPIneqSolver, dynamic, obj creation\" << endl;\n {\n boost::timer::auto_cpu_timer t;\n for (int ii=0; ii < N_TEST; ii++)\n {\n solver = new QPIneqSolver(num_vars,num_ineq);\n solver->solve(Q,c,A,b,x);\n }\n }\n cout << \" error: \" << (x - x_unc).norm() << endl;\n cout << \"QPIneqSolver, dynamic, object reuse\" << endl;\n {\n boost::timer::auto_cpu_timer t;\n for (int ii=0; ii < N_TEST; ii++)\n solver->solve(Q,c,A,b,x);\n }\n cout << \" error: \" << (x - x_unc).norm() << endl;\n }\n\n // Fixed size\n Matrix Q_fixed(Q);\n Matrix c_fixed(c);\n Matrix A_fixed(A);\n Matrix b_fixed(b);\n\n // Q_fixed.setRandom();\n // c_fixed.setRandom();\n // A_fixed.setRandom();\n\n x_unc = -Q_fixed.ldlt().solve(c_fixed);\n\n b_fixed.array() = (A_fixed*x_unc).array() - 0.12;\n\n Matrix x_fixed;\n cout << \"quadprog, fixed code\" << endl;\n {\n boost::timer::auto_cpu_timer t;\n for (int ii=0; ii < N_TEST; ii++)\n quadprog(Q_fixed,c_fixed,A_fixed,b_fixed,x_fixed);\n }\n cout << \" error: \" << (x_fixed - x_unc).norm() << endl;\n {\n QPIneqSolver *solver;\n cout << \"QPIneqSolver, fixed\" << endl;\n {\n boost::timer::auto_cpu_timer t;\n for (int ii=0; ii < N_TEST; ii++)\n {\n solver = new QPIneqSolver(num_vars,num_ineq);\n solver->solve(Q_fixed,c_fixed,A_fixed,b_fixed,x_fixed);\n }\n }\n cout << \" error: \" << (x_fixed - x_unc).norm() << endl;\n cout << \"QPIneqSolver, fixed, object reuse\" << endl;\n {\n boost::timer::auto_cpu_timer t;\n for (int ii=0; ii < N_TEST; ii++)\n solver->solve(Q_fixed,c_fixed,A_fixed,b_fixed,x_fixed); \n }\n cout << \" error: \" << (x_fixed - x_unc).norm() << endl;\n }\n\n cout << \"QPEqSolver, equality constraints, dynamic\" << endl;\n {\n QPEqSolver solver(num_vars,num_eq);\n {\n boost::timer::auto_cpu_timer t;\n for (int ii=0; ii < N_TEST; ii++)\n solver.solve(Q,c,E,f,x);\n }\n }\n\n /*\n // known to be broken\n cout << \"quadprog, ineq/eq constraints, dynamic\" << endl;\n {\n //b = A*x - 0.12;\n QPGenSolver solver(num_vars,num_ineq,num_eq);\n {\n boost::timer::auto_cpu_timer t;\n for (int ii=0; ii < N_TEST; ii++)\n solver.solve(Q,c,A,b,E,f,x);\n }\n }\n */\n}\n\nint main(int argc, char ** argv)\n{\n srand((unsigned int) time(0));\n cout << \"TESTING DOUBLE\" << endl;\n test();\n cout << \"TESTING FLOAT\" << endl;\n test();\n return 0;\n}", "meta": {"hexsha": "4a2a9c9d19ebbd9a16fbd6cbaee534040dd02402", "size": 4823, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "driver.cpp", "max_stars_repo_name": "jarredbarber/eigen-QP", "max_stars_repo_head_hexsha": "c319da488208b10be4f82f6887dea94e802766b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-09-23T20:00:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T16:40:24.000Z", "max_issues_repo_path": "driver.cpp", "max_issues_repo_name": "jarredbarber/eigen-QP", "max_issues_repo_head_hexsha": "c319da488208b10be4f82f6887dea94e802766b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T05:49:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-13T01:47:12.000Z", "max_forks_repo_path": "driver.cpp", "max_forks_repo_name": "jarredbarber/eigen-QP", "max_forks_repo_head_hexsha": "c319da488208b10be4f82f6887dea94e802766b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-02-07T15:55:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T06:43:00.000Z", "avg_line_length": 28.7083333333, "max_line_length": 87, "alphanum_fraction": 0.5535973461, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972784807408, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6790596872907131}} {"text": "/**\n * \\file\n *\n * \\author Nicholas J. Curtis\n * \\date 04/29/2016\n *\n * \\brief Defines an interface for boost's runge_kutta_fehlberg78 solver\n *\n*/\n\n#ifndef RK78_TYPEDEFS_HPP\n#define RK78_TYPEDEFS_HPP\n\n#include \nusing namespace boost::numeric::odeint;\n\n//our code\nextern \"C\" {\n\t#include \"dydt.h\"\n\t#include \"header.h\"\n\t#include \"solver_options.h\"\n}\n\n#ifdef GENERATE_DOCS\nnamespace rk78 {\n#endif\n\n//! state vector\ntypedef std::vector< double > state_type;\n\n//! solver type\ntypedef runge_kutta_fehlberg78< state_type , double > stepper;\n\n//! controller type\ntypedef controlled_runge_kutta< stepper > controller;\n\n//stiffness measure for project\n//do a binary search to find the maximum available stepsize\n#ifdef LOG_OUTPUT\n//#define STIFFNESS_MEASURE\n#endif\n#ifdef STIFFNESS_MEASURE\n#include \n#endif\n\n/**\n \\brief A wrapper class to evaluate the rhs function y' = f(y)\n stores the state variable, and provides to dydt\n*/\nclass rhs_eval {\n\tdouble m_statevar;\npublic:\n\trhs_eval() {\n\t\tthis->m_statevar = -1;\n\t}\n\n\tvoid set_state_var(const double state_var)\n\t{\n\t\tthis->m_statevar = state_var;\n\t}\n\n\t//wrapper for the pyJac RHS fn\n\tvoid operator() (const state_type &y , state_type &fy , const double t) const\n\t{\n\t\tdydt(t, this->m_statevar, &y[0], &fy[0]);\n\t}\n};\n\n#ifdef GENERATE_DOCS\n}\n#endif\n\n#endif", "meta": {"hexsha": "b322b934733c90df80e5159e83832b6602db05a6", "size": 1377, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "rk78/rk78_typedefs.hpp", "max_stars_repo_name": "arghdos/accelerInt", "max_stars_repo_head_hexsha": "d66b615d61438be3caa76fa178fb8a913bed77c1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T12:40:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T12:35:45.000Z", "max_issues_repo_path": "rk78/rk78_typedefs.hpp", "max_issues_repo_name": "arghdos/accelerInt", "max_issues_repo_head_hexsha": "d66b615d61438be3caa76fa178fb8a913bed77c1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-03-02T19:15:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-15T10:50:14.000Z", "max_forks_repo_path": "rk78/rk78_typedefs.hpp", "max_forks_repo_name": "arghdos/accelerInt", "max_forks_repo_head_hexsha": "d66b615d61438be3caa76fa178fb8a913bed77c1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2017-06-01T01:38:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T13:57:17.000Z", "avg_line_length": 18.8630136986, "max_line_length": 78, "alphanum_fraction": 0.7269426289, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6790596794343284}} {"text": "#include \"NuiMatrixUtilities.h\"\n\n#include \n\nnamespace NuiMatrixUtilities\n{\n\tVector3f rodrigues2(const Eigen::Matrix3f& matrix)\n\t{\n\t\tEigen::JacobiSVD svd(matrix, Eigen::ComputeFullV | Eigen::ComputeFullU); \n\t\tEigen::Matrix3f R = svd.matrixU() * svd.matrixV().transpose();\n\n\t\tdouble rx = R(2, 1) - R(1, 2);\n\t\tdouble ry = R(0, 2) - R(2, 0);\n\t\tdouble rz = R(1, 0) - R(0, 1);\n\n\t\tdouble s = sqrt((rx*rx + ry*ry + rz*rz)*0.25);\n\t\tdouble c = (R.trace() - 1) * 0.5;\n\t\tc = c > 1. ? 1. : c < -1. ? -1. : c;\n\n\t\tdouble theta = acos(c);\n\n\t\tif( s < 1e-5 )\n\t\t{\n\t\t\tdouble t;\n\n\t\t\tif( c > 0 )\n\t\t\t\trx = ry = rz = 0;\n\t\t\telse\n\t\t\t{\n\t\t\t\tt = (R(0, 0) + 1)*0.5;\n\t\t\t\trx = sqrt( std::max(t, 0.0) );\n\t\t\t\tt = (R(1, 1) + 1)*0.5;\n\t\t\t\try = sqrt( std::max(t, 0.0) ) * (R(0, 1) < 0 ? -1.0 : 1.0);\n\t\t\t\tt = (R(2, 2) + 1)*0.5;\n\t\t\t\trz = sqrt( std::max(t, 0.0) ) * (R(0, 2) < 0 ? -1.0 : 1.0);\n\n\t\t\t\tif( fabs(rx) < fabs(ry) && fabs(rx) < fabs(rz) && (R(1, 2) > 0) != (ry*rz > 0) )\n\t\t\t\t\trz = -rz;\n\t\t\t\ttheta /= sqrt(rx*rx + ry*ry + rz*rz);\n\t\t\t\trx *= theta;\n\t\t\t\try *= theta;\n\t\t\t\trz *= theta;\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdouble vth = 1/(2*s);\n\t\t\tvth *= theta;\n\t\t\trx *= vth; ry *= vth; rz *= vth;\n\t\t}\n\t\treturn Eigen::Vector3d(rx, ry, rz).cast();\n\t}\n}", "meta": {"hexsha": "7f9ae854f49403b6b34e6be505d3b25435fc5d81", "size": 1241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Foundation/NuiMatrixUtilities.cpp", "max_stars_repo_name": "hustztz/NatureUserInterfaceStudio", "max_stars_repo_head_hexsha": "3cdac6b6ee850c5c8470fa5f1554c7447be0d8af", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-07-14T13:04:35.000Z", "max_stars_repo_stars_event_max_datetime": "2017-04-01T09:58:27.000Z", "max_issues_repo_path": "src/Foundation/NuiMatrixUtilities.cpp", "max_issues_repo_name": "hustztz/NatureUserInterfaceStudio", "max_issues_repo_head_hexsha": "3cdac6b6ee850c5c8470fa5f1554c7447be0d8af", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Foundation/NuiMatrixUtilities.cpp", "max_forks_repo_name": "hustztz/NatureUserInterfaceStudio", "max_forks_repo_head_hexsha": "3cdac6b6ee850c5c8470fa5f1554c7447be0d8af", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-11-21T15:33:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-21T15:33:35.000Z", "avg_line_length": 23.4150943396, "max_line_length": 95, "alphanum_fraction": 0.4834810637, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026505426832, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6789639041621292}} {"text": "#ifndef EXPSUM_LSQR_HPP\n#define EXPSUM_LSQR_HPP\n\n#include \n\nnamespace expsum\n{\n///\n/// lsqr\n///\n/// `lsqr` solves a least squares problem\n///\n/// ``` math\n/// \\min \\| A\\bm{x} - \\bm{b} \\|_{2},\n/// ```\n///\n/// where ``$A \\in \\mathcal{C}^{m \\times n}, \\, \\bm{b} \\in \\mathcal{C}^{n} $``\n/// with ``$m \\geq n$``.\n///\n/// @param[in] matvec A function object that compute matrix-vector product\n/// `y += A * x`\n/// @param[in] matvec_trans A function object that compute matrix-vector\n/// product `y += A.t() * x`\n/// @param[inout] u A vector of length m. On input the right hand side vector\n/// ``$b$``, on exit, `u` is overwritten.\n/// @param[out] x A vector of length n. On input and initial guess of solution,\n/// on exit, the computed solution.\n/// @param[in] precond_solve Functor for applying preconditioner to a vector.\n/// @param[out] work A matrix of size ``$n \\times 3$`` used as workspace.\n/// @param[inout] iterations On input the max number of iteration, on exit the\n/// number of performed iterations.\n/// @param[inout] tol_error On input the tolerance error, on exit as estimation\n/// of the relative error.\n///\n\ntemplate \nvoid lsqr(MatVec matvec, MatVecTrans matvec_trans, VectorU& u, VectorX& x,\n const Preconditioner& apply_preconditioner, MatrixWork& work,\n arma::uword& iterations, typename VectorX::pod_type& tol_error)\n{\n using value_type = typename VectorX::elem_type;\n using real_type = typename VectorX::pod_type;\n using size_type = arma::uword;\n\n using std::sqrt;\n using std::real;\n using std::abs;\n using std::norm;\n\n const real_type atol = tol_error;\n const real_type btol = tol_error;\n\n auto p = work.col(0);\n auto v = work.col(1);\n auto w = work.col(2);\n //\n // --- Initialization\n //\n x.zeros();\n real_type alpha = real_type();\n real_type beta = arma::norm(u);\n if (beta > real_type())\n {\n u *= real_type(1) / beta; // normalize\n matvec_trans(u, value_type(), p); // p <-- A.t() * u;\n apply_preconditioner(p, v); // v <-- M.inv() * p\n alpha = sqrt(real(arma::cdot(v, p)));\n if (alpha > real_type())\n {\n v *= real_type(1) / alpha; // normalize\n w = v;\n }\n }\n\n // Estimation of the norm of `A.t() * r`\n real_type norm_Atr = alpha * beta;\n if (norm_Atr == real_type())\n {\n // x = 0 is the exact solution\n return;\n }\n\n real_type rhobar = alpha;\n real_type phibar = beta;\n\n // Estimations of the Frobenius norm of matrix A\n real_type norm_A = real_type();\n // Norm of r.h.s. vector b\n real_type norm_b = beta;\n // Estimation of the norm of residual vector `r = b - A * x`.\n real_type norm_r = beta;\n // Estimation of the norm of solution vector x.\n real_type norm_x = real_type();\n\n real_type cs2 = real_type(-1);\n real_type sn2 = real_type();\n real_type z = real_type();\n real_type norm_bb = real_type();\n real_type norm_xx = real_type();\n\n size_type iter = 0;\n while (++iter <= iterations)\n {\n //\n // --- Bidiagonalization\n //\n // Perform the next step of the bidiagonalization with M-weighted inner\n // product. `beta, u, alpha, v`. These satisfy the relations\n //\n // ``` math\n // \\beta_{i+1} \\bm{u}_{i+1}\n // &= A \\bm{v}_{i} - \\alpha_{i} \\bm{u}_{i},\n // \\alpha_{i+1} \\bm{v}_{i+1}\n // &= M^{-1} A^{H} \\bm{u}_{i+1} - \\beta_{i+1} \\bm{v}_{i},\n // \\alpha_{i+1} &= (\\bm{v}_{i+1}^{H} M \\bm{v}_{i+1}^{})^{1/2}\n // ```\n //\n matvec(v, -alpha, u); // u <-- A * v - alpha * u\n beta = arma::norm(u);\n norm_bb += norm(alpha) + norm(beta);\n\n if (beta > real_type())\n {\n u *= real_type(1) / beta;\n matvec_trans(u, -beta, p); // p <-- A.t() * u - beta * p\n apply_preconditioner(p, v); // v <-- M.inv() * p\n alpha = sqrt(real(arma::cdot(v, p)));\n if (alpha > real_type())\n {\n v *= real_type(1) / alpha;\n }\n }\n //\n // --- Orthogonal transformation\n //\n // Construct and apply next orthogonal transformation (plane rotation)\n // to eliminate the subdiagonal element (beta) of the lower-bidiagonal\n // matrix, giving an upper-bidiagonal matrix. The explicit form of the\n // transformation is given as\n //\n // [cs sn][rhobar 0 phibar] [rho theta phi ]\n // [sn -cs][ beta alpha 0] = [ 0 rhobar' phibar']\n //\n real_type rho = sqrt(norm(rhobar) + norm(beta));\n real_type cs = rhobar / rho;\n real_type sn = beta / rho;\n real_type theta = sn * alpha;\n rhobar = -cs * alpha;\n real_type phi = cs * phibar;\n phibar *= sn;\n //\n // Update vectors\n //\n // norm_dd += (w / rho).squaredNorm();\n x += (phi / rho) * w;\n w = v - (theta / rho) * w;\n //\n // Estimate norm of x using the result of plane rotation\n //\n real_type delta = sn2 * rho;\n real_type gamma_bar = -cs2 * rho;\n real_type rhs = phi - delta * z;\n real_type zbar = rhs / gamma_bar;\n norm_x = sqrt(norm_xx + norm(zbar));\n real_type gamma = sqrt(norm(gamma_bar) + norm(theta));\n cs2 = gamma_bar / gamma;\n sn2 = theta / gamma;\n z = rhs / gamma;\n norm_xx += norm(z);\n\n //\n // Test for convergence.\n //\n norm_A = sqrt(norm_bb);\n // cond_A = norm_A * sqrt(norm_dd);\n norm_r = phibar;\n norm_Atr = phibar * alpha * abs(cs);\n //\n // Stop iteration if\n //\n // |A^{T} \\bm{r}|_{F} / |A^{T}|_F |\\bm{r}| < tol\n //\n // if (norm_Atr <= norm_A * norm_r * tol_error)\n // {\n // break;\n // }\n if (norm_r <= btol * norm_b + atol * norm_A * norm_x)\n {\n break;\n }\n }\n\n tol_error = norm_r;\n iterations = iter;\n}\n\n} // namespace expsum\n\n#endif /* EXPSUM_LSQR_HPP */\n", "meta": {"hexsha": "3e42c82a1591653d47997f5c0b54e016b97ac426", "size": 6414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/fitting/lsqr.hpp", "max_stars_repo_name": "hide-ikeno/expsum", "max_stars_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/expsum/fitting/lsqr.hpp", "max_issues_repo_name": "hide-ikeno/expsum", "max_issues_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/expsum/fitting/lsqr.hpp", "max_forks_repo_name": "hide-ikeno/expsum", "max_forks_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9104477612, "max_line_length": 80, "alphanum_fraction": 0.5219831618, "num_tokens": 1801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070060380482, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6789170972368549}} {"text": "#include \n#include \n#include \n#include \ntypedef boost::multiprecision::cpp_dec_float_50 decfloat;\n\nint main()\n{\n const decfloat ln_two = boost::math::constants::ln_two();\n decfloat numerator = 1, denominator = ln_two;\n\n for(int n = 1; n <= 17; n++) {\n decfloat h = (numerator *= n) / (denominator *= ln_two) / 2;\n decfloat tenths_dig = floor((h - floor(h)) * 10);\n std::cout << \"h(\" << std::setw(2) << n << \") = \" << std::setw(25) << std::fixed << h <<\n (tenths_dig == 0 || tenths_dig == 9 ? \" is \" : \" is NOT \") << \"an almost-integer.\\n\";\n }\n}\n", "meta": {"hexsha": "23a4a0b2955b84855fbc586652352b268b51df68", "size": 694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/hickerson-series-of-almost-integers.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "lang/C++/hickerson-series-of-almost-integers.cpp", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/C++/hickerson-series-of-almost-integers.cpp", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 36.5263157895, "max_line_length": 97, "alphanum_fraction": 0.5936599424, "num_tokens": 208, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9489172615983309, "lm_q2_score": 0.7154239836484144, "lm_q1q2_score": 0.6788781674454225}} {"text": "/**\n * @file uniformcubicspline.cc\n * @brief NPDE exam problem summer 2019 \"CLEmpiricFlux\" code\n * @author Oliver Rietmann\n * @date 18.07.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"uniformcubicspline.h\"\n\n#include \n#include \n\nnamespace {\n\ntemplate \nconstexpr T Square(T x) {\n return x * x;\n}\n\ntemplate \nconstexpr T Cube(T x) {\n return x * x * x;\n}\n\nconstexpr int getJ(double a, double b, unsigned int n, double u) {\n return u < b ? (int)(n * ((u - a) / (b - a)) + 1.0) : n;\n}\n\nconstexpr double zeta(double a, double b, unsigned int n, double j) {\n return a + j * (b - a) / n;\n}\n\n} // namespace\n\nnamespace CLEmpiricFlux {\n\nUniformCubicSpline::UniformCubicSpline(double a, double b, Eigen::VectorXd f,\n Eigen::VectorXd M)\n : _n(f.size() - 1), _a(a), _b(b), _f(std::move(f)), _M(std::move(M)) {\n assert(b >= a);\n assert(_f.size() >= 2);\n assert(_f.size() == _M.size());\n}\n\ndouble UniformCubicSpline::operator()(double u) const {\n assert((u >= _a) && (u <= _b));\n int j = getJ(_a, _b, _n, u);\n double h = (_b - _a) / _n;\n double tau = (u - zeta(_a, _b, _n, j - 1)) / h;\n\n return _f(j) * tau + _f(j - 1) * (1.0 - tau) +\n Square(h) / 6.0 *\n (_M(j) * (Cube(tau) - tau) +\n _M(j - 1) * (-Cube(tau) + 3.0 * Square(tau) - 2.0 * tau));\n}\n\ndouble UniformCubicSpline::derivative(double u) const {\n assert((u >= _a) && (u <= _b));\n int j = getJ(_a, _b, _n, u);\n double h = (_b - _a) / _n;\n double tau = (u - zeta(_a, _b, _n, j - 1)) / h;\n\n return (_f(j) - _f(j - 1) +\n Square(h) / 6.0 *\n (_M(j) * (3.0 * Square(tau) - 1.0) +\n _M(j - 1) * (-3.0 * Square(tau) + 6.0 * tau - 2.0))) *\n (1.0 / h);\n}\n\n} // namespace CLEmpiricFlux\n", "meta": {"hexsha": "14648973ae547b4d92c24e2708a116db92de1e32", "size": 1806, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/CLEmpiricFlux/templates/uniformcubicspline.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/CLEmpiricFlux/templates/uniformcubicspline.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/CLEmpiricFlux/templates/uniformcubicspline.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 25.0833333333, "max_line_length": 77, "alphanum_fraction": 0.5348837209, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.8104789155369048, "lm_q1q2_score": 0.6788733129438796}} {"text": "#include \n\n//[[Rcpp::depends(RcppEigen)]]\n#include \n\n//[[Rcpp::depends(BH)]]\n#include \n#include \n\n#include \"logLikelihoods.hpp\"\n#include \"AuxiliaryFunctions.hpp\"\n\ndouble logPoissonGammaDistribution(const double & x, const double & mean, const double & dispersion)\n{\n double eta = dispersion;\n if (!(dispersion > 0))\n {\n eta = 2e-16;\n }\n\n const double logProbability = boost::math::lgamma(x + eta) - boost::math::lgamma(eta) -\n boost::math::lgamma(x + 1) + x * (std::log(mean) - std::log(mean + eta)) + eta * (std::log(eta) -\n std::log(mean + eta));\n\n return logProbability;\n}\n\ndouble logInflatedTruncatedPoissonGammaDistribution(const double & x, const double & mean, const double & dispersion,\n const double & p, const double & inflation, const double & truncation)\n{\n const double logTruncatedProbability = (logPoissonGammaDistribution(x, mean, dispersion) -\n std::log(1.0 - std::exp(dispersion * (std::log(dispersion) - std::log(mean + dispersion)))));\n\n double logProbability;\n if (x == inflation)\n {\n logProbability = std::log(p + std::exp(std::log(1.0 - p) + logTruncatedProbability));\n }\n else\n {\n logProbability = std::log(1.0 - p) + logTruncatedProbability;\n }\n\n return logProbability;\n}\n\n//[[Rcpp::export(.devianceResidualPoissonGammaDistribution)]]\ndouble devianceResidualPoissonGammaDistribution(const double & x, const double & mean, const double & dispersion)\n{\n\t// if (std::abs(x - mean) < 2e-8)\n\t// {\n\t// \treturn 0.0;\n\t// }\n\n\tdouble eta = dispersion;\n\tif (!(dispersion > 0))\n\t{\n\t eta = 2e-16;\n\t}\n\n\tdouble deviance_ma = (x + eta) * (std::log(mean + eta) - std::log(x + eta));\n if (x > 0)\n {\n deviance_ma += x * (std::log(x) - std::log(mean));\n }\n\n return boost::math::sign(x - mean) * std::pow(2.0 * deviance_ma, 0.5);\n}\n\ndouble devianceResidualPG1(const double & x, const double & mean, const double & dispersion)\n{\n double eta = dispersion;\n if (!(dispersion > 0))\n {\n eta = 2e-16;\n }\n\n double deviance_ma = (x - mean) * std::log(eta + 1) / eta -\n boost::math::lgamma((eta * x + mean) / eta) +\n boost::math::lgamma(x * (eta + 1) / eta);\n\n if (x > 0)\n {\n deviance_ma += boost::math::lgamma(x / eta) - boost::math::lgamma(mean / eta);\n }\n\n return boost::math::sign(x - mean) * std::pow(2.0 * deviance_ma, 0.5);\n}\n\n\ndouble logMultinomialCoefficient(const int & totalCounts, const Eigen::VectorXd & counts)\n{\n std::size_t N = counts.size();\n\n double logGammaCounts = 0;\n for (std::size_t n = 0; n < N; n++)\n {\n logGammaCounts += lgamma(counts[n] + 1);\n }\n return lgamma(totalCounts + 1) - logGammaCounts;\n}\n\ndouble logDirichletMultinomial(const Eigen::VectorXd & counts, const Eigen::VectorXd & alleleFrequencies)\n{\n std::size_t N = alleleFrequencies.size();\n int sumCounts = counts.sum();\n\n double groupSum = 0.0;\n for (std::size_t n = 0; n < N; n++)\n {\n groupSum += counts[n] * std::log(alleleFrequencies[n]);\n\n }\n\n double resLogDirichletMultinomial = logMultinomialCoefficient(sumCounts, counts) + groupSum;\n return resLogDirichletMultinomial;\n}\n\ndouble logDirichletMultinomialTheta(const Eigen::VectorXd & counts, const double & theta, const Eigen::VectorXd & alleleFrequencies)\n{\n std::size_t N = alleleFrequencies.size();\n int sumCounts = counts.sum();\n\n double groupSum = 0.0;\n double gamma_plus = 1/theta - 1;\n for (std::size_t n = 0; n < N; n++)\n {\n double gamma_j = gamma_plus * alleleFrequencies[n];\n groupSum += lgamma(counts[n] + gamma_j) - lgamma(gamma_j);\n }\n\n groupSum += (lgamma(gamma_plus) - lgamma(sumCounts + gamma_plus));\n\n double resLogDirichletMultinomial = logMultinomialCoefficient(sumCounts, counts) + groupSum;\n return resLogDirichletMultinomial;\n}\n\nEigen::VectorXd logLikelihoodAlleleCoverage(const Eigen::VectorXd & coverage, const std::vector & expectedContributionMatrix,\n const std::vector & alleleIndex, const Eigen::VectorXd partialSumAlleles,\n const Eigen::VectorXd & sampleParameters, const Eigen::VectorXd & mixtureProportions,\n const Eigen::VectorXd & markerImbalances)\n{\n const std::size_t & M = alleleIndex.size();\n\n const double & referenceMarkerAverage = sampleParameters[0];\n const double & dispersion = sampleParameters[1];\n\n Eigen::VectorXd logLikelihood = Eigen::VectorXd::Zero(M);\n for (std::size_t m = 0; m < M; m++)\n {\n const Eigen::VectorXd & alleleIndex_m = alleleIndex[m];\n const Eigen::MatrixXd & expectedContributionMatrix_m = expectedContributionMatrix[m];\n const Eigen::VectorXd & expectedContribution = expectedContributionMatrix_m * mixtureProportions;\n\n double logLikelihood_m = 0.0;\n for (std::size_t a = 0; a < alleleIndex_m.size(); a++)\n {\n const std::size_t & n = partialSumAlleles[m] + alleleIndex_m[a];\n\n double mu_ma = referenceMarkerAverage * markerImbalances[m] * expectedContribution[a];\n if (expectedContribution[a] > 0)\n {\n logLikelihood_m += logPoissonGammaDistribution(coverage[n], mu_ma, mu_ma / dispersion);\n }\n }\n\n logLikelihood[m] = logLikelihood_m;\n }\n\n return logLikelihood;\n}\n\nEigen::VectorXd logLikelihoodNoiseCoverage(const Eigen::VectorXd & coverage, const std::vector & noiseIndex,\n const Eigen::VectorXd & partialSumAlleles,\n const double & noiseLevel, const double & noiseDispersion, const double & p)\n{\n const std::size_t & M = noiseIndex.size();\n\n Eigen::VectorXd logLikelihood = Eigen::VectorXd::Zero(M);\n for (std::size_t m = 0; m < M; m++)\n {\n const Eigen::VectorXd & noiseIndex_m = noiseIndex[m];\n for (std::size_t a = 0; a < noiseIndex_m.size(); a++)\n {\n const std::size_t & n = partialSumAlleles[m] + noiseIndex_m[a];\n logLikelihood[m] += logInflatedTruncatedPoissonGammaDistribution(coverage[n], noiseLevel, noiseDispersion, p, 1.0, 0.0);\n }\n }\n\n return logLikelihood;\n}\n\n\nEigen::VectorXd logGenotypeProbabilityHWE(const Eigen::VectorXd & alleleFrequencies, const Eigen::MatrixXd & unknownProfiles, const std::size_t & numberOfMarkers, const Eigen::VectorXd & numberOfAlleles)\n{\n Eigen::VectorXd partialNumberOfAlleles = partialSumEigen(numberOfAlleles);\n\n Eigen::VectorXd logPriorProbability = Eigen::VectorXd::Zero(numberOfMarkers);\n for (std::size_t m = 0; m < numberOfMarkers; m++)\n {\n Eigen::MatrixXd profiles_m = unknownProfiles.block(partialNumberOfAlleles[m], 0, numberOfAlleles[m], unknownProfiles.cols());\n\n Eigen::VectorXd profileCounts_m = profiles_m.rowwise().sum();\n Eigen::VectorXd alleleFractions_m = alleleFrequencies.segment(partialNumberOfAlleles[m], numberOfAlleles[m]);\n\n logPriorProbability[m] = logDirichletMultinomial(profileCounts_m, alleleFractions_m);\n }\n\n return logPriorProbability;\n}\n\n\nEigen::VectorXd logGenotypeProbabilityThetaCorrection(const Eigen::VectorXd & alleleFrequencies, const double & theta, const Eigen::MatrixXd & unknownProfiles, const Eigen::MatrixXd & knownProfiles, const std::size_t & numberOfMarkers, const Eigen::VectorXd & numberOfAlleles)\n{\n Eigen::MatrixXd profiles = bindColumns(knownProfiles, unknownProfiles);\n std::size_t numberOfContributors = profiles.cols();\n std::size_t numberOfKnownContributors = numberOfContributors - unknownProfiles.cols();\n\n Eigen::VectorXd partialNumberOfAlleles = partialSumEigen(numberOfAlleles);\n Eigen::VectorXd thetaCorrectedProbabilty = Eigen::VectorXd::Zero(numberOfMarkers);\n for (std::size_t m = 0; m < numberOfMarkers; m++)\n {\n Eigen::MatrixXd profiles_m = profiles.block(partialNumberOfAlleles[m], 0, numberOfAlleles[m], numberOfContributors);\n\n Eigen::VectorXd profileCounts = profiles_m.rowwise().sum();\n Eigen::VectorXd alleleFractions_m = alleleFrequencies.segment(partialNumberOfAlleles[m], numberOfAlleles[m]);\n\n double logProbabilityOfUnknownProfiles = logDirichletMultinomialTheta(profileCounts, theta, alleleFractions_m);\n double logProbabilty_m = logProbabilityOfUnknownProfiles;\n\n if (numberOfKnownContributors != 0)\n {\n Eigen::MatrixXd knownProfiles_m = knownProfiles.block(partialNumberOfAlleles[m], 0, numberOfAlleles[m], numberOfKnownContributors);\n\n Eigen::VectorXd knownCounts = knownProfiles_m.rowwise().sum();\n\n double logProbabilityOfKnownProfiles = logDirichletMultinomialTheta(knownCounts, theta, alleleFractions_m);\n logProbabilty_m -= logProbabilityOfKnownProfiles;\n }\n\n thetaCorrectedProbabilty[m] = logProbabilty_m;\n }\n\n return thetaCorrectedProbabilty;\n}\n\nEigen::VectorXd logPriorGenotypeProbability(const Eigen::VectorXd & alleleFrequencies, const double & theta, const Eigen::MatrixXd & unknownProfiles, const Eigen::MatrixXd & knownProfiles, const std::size_t & numberOfMarkers, const Eigen::VectorXd & numberOfAlleles)\n{\n Eigen::VectorXd logPriorProbability;\n if (theta == 0.0)\n {\n logPriorProbability = logGenotypeProbabilityHWE(alleleFrequencies, unknownProfiles, numberOfMarkers, numberOfAlleles);\n }\n else\n {\n logPriorProbability = logGenotypeProbabilityThetaCorrection(alleleFrequencies, theta, unknownProfiles, knownProfiles, numberOfMarkers, numberOfAlleles);\n }\n\n return logPriorProbability;\n}\n", "meta": {"hexsha": "f7c2d9f9e37ba39777de0ef0b5a6ddfa4141ebf6", "size": 9857, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/logLikelihoods.cpp", "max_stars_repo_name": "svilsen/MPSMixtures", "max_stars_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/logLikelihoods.cpp", "max_issues_repo_name": "svilsen/MPSMixtures", "max_issues_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/logLikelihoods.cpp", "max_forks_repo_name": "svilsen/MPSMixtures", "max_forks_repo_head_hexsha": "07b21c593bee795162f6282446ff370985ceec38", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.7662835249, "max_line_length": 276, "alphanum_fraction": 0.6681546109, "num_tokens": 2474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896693699844, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.678767626157239}} {"text": "#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point;\n\ntypedef CGAL::Delaunay_triangulation_2 Triangulation;\n\ntypedef boost::graph_traits::vertex_descriptor vertex_descriptor;\ntypedef boost::graph_traits::vertex_iterator vertex_iterator;\ntypedef boost::graph_traits::edge_descriptor edge_descriptor;\n\n// The BGL makes use of indices associated to the vertices\n// We use a std::map to store the index\ntypedef std::map VertexIndexMap;\n\n// A std::map is not a property map, because it is not lightweight\ntypedef boost::associative_property_map VertexIdPropertyMap;\n\nint main(int argc,char* argv[])\n{\n const char* filename = (argc > 1) ? argv[1] : \"data/points.xy\";\n std::ifstream input(filename);\n Triangulation tr;\n\n Point p;\n while(input >> p)\n tr.insert(p);\n\n // Associate indices to the vertices\n VertexIndexMap vertex_id_map;\n VertexIdPropertyMap vertex_index_pmap(vertex_id_map);\n int index = 0;\n\n for(vertex_descriptor vd : vertices(tr))\n vertex_id_map[vd] = index++;\n\n // We use the default edge weight which is the squared length of the edge\n // This property map is defined in graph_traits_Triangulation_2.h\n\n // In the function call you can see a named parameter: vertex_index_map\n std::list mst;\n boost::kruskal_minimum_spanning_tree(tr, std::back_inserter(mst),\n vertex_index_map(vertex_index_pmap));\n\n std::cout << \"The edges of the Euclidean mimimum spanning tree:\" << std::endl;\n for(edge_descriptor ed : mst)\n {\n vertex_descriptor svd = source(ed, tr);\n vertex_descriptor tvd = target(ed, tr);\n Triangulation::Vertex_handle sv = svd;\n Triangulation::Vertex_handle tv = tvd;\n std::cout << \"[ \" << sv->point() << \" | \" << tv->point() << \" ] \" << std::endl;\n }\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "4de38c2adef5a9e759c915b5294d6a23a23d4dc4", "size": 2348, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "BGL/examples/BGL_triangulation_2/emst.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "BGL/examples/BGL_triangulation_2/emst.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "BGL/examples/BGL_triangulation_2/emst.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 35.5757575758, "max_line_length": 88, "alphanum_fraction": 0.6920783646, "num_tokens": 568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6786578421570519}} {"text": "#include \n#include \n#include \n#include \n\n/**\n * Generate all prime numbers up to a limit\n * @param limit test for primality up to this limit, not including the limit\n * @return the prime numbers\n */\nstd::vector getPrimes( unsigned long limit )\n{\n std::vector primes;\n \n // special cases\n if ( limit <= 5 )\n {\n if ( limit > 2 )\n {\n primes.push_back( 2 );\n if ( limit > 3 )\n {\n\tprimes.push_back( 3 );\n }\n } \n return primes;\n }\n \n // multiples of 2 and 3 will not be used, just add them by hand\n primes.push_back( 2 );\n primes.push_back( 3 );\n \n // crossed out nonprimes\n boost::dynamic_bitset<> crossOut( limit );\n \n // add primes to result and cross out nonprimes\n unsigned long crossOutLimit = static_cast( sqrt( limit ) ) + 1;\n unsigned long i = 5;\n for ( ; i < crossOutLimit; i += 6 )\n {\n for ( unsigned long d = 0; d != 4; d += 2 )\n {\n unsigned long num = i + d;\n if ( !crossOut.test( num ) )\n {\n\tprimes.push_back( num );\n\tfor ( unsigned long j = num * num; j < limit; j += num )\n\t{\n\t crossOut.set( j );\n\t}\n }\n }\n }\n \n // add extra primes to result \n for ( ; i < limit - 2; i += 6 )\n {\n for ( unsigned long d = 0; d != 4; d += 2 )\n {\n unsigned long num = i + d;\n if ( !crossOut.test( num ) )\n {\n\tprimes.push_back( num );\n }\n }\n }\n \n // one may be missing\n if ( i < limit && !crossOut.test( i ) )\n {\n primes.push_back( i );\n }\n \n return primes;\n}\n\nint main()\n{\n unsigned long limit = 10000000;\n std::vector primes = getPrimes( limit );\n std::cout << \"Trere are \" << primes.size() << \" primes below \" << limit << \".\" << std::endl;\n return 0;\n}\n", "meta": {"hexsha": "62c629e679535a00c8d61ec45a1e5289bc3e21ac", "size": 1791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "recipes/C++/577899_Faster_prime_generator/recipe-577899.cpp", "max_stars_repo_name": "tdiprima/code", "max_stars_repo_head_hexsha": "61a74f5f93da087d27c70b2efe779ac6bd2a3b4f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2023.0, "max_stars_repo_stars_event_min_datetime": "2017-07-29T09:34:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-24T08:00:45.000Z", "max_issues_repo_path": "recipes/C++/577899_Faster_prime_generator/recipe-577899.cpp", "max_issues_repo_name": "unhacker/code", "max_issues_repo_head_hexsha": "73b09edc1b9850c557a79296655f140ce5e853db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 32.0, "max_issues_repo_issues_event_min_datetime": "2017-09-02T17:20:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T17:49:37.000Z", "max_forks_repo_path": "recipes/C++/577899_Faster_prime_generator/recipe-577899.cpp", "max_forks_repo_name": "unhacker/code", "max_forks_repo_head_hexsha": "73b09edc1b9850c557a79296655f140ce5e853db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 780.0, "max_forks_repo_forks_event_min_datetime": "2017-07-28T19:23:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T20:39:41.000Z", "avg_line_length": 21.3214285714, "max_line_length": 94, "alphanum_fraction": 0.5633724176, "num_tokens": 536, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314768368161, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6786537755437008}} {"text": "#include \n\n// Rational number\n// Positive/negative infinity can be allowed.\ntemplate \nstruct Rational {\n public:\n // #include \n // using multip = boost::multiprecision;\n // using BigInt = boost::multiprecision::checked_int128_t;\n using BigInt = __int128_t;\n\n T nume, deno;\n\n Rational() : nume(0), deno(1) {}\n\n Rational(T n) : nume(n), deno(1) {}\n\n Rational(BigInt n, BigInt d) {\n if constexpr (allow_infinity) {\n assert(d != 0 or n != 0); // 0/0 is undefined\n } else {\n assert(d != 0);\n }\n if (allow_infinity and d == 0) {\n n = (n < 0) ? -1 : 1; // infinity\n } else if (n == 0) {\n d = 1;\n } else {\n const int sign = ((n < 0) xor (d < 0)) ? -1 : 1;\n if (n < 0) n = -n;\n if (d < 0) d = -d;\n const auto g = gcd_(n, d);\n if (g > 1) {\n n /= g;\n d /= g;\n }\n n *= sign;\n }\n nume = static_cast(n);\n deno = static_cast(d);\n }\n\n Rational(const Rational &x) = default;\n Rational(Rational &&x) = default;\n Rational &operator=(const Rational &x) = default;\n Rational &operator=(Rational &&x) = default;\n\n // Cast to a floating point number.\n template \n explicit operator Float() const {\n static_assert(std::is_floating_point::value);\n return (Float)nume / (Float)deno;\n }\n\n Rational operator+() const { return *this; }\n Rational operator-() const {\n Rational ret;\n ret.nume = -nume;\n ret.deno = deno;\n return ret;\n }\n\n friend bool operator==(const Rational &x, const Rational &y) {\n return (x.nume == y.nume) and (x.deno == y.deno);\n }\n friend bool operator!=(const Rational &x, const Rational &y) {\n return not(x == y);\n }\n friend bool operator<(const Rational &x, const Rational &y) {\n if constexpr (allow_infinity) {\n if (x.deno == 0 and y.deno == 0) return x.nume < y.nume;\n }\n return static_cast(x.nume) * y.deno <\n static_cast(y.nume) * x.deno;\n }\n friend bool operator>(const Rational &x, const Rational &y) { return y < x; }\n friend bool operator<=(const Rational &x, const Rational &y) {\n return not(x > y);\n }\n friend bool operator>=(const Rational &x, const Rational &y) {\n return not(x < y);\n }\n\n friend Rational operator+(const Rational &x, const Rational &y) {\n if constexpr (allow_infinity) {\n if (x.deno == 0 and y.deno == 0) {\n assert(x.nume == y.nume); // (infinity - infinity) is undefined\n return x;\n }\n if (x.deno == 0) return x;\n if (y.deno == 0) return y;\n }\n auto g = gcd_(x.deno, y.deno);\n BigInt xd = x.deno / g;\n BigInt yd = y.deno / g;\n BigInt zn = x.nume * yd + y.nume * xd;\n BigInt zd = xd * y.deno;\n return Rational(std::move(zn), std::move(zd));\n }\n Rational &operator+=(const Rational &x) { return (*this = *this + x); }\n\n friend Rational operator-(const Rational &x, const Rational &y) {\n return x + (-y);\n }\n Rational &operator-=(const Rational &x) { return (*this = *this - x); }\n\n friend Rational operator*(const Rational &x, const Rational &y) {\n if (x.nume == 0 or y.nume == 0) return Rational(0);\n auto g1 = gcd_(abs_(x.nume), y.deno);\n auto g2 = gcd_(abs_(y.nume), x.deno);\n return Rational(BigInt(x.nume / g1) * BigInt(y.nume / g2),\n BigInt(x.deno / g2) * BigInt(y.deno / g1));\n }\n Rational &operator*=(const Rational &x) { return (*this = *this * x); }\n\n Rational inv() const { return Rational(deno, nume); }\n\n friend Rational operator/(const Rational &x, const Rational &y) {\n return x * y.inv();\n }\n Rational &operator/=(const Rational &x) { return (*this = *this / x); }\n\n friend std::ostream &operator<<(std::ostream &os, const Rational &x) {\n return os << x.nume << \"/\" << x.deno;\n }\n\n private:\n template \n static inline U abs_(const U &x) {\n // return std::abs(x);\n // return boost::multiprecision::abs(x);\n return (x < 0) ? -x : x;\n }\n template \n static U gcd_(const U &a, const U &b) {\n // return std::gcd(a, b);\n return (b == 0) ? a : gcd_(b, a % b);\n }\n};\nusing Rat = Rational;\n// using Rat = Rational; // for testing overflow\n\n// Parse a decimal number into a rational.\n// (e.g. \"0.2029\" => 2029/10000 )\nstd::istream &operator>>(std::istream &is, Rat &x) {\n long long nume = 0, deno = 1;\n char ch;\n while (is.get(ch)) {\n if (not std::isspace(ch)) break;\n }\n int sgn = 1;\n if (ch == '-') {\n sgn = -1;\n is.get(ch);\n }\n bool in_frac = false;\n while (true) {\n if (not std::isdigit(ch)) {\n is.unget();\n break;\n }\n nume = (nume * 10) + int(ch - '0');\n if (in_frac) deno *= 10;\n if (not(is.get(ch))) break;\n if (ch == '.') {\n in_frac = true;\n if (not(is.get(ch))) break;\n }\n }\n x = Rat(nume * sgn, deno);\n return is;\n}\n", "meta": {"hexsha": "ddf08ffc4abf4a9031ba93f020e8b9d914f19e95", "size": 4936, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/rational.hpp", "max_stars_repo_name": "keijak/hikidashi-cpp", "max_stars_repo_head_hexsha": "63d01dfa1587fa56fd7f4e50712f7c10d8168520", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/rational.hpp", "max_issues_repo_name": "keijak/hikidashi-cpp", "max_issues_repo_head_hexsha": "63d01dfa1587fa56fd7f4e50712f7c10d8168520", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rational.hpp", "max_forks_repo_name": "keijak/hikidashi-cpp", "max_forks_repo_head_hexsha": "63d01dfa1587fa56fd7f4e50712f7c10d8168520", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.367816092, "max_line_length": 79, "alphanum_fraction": 0.5709076175, "num_tokens": 1555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181874, "lm_q2_score": 0.7662936324115012, "lm_q1q2_score": 0.6786537590500902}} {"text": "// STL includes\n#include \n#include \n#include \n#include \n\n// BGL includes\n#include \n#include \n\nusing namespace std;\n\ntypedef boost::adjacency_list graph;\ntypedef boost::graph_traits::vertex_descriptor vertex_desc;\n\nbool perfect_matching(const graph &G) {\n int n = boost::num_vertices(G);\n vector mate_map(n); // exterior property map\n\n boost::edmonds_maximum_cardinality_matching(G,\n boost::make_iterator_property_map(mate_map.begin(), boost::get(boost::vertex_index, G)));\n int matching_size = boost::matching_size(G,\n boost::make_iterator_property_map(mate_map.begin(), boost::get(boost::vertex_index, G)));\n\n return 2 * matching_size == n;\n}\n\nvoid solve() {\n \n int n; cin >> n;\n int c; cin >> c;\n unsigned int f; cin >> f;\n \n graph G(n);\n\n string x;\n vector> ch(n, set());\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < c; ++j) {\n cin >> x;\n ch[i].insert(x);\n }\n }\n \n \n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < i; ++j) {\n vector intersection;\n set_intersection(ch[i].begin(), ch[i].end(), ch[j].begin(), ch[j].end(), back_inserter(intersection));\n if (intersection.size() > f) {\n boost::add_edge(i, j, G);\n }\n }\n }\n\n cout << (perfect_matching(G) ? \"not optimal\" : \"optimal\") << endl;\n}\n\nint main()\n{\n ios_base::sync_with_stdio(false);\n int t; cin >> t;\n for (int i = 0; i < t; ++i) {\n solve();\n }\n return 0;\n}", "meta": {"hexsha": "99cd476bd9e6984d85280c981887ec69ffd26793", "size": 1643, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/buddy_selection.cpp", "max_stars_repo_name": "dsparber/algolab", "max_stars_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2021-01-01T17:19:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-09T12:27:57.000Z", "max_issues_repo_path": "src/buddy_selection.cpp", "max_issues_repo_name": "dsparber/algolab", "max_issues_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/buddy_selection.cpp", "max_forks_repo_name": "dsparber/algolab", "max_forks_repo_head_hexsha": "9781eb5c7444236f796f167f1f39fc9d913e5c53", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-01-28T10:55:25.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-28T10:55:25.000Z", "avg_line_length": 24.5223880597, "max_line_length": 110, "alphanum_fraction": 0.6098600122, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314738181875, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6786537590500901}} {"text": "/** @file mvn_cdf.cpp\n * @author Mark J. Olah (mjo\\@cs.unm DOT edu)\n * @date 2017-2019\n * @brief\n * \n */\n#include \"PriorHessian/mvn_cdf.h\"\n\n#include \n#include \n\n#include \n\n#include \n#include \n\n\nnamespace {\n const double sqrt2 = sqrt(2.);\n const double inv_sqrt2 = 1./sqrt2;\n const double inv_2pi = 1./(2.*arma::datum::pi);\n}\n\nnamespace prior_hessian {\n\n\n/** area of the lower tail of the unit normal curve below t. */\ndouble unit_normal_cdf( double t )\n{\n if(t==-INFINITY) return 0;\n if(t==INFINITY) return 1;\n return std::max(std::min(.5*std::erfc(-t*::inv_sqrt2),1.0),0.0);\n}\n\ndouble unit_normal_icdf( double u )\n{\n if(u<=0) return -INFINITY;\n if(u>=1) return INFINITY;\n return -::sqrt2*boost::math::erfc_inv(2*u);\n}\n\ndouble bounded(double x)\n{\n return std::min(std::max(x,0.),1.);\n}\n\n/* Integrates the between y(x)=0 and y(x) = a*x, and right of h, to infinity\n * \n * when h=0 this is the triangle from the x-axis with angle arctan(a)\n * h - location of vertical line to integrate to the right from\n * a - slope of line above the x-axis\n * gh - normcdf(h);\n */\ndouble owen_t_integral(double h, double a, double gh)\n{\n //Check pre-conditions\n if(std::isnan(h)) throw ParameterValueError(\"a is NaN\");\n if(!(gh >=0 && gh<=1)) throw ParameterValueError(\"gh is not in [0,1]\");\n //Edge cases\n if(h == INFINITY) return 0;\n if(std::isnan(a)) throw ParameterValueError(\"a is NaN\");\n if(a == 0) return 0;\n if(h == 0) return std::atan(a)*::inv_2pi;\n if(a == INFINITY) return (h>0) ? .5*(1-gh) : .5*gh;\n if(a==1) return .5*gh*(1-gh); //This formula works for h and -h by symmetry\n //Use owens 2.4 and 2.5 to handle negative h and a\n if(a<0 && h<0) return -owen_t_integral(-h,-a,1-gh);\n if(a<0) return -owen_t_integral(h,-a,gh);\n if(h<0) return owen_t_integral(-h,a,1-gh);\n \n assert(h>0 && std::isfinite(h));\n assert(a>0 && std::isfinite(a));\n //Use Owens 2.3 to invert a if >1. This requires an additional normcdf call.\n if(a>1) {\n double ah = a*h;\n double gah = unit_normal_cdf(ah);\n double v1 = owen_t_integral(ah,1/a,gah);\n return .5*(gh+gah) -gh*gah - v1;\n }\n \n assert(a>0 && a<1);\n \n const int max_iter = 1000;\n const double eps = 1E-10;\n double theta = std::atan(a);\n double asq = a*a;\n double asq_powj = asq;\n double h2 = h*h/2;\n double e2h = std::exp(-h2);\n if(e2h==0) return 0;\n double Qj = 1;\n double Sj = Qj;\n double s = 1 - e2h; //First term of series.\n for(int j=1; j1 || !std::isfinite(r)) throw ParameterValueError(\"r is not in interval [-1,1]\");\n \n if(h==-INFINITY || k==-INFINITY) return 0;\n if(h==INFINITY && k==INFINITY) return 1;\n if(fabs(r)==1) { //Degenerate case.\n if(r>0) return unit_normal_cdf(std::min(h,k));\n else return unit_normal_cdf(h) - unit_normal_cdf(-k);\n }\n assert(fabs(r)<1);\n double sigma = sqrt(1-r*r);\n double gh = unit_normal_cdf(h);\n double ah = (k-r*h)/(h*sigma);\n double bint;\n if(h==k) {\n if(h==0.) return .25+asin(r)*::inv_2pi;\n bint = gh - 2*owen_t_integral(h,ah,gh);\n } else if(h==-k) { \n bint = .5 - 2*owen_t_integral(h,ah,gh);\n } else {\n double gk = unit_normal_cdf(k);\n double ak = (h-r*k)/(k*sigma);\n double t1 = owen_t_integral(h,ah,gh);\n double t2 = owen_t_integral(k,ak,gk);\n bint = .5*(gh+gk) - t1 - t2;\n }\n if( h*k < 0 || (h*k == 0 && (h<0 || k<0))) bint -= .5;\n return std::min(std::max(bint,0.0),1.0);\n}\n\n\n\n\n/** compute the bivariate normal cdf integral\n * computes the probability for two normal variates X and Y\n * whose correlation is R, that AH <= X and AK <= Y.\n * \n * Adapted to modern C++ with efficiency improvements by:\n * Mark Olah (mjo@cs.unm DOT edu)\n * 10/2018\n * \n * Reference:\n * Thomas Donnelly,\n * Algorithm 462: Bivariate Normal Distribution,\n * Communications of the ACM,\n * October 1973, Volume 16, Number 10, page 638.\n */ \ndouble donnelly_bvn_integral( double ah, double ak, double r )\n{\n static double eps = 1.0E-15;\n if (r<-1 || r>1) throw ParameterValueError(\"must have -1<=rho<=1\");\n if ((ah==INFINITY) || (ak==INFINITY)) return 0;\n if ((ah==-INFINITY) && (ak==-INFINITY)) return 1;\n \n double gh = unit_normal_cdf(-ah)/2.0;\n double gk = unit_normal_cdf(-ak)/2.0;\n\n if(r == 0.0) return bounded(4*gh*gk);\n\n double b = 0.0; //return value\n double rr = (1+r)*(1-r);\n if(rr==0) { //Degenerate cases r=-1 r=0 r=1\n if(r<0) {\n if(ah+ak<0) b = 2*(gh+gk)-1;\n } else {\n if(ah-ak<0) b = 2*gk;\n else b = 2*gh;\n }\n return bounded(b);\n }\n\n double sigma_inv = 1./sqrt(rr);\n double con = arma::datum::pi * eps;\n double wh;\n double wk;\n double gw;\n int is;\n if(ah == 0) {\n if(ak == 0) return bounded(0.25+asin(r)*::inv_2pi); // (0,0)\n //(0, !0)\n b = gk;\n wh = -ak;\n wk = (ah/ak - r)*sigma_inv;\n gw = 2*gk;\n is = 1;\n } else {\n // (!0, 0)\n b = gh; \n wh = -ah;\n wk = (ak/ah - r)*sigma_inv;\n gw = 2*gh;\n is = -1;\n if(ak != 0) { // ( !0, !0)\n b = gh+gk;\n if (ah*ak < 0) b-= 0.5;\n }\n }\n// std::cout<<\"NEW ah:\"< 1) {\n sgn = -sgn;\n wh *= wk;\n double g2 = unit_normal_cdf(wh);\n wk = 1./wk;\n if(wk < 0) b += 0.5;\n b += -.5*(gw+g2) + gw*g2;\n// std::cout<<\"nn b: \"<\n#include \n#include \n\n#include \"gauss_quad.hpp\"\n\nnamespace DGHydro {\n\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n// Constructor\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nGaussQuad::GaussQuad(int n) : n(n)\n{\n if (n <= 0)\n throw std::runtime_error(\"Can not create Gaussian Quadrature with a number of point that is not positive\");\n\n FindAbscissae();\n FindWeights();\n}\n\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n// Destructor\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nGaussQuad::~GaussQuad()\n{\n delete[] x;\n delete[] w;\n}\n\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n//\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nvoid GaussQuad::FindAbscissae()\n{\n if (x == nullptr) x = new double[n];\n\n double dx = 2.0/(double) n;\n double tol = 1.0e-12;\n\n for (int i = 0; i < n; i++) {\n // Divide up interval: each contains a single zero\n double a = -1.0 + i*dx;\n double b = -1.0 + (i + 1)*dx;\n\n // Find zero by bisection\n while (1) {\n double c = 0.5*(a + b);\n\n double f = boost::math::legendre_p(n, c);\n\n if (f == 0.0 || 0.5*(b - a) < tol) {\n x[i] = c;\n break;\n }\n\n if (sgn(f) == sgn(boost::math::legendre_p(n, a))) {\n a = c;\n } else {\n b = c;\n }\n }\n\n }\n\n}\n\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n//\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nvoid GaussQuad::FindWeights()\n{\n if (w == nullptr) w = new double[n];\n\n for (int i = 0; i < n; i++) {\n // Derivative of Legendre polynomial\n double p_prime = n*(x[i]*boost::math::legendre_p(n, x[i]) -\n boost::math::legendre_p(n - 1, x[i]))/(x[i]*x[i]-1.0);\n // Gaussian weight\n w[i] = 2.0/(1 - x[i]*x[i])/p_prime/p_prime;\n }\n}\n\n}\n", "meta": {"hexsha": "ac880b9f480081939a0c474f8e5de5b2b51a0dd7", "size": 2048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gauss_quad/gauss_quad.cpp", "max_stars_repo_name": "SijmeJan/DGHydro", "max_stars_repo_head_hexsha": "178ae1f95e622ade465d734eca08893d98505dee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gauss_quad/gauss_quad.cpp", "max_issues_repo_name": "SijmeJan/DGHydro", "max_issues_repo_head_hexsha": "178ae1f95e622ade465d734eca08893d98505dee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gauss_quad/gauss_quad.cpp", "max_forks_repo_name": "SijmeJan/DGHydro", "max_forks_repo_head_hexsha": "178ae1f95e622ade465d734eca08893d98505dee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2727272727, "max_line_length": 111, "alphanum_fraction": 0.3725585938, "num_tokens": 514, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467643431001, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6785637090905255}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n Matrix3d v = Matrix3d::Random();\ncout << \"The matrix v is:\" << endl;\ncout << v << endl;\n\nVector3d v0(1, v(1,0), v(2,0));\ncout << \"The first Householder vector is: v_0 = \" << v0.transpose() << endl;\nVector3d v1(0, 1, v(2,1));\ncout << \"The second Householder vector is: v_1 = \" << v1.transpose() << endl;\nVector3d v2(0, 0, 1);\ncout << \"The third Householder vector is: v_2 = \" << v2.transpose() << endl;\n\nVector3d h = Vector3d::Random();\ncout << \"The Householder coefficients are: h = \" << h.transpose() << endl;\n\nMatrix3d H0 = Matrix3d::Identity() - h(0) * v0 * v0.adjoint();\ncout << \"The first Householder reflection is represented by H_0 = \" << endl;\ncout << H0 << endl;\nMatrix3d H1 = Matrix3d::Identity() - h(1) * v1 * v1.adjoint();\ncout << \"The second Householder reflection is represented by H_1 = \" << endl;\ncout << H1 << endl;\nMatrix3d H2 = Matrix3d::Identity() - h(2) * v2 * v2.adjoint();\ncout << \"The third Householder reflection is represented by H_2 = \" << endl;\ncout << H2 << endl;\ncout << \"Their product is H_0 H_1 H_2 = \" << endl;\ncout << H0 * H1 * H2 << endl;\n\nHouseholderSequence hhSeq(v, h);\nMatrix3d hhSeqAsMatrix(hhSeq);\ncout << \"If we construct a HouseholderSequence from v and h\" << endl;\ncout << \"and convert it to a matrix, we get:\" << endl;\ncout << hhSeqAsMatrix << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "f653ca7da4143c3ea35345064e37d195fc7b806f", "size": 1467, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_HouseholderSequence_HouseholderSequence.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_HouseholderSequence_HouseholderSequence.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_HouseholderSequence_HouseholderSequence.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3409090909, "max_line_length": 78, "alphanum_fraction": 0.6475800954, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.678563706646538}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n Vector3d v(-1,2,-3);\ncout << \"the absolute values:\" << endl << v.array().abs() << endl;\ncout << \"the absolute values plus one:\" << endl << v.array().abs()+1 << endl;\ncout << \"sum of the squares: \" << v.array().square().sum() << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "cd12add24ee58467fae09192b91cc5f0df921545", "size": 385, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_array_const.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_array_const.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_MatrixBase_array_const.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.6470588235, "max_line_length": 77, "alphanum_fraction": 0.6155844156, "num_tokens": 109, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8397339756938818, "lm_q2_score": 0.8080672112416737, "lm_q1q2_score": 0.6785614919238384}} {"text": "//\n// $Id: MatrixInverse.hpp 4146 2012-11-26 23:46:34Z pcbrefugee $\n//\n//\n// NB: Variations of this file appear in many open source projects,\n// with no copyright claims or license statements made in any of them. \n// Assumed to be public domain, or at least as open as the boost license,\n// since the farthest back we can seem to trace it is the Boost Wiki at\n// http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?Effective_UBLAS/Matrix_Inversion\n//\n\n#ifndef _MATRIXINVERSE_HPP_\n#define _MATRIXINVERSE_HPP_\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace toppic {\n\nnamespace matrix_inverse {\n\n\n/* Matrix inversion routine.\nUses lu_factorize and lu_substitute in uBLAS to invert a matrix */\nbool InvertMatrix(const boost::numeric::ublas::matrix& input, \n boost::numeric::ublas::matrix& inverse)\n{\n\n using namespace boost::numeric::ublas;\n typedef permutation_matrix pmatrix;\n\n // create a working copy of the input\n matrix A(input);\n // create a permutation matrix for the LU-factorization\n pmatrix pm(A.size1());\n\n // perform LU-factorization\n int res = lu_factorize(A,pm);\n if( res != 0 ) return false;\n\n // create identity matrix of \"inverse\"\n inverse = identity_matrix(A.size1());\n\n // backsubstitute to get the inverse\n lu_substitute(A, pm, inverse);\n\n return true;\n}\n\n\n/**\n* Invert a matrix via gauss-jordan algorithm (PARTIAL PIVOT)\n*\n* @param m The matrix to invert. Must be square.\n* @param singular If the matrix was found to be singular, then this\n* is set to true, else set to false.\n* @return If singular is false, then the inverted matrix is returned.\n* Otherwise it contains random values.\n*/\n\n//#define T double /// for debug\nboost::numeric::ublas::matrix\ngjinverse(const boost::numeric::ublas::matrix &m, \n bool &singular)\n{\n using namespace boost::numeric::ublas;\n\n const size_t size = m.size1();\n\n // Cannot invert if non-square matrix or 0x0 matrix.\n // Report it as singular in these cases, and return \n // a 0x0 matrix.\n if (size != m.size2() || size == 0)\n {\n singular = true;\n matrix A(0,0);\n return A;\n }\n\n // Handle 1x1 matrix edge case as general purpose \n // inverter below requires 2x2 to function properly.\n if (size == 1)\n {\n matrix A(1, 1);\n if (m(0,0) == 0.0)\n {\n singular = true;\n return A;\n }\n singular = false;\n A(0,0) = 1/m(0,0);\n return A;\n }\n\n // Create an augmented matrix A to invert. Assign the\n // matrix to be inverted to the left hand side and an\n // identity matrix to the right hand side.\n matrix A(size, 2*size);\n matrix_range > Aleft(A, \n range(0, size), \n range(0, size));\n Aleft = m;\n matrix_range > Aright(A, \n range(0, size), \n range(size, 2*size));\n Aright = identity_matrix(size);\n\n // Doing partial pivot\n for (size_t k = 0; k < size; k++)\n {\n // Swap rows to eliminate zero diagonal elements.\n for (size_t kk = 0; kk < size; kk++)\n {\n if ( A(kk,kk) == 0 ) // XXX: test for \"small\" instead\n {\n // Find a row(l) to swap with row(k)\n int l = -1;\n for (size_t i = kk+1; i < size; i++) \n {\n if ( A(i,kk) != 0 )\n {\n l = i; \n break;\n }\n }\n\n // Swap the rows if found\n if ( l < 0 ) \n {\n std::cerr << \"Error:\" << __FUNCTION__ << \":\"\n << \"Input matrix is singular, because cannot find\"\n << \" a row to swap while eliminating zero-diagonal.\";\n singular = true;\n return Aleft;\n }\n else \n {\n matrix_row > rowk(A, kk);\n matrix_row > rowl(A, l);\n rowk.swap(rowl);\n\n/*#if defined(DEBUG) || !defined(NDEBUG)\n std::cerr << __FUNCTION__ << \":\"\n << \"Swapped row \" << kk << \" with row \" << l \n << \":\" << A << \"\\n\";\n#endif*/\n }\n }\n }\n\n ///////////////////////////////////////////////////////////////////////////////////////////////////////// \n // normalize the current row\n for (size_t j = k+1; j < 2*size; j++)\n A(k,j) /= A(k,k);\n A(k,k) = 1;\n\n // normalize other rows\n for (size_t i = 0; i < size; i++)\n {\n if ( i != k ) // other rows // FIX: PROBLEM HERE\n {\n if ( A(i,k) != 0 )\n {\n for (size_t j = k+1; j < 2*size; j++)\n A(i,j) -= A(k,j) * A(i,k);\n A(i,k) = 0;\n }\n }\n }\n\n/*#if defined(DEBUG) || !defined(NDEBUG)\n std::cerr << __FUNCTION__ << \":\"\n << \"GJ row \" << k << \" : \" << A << \"\\n\";\n#endif*/\n }\n\n singular = false;\n return Aright;\n}\n\n}\n\n}\n\n#endif // _MATRIXINVERSE_HPP_\n", "meta": {"hexsha": "445436690dfbb834006122e9c9d7f69b657686ee", "size": 5735, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ms/feature/matrix_inverse.hpp", "max_stars_repo_name": "toppic-suite/toppic-suite", "max_stars_repo_head_hexsha": "b5f0851f437dde053ddc646f45f9f592c16503ec", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-05-23T14:37:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T23:48:38.000Z", "max_issues_repo_path": "src/ms/feature/matrix_inverse.hpp", "max_issues_repo_name": "toppic-suite/toppic-suite", "max_issues_repo_head_hexsha": "b5f0851f437dde053ddc646f45f9f592c16503ec", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2019-08-31T08:17:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-11T20:58:06.000Z", "max_forks_repo_path": "src/ms/feature/matrix_inverse.hpp", "max_forks_repo_name": "toppic-suite/toppic-suite", "max_forks_repo_head_hexsha": "b5f0851f437dde053ddc646f45f9f592c16503ec", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-04-25T01:39:38.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-20T19:25:07.000Z", "avg_line_length": 29.1116751269, "max_line_length": 114, "alphanum_fraction": 0.522929381, "num_tokens": 1428, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7634837527911056, "lm_q1q2_score": 0.6785528989817162}} {"text": "/*=============================================================================\n Copyright (c) 2010-2016 Bolero MURAKAMI\n https://github.com/bolero-MURAKAMI/Sprig\n\n Distributed under the Boost Software License, Version 1.0. (See accompanying\n file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n#ifndef SPRIG_CURVE_BEZIER_HPP\n#define SPRIG_CURVE_BEZIER_HPP\n\n#include \n\n#ifdef SPRIG_USING_PRAGMA_ONCE\n#\tpragma once\n#endif\t// #ifdef SPRIG_USING_PRAGMA_ONCE\n\n#include \n#include \n\nnamespace sprig {\n\t//\n\t// bezier\n\t//\n\ttemplate\n\tSPRIG_INLINE Point\n\tbezier(T const& t, Point const& p0, Point const& p1, Point const& p2) {\n\t\tnamespace bg = boost::geometry;\n\t\tusing sprout::detail::pow2;\n\t\treturn Point(\n\t\t\tpow2(1 - t) * bg::get<0>(p0)\n\t\t\t\t+ 2 * t * (1 - t) * bg::get<0>(p1)\n\t\t\t\t+ pow2(t) * bg::get<0>(p2)\n\t\t\t\t,\n\t\t\tpow2(1 - t) * bg::get<1>(p0)\n\t\t\t\t+ 2 * t * (1 - t) * bg::get<1>(p1)\n\t\t\t\t+ pow2(t) * bg::get<1>(p2)\n\t\t\t);\n\t}\n\ttemplate\n\tSPRIG_INLINE Point\n\tbezier(T const& t, Point const& p0, Point const& p1, Point const& p2, Point const& p3) {\n\t\tnamespace bg = boost::geometry;\n\t\tusing sprout::detail::pow2;\n\t\tusing sprout::detail::pow3;\n\t\treturn Point(\n\t\t\tpow3(1 - t) * bg::get<0>(p0)\n\t\t\t\t+ 3 * t * pow2(1 - t) * bg::get<0>(p1)\n\t\t\t\t+ 3 * pow2(t) * (1 - t) * bg::get<0>(p2)\n\t\t\t\t+ pow3(t) * bg::get<0>(p3)\n\t\t\t\t,\n\t\t\tpow3(1 - t) * bg::get<1>(p0)\n\t\t\t\t+ 3 * t * pow2(1 - t) * bg::get<1>(p1)\n\t\t\t\t+ 3 * pow2(t) * (1 - t) * bg::get<1>(p2)\n\t\t\t\t+ pow3(t) * bg::get<1>(p3)\n\t\t\t);\n\t}\n\ttemplate\n\tSPRIG_INLINE Point\n\tbezier(T const& t, Point const& p0, Point const& p1, Point const& p2, Point const& p3, Point const& p4) {\n\t\tnamespace bg = boost::geometry;\n\t\tusing sprout::detail::pow2;\n\t\tusing sprout::detail::pow3;\n\t\tusing sprout::detail::pow4;\n\t\treturn Point(\n\t\t\tpow4(1 - t) * bg::get<0>(p0)\n\t\t\t\t+ 4 * t * pow3(1 - t) * bg::get<0>(p1)\n\t\t\t\t+ 6 * pow2(t) * pow2(1 - t) * bg::get<0>(p2)\n\t\t\t\t+ 4 * pow3(t) * (1 - t) * bg::get<0>(p3)\n\t\t\t\t+ pow4(t) * bg::get<0>(p4)\n\t\t\t\t,\n\t\t\tpow4(1 - t) * bg::get<1>(p0)\n\t\t\t\t+ 4 * t * pow3(1 - t) * bg::get<1>(p1)\n\t\t\t\t+ 6 * pow2(t) * pow2(1 - t) * bg::get<1>(p2)\n\t\t\t\t+ 4 * pow3(t) * (1 - t) * bg::get<1>(p3)\n\t\t\t\t+ pow4(t) * bg::get<1>(p4)\n\t\t\t);\n\t}\n\ttemplate\n\tSPRIG_INLINE Point\n\tbezier(T const& t, Point const& p0, Point const& p1, Point const& p2, Point const& p3, Point const& p4, Point const& p5) {\n\t\tnamespace bg = boost::geometry;\n\t\tusing sprout::detail::pow2;\n\t\tusing sprout::detail::pow3;\n\t\tusing sprout::detail::pow4;\n\t\tusing sprout::detail::pow5;\n\t\treturn Point(\n\t\t\tpow5(1 - t) * bg::get<0>(p0)\n\t\t\t\t+ 5 * t * pow4(1 - t) * bg::get<0>(p1)\n\t\t\t\t+ 10 * pow2(t) * pow3(1 - t) * bg::get<0>(p2)\n\t\t\t\t+ 10 * pow3(t) * pow2(1 - t) * bg::get<0>(p3)\n\t\t\t\t+ 5 * pow4(t) * (1 - t) * bg::get<0>(p4)\n\t\t\t\t+ pow5(t) * bg::get<0>(p5)\n\t\t\t\t,\n\t\t\tpow5(1 - t) * bg::get<1>(p0)\n\t\t\t\t+ 5 * t * pow4(1 - t) * bg::get<1>(p1)\n\t\t\t\t+ 10 * pow2(t) * pow3(1 - t) * bg::get<1>(p2)\n\t\t\t\t+ 10 * pow3(t) * pow2(1 - t) * bg::get<1>(p3)\n\t\t\t\t+ 5 * pow4(t) * (1 - t) * bg::get<1>(p4)\n\t\t\t\t+ pow5(t) * bg::get<1>(p5)\n\t\t\t);\n\t}\n}\t// namespace sprig\n\n#endif\t// #ifndef SPRIG_CURVE_BEZIER_HPP\n", "meta": {"hexsha": "275d2bafd16fe02f80679516f4277670a60041d4", "size": 3352, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sprig/curve/bezier.hpp", "max_stars_repo_name": "bolero-MURAKAMI/Sprig", "max_stars_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-10-24T13:56:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-28T13:21:22.000Z", "max_issues_repo_path": "sprig/curve/bezier.hpp", "max_issues_repo_name": "bolero-MURAKAMI/Sprig", "max_issues_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sprig/curve/bezier.hpp", "max_forks_repo_name": "bolero-MURAKAMI/Sprig", "max_forks_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T03:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-28T13:21:22.000Z", "avg_line_length": 31.9238095238, "max_line_length": 123, "alphanum_fraction": 0.5438544153, "num_tokens": 1366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869884059266, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.678370049287069}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nusing namespace Eigen;\n\ndouble division(int a, int b)\n{\n if( b == 0 )\n {\n throw \"Division by zero condition!\";\n }\n return (a/b);\n}\nint main()\n{\n\n MatrixXd m(3, 3);\n\tm << 0.1, 0, 0,\n 0, 0.2, 0,\n 0, 0, 0.4;\n RowVector3d x, u;\n x << 0.5, 0.6, 0.7;\n u << 0.3, 0.2, 0.5;\n cout << m.determinant() << endl;\n cout << m.inverse() << endl;\n cout << m.row(0).size() << endl;\n\t\n cout << pow(2 * 3.14159, m.row(0).size()/2.) << endl;\n\t\n\n cout << x - u << endl;\n cout << (x - u) * m.inverse() << endl;\n\tcout << exp(-0.5 * (x - u) * m.inverse() * (x - u).transpose()) << endl;\n\t/*\n\tVectorXd r(4);\n\tr = m.row(1);\n\t\n\tdouble* data = r;\n\tcout << data << endl;\n\tcout << r <\n\nnamespace scpp::models\n{\n\ntemplate \nvoid deg2rad(T °)\n{\n deg *= M_PI / 180.;\n}\n\ntemplate \nvoid rad2deg(T &rad)\n{\n rad *= 180. / M_PI;\n}\n\ntemplate \nEigen::Matrix quaternionToVector(const Eigen::Quaternion &q)\n{\n Eigen::Matrix q_vec;\n q_vec << q.w(), q.vec();\n return q_vec;\n}\n\n// sequence x-y'-z'' is XYZ = Z''Y'X\ntemplate \nEigen::Quaternion eulerToQuaternionXYZ(const Eigen::Matrix &eta)\n{\n Eigen::Quaternion q;\n q = Eigen::AngleAxis(eta.x(), Eigen::Matrix::UnitX()) *\n Eigen::AngleAxis(eta.y(), Eigen::Matrix::UnitY()) *\n Eigen::AngleAxis(eta.z(), Eigen::Matrix::UnitZ());\n\n return q;\n}\n\ntemplate \nEigen::Matrix eulerRotationMatrixXY(const Eigen::Matrix &eta)\n{\n const T phi = eta.x();\n const T theta = eta.y();\n\n Eigen::Matrix M;\n M.row(0) << cos(theta), T(0.), sin(theta);\n M.row(1) << sin(theta) * sin(phi), cos(phi), -sin(phi) * cos(theta);\n M.row(2) << -sin(theta) * cos(phi), sin(phi), cos(phi) * cos(theta);\n\n return M;\n}\n\n// sequence x-y-z is ZYX\ntemplate \nEigen::Quaternion eulerToQuaternionZYX(const Eigen::Matrix &eta)\n{\n Eigen::Quaternion q;\n q = Eigen::AngleAxis(eta.z(), Eigen::Matrix::UnitZ()) *\n Eigen::AngleAxis(eta.y(), Eigen::Matrix::UnitY()) *\n Eigen::AngleAxis(eta.x(), Eigen::Matrix::UnitX());\n return q;\n}\n\ntemplate \nEigen::Matrix quaternionToEulerXYZ(const Eigen::Quaternion &q)\n{\n const Eigen::Matrix R = q.toRotationMatrix();\n const T phi = atan2(-R(1, 2), R(2, 2));\n const T theta = asin(R(0, 2));\n const T psi = atan2(-R(0, 1), R(0, 0));\n return Eigen::Matrix(phi, theta, psi);\n}\n\ntemplate \nEigen::Matrix quaternionToEulerZYX(const Eigen::Quaternion &q)\n{\n const Eigen::Matrix R = q.toRotationMatrix();\n const T phi = atan2(R(1, 0), R(0, 0));\n const T theta = asin(-R(2, 0));\n const T psi = atan2(R(2, 1), R(2, 2));\n return Eigen::Matrix(psi, theta, phi);\n}\n\ntemplate \nEigen::Quaternion vectorToQuaternion(const Eigen::Matrix &v)\n{\n return Eigen::Quaternion(std::sqrt(1. - v.squaredNorm()), v.x(), v.y(), v.z());\n}\n\ntemplate \nEigen::Quaternion vectorToQuaternion(const Eigen::Matrix &v)\n{\n return Eigen::Quaternion(v(3), v(0), v(1), v(2));\n}\n\ntemplate \nEigen::Matrix rotationJacobianXYZ(const Eigen::Matrix &eta)\n{\n // const T phi = eta.x();\n const T theta = eta.y();\n const T psi = eta.z();\n\n Eigen::Matrix M;\n M.row(0) << cos(psi), -sin(psi), T(0.);\n M.row(1) << cos(theta) * sin(psi), cos(theta) * cos(psi), T(0.);\n M.row(2) << -sin(theta) * cos(psi), sin(theta) * sin(psi), cos(theta);\n\n return M / cos(theta);\n}\n\ntemplate \nEigen::Matrix rotationJacobianXY(const Eigen::Matrix &eta)\n{\n const T theta = eta.y();\n\n Eigen::Matrix M;\n M.row(0) << cos(theta), sin(theta);\n M.row(1) << -sin(theta), cos(theta);\n\n return M;\n}\n\ntemplate \nEigen::Matrix omegaMatrix(const Eigen::Matrix &w)\n{\n Eigen::Matrix omega;\n omega << T(0.), -w(0), -w(1), -w(2),\n w(0), T(0.), w(2), -w(1),\n w(1), -w(2), T(0.), w(0),\n w(2), w(1), -w(0), T(0.);\n\n return omega;\n}\n\ntemplate \nEigen::Matrix omegaMatrixReduced(const Eigen::Matrix &q)\n{\n Eigen::Matrix omega;\n const T qw = sqrt(1. - q.squaredNorm());\n omega << qw, -q(2), q(1),\n q(2), qw, -q(0),\n -q(1), q(0), qw;\n\n return omega;\n}\n\n} // namespace scpp::models", "meta": {"hexsha": "fad5c8e694fb0b6bb7454eb0b303efcee4840919", "size": 3887, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "scpp_models/include/common.hpp", "max_stars_repo_name": "Zentrik/SCpp", "max_stars_repo_head_hexsha": "92176e57747ff5629a4ab3eeb3a86b3de21aaa48", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 110.0, "max_stars_repo_stars_event_min_datetime": "2019-01-30T05:39:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T11:31:27.000Z", "max_issues_repo_path": "scpp_models/include/common.hpp", "max_issues_repo_name": "Zentrik/SCpp", "max_issues_repo_head_hexsha": "92176e57747ff5629a4ab3eeb3a86b3de21aaa48", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2019-04-02T09:46:26.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-16T13:03:16.000Z", "max_forks_repo_path": "scpp_models/include/common.hpp", "max_forks_repo_name": "Zentrik/SCpp", "max_forks_repo_head_hexsha": "92176e57747ff5629a4ab3eeb3a86b3de21aaa48", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 32.0, "max_forks_repo_forks_event_min_datetime": "2019-07-11T06:58:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:05:48.000Z", "avg_line_length": 26.2635135135, "max_line_length": 86, "alphanum_fraction": 0.573964497, "num_tokens": 1389, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206791658465, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6782556912666926}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace Eigen;\nusing namespace std;\n\nconst double eps = 0.0001; // 用于浮点数比较大小\nconst int sampleNum = 5000; // 样本数目,100\nconst int attriNum = 768; // 一个样本特征数目,2\n\n\n/*\n// 用于导入数据 [这个函数本应该从LoadData中调用的,但是我没成功...]\ndouble** load(string filename, int m, int n){\n // 初始化数组\n double** ans = (double **)malloc(m * sizeof(double *));\n for(int i=0;i loadEigen(string filename, int m ,int n){\n Matrix ans = MatrixXd::Zero(m, n);;\n ifstream inFile(filename, ios::in);\n\tstring lineStr; //每一行的结果\n for(int i=0;i theta_gradient(MatrixXd X_bar ,Matrix Y,Matrix beta,double alpha){\n Matrix ans = alpha * beta;\n // ans.fill(0);\n for(int i=0;i predict(MatrixXd X_bar,Matrix beta){\n Matrix y_pred;\n y_pred.fill(0);\n for(int i=0;i0.5)\n y_pred(i,0)= 1; // 否则默认是0\n }\n return y_pred;\n}\n\ndouble accuracy(Matrix y_pred, Matrix y){\n int num = 0;\n for(int i=0;i maps\r\n intervals of int to ints. \r\n\r\n If we insert a value pair (discrete_interval(2,6), 1) into the interval_map, it\r\n increases the content of all value pairs in the map by 1, if their interval\r\n part overlaps with discrete_interval(2,6).\r\n\r\n \\include overlap_counter_/overlap_counter.cpp\r\n*/\r\n//[example_overlap_counter\r\n#include \r\n#include \r\n\r\nusing namespace std;\r\nusing namespace boost::icl;\r\n\r\n\r\n/* The most simple example of an interval_map is an overlap counter.\r\n If intervals are added that are associated with the value 1,\r\n all overlaps of added intervals are counted as a result in the\r\n associated values. \r\n*/\r\ntypedef interval_map OverlapCounterT;\r\n\r\nvoid print_overlaps(const OverlapCounterT& counter)\r\n{\r\n for(OverlapCounterT::const_iterator it = counter.begin(); it != counter.end(); it++)\r\n {\r\n discrete_interval itv = (*it).first;\r\n int overlaps_count = (*it).second;\r\n if(overlaps_count == 1)\r\n cout << \"in interval \" << itv << \" intervals do not overlap\" << endl;\r\n else\r\n cout << \"in interval \" << itv << \": \"<< overlaps_count << \" intervals overlap\" << endl;\r\n }\r\n}\r\n\r\nvoid overlap_counter()\r\n{\r\n OverlapCounterT overlap_counter;\r\n discrete_interval inter_val;\r\n\r\n inter_val = discrete_interval::right_open(4,8);\r\n cout << \"-- adding \" << inter_val << \" -----------------------------------------\" << endl;\r\n overlap_counter += make_pair(inter_val, 1);\r\n print_overlaps(overlap_counter);\r\n cout << \"-----------------------------------------------------------\" << endl;\r\n\r\n inter_val = discrete_interval::right_open(6,9);\r\n cout << \"-- adding \" << inter_val << \" -----------------------------------------\" << endl;\r\n overlap_counter += make_pair(inter_val, 1);\r\n print_overlaps(overlap_counter);\r\n cout << \"-----------------------------------------------------------\" << endl;\r\n\r\n inter_val = discrete_interval::right_open(1,9);\r\n cout << \"-- adding \" << inter_val << \" -----------------------------------------\" << endl;\r\n overlap_counter += make_pair(inter_val, 1);\r\n print_overlaps(overlap_counter);\r\n cout << \"-----------------------------------------------------------\" << endl;\r\n \r\n}\r\n\r\nint main()\r\n{\r\n cout << \">>Interval Container Library: Sample overlap_counter.cpp <<\\n\";\r\n cout << \"-----------------------------------------------------------\\n\";\r\n overlap_counter();\r\n return 0;\r\n}\r\n\r\n// Program output:\r\n\r\n// >>Interval Container Library: Sample overlap_counter.cpp <<\r\n// -----------------------------------------------------------\r\n// -- adding [4,8) -----------------------------------------\r\n// in interval [4,8) intervals do not overlap\r\n// -----------------------------------------------------------\r\n// -- adding [6,9) -----------------------------------------\r\n// in interval [4,6) intervals do not overlap\r\n// in interval [6,8): 2 intervals overlap\r\n// in interval [8,9) intervals do not overlap\r\n// -----------------------------------------------------------\r\n// -- adding [1,9) -----------------------------------------\r\n// in interval [1,4) intervals do not overlap\r\n// in interval [4,6): 2 intervals overlap\r\n// in interval [6,8): 3 intervals overlap\r\n// in interval [8,9): 2 intervals overlap\r\n// -----------------------------------------------------------\r\n//]\r\n", "meta": {"hexsha": "87dfb6ce92ce81d6b190e1ca89a873441c29a747", "size": 4508, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/icl/example/overlap_counter_/overlap_counter.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/boost/libs/icl/example/overlap_counter_/overlap_counter.cpp", "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/boost/libs/icl/example/overlap_counter_/overlap_counter.cpp", "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 41.3577981651, "max_line_length": 100, "alphanum_fraction": 0.5139751553, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916240341031, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6780288596970659}} {"text": "// Software License for MTL\n//\n// Copyright (c) 2007 The Trustees of Indiana University.\n// 2008 Dresden University of Technology and the Trustees of Indiana University.\n// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n//\n// This file is part of the Matrix Template Library\n//\n// See also license.mtl.txt in the distribution.\n\n#include \n#include \n#include \n\n\nusing namespace std;\n\n\ndouble f(double) { /* cout << \"double\\n\"; */ return 1.0; }\ncomplex f(complex) \n{ \n //cout << \"complex\\n\"; \n return complex(1.0, -1.0); \n}\n\n \nint main(int, char**)\n{\n using namespace mtl; using mtl::io::tout;\n unsigned size=4, row= size+1, col=size;\n\n double tol(0.00001);\n dense_vector vec(size), vec1(size);\n dense2D A(row, col), Q(row, row), R(row, col), A_test(row, col),\n\t A_t(col, row), Q_t(col, col), R_t(col, row), A_t_test(col, row);\n dense2D > dz(row, col), Qz(row, row), Rz(row, col);\n dense2D > dc(size, size);\n compressed2D Ac(size, size), Qc(size, size), Rc(size, size), A_testc(size, size) ;\n A= 0; \n\n A[0][0]=1; A[0][1]=1; A[0][2]=1;\n A[1][0]=3; A[1][1]=-1; A[1][2]=-2;\n A[2][0]=1; A[2][1]=7; A[2][2]=1;\n A[3][3]=-10; A[4][0]=4; A[4][2]=3;\n tout<<\"A=\\n\"<< A <<\"\\n\";\n laplacian_setup(Ac, 2,2);\n\n \n tout<<\"START-----dense2d---------row > col\\n\";\n \n dense2D A1(A[iall][iall]), A2(A);\n boost::tie(Q, R)= qr(A1);\n tout<<\"R=\\n\"<< R <<\"\\n\";\n tout<<\"Q=\\n\"<< Q <<\"\\n\";\n A_test= Q*R-A2;\n tout<<\"Q*R=\\n\"<< Q*R <<\"\\n\";\n\t\n tout<< \"one_norm(Rest A)=\" << one_norm(A_test) << \"\\n\";\n MTL_THROW_IF(one_norm(A_test) > tol, mtl::logic_error(\"wrong QR decomposition of matrix A\"));\n\n\t\n tout<<\"START------dense2d-------row < col\\n\";\n\n A_t= trans(A);\n boost::tie(Q_t, R_t)= qr(A_t);\n tout<<\"R_t=\\n\"<< R_t <<\"\\n\";\n tout<<\"Q_t=\\n\"<< Q_t <<\"\\n\";\n A_t_test= Q_t*R_t-A_t;\n tout<<\"Q_t*R_t=\\n\"<< Q_t*R_t <<\"\\n\";\n\t\t\t\n tout<< \"one_norm(Rest A')=\" << one_norm(A_t_test) << \"\\n\";\n MTL_THROW_IF(one_norm(A_t_test) > tol, mtl::logic_error(\"wrong QR decomposition of matrix trans(A)\"));\n\t\n tout<<\"START-------compressed2d-------row > col\\n\";\n#if 1\n boost::tie(Qc, Rc)= qr(Ac);\n tout<<\"R=\\n\"<< Rc <<\"\\n\";\n tout<<\"Q=\\n\"<< Qc <<\"\\n\";\n A_testc= Qc*Rc-Ac;\n tout<<\"Q*R=\\n\"<< Qc*Rc <<\"\\n\";\n tout<<\"A=\\n\"<< Ac <<\"\\n\";\n\t\n tout<< \"one_norm(Rest A)=\" << one_norm(A_testc) << \"\\n\";\n MTL_THROW_IF(one_norm(A_testc) > tol, mtl::logic_error(\"wrong QR decomposition of matrix A\")); \n#endif\n\n#if 0\n dz[0][0]=complex(1.0, 0.0);\n dz[0][1]=complex(1.0, 0.0);\n dz[0][2]=complex(1,0);\n dz[1][0]=complex(1,0);\n dz[1][1]=complex(-1,0);\n dz[1][2]=complex(-2,0);\n dz[2][0]=complex(1,0);\n dz[2][1]=complex(-2,0);\n dz[2][2]=complex(1,0);\n dz[3][3]=complex(-10,0);\n tout<<\"MAtrix complex=\\n\"<< dz <<\"\\n\";\n\n tout<<\"START-----complex---------\"<< dz[0][0] << \"\\n\";\n //\n boost::tie(Qz, Rz)= qr(dz);\n // Rz= qr_zerl(dz).second;\n // tout<<\"MAtrix R=\"<< Rz <<\"\\n\";\n // tout<<\"MAtrix Q=\"<< Qz <<\"\\n\";\n // tout<<\"MAtrix A=Q*R--outside\"<< Qz*Rz <<\"\\n\";\n#endif\n return 0;\n}\n\n", "meta": {"hexsha": "702ddeb88523a452464ab21b0d272fa03ca199f3", "size": 3608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/test/qr_test.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/test/qr_test.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/test/qr_test.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 31.9292035398, "max_line_length": 126, "alphanum_fraction": 0.5268847007, "num_tokens": 1245, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737806, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6780288399789063}} {"text": "#pragma once\n\n#include \n#include \n#include \n#include \"constants.hpp\"\n\nnamespace vgl {\ntemplate \nvoid print_quat(Eigen::Quaternion const& quat) {\n std::cout << quat.w() << \" \" << quat.x() << \" \" << quat.y() << \" \" << quat.z() << std::endl;\n}\n\ntemplate \nEigen::Matrix quat_to_euler_angles(Eigen::Quaternion const& q) {\n return 180.0 / math::pi *\n Eigen::Matrix(\n std::atan2(2.0 * (q.w() * q.x() + q.y() * q.z()), 1.0 - 2.0 * (q.x() * q.x() + q.y() * q.y())),\n std::asin(2.0 * (q.w() * q.y() - q.x() * q.z())),\n std::atan2(2.0 * (q.w() * q.z() + q.x() * q.y()), 1.0 - 2.0 * (q.y() * q.y() + q.z() * q.z())));\n}\n\nstruct Pose {\n Pose() noexcept;\n Pose(Eigen::Quaterniond const& R, Eigen::Vector3d const& t) noexcept;\n Pose(Eigen::Matrix4d const& T) noexcept;\n Pose inverse() const;\n Eigen::Matrix4d to_matrix() const;\n void from_matrix(Eigen::Matrix4d const& T);\n void print();\n\n Eigen::Quaterniond rotation = Eigen::Quaterniond(1.0, 0.0, 0.0, 0.0);\n Eigen::Vector3d translation = Eigen::Vector3d(0.0, 0.0, 0.0);\n};\n} // namespace vgl\n", "meta": {"hexsha": "28b40865f81ab21e5818f45c783802fe565c53c0", "size": 1209, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/vgl/math/pose.hpp", "max_stars_repo_name": "alexsr/vgl", "max_stars_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-18T18:27:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-18T18:27:19.000Z", "max_issues_repo_path": "src/vgl/math/pose.hpp", "max_issues_repo_name": "alexsr/vgl", "max_issues_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vgl/math/pose.hpp", "max_forks_repo_name": "alexsr/vgl", "max_forks_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.5833333333, "max_line_length": 111, "alphanum_fraction": 0.5483870968, "num_tokens": 414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7853085708384736, "lm_q1q2_score": 0.6780288368232844}} {"text": "#include \n#include \n#include \n\n#include \n#include \n#include \n\nint main() {\n double a11, a12, a13, a21, a22, a23, a31, a32, a33;\n Eigen::Matrix3d Im;\n\n std::cin >> a11 >> a12 >> a13\n >> a21 >> a22 >> a23\n >> a31 >> a32 >> a33;\n\n if (std::cin.fail()) {\n std::cerr << \"Invalid input. Expected 3x3 matrix in the form a11 a12 a13 a21 ... a33, separated by whitespace.\" << std::endl;\n abort();\n }\n\n Im << a11, a12, a13,\n a21, a22, a23,\n a31, a32, a33;\n\n // The inertia tensor should be a real symmetric matrix; real symmetric\n // matrices are self-adjoint.\n // A real symmetric n-dimensional matrix always possesses n real\n // mutually orthogonal eigenvectors/eigenvalues.\n // http://farside.ph.utexas.edu/teaching/336k/Newtonhtml/node66.html\n Eigen::SelfAdjointEigenSolver eigenSolver(Im);\n\n if (eigenSolver.info() != Eigen::Success) {\n std::cerr << \"Failed to solve for principal axes of rotation. Invalid inertia tensor?\" << std::endl;\n abort();\n }\n\n // http://farside.ph.utexas.edu/teaching/336k/Newtonhtml/node67.html\n Eigen::Vector3d eigenvalues(eigenSolver.eigenvalues());\n std::cout << eigenvalues[0] << \" \"\n << eigenvalues[1] << \" \"\n << eigenvalues[2] << std::endl;\n Eigen::Quaterniond q(eigenSolver.eigenvectors());\n q.normalize();\n std::cout << q.w() << \" \"\n << q.x() << \" \"\n << q.y() << \" \"\n << q.z() << \" \" << std::endl;\n}\n", "meta": {"hexsha": "b02aeceb15e617bd5a21533982d641412026ce64", "size": 1610, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fishbowl/body-frame-calc/main.cpp", "max_stars_repo_name": "cuauv/software", "max_stars_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 70.0, "max_stars_repo_stars_event_min_datetime": "2015-11-16T18:04:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-05T09:04:02.000Z", "max_issues_repo_path": "fishbowl/body-frame-calc/main.cpp", "max_issues_repo_name": "cuauv/software", "max_issues_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-03T05:13:19.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-03T06:19:39.000Z", "max_forks_repo_path": "fishbowl/body-frame-calc/main.cpp", "max_forks_repo_name": "cuauv/software", "max_forks_repo_head_hexsha": "5ad4d52d603f81a7f254f365d9b0fe636d03a260", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2015-12-15T17:29:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T14:15:12.000Z", "avg_line_length": 32.2, "max_line_length": 133, "alphanum_fraction": 0.5745341615, "num_tokens": 459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242074, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6779568775185626}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace Eigen;\n\nnamespace robot_kf {\n\nKalmanFilter::KalmanFilter(void)\n : x_(Vector3d::Zero())\n , cov_x_(9999 * Matrix3d::Identity())\n , A_(Matrix3d::Identity())\n , Hgps_((Matrix() << 1, 0, 0, 0, 1, 0).finished())\n , Hcomp_((Matrix() << 0, 0, 1).finished())\n{}\n\nKalmanFilter::~KalmanFilter(void)\n{}\n\nVector3d KalmanFilter::getState(void) const\n{\n return x_;\n}\n\nMatrix3d KalmanFilter::getCovariance(void) const\n{\n return cov_x_;\n}\n\nvoid KalmanFilter::update_encoders(Vector2d enc, Matrix2d cov_enc, double separation)\n{\n /* This is non-linear in theta because of the x and y elements:\n * x = (r + l)/2 * cos(theta + (r - l) / (2s))\n * y = (r + l)/2 * sin(theta + (r - l) / (2s))\n * theta = (r - l)/(2s)\n * We can linearize this around the current state estimate using the\n * Jacobians A = Jac(f, x) and W = Jac(f, u).\n */\n double const dlinear = (enc[1] + enc[0]) / 2;\n double const dtheta = (enc[1] - enc[0]) / separation;\n double const theta_halfway = x_[2] + dtheta / 2;\n\n Matrix3d const A = (Matrix3d() <<\n 1, 0, -dlinear * sin(theta_halfway),\n 0, 1, +dlinear * cos(theta_halfway),\n 0, 0, 1).finished();\n Matrix const W = (Matrix() <<\n +dlinear * sin(theta_halfway) + 0.5 * cos(theta_halfway),\n -dlinear * sin(theta_halfway) + 0.5 * cos(theta_halfway),\n -dlinear * cos(theta_halfway) + 0.5 * sin(theta_halfway),\n +dlinear * cos(theta_halfway) + 0.5 * sin(theta_halfway),\n -1.0 / separation,\n +1.0 / separation).finished();\n\n x_ += (Vector3d() <<\n dlinear * cos(theta_halfway),\n dlinear * sin(theta_halfway),\n // 0).finished();\n dtheta).finished();\n cov_x_ = A * cov_x_ * A.transpose() + W * cov_enc * W.transpose();\n normalize_yaw();\n}\n\nvoid KalmanFilter::update_gps(Vector2d gps, Matrix2d cov_gps)\n{\n measure(gps, cov_gps, Hgps_);\n}\n\nvoid KalmanFilter::update_compass(double compass, double cov_compass)\n{\n // Renormalize the compass heading so the filter behaves correctly when\n // crossing +/-pi. This prevents the heading from slowly drifting the \"long\n // way\" around the circle (i.e. through 0 instead of +/-pi).\n if (x_[2] - compass > M_PI) {\n compass = compass + 2 * M_PI;\n } else if (x_[2] - compass < -M_PI) {\n compass = compass - 2 * M_PI;\n }\n\n Matrix mat_compass, mat_cov_compass;\n mat_compass << compass;\n mat_cov_compass << cov_compass;\n\n measure(mat_compass, mat_cov_compass, Hcomp_);\n normalize_yaw();\n} \n\ntemplate \nvoid KalmanFilter::predict(Matrix u, Matrix cov_process,\n Matrix A, Matrix B)\n{\n x_ = A * x_ + B * u;\n cov_x_ = A * cov_x_ * A.transpose() + cov_process;\n}\n\ntemplate \nvoid KalmanFilter::measure(Matrix z, Matrix cov_z,\n Matrix H)\n{\n Matrix const K = cov_x_ * H.transpose() * (H * cov_x_\n * H.transpose() + cov_z).inverse();\n x_ = x_ + K * (z - H * x_);\n cov_x_ = (Matrix3d::Identity() - K * H) * cov_x_;\n}\n\nvoid KalmanFilter::normalize_yaw(void) {\n x_[2] = angles::normalize_angle(x_[2]);\n}\n\n};\n", "meta": {"hexsha": "73534674f8927c3d49c2c24a1fb06767f0d1dd21", "size": 3538, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/robot_kf.cc", "max_stars_repo_name": "mkoval/robot_kf", "max_stars_repo_head_hexsha": "985110b2dff1105519e9d3d8d2b9e9d30d270f1f", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2018-05-24T07:44:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:23:19.000Z", "max_issues_repo_path": "src/robot_kf.cc", "max_issues_repo_name": "mkoval/robot_kf", "max_issues_repo_head_hexsha": "985110b2dff1105519e9d3d8d2b9e9d30d270f1f", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/robot_kf.cc", "max_forks_repo_name": "mkoval/robot_kf", "max_forks_repo_head_hexsha": "985110b2dff1105519e9d3d8d2b9e9d30d270f1f", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-04-19T07:57:43.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-29T06:49:40.000Z", "avg_line_length": 30.5, "max_line_length": 85, "alphanum_fraction": 0.5952515546, "num_tokens": 1099, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6779220018052418}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nigl::AABB tree;\n\nfloat icp_step(Eigen::MatrixXd *Vmov, Eigen::MatrixXd Vref, Eigen::MatrixXi Fref)\n{\n using namespace Eigen;\n using namespace std;\n using namespace igl;\n\n int i;\n float dist = 0;\n\n // compute closest points\n VectorXd sqrD;\n VectorXi I;\n MatrixXd Vout;\n\n igl::point_mesh_squared_distance(*Vmov, Vref, Fref, sqrD, I, Vout);\n\n // compute rotation and translation\n MatrixXd C = Matrix3d::Constant(0);\n VectorXd oout = Vout.colwise().sum()/Vout.rows();\n VectorXd omov = (*Vmov).colwise().sum()/(*Vmov).rows();\n\n for(i=0;i<(*Vmov).rows();i++)\n C += ((*Vmov).row(i) - omov.transpose()).transpose()\n * (Vout.row(i) - oout.transpose());\n\n JacobiSVD svd(C, ComputeThinU|ComputeThinV);\n Matrix3d U = svd.matrixU();\n Matrix3d V = svd.matrixV().transpose();\n\n MatrixXd R = U*V;\n MatrixXd t = omov - R*oout;\n\n // apply rotation and translation\n (*Vmov)*=R;\n (*Vmov).transpose().colwise() -= t.col(0);\n\n // check convergence\n // angle_dist = arccos((trace(P*Q')-1)/2), P, Q rotation matrices\n // (here, Q=I)\n // http://www.boris-belousov.net/2016/12/01/quat-dist/\n dist = acos((R.trace()-1)/2.0);\n dist = dist + t.norm();\n\n return dist;\n}\n \nint icp(Eigen::MatrixXd Vref, Eigen::MatrixXi Fref,\n Eigen::MatrixXd *Vmov, Eigen::MatrixXi Fmov,\n float *diff)\n{\n using namespace Eigen;\n using namespace std;\n using namespace igl;\n\n int i;\n float dist;\n int maxiter = 100;\n float tol = 1e-6;\n\n // init distance AABB tree\n tree.init(Vref, Fref);\n\n float dist0=-1;\n\n for(i=0;i\n#include \n\n#include \n\nusing namespace std;\nusing namespace NTL;\n\nvoid usage(char *progname) {\n\tcout << \"This program returns the message m corresponding to \"\n\t\t\"two ciphertexts c1 = m^e1 (mod n), c2 = m^e2 (mod n).\"\n\t\t<< endl;\n\tcout << \"Usage: \" << progname << \" n e1 c1 e2 c2\" << endl;\n}\n\nint main(int argc, char *argv[]) {\n\tif (argc != 6) { usage(argv[0]); return 3; }\n\n\tZZ n, e1, c1, e2, c2, m, u, v, g;\n\tn = conv(argv[1]);\n\te1 = conv(argv[2]);\n\tc1 = conv(argv[3]);\n\te2 = conv(argv[4]);\n\tc2 = conv(argv[5]);\n\n\t// g = u*e1 + v*e2\n\tXGCD(g, u, v, e1, e2);\n\n\tif(g != 1) { throw domain_error(\"e1 and e2 aren't coprime.\"); }\n\n\tif(u < 0) {\n\t\tInvMod(c1, c1, n);\n\t\tu *= -1;\n\t}\n\tif(v < 0) {\n\t\tInvMod(c2, c2, n);\n\t\tv *= -1;\n\t}\n\n\tMulMod(m, PowerMod(c1, u, n), PowerMod(c2, v, n), n);\n\n\tcout << m << endl;\n}\n", "meta": {"hexsha": "31022a700c4f60c1e1b5ef0a1bfd0908792b062f", "size": 859, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "common_modulus_external.cpp", "max_stars_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_stars_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "common_modulus_external.cpp", "max_issues_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_issues_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common_modulus_external.cpp", "max_forks_repo_name": "tacopeland/forty-years-of-RSA-attacks", "max_forks_repo_head_hexsha": "d556e20880525cfa4666e23c6b50f0906d67fdce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5227272727, "max_line_length": 64, "alphanum_fraction": 0.5483119907, "num_tokens": 346, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6779219997419054}} {"text": "#ifndef UCB_MULTIARM_BANDIT_HPP\n#define UCB_MULTIARM_BANDIT_HPP\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace smmap\n{\n template \n class UCB1Normal\n {\n public:\n UCB1Normal(size_t num_bandits = 1)\n : num_arms_(num_bandits)\n , total_reward_(num_arms_, 0.0)\n , sum_of_squared_reward_(num_arms_, 0.0)\n , num_pulls_(num_arms_, 0)\n , total_pulls_(0)\n {}\n\n ssize_t selectArmToPull(Generator& generator) const\n {\n (void)generator;\n if (total_pulls_ == 0UL)\n {\n return 0L;\n }\n\n const double explore_threshold = 8.0 * std::log((double)total_pulls_ + 1.0);\n double highest_ucb = -std::numeric_limits::infinity();\n ssize_t best_arm = -1;\n size_t lowest_num_exploration_pulls = (size_t)(-1);\n\n for (size_t arm_ind = 0; arm_ind < num_arms_; arm_ind++)\n {\n if (num_pulls_[arm_ind] < explore_threshold)\n {\n if (num_pulls_[arm_ind] < lowest_num_exploration_pulls)\n {\n best_arm = arm_ind;\n lowest_num_exploration_pulls = num_pulls_[arm_ind];\n }\n }\n }\n\n // If we found an arm that qualifies for exploration, pull that arm\n if (best_arm != -1)\n {\n return best_arm;\n }\n\n for (size_t arm_ind = 0; arm_ind < num_arms_; arm_ind++)\n {\n assert(num_pulls_[arm_ind] > 1);\n\n const double average_reward = total_reward_[arm_ind] / (double)num_pulls_[arm_ind];\n const double term1_numer = (sum_of_squared_reward_[arm_ind] - (double)num_pulls_[arm_ind] * average_reward * average_reward);\n const double term1_denom = (double)(num_pulls_[arm_ind] - 1);\n const double term1 = std::abs(term1_numer)/term1_denom;\n const double term2 = std::log((double)total_pulls_) / (double)num_pulls_[arm_ind];\n const double ucb = average_reward + std::sqrt(16.0 * term1 * term2);\n\n assert(std::isfinite(ucb));\n\n if (ucb > highest_ucb)\n {\n highest_ucb = ucb;\n best_arm = (ssize_t)arm_ind;\n }\n }\n\n assert(best_arm >= 0);\n return best_arm;\n }\n\n bool generateAllModelActions() const\n {\n return false;\n }\n\n void updateArms(const ssize_t arm_pulled, const double reward)\n {\n total_reward_[(size_t)arm_pulled] += reward;\n sum_of_squared_reward_[(size_t)arm_pulled] += reward * reward;\n num_pulls_[(size_t)arm_pulled]++;\n total_pulls_++;\n }\n\n Eigen::VectorXd getMean() const\n {\n Eigen::VectorXd mean((ssize_t)num_arms_);\n for (size_t arm_ind = 0; arm_ind < num_arms_; arm_ind++)\n {\n mean((ssize_t)arm_ind) = total_reward_[arm_ind] / (double)num_pulls_[arm_ind];\n }\n return mean;\n }\n\n Eigen::VectorXd getUCB() const\n {\n Eigen::VectorXd ucb((ssize_t)num_arms_);\n for (size_t arm_ind = 0; arm_ind < num_arms_; arm_ind++)\n {\n const double average_reward = total_reward_[arm_ind] / (double)num_pulls_[arm_ind];\n const double term1_numer = (sum_of_squared_reward_[arm_ind] - (double)num_pulls_[arm_ind] * average_reward * average_reward);\n const double term1_denom = (double)(num_pulls_[arm_ind] - 1);\n const double term1 = std::abs(term1_numer)/term1_denom;\n const double term2 = std::log((double)total_pulls_) / (double)num_pulls_[arm_ind];\n ucb((ssize_t)arm_ind) = average_reward + std::sqrt(16.0 * term1 * term2);\n }\n return ucb;\n }\n\n private:\n size_t num_arms_;\n\n std::vector total_reward_;\n std::vector sum_of_squared_reward_;\n std::vector num_pulls_;\n size_t total_pulls_;\n };\n}\n\n#endif // UCB_MULTIARM_BANDIT_HPP\n", "meta": {"hexsha": "c07c1e7a3848f54441c1042be895917c48026e35", "size": 4784, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "smmap/include/smmap/ucb_multiarm_bandit.hpp", "max_stars_repo_name": "UM-ARM-Lab/mab_ms", "max_stars_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-08-20T12:12:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-06T09:43:27.000Z", "max_issues_repo_path": "smmap/include/smmap/ucb_multiarm_bandit.hpp", "max_issues_repo_name": "UM-ARM-Lab/mab_ms", "max_issues_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "smmap/include/smmap/ucb_multiarm_bandit.hpp", "max_forks_repo_name": "UM-ARM-Lab/mab_ms", "max_forks_repo_head_hexsha": "f199f05b88060182cfbb47706bd1ff3479032c43", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-31T03:12:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T03:12:23.000Z", "avg_line_length": 36.8, "max_line_length": 145, "alphanum_fraction": 0.5052257525, "num_tokens": 1076, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6779219973745209}} {"text": "/*\n * This file is part of the Visual Computing Library (VCL) release under the\n * MIT license.\n *\n * Copyright (c) 2018 Basil Fierz\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n#include \"problems.h\"\n\n// C++ standard library\n#include \n\n// Eigen library\n#include \n\n// VCL\n#include \n\nvoid createRandomProblems(\n\tsize_t nr_problems,\n\tVcl::Core::InterleavedArray& F,\n\tVcl::Core::InterleavedArray* R)\n{\n\t// Random number generator\n\tstd::mt19937_64 rng;\n\tstd::uniform_real_distribution d;\n\n\tfor (int i = 0; i < (int)nr_problems; i++)\n\t{\n\t\t// Rest-state\n\t\tEigen::Matrix3f M;\n\t\tM << d(rng), d(rng), d(rng),\n\t\t\td(rng), d(rng), d(rng),\n\t\t\td(rng), d(rng), d(rng);\n\t\tF.at(i) = M;\n\n\t\tif (R)\n\t\t{\n\t\t\tEigen::Matrix3f Rot;\n\t\t\tVcl::Mathematics::PolarDecomposition(M, Rot, nullptr);\n\t\t\tR->template at(i) = Rot;\n\t\t}\n\t}\n}\n\nvoid createSymmetricProblems(\n\tsize_t nr_problems,\n\tVcl::Core::InterleavedArray& F,\n\tVcl::Core::InterleavedArray* R)\n{\n\t// Random number generator\n\tstd::mt19937_64 rng;\n\tstd::uniform_real_distribution d;\n\n\tfor (int i = 0; i < (int)nr_problems; i++)\n\t{\n\t\t// Rest-state\n\t\tEigen::Matrix3f M;\n\t\tM << d(rng), d(rng), d(rng),\n\t\t\td(rng), d(rng), d(rng),\n\t\t\td(rng), d(rng), d(rng);\n\t\tEigen::Matrix3f MtM = M.transpose() * M;\n\t\tF.at(i) = MtM;\n\n\t\tif (R)\n\t\t{\n\t\t\tEigen::Matrix3f Rot;\n\t\t\tVcl::Mathematics::PolarDecomposition(MtM, Rot, nullptr);\n\t\t\tR->template at(i) = Rot;\n\t\t}\n\t}\n}\n\nvoid createRotationProblems(\n\tsize_t nr_problems,\n\tfloat max_angle,\n\tfloat max_compression,\n\tVcl::Core::InterleavedArray& F,\n\tVcl::Core::InterleavedArray* R)\n{\n\t// Random number generator\n\tstd::mt19937_64 rng;\n\tstd::uniform_real_distribution d;\n\tstd::uniform_real_distribution a{ -max_angle, max_angle };\n\n\tfor (int i = 0; i < (int)nr_problems; i++)\n\t{\n\t\t// Rest-state\n\t\tEigen::Matrix3f X0;\n\t\tX0 << d(rng), d(rng), d(rng),\n\t\t\td(rng), d(rng), d(rng),\n\t\t\td(rng), d(rng), d(rng);\n\n\t\t// Rotation angle\n\t\tfloat angle = a(rng);\n\n\t\t// Rotation axis\n\t\tEigen::Matrix rot_vec;\n\t\trot_vec << d(rng), d(rng), d(rng);\n\t\trot_vec.normalize();\n\n\t\t// Rotation matrix\n\t\tEigen::Matrix3f Rot = Eigen::AngleAxis{ angle, rot_vec }.toRotationMatrix();\n\t\tif (R)\n\t\t\tR->template at(i) = Rot;\n\n\t\tif (max_compression > 0)\n\t\t{\n\t\t\tEigen::Matrix scaling;\n\t\t\tscaling << (1.0f - max_compression * d(rng)), (1.0f - max_compression * d(rng)), (1.0f - max_compression * d(rng));\n\n\t\t\tEigen::JacobiSVD svd{ Rot, Eigen::ComputeFullU | Eigen::ComputeFullV };\n\t\t\tRot *= svd.matrixV() * scaling.asDiagonal() * svd.matrixV().transpose();\n\t\t}\n\n\t\tEigen::Matrix3f X = Rot * X0;\n\t\tF.at(i) = X * X0.inverse();\n\t}\n}\n\nvoid computeEigenReferenceSolution(\n\tsize_t nr_problems,\n\tconst Vcl::Core::InterleavedArray& ATA,\n\tVcl::Core::InterleavedArray& U,\n\tVcl::Core::InterleavedArray& S)\n{\n\t// Compute reference using Eigen\n\tfor (int i = 0; i < static_cast(nr_problems); i++)\n\t{\n\t\tVcl::Matrix3f A = ATA.at(i);\n\n\t\tEigen::SelfAdjointEigenSolver solver;\n\t\tsolver.compute(A, Eigen::ComputeEigenvectors);\n\n\t\tU.at(i) = solver.eigenvectors();\n\t\tS.at(i) = solver.eigenvalues();\n\t}\n}\n", "meta": {"hexsha": "57b833375c3ca620b95b254b4e6f162db5a499eb", "size": 4392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/benchmarks/vcl.math/problems.cpp", "max_stars_repo_name": "bfierz/vcl", "max_stars_repo_head_hexsha": "6ef8d446b6a2f46543a5b3f9f76cad0d8f691969", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2015-05-15T09:14:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T13:00:17.000Z", "max_issues_repo_path": "src/benchmarks/vcl.math/problems.cpp", "max_issues_repo_name": "bfierz/vcl", "max_issues_repo_head_hexsha": "6ef8d446b6a2f46543a5b3f9f76cad0d8f691969", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 54.0, "max_issues_repo_issues_event_min_datetime": "2015-05-14T09:21:51.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-28T06:09:06.000Z", "max_forks_repo_path": "src/benchmarks/vcl.math/problems.cpp", "max_forks_repo_name": "bfierz/vcl", "max_forks_repo_head_hexsha": "6ef8d446b6a2f46543a5b3f9f76cad0d8f691969", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-04-18T06:16:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-16T08:00:12.000Z", "avg_line_length": 28.1538461538, "max_line_length": 118, "alphanum_fraction": 0.6739526412, "num_tokens": 1365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.822189123986562, "lm_q1q2_score": 0.6778636361002347}} {"text": "/**\n * @file\n * @brief NPDE homework \"Handling degrees of freedom (DOFs) in LehrFEM++\"\n * @author Julien Gacon\n * @date March 1st, 2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"lfppdofhandling.h\"\n\n#include \n#include \n#include \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 countEntityDofs(\n const lf::assemble::DofHandler &dofhandler) {\n std::array entityDofs;\n\n for(int codim = 0; codim < 3; codim++) {\n int n = 0;\n for(auto& entity : dofhandler.Mesh()->Entities(codim)) {\n n += dofhandler.NumInteriorDofs(*entity);\n }\n entityDofs[codim] = n;\n }\n\n return entityDofs;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\nstd::size_t countBoundaryDofs(const lf::assemble::DofHandler &dofhandler) {\n std::shared_ptr mesh = dofhandler.Mesh();\n // given an entity, bd\\_flags(entity) == true, if the entity is on the\n // boundary\n lf::mesh::utils::AllCodimMeshDataSet bd_flags(\n lf::mesh::utils::flagEntitiesOnBoundary(mesh));\n std::size_t no_dofs_on_bd = 0;\n\n for(auto& entity : dofhandler.Mesh()->Entities(1)) {\n if(bd_flags(*entity)) {\n no_dofs_on_bd += dofhandler.NumInteriorDofs(*entity);\n }\n }\n\n for(auto& entity : dofhandler.Mesh()->Entities(2)) {\n if(bd_flags(*entity)) {\n no_dofs_on_bd += dofhandler.NumInteriorDofs(*entity);\n }\n }\n\n return no_dofs_on_bd;\n}\n/* SAM_LISTING_END_2 */\n\n// clang-format off\n/* SAM_LISTING_BEGIN_3 */\ndouble integrateLinearFEFunction(\n const lf::assemble::DofHandler& dofhandler,\n const Eigen::VectorXd& mu) {\n double I = 0;\n\n for(auto entity : dofhandler.Mesh()->Entities(0)) {\n auto indices = dofhandler.GlobalDofIndices(*entity);\n\n assert(dofhandler.NumLocalDofs(*entity) == 3);\n\n double area = lf::geometry::Volume(*entity->Geometry());\n\n for(auto dof_idx : indices) {\n I += area * (mu[dof_idx]) / 3.;\n }\n\n }\n\n return I;\n}\n/* SAM_LISTING_END_3 */\n// clang-format on\n\n/* SAM_LISTING_BEGIN_4 */\ndouble integrateQuadraticFEFunction(const lf::assemble::DofHandler &dofhandler,\n const Eigen::VectorXd &mu) {\n double I = 0;\n\n for(auto entity : dofhandler.Mesh()->Entities(0)) {\n auto indices = dofhandler.GlobalDofIndices(*entity);\n\n assert(dofhandler.NumLocalDofs(*entity) == 6);\n\n double area = lf::geometry::Volume(*entity->Geometry());\n\n int i = 0;\n for(auto dof_idx : indices) {\n\n if(i >= 3) {\n I += area * (mu[dof_idx]) / 3.;\n }\n\n i++;\n }\n\n }\n\n return I;\n}\n/* SAM_LISTING_END_4 */\n\n/* SAM_LISTING_BEGIN_5 */\nEigen::VectorXd convertDOFsLinearQuadratic(\n const lf::assemble::DofHandler &dofh_Linear_FE,\n const lf::assemble::DofHandler &dofh_Quadratic_FE,\n const Eigen::VectorXd &mu) {\n if (dofh_Linear_FE.Mesh() != dofh_Quadratic_FE.Mesh()) {\n throw \"Underlying meshes must be the same for both DOF handlers!\";\n }\n std::shared_ptr mesh =\n dofh_Linear_FE.Mesh(); // get the mesh\n Eigen::VectorXd zeta(dofh_Quadratic_FE.NumDofs()); // initialise empty zeta\n // safety guard: always set zero if you're not sure to set every entry later\n // on for us this shouldn't be a problem, but just to be sure\n zeta.setZero();\n\n for (const auto *cell : mesh->Entities(0)) {\n // check if the spaces are actually linear and quadratic\n //====================\n assert(dofh_Linear_FE.NumLocalDofs(*cell) == 3);\n assert(dofh_Quadratic_FE.NumLocalDofs(*cell) == 6);\n //====================\n // get the global dof indices of the linear and quadratic FE spaces, note\n // that the vectors obey the LehrFEM++ numbering, which we will make use of\n // lin\\_dofs will have size 3 for the 3 dofs on the nodes and\n // quad\\_dofs will have size 6, the first 3 entries being the nodes and\n // the last 3 the edges\n //====================\n auto lin_indices = dofh_Linear_FE.GlobalDofIndices(*cell);\n auto quad_indices = dofh_Quadratic_FE.GlobalDofIndices(*cell);\n\n for(size_t i = 0; i < 3; i++) {\n zeta[quad_indices[i]] = mu[lin_indices[i]];\n zeta[quad_indices[i+3]] = 0.5 * (mu[lin_indices[i]] + mu[lin_indices[(i + 1) % 3]]);\n\n i++;\n }\n\n // assign the coefficients of mu to the correct entries of zeta, use\n // the previous subproblem 2-9.a\n //====================\n }\n return zeta;\n}\n/* SAM_LISTING_END_5 */\n\n} // namespace LFPPDofHandling\n", "meta": {"hexsha": "1405d7150b0b4697322d3b74dd32b433f82a1349", "size": 4692, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/LFPPDofHandling/mysolution/lfppdofhandling.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/LFPPDofHandling/mysolution/lfppdofhandling.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/LFPPDofHandling/mysolution/lfppdofhandling.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.6097560976, "max_line_length": 90, "alphanum_fraction": 0.6357630009, "num_tokens": 1334, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.826711776992821, "lm_q2_score": 0.8198933337131076, "lm_q1q2_score": 0.6778154748585311}} {"text": "#ifndef GEOUTILS_HPP\n#define GEOUTILS_HPP\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"quickhull.hpp\"\n#include \"sdlp.hpp\"\n\nnamespace geoutils\n{\n\n // Each col of hPoly denotes a facet (outter_normal^T,point^T)^T\n // The outter_normal is assumed to be NORMALIZED\n inline bool findInterior(const Eigen::MatrixXd &hPoly,\n Eigen::Vector3d &interior)\n {\n int m = hPoly.cols();\n\n Eigen::MatrixXd A(m, 4);\n Eigen::VectorXd b(m), c(4), x(4);\n A.leftCols<3>() = hPoly.topRows<3>().transpose();\n A.rightCols<1>().setConstant(1.0);\n b = hPoly.topRows<3>().cwiseProduct(hPoly.bottomRows<3>()).colwise().sum().transpose();\n c.setZero();\n c(3) = -1.0;\n\n double minmaxsd = sdlp::linprog(c, A, b, x);\n interior = x.head<3>();\n\n return minmaxsd < 0.0 && !std::isinf(minmaxsd);\n }\n\n inline double findInteriorDist(const Eigen::MatrixXd &hPoly,\n Eigen::Vector3d &interior)\n {\n int m = hPoly.cols();\n\n Eigen::MatrixXd A(m, 4);\n Eigen::VectorXd b(m), c(4), x(4);\n A.leftCols<3>() = hPoly.topRows<3>().transpose();\n A.rightCols<1>().setConstant(1.0);\n b = hPoly.topRows<3>().cwiseProduct(hPoly.bottomRows<3>()).colwise().sum().transpose();\n c.setZero();\n c(3) = -1.0;\n\n double minmaxsd = sdlp::linprog(c, A, b, x);\n interior = x.head<3>();\n\n return -minmaxsd;\n }\n\n struct filterLess\n {\n inline bool operator()(const Eigen::Vector3d &l,\n const Eigen::Vector3d &r)\n {\n return l(0) < r(0) ||\n (l(0) == r(0) &&\n (l(1) < r(1) ||\n (l(1) == r(1) &&\n l(2) < r(2))));\n }\n };\n\n inline void filterVs(const Eigen::MatrixXd &rV,\n const double &epsilon,\n Eigen::MatrixXd &fV)\n {\n double mag = std::max(fabs(rV.maxCoeff()), fabs(rV.minCoeff()));\n double res = mag * std::max(fabs(epsilon) / mag, DBL_EPSILON);\n std::set filter;\n fV = rV;\n int offset = 0;\n Eigen::Vector3d quanti;\n for (int i = 0; i < rV.cols(); i++)\n {\n quanti = (rV.col(i) / res).array().round();\n if (filter.find(quanti) == filter.end())\n {\n filter.insert(quanti);\n fV.col(offset) = rV.col(i);\n offset++;\n }\n }\n fV = fV.leftCols(offset).eval();\n return;\n }\n\n // Each col of hPoly denotes a facet (outter_normal^T,point^T)^T\n // The outter_normal is assumed to be NORMALIZED\n // proposed epsilon is 1.0e-6\n inline void enumerateVs(const Eigen::MatrixXd &hPoly,\n const Eigen::Vector3d &inner,\n Eigen::MatrixXd &vPoly,\n const double epsilon = 1.0e-6)\n {\n Eigen::RowVectorXd b = hPoly.topRows<3>().cwiseProduct(hPoly.bottomRows<3>()).colwise().sum() -\n inner.transpose() * hPoly.topRows<3>();\n Eigen::MatrixXd A = hPoly.topRows<3>().array().rowwise() / b.array();\n\n quickhull::QuickHull qh;\n double qhullEps = std::min(epsilon, quickhull::defaultEps());\n // CCW is false because the normal in quickhull towards interior\n const auto cvxHull = qh.getConvexHull(A.data(), A.cols(), false, true, qhullEps);\n const auto &idBuffer = cvxHull.getIndexBuffer();\n int hNum = idBuffer.size() / 3;\n Eigen::MatrixXd rV(3, hNum);\n Eigen::Vector3d normal, point, edge0, edge1;\n for (int i = 0; i < hNum; i++)\n {\n point = A.col(idBuffer[3 * i + 1]);\n edge0 = point - A.col(idBuffer[3 * i]);\n edge1 = A.col(idBuffer[3 * i + 2]) - point;\n normal = edge0.cross(edge1); //cross in CW gives an outter normal\n rV.col(i) = normal / normal.dot(point);\n }\n filterVs(rV, epsilon, vPoly);\n vPoly = (vPoly.array().colwise() + inner.array()).eval();\n return;\n }\n\n // Each col of hPoly denotes a facet (outter_normal^T,point^T)^T\n // The outter_normal is assumed to be NORMALIZED\n // proposed epsilon is 1.0e-6\n inline bool enumerateVs(const Eigen::MatrixXd &hPoly,\n Eigen::MatrixXd &vPoly,\n const double epsilon = 1.0e-6)\n {\n Eigen::Vector3d inner;\n if (findInterior(hPoly, inner))\n {\n enumerateVs(hPoly, inner, vPoly, epsilon);\n return true;\n }\n else\n {\n return false;\n }\n }\n\n} // namespace geoutils\n\n#endif", "meta": {"hexsha": "383a0943b4f61f286488f863d45cb3c339a407d0", "size": 4433, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mapping/occ_grid/include/occ_grid/geoutils.hpp", "max_stars_repo_name": "ZJU-FAST-Lab/std-trees", "max_stars_repo_head_hexsha": "322020c044469f33685bbc8e5b84c6c5734cd271", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2021-09-15T08:37:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T09:54:28.000Z", "max_issues_repo_path": "mapping/occ_grid/include/occ_grid/geoutils.hpp", "max_issues_repo_name": "ZJU-FAST-Lab/std-trees", "max_issues_repo_head_hexsha": "322020c044469f33685bbc8e5b84c6c5734cd271", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-20T09:03:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T09:03:24.000Z", "max_forks_repo_path": "mapping/occ_grid/include/occ_grid/geoutils.hpp", "max_forks_repo_name": "ZJU-FAST-Lab/std-trees", "max_forks_repo_head_hexsha": "322020c044469f33685bbc8e5b84c6c5734cd271", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-03-12T06:18:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T13:18:02.000Z", "avg_line_length": 30.156462585, "max_line_length": 99, "alphanum_fraction": 0.5673358899, "num_tokens": 1318, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505402422644, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6776621571002216}} {"text": "\n#include \n#include \n\nint main()\n{\n Eigen::Isometry3d original = Eigen::Isometry3d::Identity();\n original.translate(1.414214*Eigen::Vector3d::UnitY());\n original.rotate(Eigen::AngleAxisd(45.0*M_PI/180.0, Eigen::Vector3d::UnitZ()));\n\n std::cout << \"original:\\n\" << original.matrix() << \"\\n\" << std::endl;\n\n Eigen::Isometry3d cycle1 = Eigen::Isometry3d::Identity();\n cycle1.translate(1.414214*Eigen::Vector3d::UnitY());\n cycle1.rotate(Eigen::AngleAxisd(90*M_PI/180.0, Eigen::Vector3d::UnitX()));\n cycle1.rotate(Eigen::AngleAxisd(45.0*M_PI/180.0, Eigen::Vector3d::UnitY()));\n\n std::cout << \"cycle 1:\\n\" << cycle1.matrix() << \"\\n\" << std::endl;\n\n Eigen::Isometry3d diff_front = cycle1 * original.inverse();\n std::cout << \"diff_front:\\n\" << diff_front.matrix() << \"\\n\" << std::endl;\n\n Eigen::Isometry3d diff_back = original.inverse() * cycle1;\n std::cout << \"diff_back:\\n\" << diff_back.matrix() << \"\\n\" << std::endl;\n\n Eigen::Isometry3d x_90 = Eigen::Isometry3d::Identity();\n x_90.rotate(Eigen::AngleAxisd(90.0*M_PI/180.0, Eigen::Vector3d::UnitX()));\n std::cout << \"x_90:\\n\" << x_90.matrix() << \"\\n\" << std::endl;\n}\n", "meta": {"hexsha": "055cf038209516f9d82d96cc87845841d713665d", "size": 1153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "dart/matrix.cpp", "max_stars_repo_name": "mxgrey/sandbox", "max_stars_repo_head_hexsha": "6f3c316702a47053499222dbf293efe6c1f43f0c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dart/matrix.cpp", "max_issues_repo_name": "mxgrey/sandbox", "max_issues_repo_head_hexsha": "6f3c316702a47053499222dbf293efe6c1f43f0c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dart/matrix.cpp", "max_forks_repo_name": "mxgrey/sandbox", "max_forks_repo_head_hexsha": "6f3c316702a47053499222dbf293efe6c1f43f0c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.4333333333, "max_line_length": 80, "alphanum_fraction": 0.6539462272, "num_tokens": 387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391664210672, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.6776210815327447}} {"text": "/*\nDemonstrate the Eigen automatic differentiation module by training a multilayer perceptron (fully-connected feedforward neural-network).\nPython3.8 and matplotlib are used for plotting the results.\nCompile with:\n g++ eigen3_autodiff.cpp -o eigen3_autodiff -std=c++11 -O3 -ffast-math -I /usr/include/eigen3/ -I /usr/local/include/matplotlib-cpp.h -I /usr/include/python3.8 -l python3.8\n ./eigen3_autodiff 0.01 5 # step hidden_layer1_size hidden_layer2_size ...\n*/\n#include \n#include \n#include \n#include \n#include \"matplotlibcpp.h\"\nnamespace pyplot = matplotlibcpp;\n\n////////////////////////////////////////////////// ALIASES\n\nusing Jet = Eigen::AutoDiffScalar; // real number with many dual parts\nusing Jetvec = Eigen::Matrix; // vector of jets\nusing Jetmat = Eigen::Matrix; // matrix of jets\n\n////////////////////////////////////////////////// HELPERS\n\n// Returns a random real uniform on [-1, 1]\ninline double randf();\n\n// Returns a vector of just the real parts of the given jet vector\ninline Eigen::VectorXd reals(Jetvec const& jv);\n\n// Pulls scalar data embedded in Eigen objects out to plain doubles\ninline std::vector extract_values(std::vector> const& vec_eig);\n\n////////////////////////////////////////////////// MAIN CLASS\n\nclass MLP {\n std::vector const dims; // network dimensionalities (input_size, hidden_layer1_size, ..., output_size)\n std::vector weights; // container of weight matrices\n std::vector biases; // container of bias vectors\n std::vector params; // pointers to each individual parameter\n\npublic:\n MLP(std::vector const& dims) :\n dims(dims),\n weights(dims.size()-1),\n biases(dims.size()-1) {\n // Parse the dims architecture to count up the parameters\n int n_params = 0;\n for(int layer=0; layer get_dims() const {\n return dims;\n }\n\n inline std::vector get_weights() const {\n return weights;\n }\n\n inline std::vector get_biases() const {\n return biases;\n }\n\n ////////////////////////////////////////////////// WORKERS\n\n // Returns the sigmoid function of a given scalar jet\n inline Jet neuron(Jet const& x) const {\n return pow(Jet(1)+exp(-x), -1);\n }\n\n // Returns the jet vector MLP output corresponding to the given real input vector\n template \n inline Jetvec feedforward(Eigen::MatrixBase const& input) const {\n Jetvec act = input.template cast();\n for(int layer=0; layer\n inline std::vector feedforward(std::vector const& input_set) const {\n std::vector output_set;\n for(V const& input : input_set) {\n output_set.push_back(reals(feedforward(input)));\n }\n return output_set;\n }\n\n // Common quadratic cost function for a single input-output pair\n template \n Jet inline cost_function(Eigen::MatrixBase const& input, Eigen::MatrixBase const& output) const {\n Jetvec err = output.template cast() - feedforward(input);\n return err.dot(err);\n }\n\n // Cost function summed over an entire input-output pair batch\n template \n Jet inline cost_function(std::vector const& input_set, std::vector const& output_set) const {\n Jet cost(0);\n for(int i=0; i\n void train(std::vector const& input_set, std::vector const& output_set,\n double step, double tol=1e-5, int max_epoch=10000) {\n assert(input_set.size() == output_set.size());\n std::cout << \"Training with step-size \" << step << \"...\" << std::endl;\n std::vector ordering;\n for(int i=0; i::infinity();\n int epoch = 0;\n while(epoch < max_epoch) {\n double epoch_cost = 0;\n for(int i=0; i

\" << endl;\n return EXIT_FAILURE;\n }\n\n // parse parameters\n a = stod(argv[1], NULL);\n b = stod(argv[2], NULL);\n c = stod(argv[3], NULL);\n x0 = stod(argv[4], NULL);\n tn = stod(argv[5], NULL);\n dt = stod(argv[6], NULL);\n // TODO: add stepper and t0?\n\n // initialize state\n state_t x(1);\n x[0] = x0;\n\n // precalculate coefficients\n calc_coefficients(x0);\n\n // show floating-point width\n //cout << \"sizeof(real_t)=\" << sizeof(real_t) << endl;\n\n // stepper\n runge_kutta4 stp;\n\n // integrate w/ debug output\n out.open(\"out.dat\");\n /*size_t steps =*/ integrate_const(stp, ode, x, t0, tn, dt, observe);\n out.close();\n\n // show final output\n //cout << \"steps=\" << steps << \" x=\" << x[0] << endl;\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "5487c82e959983bc81f06ffaa5cd501a3e9d3b12", "size": 4362, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "solve_p2.cpp", "max_stars_repo_name": "delaneygmacd/jmu-reu-ode", "max_stars_repo_head_hexsha": "3478a7ae55f2c29ca6eef9c97e0179960e2d7655", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-06-09T16:48:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T17:12:01.000Z", "max_issues_repo_path": "solve_p2.cpp", "max_issues_repo_name": "delaneygmacd/jmu-reu-ode", "max_issues_repo_head_hexsha": "3478a7ae55f2c29ca6eef9c97e0179960e2d7655", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "solve_p2.cpp", "max_forks_repo_name": "delaneygmacd/jmu-reu-ode", "max_forks_repo_head_hexsha": "3478a7ae55f2c29ca6eef9c97e0179960e2d7655", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-11T15:51:05.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-11T15:51:05.000Z", "avg_line_length": 24.0994475138, "max_line_length": 78, "alphanum_fraction": 0.5371389271, "num_tokens": 1513, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.8244619199068831, "lm_q1q2_score": 0.6701781494939243}} {"text": "/**\n * @file model_predictive_controller.cpp\n * @brief Finite-horizon Model Predictive Controller.\n * \n */\n\n#include \n#include \n#include \n\nusing namespace controller;\n\nMPC::MPC(const Eigen::MatrixXd& Q, const Eigen::MatrixXd& R, const double S) :\n Q(Q), R(R), saturation(S), converged(false)\n{\n P_new.setZero();\n Ad.setZero(Q.rows(), Q.cols());\n I.setIdentity(Q.rows(), Q.cols());\n cmd_vel.setZero(1, R.rows()); // [translation rate, rotation rate].\n}\n\nEigen::MatrixXd MPC::computeDiscrete(const Eigen::MatrixXd& A, const Eigen::MatrixXd& B, const Eigen::MatrixXd& E, unsigned int numIteration, double tolarance, double dt)\n{\n // A Cost-to-go matrix P evolving backwards in time from Q is defined as,\n P = Q;\n\n // Discretization.\n Ad = (I + A * dt * 0.5) * (I - A * dt * 0.5).inverse();\n Bd = B * dt;\n\n // Iterating over a finite-horizon Algebraic Riccati Equation to a steady-state solution; that is, P_new - P ~= 0 + tolarance.\n for(unsigned int i = 0; i < numIteration; i++)\n {\n P_new = Ad.transpose() * P * Ad - (Ad.transpose() * P * Bd) * (R + Bd.transpose() * P * Bd).inverse() * (Bd.transpose() * P * Ad) + Q;\n\n // Check system convergence.\n difference = fabs((P_new - P).maxCoeff());\n if(difference < tolarance)\n {\n // std::cout << \"Solution found at i = \" << i << std::endl;\n\n converged = true;\n break;\n }\n\n // Update Riccati solution.\n P = P_new;\n }\n\n // Get cmd_vel.\n if(converged)\n {\n K = (R + Bd.transpose() * P * Bd).inverse() * Bd.transpose() * P * Ad;\n controlUpdate = K * E;\n\n // Compute magnitude of velocity vector.\n cmd_vel << \n sqrt(pow(controlUpdate(0, 0), 2.0) + pow(controlUpdate(0, 1), 2.0) + pow(controlUpdate(0, 2), 2.0)),\n sqrt(pow(controlUpdate(1, 0), 2.0) + pow(controlUpdate(1, 1), 2.0) + pow(controlUpdate(1, 2), 2.0));\n \n // Saturate output signal.\n if(cmd_vel(0, 0) > saturation) cmd_vel(0, 0) = saturation;\n if(cmd_vel(0, 0) < -saturation) cmd_vel(0, 0) = -saturation;\n if(cmd_vel(0, 1) > saturation) cmd_vel(0, 1) = saturation;\n if(cmd_vel(0, 1) < -saturation) cmd_vel(0, 1) = -saturation;\n\n return cmd_vel;\n }\n else\n {\n std::cout << \"MPC controller did not converge. Resetting cmd_vel... 沒有解決方案\" << std::endl;\n cmd_vel.setZero();\n\n return cmd_vel;\n }\n\n converged = false;\n}", "meta": {"hexsha": "d5b9aa4b0b2c5b807e5f7fbb293f720ec89943aa", "size": 2517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/control_system/src/model_predictive_controller.cpp", "max_stars_repo_name": "duckstarr/controller", "max_stars_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-05-15T21:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-03T04:34:54.000Z", "max_issues_repo_path": "src/control_system/src/model_predictive_controller.cpp", "max_issues_repo_name": "duckstarr/controller", "max_issues_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/control_system/src/model_predictive_controller.cpp", "max_forks_repo_name": "duckstarr/controller", "max_forks_repo_head_hexsha": "ed8020a4ba010981a6ea7377f39f0d1490359450", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2692307692, "max_line_length": 170, "alphanum_fraction": 0.5740961462, "num_tokens": 747, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087926320944, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6700727443058808}} {"text": "///////////////////////////////////////////////////////////////////////////////\n// Copyright Christopher Kormanyos 2019.\n// Distributed under the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n\n// chapter10_08-001_pi_millions_with_boost.cpp\n\n// This program can be used to compute millions of digits of pi.\n// In fact, it has been used to compute more than one billion\n// decimal digits of pi. Boost.Multiprecision is combined with\n// GMP (or MPIR) in order to carry out the calculation of pi.\n\n// This program requires inclusion of Boost.Multiprecision\n// and linking with GMP (or MPIR on certain targets).\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace pi { namespace millions { namespace detail {\n\n// *****************************************************************************\n// Function : template\n// const float_type& calculate_pi_template(const bool print_progress)\n//\n// Description : Compute pi using a quadratically convergent Gauss AGM,\n// in the Schoenhage variant. For a description of the algorithm,\n// see Algorithm 16.148, Chapter 16, page 236 in the book\n// J. Arndt and C. Haenel, \"Pi Unleashed\",\n// (Springer Verlag, Heidelberg, 2001).\n//\n// The parameter print_progress_to_cout (= true),\n// will print calculation progress to std::cout.\n//\n// Book reference for \"Pi Unleashed\":\n// https://www.springer.com/de/book/9783642567353\n//\n// *****************************************************************************\ntemplate\nconst float_type& pi(const bool print_progress = false)\n{\n static bool is_init;\n\n static float_type val_pi;\n\n if(!is_init)\n {\n is_init = true;\n\n const std::regex rx(\"^[^e]+[e0+-]+([0-9]+)$\");\n\n std::match_results mr;\n\n std::stringstream ss;\n ss.setf(std::ios::scientific);\n ss.precision(static_cast(4));\n\n float_type a (1.0F);\n float_type bB(0.5F);\n float_type s (0.5F);\n float_type t (0.375F);\n\n // This loop is designed for computing a maximum of a few billion\n // decimal digits of pi. The number of digits roughly doubles\n // with each iteration of the loop. After 20 iterations,\n // the precision is about 2.8 million decimal digits.\n // After 29 iterations, the precision is more than one\n // billion decimal digits.\n\n for(std::uint_least16_t k = UINT8_C(1); k < UINT8_C(64); ++k)\n {\n using std::sqrt;\n\n a += sqrt(bB);\n a /= 2U;\n val_pi = a;\n val_pi *= val_pi;\n bB = (val_pi - t);\n bB *= 2U;\n\n const float_type iterate_term((bB - val_pi) * (UINT64_C(1) << k));\n\n s += iterate_term;\n\n // Extract the base-10 order of magnitude\n // to estimate the base-10 digits in this\n // iteration.\n\n // Here, we produce a short printout\n // of the iteration term that is subsequently\n // parsed with a regular expression\n // for extracting the base-10 order.\n\n // Note: We are only extracting a few digits from iterate_term.\n // So piping it to a stringstream is not exorbitantly costly here.\n ss << iterate_term;\n\n const std::string str_iterate_term(ss.str());\n\n const bool is_match =\n std::regex_match(str_iterate_term, mr, rx);\n\n const std::uint64_t digits10_iterate =\n (is_match ? (std::max)(boost::lexical_cast(mr[1U]), std::uint64_t(0U))\n : UINT64_C(0));\n\n if(print_progress)\n {\n std::cout << \"Base-10 digits of iteration \"\n << std::right\n << std::setw(3)\n << k\n << \": \"\n << std::right\n << std::setw(12)\n << digits10_iterate\n << '\\n';\n }\n\n // Test the approximate base-10 digits\n // of this iteration term.\n\n // If we have attained at least half or more\n // of the total desired digits with this\n // iteration, the calculation is finished\n // because the change from the next iteration will be\n // insignificantly small.\n BOOST_CONSTEXPR_OR_CONST std::uint64_t digits10_iterate_goal =\n static_cast((static_cast(std::numeric_limits::digits10) + 1LL) / 2LL) + 16LL;\n\n if(digits10_iterate > digits10_iterate_goal)\n {\n break;\n }\n\n t = val_pi;\n t += bB;\n t /= 4U;\n\n ss.str(std::string());\n }\n\n if(print_progress)\n {\n std::cout << \"Iteration loop done, compute inverse\" << '\\n';\n }\n\n val_pi += bB;\n val_pi /= s;\n\n if(print_progress)\n {\n std::cout << \"The pi calculation is done.\" << '\\n';\n }\n }\n\n return val_pi;\n}\n\ntemplate\nstd::ostream& report_pi_timing(std::ostream& os, const float elapsed)\n{\n return os << \"=================================================\" << '\\n'\n << \"Computed \"\n << static_cast(std::numeric_limits::digits10 - 1)\n << \" digits of pi.\\n\"\n << \"Total computation time : \"\n << std::fixed\n << std::setprecision(2)\n << elapsed\n << \" seconds\"\n << '\\n'\n << \"=================================================\"\n << '\\n';\n}\n\n} } } // namespace pi::millions::detail\n\nnamespace pi { namespace millions {\n\ntemplate\nvoid print_pi(std::ostream& os)\n{\n // Calculate the value of pi. When doing so, print the calculation\n // messages to the console. Use the clock function to obtain the\n // total time of the pi calculation.\n\n using local_time_point_type =\n std::chrono::high_resolution_clock::time_point;\n\n const local_time_point_type start = std::chrono::high_resolution_clock::now();\n detail::pi(true);\n const local_time_point_type stop = std::chrono::high_resolution_clock::now();\n\n // Evaluate the time that was required for the pi calculation.\n const float elapsed =\n static_cast(std::chrono::duration_cast(stop - start).count())\n / static_cast(1000.0F);\n\n // Report the time of the pi calculation to the console.\n static_cast(detail::report_pi_timing(std::cout, elapsed));\n\n // Report the time of the pi calculation to the output stream.\n static_cast(detail::report_pi_timing(os, elapsed));\n\n // Report that we are writing the output file.\n std::cout << \"Writing the output file.\" << '\\n';\n\n // Pipe the value of pi into a stringstream object.\n std::stringstream ss;\n\n // Pipe the value of pi into a stringstream object with full precision.\n ss << std::fixed\n << std::setprecision(std::streamsize(std::numeric_limits::digits10) - 1)\n << detail::pi();\n\n // Extract the string value of pi.\n const std::string str_pi(ss.str());\n\n // Print pi using the following paramater-tunable format.\n\n // pi = 3.1415926535 8979323846 2643383279 5028841971 6939937510 : 50\n // 5820974944 5923078164 0628620899 8628034825 3421170679 : 100\n // 8214808651 3282306647 0938446095 5058223172 5359408128 : 150\n // 4811174502 8410270193 8521105559 6446229489 5493038196 : 200\n // ...\n\n BOOST_CONSTEXPR_OR_CONST char* char_set_separator = \" \";\n BOOST_CONSTEXPR_OR_CONST char* char_group_separator = \"\\n\";\n\n BOOST_CONSTEXPR_OR_CONST std::size_t digits_per_set = 10U;\n BOOST_CONSTEXPR_OR_CONST std::size_t digits_per_line = digits_per_set * 5U;\n BOOST_CONSTEXPR_OR_CONST std::size_t digits_per_group = digits_per_line * 10U;\n\n // The digits after the decimal point are grouped\n // in sets of digits_per_set with digits_per_line\n // digits per line. The running-digit count is reported\n // at the end of each line.\n \n // The char_set_separator character string is inserted\n // between sets of digits. Between groups of lines,\n // we insert a char_group_separator character string\n // (which likely might be selected as a newline).\n\n // For a simple verification of 1,000,000 digits,\n // for example, go to Wolfram Alpha and ask:\n // 1000000th digit of Pi.\n // This prints out 50 digits of pi in the neighborhood\n // of a million digits, with the millionth digit in bold.\n\n std::string::size_type pos;\n\n if( ((pos = str_pi.find(char('3'), 0U)) != std::string::npos)\n && ((pos = str_pi.find(char('.'), 1U)) != std::string::npos)\n && ((pos = str_pi.find(char('1'), 1U)) != std::string::npos))\n {\n ;\n }\n else\n {\n pos = 0U;\n }\n\n os << \"pi = \" << str_pi.substr(0U, pos);\n\n const std::size_t digit_offset = pos;\n\n // Extract the digits after the decimal point in a loop.\n // Insert spaces, newlines and a running-digit count\n // in order to create a format for comfortable reading.\n\n bool all_output_streaming_is_finished = false;\n\n while(all_output_streaming_is_finished == false)\n {\n // Print a set of digits (i.e. having 10 digits per set).\n const std::string str_pi_substring(str_pi.substr(pos, digits_per_set));\n\n os << str_pi_substring << char_set_separator;\n\n pos += (std::min)(std::string::size_type(digits_per_set),\n str_pi_substring.length());\n\n const std::size_t number_of_digits(pos - digit_offset);\n\n // Check if all output streaming is finished.\n all_output_streaming_is_finished = (pos >= str_pi.length());\n\n if(all_output_streaming_is_finished)\n {\n // Write the final digit count.\n // Break from the printing loop.\n // Flush the output stream with std::endl.\n\n os << \": \" << number_of_digits << std::endl;\n }\n else\n {\n const bool this_line_is_finished =\n (std::size_t(number_of_digits % digits_per_line) == std::size_t(0U));\n\n if(this_line_is_finished)\n {\n // Print the running-digit count and start a new line.\n os << \": \" << number_of_digits << std::endl;\n\n const bool this_group_of_lines_is_finished =\n (std::size_t(number_of_digits % digits_per_group) == std::size_t(0U));\n\n if(this_group_of_lines_is_finished)\n {\n // Insert a character (which might be a blank line)\n // after a group of lines.\n os << char_group_separator;\n }\n\n // Insert spaces at the start of the new line.\n os << \" \";\n }\n }\n }\n}\n\n} } // namespace pi::millions\n\nint main()\n{\n using float_type =\n boost::multiprecision::number,\n boost::multiprecision::et_off>;\n\n std::ofstream out(\"pi.out\");\n\n if(out.is_open())\n {\n pi::millions::print_pi(out);\n\n out.close();\n }\n\n return 0;\n}\n", "meta": {"hexsha": "e164c449ccabc1d98d145075fc87fccec5e4e804", "size": 11139, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code_snippets/chapter10/chapter10_08-001_pi_millions_with_boost.cpp", "max_stars_repo_name": "gianricardo/real-time-cpp", "max_stars_repo_head_hexsha": "9fa7d8dfced7a2ff3f8d1d1d4aeff24a76a2dbec", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-19T08:10:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-19T08:10:23.000Z", "max_issues_repo_path": "code_snippets/chapter10/chapter10_08-001_pi_millions_with_boost.cpp", "max_issues_repo_name": "dustex/real-time-cpp", "max_issues_repo_head_hexsha": "dedab60eefc6c5db94d53f1e1a890cfba8ae3f76", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code_snippets/chapter10/chapter10_08-001_pi_millions_with_boost.cpp", "max_forks_repo_name": "dustex/real-time-cpp", "max_forks_repo_head_hexsha": "dedab60eefc6c5db94d53f1e1a890cfba8ae3f76", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2893258427, "max_line_length": 127, "alphanum_fraction": 0.6161235299, "num_tokens": 2758, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6699788722212857}} {"text": "#pragma once\n\n#include \"EM.hpp\"\n#include \n#include \n\ntemplate\nrequires ContainerOf >\nEigen::Matrix weightedSum(\n const std::vector& a,\n const C& x)\n{\n typedef Eigen::Matrix Vec;\n assert( a.size() == x.size() );\n int n = x.begin()->size();\n return std::transform_reduce(a.begin(), a.end(), x.begin(), \n (Vec)Vec::Zero(n));\n}\n\n\ntemplate\nclass IndependentGaussian\n : public ProbabilityDistribution, Float > {\nprivate:\n typedef Eigen::Matrix Vec;\npublic:\n size_t n;\n Vec deviation;\n Vec mean;\n \n IndependentGaussian(size_t _n = N) : \n n{_n}\n {\n assert((N==Eigen::Dynamic || n==N) && \"Wrong number of dimensions\");\n init();\n }\n \n IndependentGaussian(const Vec& _deviation, const Vec& _mean) : \n n{(size_t)_deviation.size()},\n deviation{_deviation},\n mean{_mean}\n {\n assert((N==Eigen::Dynamic || n==N) && \"Wrong number of dimensions\");\n }\n \n Float operator()(const Vec& x) const{\n assert((size_t)x.size() == n);\n Float p = 1.0;\n Float s = 0.0;\n for(size_t j=0; j\n requires ContainerOf\n void likelihoodEstimate(const std::vector& a, \n const C& x)\n {\n Float sumA = std::reduce(a.begin(), a.end());\n if(sumA == 0.0){\n return;\n }\n mean = weightedSum(a, x)/sumA;\n \n Vec s2 = std::transform_reduce(\n a.begin(), a.end(), x.begin(),\n (Vec)Vec::Zero(n),\n std::plus<>(),\n [&](Float ai, const Vec& xi) -> Vec {\n return ai*(xi-mean).unaryExpr([&](auto xi_m){ return xi_m*xi_m; });\n });\n\n deviation = (s2/sumA).cwiseSqrt();\n } \nprivate:\n static constexpr Float one_two_pi = 1.0/sqrt(2*M_PI);\n void init(){\n mean = Vec::Zero(n);\n deviation = Vec::Constant(n, 1.0);\n }\n};\n\n\ntemplate\nclass Gaussian\n : public ProbabilityDistribution, Float > {\nprivate:\n typedef Eigen::Matrix Vec;\n typedef Eigen::Matrix Mat;\n size_t n;\npublic:\n Vec mean;\n class : public Mat{\n public:\n Float constantFactor{ calculateConstantFactor() };\n void operator=(const Mat& _invCovariance){\n assert(_invCovariance.rows() == _invCovariance.cols() && \"The inverse covariance matrix must be square\");\n Mat::operator=(_invCovariance);\n constantFactor = calculateConstantFactor();\n }\n private:\n Float calculateConstantFactor(){\n return pow(one_two_pi, this->rows())*sqrt(this->determinant());\n }\n } invCovariance;\n\n Gaussian(size_t _n=N) : \n n{_n},\n mean{ Vec::Zero(n) },\n invCovariance{ Vec::Constant(n, 1.0).asDiagonal() }\n {\n assert((N==Eigen::Dynamic || n==N) && \"Wrong number of dimensions\");\n }\n \n Gaussian(const Mat& _invCovariance, const Vec& _mean) : \n n{(size_t)_mean.size()},\n mean{_mean},\n invCovariance{_invCovariance}\n {\n assert((N==Eigen::Dynamic || n==N) && \"Wrong number of dimensions\");\n }\n \n Float operator()(const Vec& x) const{\n assert((size_t)x.size() == n);\n return invCovariance.constantFactor * exp(-0.5*(x-mean).dot(invCovariance*(x-mean)));\n }\n \n template \n requires ContainerOf\n void likelihoodEstimate(const std::vector& a, \n const C& x)\n {\n Float sumA = std::reduce(a.begin(), a.end());\n if(sumA == 0.0){\n return;\n }\n mean = weightedSum(a, x)/sumA;\n \n Mat Cov = std::transform_reduce(\n a.begin(), a.end(), x.begin(),\n (Mat)Mat::Zero(n, n),\n std::plus<>(),\n [&](Float ai, const Vec& xi) -> Mat {\n return ai*(xi-mean)*(xi-mean).transpose();\n });\n //FIXME: what if there is no inverse?\n invCovariance = (Cov/sumA).inverse();\n } \nprivate:\n static constexpr Float one_two_pi = 1.0/sqrt(2*M_PI);\n};\n\n\n", "meta": {"hexsha": "0924da04064dd3dd9f199b80cc680144ac35a666", "size": 4613, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Gaussian.hpp", "max_stars_repo_name": "waterlaz/Expectation-Maximization", "max_stars_repo_head_hexsha": "ec20426d8746c08fb043fc3a989167f5ebd51f3b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Gaussian.hpp", "max_issues_repo_name": "waterlaz/Expectation-Maximization", "max_issues_repo_head_hexsha": "ec20426d8746c08fb043fc3a989167f5ebd51f3b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Gaussian.hpp", "max_forks_repo_name": "waterlaz/Expectation-Maximization", "max_forks_repo_head_hexsha": "ec20426d8746c08fb043fc3a989167f5ebd51f3b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3821656051, "max_line_length": 117, "alphanum_fraction": 0.5438976805, "num_tokens": 1220, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859265, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6699392825844332}} {"text": "#include \"iostream\"\n#include \n#include \n#include \"CoupledPde.hpp\"\n#include \"gnuplot_i.hpp\"\n#include \n// #include \n\n\nusing namespace Eigen;\nusing namespace std;\n\n\ndouble model_prob_1_rhs(double x){return 2.0;}\ndouble model_prob_2_rhs(double x){return 34.0*sin(x);}\ndouble model_prob_3_rhs(double x, double y){return exp(-(x*x+y*y));}\ndouble uj0(double x){return 1*sin(x)+1;}\n\n\n\nint main(int argc, char* argv[]) {\n // int nthreads, tid;\n // #pragma omp parallel\n // {\n // /* Obtain thread number */\n // tid = omp_get_thread_num();\n // printf(\"Hello World from thread = %d\\n\", tid);\n\n // /* Only master thread does this */\n // if (tid == 0) {\n // nthreads = omp_get_num_threads();\n // printf(\"Number of threads = %d\\n\", nthreads);\n // }\n // }\n \n \n\n SecondOrderOde ode_mp1(500, -5.0, 0.0, model_prob_1_rhs, 0.0, 15.0);\n SecondOrderOde ode_mp2(5, -5.0, 0.0, model_prob_1_rhs, 0.0, 15.0);\n BoundaryConditions bc_mp1;\n BoundaryConditions bc_mp2;\n bc_mp1.SetX0DirichletBc1D(0.15);\n bc_mp1.SetXNNeumannBc1D(0);\n bc_mp2.SetX0NeumannBc1D(1.0);\n bc_mp2.SetXNNeumannBc1D(0);\n // bc_mp1.SetX0NeumannBc1D(0);\n // bc_mp1.SetXNDirichletBc1D(0);\n // bc_mp1.SetXNNeumannBc1D(0);\n // bc_mp1.SetXNRobinBc1D(0);\n BvpPde oxygen(&ode_mp1, &bc_mp1,0.001, 1.0, 10.0, 128, uj0);\n BvpPde organic_mater_1(&ode_mp2, &bc_mp2,0.001, 1.0, 10.0, 128, uj0);\n // BvpOde oxygen(&ode_mp1, &bc_mp1, 10);\n oxygen.SetFilename(\"oxygen_results.dat\");\n organic_mater_1.SetFilename(\"om1_results.dat\");\n // oxygen.Solve();\n CoupledPde cpde(&oxygen, &organic_mater_1);\n cpde.SolveSystem();\n\n\n Gnuplot g1, g2;\n g1.set_style(\"lines\").plot_xy(oxygen.mpGrid->xGrid,oxygen.solution,\"differentiation\");\n g2.set_style(\"lines\").plot_xy(organic_mater_1.mpGrid->xGrid,organic_mater_1.solution,\"differentiation\");\n // g1.set_style(\"lines\").plot_equation(\"0.5*x*(1-x)\",\"exact solution\");\n\n // Gnuplot g2;\n // SecondOrderOde ode_mp2(10.0, 5.0, 0.0, uj0, 0.0, 20.0);\n // BoundaryConditions bc_mp2;\n // bc_mp2.SetX0NeumannBc1D(10.0);\n // bc_mp2.SetXNDirichletBc1D(0.0);\n // BvpOde organic_mater_1(&ode_mp2, &bc_mp2, 64);\n // organic_mater_1.SetFilename(\"model_problem_results2.dat\");\n // organic_mater_1.Solve();\n // g2.set_style(\"points\").plot_xy(organic_mater_1.mpGrid->xGrid,organic_mater_1.solution);\n // g2.set_style(\"lines\").plot_equation(\"(4*exp(x) + exp(-4*x) ) / (4*exp(pi)+exp(-4*pi))-5*sin(x)-3*cos(x)\",\"exact solution\");\n\n return 0;\n}", "meta": {"hexsha": "cbb6977216cd0d9a6ff9eafa684189475a9d049c", "size": 2619, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "biogeochemistry/reaction_network", "max_stars_repo_head_hexsha": "7941b11e0bb228fa47107a9d48947b18ed5c75e6", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "biogeochemistry/reaction_network", "max_issues_repo_head_hexsha": "7941b11e0bb228fa47107a9d48947b18ed5c75e6", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "biogeochemistry/reaction_network", "max_forks_repo_head_hexsha": "7941b11e0bb228fa47107a9d48947b18ed5c75e6", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.012987013, "max_line_length": 130, "alphanum_fraction": 0.649102711, "num_tokens": 934, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859264, "lm_q2_score": 0.7634837581726991, "lm_q1q2_score": 0.66993927786221}} {"text": "/**\n * @file pose_estimation_3d2d.cpp\n * @version v1.0.0\n * @date Oct,27 2017\n * @author jacob.lin\n */\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std;\nusing namespace cv;\n\n/* find the two photo feature matches points */\nvoid find_feature_matches(const cv::Mat&, const cv::Mat&, std::vector&, std::vector&, std::vector&);\n\n/* Converts the pixel coordinate system to the normalized imaging plane coordinate system */\ncv::Point2d pixel2cam(const cv::Point2d&, const cv::Mat&);\n\n/* */\nvoid bundleAdjustment( const std::vector, const std::vector, const cv::Mat&, cv::Mat&, cv::Mat&);\n\nint main(int argc, char** argv)\n{\n if (argc != 5) {\n cout << \"usage: pose_estimation_3d2d img1 img2 depth1 depth2.\" << endl;\n return 1;\n }\n \n //-- 1st, read photo\n cv::Mat img_1 = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);\n cv::Mat img_2 = cv::imread(argv[2], CV_LOAD_IMAGE_COLOR);\n \n if (img_1.empty() || img_2.empty()) {\n cout << \"img1 or img2 is no find.\" << endl;\n return 1;\n }\n \n //-- 2nd, find the two photo feature matches points\n std::vector keypoints_1, keypoints_2;\n std::vector matches;\n find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n cout << \"feature matches points total is \" << matches.size() << endl;\n \n //-- 3rd, create 3 dimensions point correspondences\n cv::Mat d1 = cv::imread(argv[3], CV_LOAD_IMAGE_UNCHANGED); // 深度图为16位无符号数,单通道图像\n cv::Mat K = (cv::Mat_(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n std::vector pts_3d;\n std::vector pts_2d;\n for (cv::DMatch m:matches) {\n ushort d = d1.ptr(int (keypoints_1[m.queryIdx].pt.y))[int (keypoints_1[m.queryIdx].pt.x)];\n \n if (d == 0) { /* bad depth */\n continue;\n }\n float dd = d/5000.0;\n cv::Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n pts_3d.push_back(cv::Point3d (p1.x*dd, p1.y*dd, dd));\n pts_2d.push_back(keypoints_2[m.trainIdx].pt);\n }\n cout << \"3d-2d pairs: \" << pts_3d.size() << endl;\n \n //-- 4th, use PnP or bundle adjustment compute camera pose.\n cv::Mat r, t;\n cv::solvePnP(pts_3d, pts_2d, K, cv::Mat(), r, t, false); // 调用OpenCV 的 PnP 求解,可选择EPNP,DLS等方法\n cv::Mat R;\n cv::Rodrigues(r, R); // r为旋转向量形式,用Rodrigues公式转换为矩阵\n \n cout << \"R = \" << endl << R << endl;\n cout << \"t = \" << endl << t << endl;\n \n cout << \"calling bundle adjustment\" << endl;\n \n bundleAdjustment(pts_3d, pts_2d, K, R, t);\n \n return 0;\n}\n\n/**\n * find the two photo feature matches points\n */\nvoid find_feature_matches(const cv::Mat& img_1, const cv::Mat& img_2, std::vector& keypoints_1, std::vector& keypoints_2, std::vector& matches)\n{\n //-- Initialize\n cv::Mat descriptors_1, descriptors_2;\n cv::Ptr detector = cv::ORB::create();\n cv::Ptr descriptor = cv::ORB::create();\n cv::Ptr matcher = cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n \n //-- 1st: detect Oriented FAST KeyPoint \n detector->detect(img_1, keypoints_1);\n detector->detect(img_2, keypoints_2);\n \n //-- 2nd: Calculates BRIEF descriptors with KeyPoint's coordinate\n descriptor->compute(img_1, keypoints_1, descriptors_1);\n descriptor->compute(img_2, keypoints_2, descriptors_2);\n \n //-- 3rd: 对两幅图像中的BRIEF描述子进行匹配,使用 Hamming 距离\n std::vector match;\n matcher->match(descriptors_1, descriptors_2, match);\n \n //-- 4th: 匹配点对筛选\n double min_dist = 10000, max_dist = 0;\n \n /* 找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离 */\n for (int i = 0; i < descriptors_1.rows; i++) {\n double dist = match[i].distance;\n if (dist < min_dist) {\n min_dist = dist;\n }\n if (dist > max_dist) {\n max_dist = dist;\n }\n }\n \n printf(\"-- Max distance : %f \\r\\n\", max_dist);\n printf(\"-- Min distance : %f \\r\\n\", min_dist);\n \n // 当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.但有时候最小距离会非常小,设置一个经验值30作为下限.\n for (int i = 0; i < descriptors_2.rows; i ++) {\n if (match[i].distance <= max(2*min_dist, 30.0)) {\n matches.push_back(match[i]);\n }\n }\n}\n\n/**\n * Converts the pixel coordinate system to the normalized imaging plane coordinate system\n */\ncv::Point2d pixel2cam(const cv::Point2d& p, const cv::Mat& K)\n{\n return cv::Point2d\n (\n (p.x - K.at(0, 2)) / K.at(0, 0),\n (p.y - K.at(1, 2)) / K.at(1, 1)\n );\n}\n\nvoid bundleAdjustment(\n const std::vector points_3d, \n const std::vector points_2d,\n const cv::Mat& K,\n cv::Mat& R,\n cv::Mat& t )\n{\n // Initialize g2o\n typedef g2o::BlockSolver> Block; // pose 维度为 6, landmark 维度为 3\n Block::LinearSolverType* linear_solver = new g2o::LinearSolverCSparse(); // 线性方程求解器\n Block* solver_ptr = new Block((std::unique_ptr)(linear_solver));\n g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg((std::unique_ptr)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(0, 0), R.at(0, 1), R.at(0, 2), \\\n R.at(1, 0), R.at(1, 1), R.at(1, 2), \\\n R.at(2, 0), R.at(2, 1), R.at(2, 2);\n pose->setId(0);\n pose->setEstimate(\n g2o::SE3Quat(\n R_mat, \n Eigen::Vector3d(t.at(0, 0), t.at(1, 0), t.at(2, 0))\n )\n );\n optimizer.addVertex(pose);\n \n int index = 1;\n for (const cv::Point3f p:points_3d) {\n g2o::VertexSBAPointXYZ* point = new g2o::VertexSBAPointXYZ();\n point->setId(index ++);\n point->setEstimate(Eigen::Vector3d(p.x, p.y, p.z));\n point->setMarginalized(true); // g2o 中必须设置 marg \n optimizer.addVertex(point);\n }\n \n // parameter : camera intrinsics\n g2o::CameraParameters* camera = new g2o::CameraParameters(\n K.at(0, 0), Eigen::Vector2d(K.at(0, 2), K.at(1, 2)), 0\n );\n camera->setId(0);\n optimizer.addParameter(camera);\n \n // edges\n index = 1;\n for (const cv::Point2f p:points_2d) {\n g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();\n edge->setId(index);\n edge->setVertex(0, dynamic_cast(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 time_used = chrono::duration_cast>(t2 - t1);\n cout << \"optimization costs time: \" << time_used.count() << \" seconds.\" << endl;\n \n cout << endl << \"after optimization: \" << endl;\n cout << \"T = \" << endl << Eigen::Isometry3d(pose->estimate()).matrix() << endl;\n}\n\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "1a9c5f33e7d7c106015c744f3b26ff1f3666f0b8", "size": 8107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_estimation_3d2d/src/pose_estimation_3d2d.cpp", "max_stars_repo_name": "LSXiang/slam_learning_journey", "max_stars_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-03-22T00:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T05:23:27.000Z", "max_issues_repo_path": "pose_estimation_3d2d/src/pose_estimation_3d2d.cpp", "max_issues_repo_name": "LSXiang/slam_learning_journey", "max_issues_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pose_estimation_3d2d/src/pose_estimation_3d2d.cpp", "max_forks_repo_name": "LSXiang/slam_learning_journey", "max_forks_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.4978723404, "max_line_length": 183, "alphanum_fraction": 0.6205748119, "num_tokens": 2621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6699392776918984}} {"text": "/*\n Copyright (C) 2016 Quaternion Risk Management Ltd\n All rights reserved.\n\n This file is part of ORE, a free-software/open-source library\n for transparent pricing and risk analysis - http://opensourcerisk.org\n\n ORE is free software: you can redistribute it and/or modify it\n under the terms of the Modified BSD License. You should have received a\n copy of the license along with this program.\n The license is also available online at \n\n This program is distributed on the basis that it will form a useful\n contribution to risk analytics and model standardisation, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n#ifndef quantext_nadaraya_watson_regression_hpp\n#define quantext_nadaraya_watson_regression_hpp\n\n#include \n\n#include \n\n/*! \\file qle/math/nadarayawatson.hpp\n \\brief Nadaraya-Watson regression\n \\ingroup math\n*/\n\nnamespace QuantExt {\nusing QuantLib::Real;\nusing QuantLib::Size;\nnamespace detail {\n\n//! Regression impl\n/*! \\ingroup math\n */\nclass RegressionImpl {\npublic:\n virtual ~RegressionImpl() {}\n virtual void update() = 0;\n virtual Real value(Real x) const = 0;\n virtual Real standardDeviation(Real x) const = 0;\n};\n\n//! Nadaraya Watson impl\n/*! \\ingroup math\n */\ntemplate class NadarayaWatsonImpl : public RegressionImpl {\npublic:\n /*! \\pre the \\f$ x \\f$ values must be sorted.\n \\pre kernel needs a Real operator()(Real x) implementation\n */\n NadarayaWatsonImpl(const I1& xBegin, const I1& xEnd, const I2& yBegin, const Kernel& kernel)\n : xBegin_(xBegin), xEnd_(xEnd), yBegin_(yBegin), kernel_(kernel) {}\n\n void update() {}\n\n Real value(Real x) const {\n\n Real tmp1 = 0.0, tmp2 = 0.0;\n\n for (Size i = 0; i < static_cast(xEnd_ - xBegin_); ++i) {\n Real tmp = kernel_(x - xBegin_[i]);\n tmp1 += yBegin_[i] * tmp;\n tmp2 += tmp;\n }\n\n return QuantLib::close_enough(tmp2, 0.0) ? 0.0 : tmp1 / tmp2;\n }\n\n Real standardDeviation(Real x) const {\n\n Real tmp1 = 0.0, tmp1b = 0.0, tmp2 = 0.0;\n\n for (Size i = 0; i < static_cast(xEnd_ - xBegin_); ++i) {\n Real tmp = kernel_(x - xBegin_[i]);\n tmp1 += yBegin_[i] * tmp;\n tmp1b += yBegin_[i] * yBegin_[i] * tmp;\n tmp2 += tmp;\n }\n\n return QuantLib::close_enough(tmp2, 0.0) ? 0.0 : std::sqrt(tmp1b / tmp2 - (tmp1 * tmp1) / (tmp2 * tmp2));\n }\n\nprivate:\n I1 xBegin_, xEnd_;\n I2 yBegin_;\n Kernel kernel_;\n};\n} // namespace detail\n\n//! Nadaraya Watson regression\n/*! This implements the estimator\n\n \\f[\n m(x) = \\frac{\\sum_i y_i K(x-x_i)}{\\sum_i K(x-x_i)}\n \\f]\n\n \\ingroup math\n*/\nclass NadarayaWatson {\npublic:\n /*! \\pre the \\f$ x \\f$ values must be sorted.\n \\pre kernel needs a Real operator()(Real x) implementation\n */\n template \n NadarayaWatson(const I1& xBegin, const I1& xEnd, const I2& yBegin, const Kernel& kernel) {\n impl_ = boost::make_shared >(xBegin, xEnd, yBegin, kernel);\n }\n\n Real operator()(Real x) const { return impl_->value(x); }\n\n Real standardDeviation(Real x) const { return impl_->standardDeviation(x); }\n\nprivate:\n boost::shared_ptr impl_;\n};\n\n} // namespace QuantExt\n\n#endif\n", "meta": {"hexsha": "c90798dafec54b961758a49700ae0fa2ec3672a0", "size": 3521, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "QuantExt/qle/math/nadarayawatson.hpp", "max_stars_repo_name": "mrslezak/Engine", "max_stars_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 335.0, "max_stars_repo_stars_event_min_datetime": "2016-10-07T16:31:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-02T07:12:03.000Z", "max_issues_repo_path": "QuantExt/qle/math/nadarayawatson.hpp", "max_issues_repo_name": "mrslezak/Engine", "max_issues_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2016-10-31T04:20:24.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T16:39:57.000Z", "max_forks_repo_path": "QuantExt/qle/math/nadarayawatson.hpp", "max_forks_repo_name": "mrslezak/Engine", "max_forks_repo_head_hexsha": "c46ff278a2c5f4162db91a7ab500a0bb8cef7657", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 180.0, "max_forks_repo_forks_event_min_datetime": "2016-10-08T14:23:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:43:05.000Z", "avg_line_length": 28.3951612903, "max_line_length": 113, "alphanum_fraction": 0.6580516899, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818409, "lm_q2_score": 0.763483758172699, "lm_q1q2_score": 0.6699392754159426}} {"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\r\n\r\n// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.\r\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\r\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\r\n\r\n// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library\r\n// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.\r\n\r\n// Use, modification and distribution is subject to the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_SIDE_BY_TRIANGLE_HPP\r\n#define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_SIDE_BY_TRIANGLE_HPP\r\n\r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\nnamespace boost { namespace geometry\r\n{\r\n\r\nnamespace strategy { namespace side\r\n{\r\n\r\n/*!\r\n\\brief Check at which side of a segment a point lies:\r\n left of segment (> 0), right of segment (< 0), on segment (0)\r\n\\ingroup strategies\r\n\\tparam CalculationType \\tparam_calculation\r\n */\r\ntemplate \r\nclass side_by_triangle\r\n{\r\npublic :\r\n\r\n // Template member function, because it is not always trivial\r\n // or convenient to explicitly mention the typenames in the\r\n // strategy-struct itself.\r\n\r\n // Types can be all three different. Therefore it is\r\n // not implemented (anymore) as \"segment\"\r\n\r\n template \r\n static inline int apply(P1 const& p1, P2 const& p2, P const& p)\r\n {\r\n typedef typename boost::mpl::if_c\r\n <\r\n boost::is_void::type::value,\r\n typename select_most_precise\r\n <\r\n typename select_most_precise\r\n <\r\n typename coordinate_type::type,\r\n typename coordinate_type::type\r\n >::type,\r\n typename coordinate_type

::type\r\n >::type,\r\n CalculationType\r\n >::type coordinate_type;\r\n\r\n coordinate_type const x = get<0>(p);\r\n coordinate_type const y = get<1>(p);\r\n\r\n coordinate_type const sx1 = get<0>(p1);\r\n coordinate_type const sy1 = get<1>(p1);\r\n coordinate_type const sx2 = get<0>(p2);\r\n coordinate_type const sy2 = get<1>(p2);\r\n\r\n // Promote float->double, small int->int\r\n typedef typename select_most_precise\r\n <\r\n coordinate_type,\r\n double\r\n >::type promoted_type;\r\n\r\n promoted_type const dx = sx2 - sx1;\r\n promoted_type const dy = sy2 - sy1;\r\n promoted_type const dpx = x - sx1;\r\n promoted_type const dpy = y - sy1;\r\n\r\n promoted_type const s \r\n = geometry::detail::determinant\r\n (\r\n dx, dy, \r\n dpx, dpy\r\n );\r\n\r\n promoted_type const zero = promoted_type();\r\n return math::equals(s, zero) ? 0 \r\n : s > zero ? 1 \r\n : -1;\r\n }\r\n};\r\n\r\n\r\n#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS\r\nnamespace services\r\n{\r\n\r\ntemplate \r\nstruct default_strategy\r\n{\r\n typedef side_by_triangle type;\r\n};\r\n\r\n}\r\n#endif\r\n\r\n}} // namespace strategy::side\r\n\r\n}} // namespace boost::geometry\r\n\r\n\r\n#endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_SIDE_BY_TRIANGLE_HPP\r\n", "meta": {"hexsha": "103e199502e3064f52d87fbe7a24a465227a992a", "size": 3788, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "master/core/third/boost/geometry/strategies/cartesian/side_by_triangle.hpp", "max_stars_repo_name": "importlib/klib", "max_stars_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "master/core/third/boost/geometry/strategies/cartesian/side_by_triangle.hpp", "max_issues_repo_name": "isuhao/klib", "max_issues_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 197.0, "max_issues_repo_issues_event_min_datetime": "2017-07-06T16:53:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-05-31T17:57:51.000Z", "max_forks_repo_path": "master/core/third/boost/geometry/strategies/cartesian/side_by_triangle.hpp", "max_forks_repo_name": "isuhao/klib", "max_forks_repo_head_hexsha": "a59837857689d0e60d3df6d2ebd12c3160efa794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 31.0491803279, "max_line_length": 80, "alphanum_fraction": 0.6158922914, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6698829262385328}} {"text": "/*\n * Copyright (c) 2015-, Filippo Basso \n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder(s) nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include \n#include \n\nnamespace unipd\n{\nnamespace calib\n{\n\nTransform3\nPlaneToPlaneCalibration::estimateTransform (const std::vector> & plane_pair_vector)\n{\n const Size1 SIZE = plane_pair_vector.size();\n assert(SIZE >= 10);\n\n Eigen::Matrix normals_1(SIZE, 3);\n Eigen::Matrix normals_2(SIZE, 3);\n Eigen::Matrix distances_1(SIZE);\n Eigen::Matrix distances_2(SIZE);\n\n for (int i = 0; i < SIZE; ++i)\n {\n const Plane3 & plane_1 = plane_pair_vector[i].first;\n const Plane3 & plane_2 = plane_pair_vector[i].second;\n\n if (plane_1.offset() > 0)\n {\n normals_1.row(i) = -plane_1.normal();\n distances_1(i) = plane_1.offset();\n }\n else\n {\n normals_1.row(i) = plane_1.normal();\n distances_1(i) = -plane_1.offset();\n }\n\n if (plane_2.offset() > 0)\n {\n normals_2.row(i) = -plane_2.normal();\n distances_2(i) = plane_2.offset();\n }\n else\n {\n normals_2.row(i) = plane_2.normal();\n distances_2(i) = -plane_2.offset();\n }\n }\n\n Transform3 transform;\n\n Eigen::Matrix USV = normals_2.transpose() * normals_1;\n Eigen::JacobiSVD > svd;\n svd.compute(USV, Eigen::ComputeFullU | Eigen::ComputeFullV);\n transform.linear() = svd.matrixV() * svd.matrixU().transpose();\n\n// transform.translation() = (normals_1.transpose() * normals_1).inverse() * normals_1.transpose() * (distances_1 - distances_2);\n\n // Use QR decomposition\n Eigen::ColPivHouseholderQR > qr(normals_1.rows(), 3);\n qr.compute(normals_1);\n Eigen::Matrix R = qr.matrixR().template triangularView();\n transform.translation() = (qr.colsPermutation() * R.transpose() * R * qr.colsPermutation().transpose()).inverse() * normals_1.transpose() * (distances_1 - distances_2);\n\n return transform;\n}\n\n} // namespace calib\n} // namespace unipd\n", "meta": {"hexsha": "f4f3d020b8ccaa471a16d5f8a8adb34f58666b34", "size": 3719, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "calibration_algorithms/src/calibration_algorithms/plane_to_plane_calibration.cpp", "max_stars_repo_name": "pionex/calibration_toolkit", "max_stars_repo_head_hexsha": "ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2016-08-02T04:40:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T22:08:55.000Z", "max_issues_repo_path": "calibration_algorithms/src/calibration_algorithms/plane_to_plane_calibration.cpp", "max_issues_repo_name": "pionex/calibration_toolkit", "max_issues_repo_head_hexsha": "ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T07:53:09.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-06T21:55:47.000Z", "max_forks_repo_path": "calibration_algorithms/src/calibration_algorithms/plane_to_plane_calibration.cpp", "max_forks_repo_name": "pionex/calibration_toolkit", "max_forks_repo_head_hexsha": "ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-06-15T00:18:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T21:16:09.000Z", "avg_line_length": 38.7395833333, "max_line_length": 170, "alphanum_fraction": 0.7015326701, "num_tokens": 974, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850004144265, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6698407618695567}} {"text": "#include \n#include \n#include \n#include \n\n//CRS\nvoid compressedSparseRow()\n{\n/*\n 0 1 2 3 4 5 6 7 8\n ┌ ┐\n 0 |0 0 0 0 0 0 0 3 0|\n 1 |0 0 8 0 0 1 0 0 0|\n 2 |0 0 0 0 0 0 0 0 0|\n 3 |4 0 0 0 0 0 0 0 0|\n 4 |0 0 0 0 0 0 0 0 0|\n 5 |0 0 2 0 0 0 0 0 0|\n 6 |0 0 0 6 0 0 0 0 0|\n 7 |0 9 0 0 5 0 0 0 0|\n └ ┘\n*/\n\n\n int rows=8;\n int cols=9;\n Eigen::Matrix dense_mat;\n dense_mat.resize(rows,cols);\n\n\n dense_mat<<0, 0, 0, 0, 0, 0, 0, 3, 0,\n 0, 0, 8, 0, 0, 1, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 4, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 0, 0, 0, 0, 0, 0,\n 0, 0, 2, 0, 0, 0, 0, 0, 0,\n 0, 0, 0, 6, 0, 0, 0, 0, 0,\n 0, 9, 0, 0, 5, 0, 0, 0, 0;\n\n //specify a tolerance:\n //sparse_mat = dense_mat.sparseView(epsilon,reference);\n Eigen::SparseMatrix sparse_mat = dense_mat.sparseView();\n\n std::cout<<\"sparse matrix number of cols:\"< SpMat; // declares a column-major sparse matrix type of double\ntypedef Eigen::Triplet T;//structure to hold a non zero as a triplet (i,j,value).\n\nvoid buildProblem(std::vector& coefficients, Eigen::VectorXd& b, int n){}\nvoid saveAsBitmap(const Eigen::VectorXd& x, int n, const char* filename){}\n//https://eigen.tuxfamily.org/dox/classEigen_1_1Triplet.html\nint main(int argc, char** argv)\n{\n if(argc!=2) {\n std::cerr << \"Error: expected one and only one argument.\\n\";\n return -1;\n }\n\n int n = 300; // size of the image\n int m = n*n; // number of unknows (=number of pixels)\n\n // Assembly:\n std::vector coefficients; // list of non-zeros coefficients\n Eigen::VectorXd b(m); // the right hand side-vector resulting from the constraints\n buildProblem(coefficients, b, n);\n\n SpMat A(m,m);\n A.setFromTriplets(coefficients.begin(), coefficients.end());\n\n // Solving:\n Eigen::SimplicialCholesky chol(A); // performs a Cholesky factorization of A\n Eigen::VectorXd x = chol.solve(b); // use the factorization to solve for the given right hand side\n\n // Export the result to a file:\n saveAsBitmap(x, n, argv[1]);\n\n return 0;\n}\n", "meta": {"hexsha": "2f371b33707ba4fb24ac7afcf6f09363e60f9fd9", "size": 3473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sparse_matrices.cpp", "max_stars_repo_name": "behnamasadi/Mastering_Eigen", "max_stars_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-04-14T16:54:17.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-13T15:55:08.000Z", "max_issues_repo_path": "src/sparse_matrices.cpp", "max_issues_repo_name": "behnamasadi/Mastering_Eigen", "max_issues_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/sparse_matrices.cpp", "max_forks_repo_name": "behnamasadi/Mastering_Eigen", "max_forks_repo_head_hexsha": "99edbc819c89a4805b777eef69044a1658d96206", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-12-25T10:08:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-06T14:27:32.000Z", "avg_line_length": 27.784, "max_line_length": 108, "alphanum_fraction": 0.5715519724, "num_tokens": 1211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527631, "lm_q2_score": 0.8289388104343892, "lm_q1q2_score": 0.669838274753459}} {"text": "///////////////////////////////////////////////////////////////\n// Copyright 2012 John Maddock. Distributed under the Boost\n// Software License, Version 1.0. (See accompanying file\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_\n\n//[safe_prime\n\n#include \n#include \n#include \n#include \n\nint main()\n{\n using namespace boost::random;\n using namespace boost::multiprecision;\n\n typedef cpp_int int_type;\n mt11213b base_gen(clock());\n independent_bits_engine gen(base_gen);\n //\n // We must use a different generator for the tests and number generation, otherwise\n // we get false positives.\n //\n mt19937 gen2(clock());\n\n for(unsigned i = 0; i < 100000; ++i)\n {\n int_type n = gen();\n if(miller_rabin_test(n, 25, gen2))\n {\n // Value n is probably prime, see if (n-1)/2 is also prime:\n std::cout << \"We have a probable prime with value: \" << std::hex << std::showbase << n << std::endl;\n if(miller_rabin_test((n-1)/2, 25, gen2))\n {\n std::cout << \"We have a safe prime with value: \" << std::hex << std::showbase << n << std::endl;\n return 0;\n }\n }\n }\n std::cout << \"Ooops, no safe primes were found - probably a bad choice of seed values!\" << std::endl;\n return 0;\n}\n\n//]\n", "meta": {"hexsha": "4421f8d7b9f3030e950f2d5eba254bf4da2242c9", "size": 1408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "deps/boost/libs/multiprecision/example/safe_prime.cpp", "max_stars_repo_name": "alexhenrie/poedit", "max_stars_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/boost/libs/multiprecision/example/safe_prime.cpp", "max_issues_repo_name": "alexhenrie/poedit", "max_issues_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/boost/libs/multiprecision/example/safe_prime.cpp", "max_forks_repo_name": "alexhenrie/poedit", "max_forks_repo_head_hexsha": "b9b31a111d9e8a84cf1e698aff2c922a79bdd859", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 30.6086956522, "max_line_length": 109, "alphanum_fraction": 0.6008522727, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.6698371989599294}} {"text": "#ifndef MIXMAT_HPP\n#define MIXMAT_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nenum mixMatType\n{\n TT,\n EE,\n};\n\ntemplate\nclass MixingMatrix\n{\npublic:\n /**\n * \\typedef _realScalarType realScalarType\n * \\brief real floating point type\n */\n typedef _realScalarType realScalarType;\n\n /**\n * \\typedef typename Eigen::Matrix mixingMatrixType\n * \\brief mixing matrix type\n */\n typedef Eigen::Matrix mixingMatrixType;\n\n\n /**\n * \\typedef typename mixingMatrixType::Index indexType\n * \\brief integral type\n */\n typedef typename mixingMatrixType::Index indexType;\n\n\n /**\n * \\typedef Eigen::LLT LLTType;\n * \\brief Cholesky decompostion type\n */\n typedef Eigen::LLT LLTType;\n\n typedef Eigen::Matrix powSpecType;\n\n\n MixingMatrix(powSpecType const & W,mixMatType const mt)\n :mW(W)\n {\n const indexType lMax = W.rows()-1;\n const indexType matDim(lMax+1);\n mM = mixingMatrixType::Zero(matDim,matDim);\n mLMax = lMax;\n mMT = mt;\n std::cout<<\"lMax = \"< wig3j =\n WignerSymbols::wigner3j((double)l1,(double)l2,\n (double)0,(double)0,(double)0);\n\n indexType l3Min = std::max(std::abs(l1-l2),indexType(0));\n indexType l3max = std::min( l3Min + indexType(wig3j.size()-1),mLMax ) ;\n\n for(indexType l3=l3Min;l3<=l3max;++l3)\n {\n if( selectWig3j( l3,l1,l2,indexType(0),indexType(0),indexType(0) ) )\n {\n mM(l1,l2) += realScalarType(2*l3+1)*mW(l3)*wig3j[l3 - l3Min]*wig3j[l3 - l3Min];\n }\n }\n\n mM(l1,l2) *= realScalarType(2*l2+1)/(4*M_PI);\n }\n }\n }\n else if(mMT == EE)\n {\n std::cout<<\"Computing EE mixing matrix\"< wig3j =\n WignerSymbols::wigner3j((double)l1,(double)l2,\n (double)0,(double)2,(double)-2);\n\n indexType l3Min = std::max(std::abs(l1-l2),indexType(0));\n indexType l3max = std::min( l3Min + indexType(wig3j.size()-1),mLMax ) ;\n\n for(indexType l3=l3Min;l3<=l3max;++l3)\n {\n if( selectWig3j( l3,l1,l2,indexType(0),indexType(2),indexType(-2) ) && (l1+l2+l3)%2 == 0 )\n {\n mM(l1,l2) += realScalarType(2*l3+1)*realScalarType(2)*mW(l3)*wig3j[l3 - l3Min]*wig3j[l3 - l3Min];\n }\n }\n\n mM(l1,l2) *= realScalarType(2*l2+1)/(8*M_PI);\n }\n }\n\n }\n\n }\n\n bool selectWig3j(indexType const l1,indexType const l2,indexType const l3,\n indexType const m1,indexType const m2,indexType const m3)\n {\n bool select(true);\n\n select = (\n std::abs(m1+m2+m3) == indexType(0)\n && l3 >= std::abs(l1-l2)\n && l3 <= l1+l2\n && std::abs(m1) <= l1\n && std::abs(m2) <= l2\n && std::abs(m3) <= l3\n );\n\n return ( select );\n }\n\n void save(std::string const fileName)\n {\n writeMatrixToFile(fileName,mM,10,\",\");\n }\n\n\n void applyMixingMatrix(powSpecType & C)\n {\n C = mM*C;\n }\n\n void applyMixingMatrixInv(powSpecType & C)\n {\n LLTType lltOfM;\n lltOfM.compute(mM);\n assert(lltOfM.info() == Eigen::Success);\n C = lltOfM.solve(C);\n }\n\nprivate:\n\n void writeMatrixToFile(std::string const & fileName,\n mixingMatrixType const& mat,unsigned int precision,\n std::string const& separation)\n {\n std::ofstream outFile;\n outFile.open(fileName.c_str(),std::ios::trunc);\n\n if(outFile.is_open())\n {\n outFile<\n#include \n\n#include \n\nnamespace paal {\n\n/**\n * @brief return centroid that minimize within-cluster sum of squares\n */\ntemplate \nvoid centroid_minimalize_w_c_s_s(Cluster && cluster, OutputIterator out) {\n assert(!boost::empty(cluster));\n using point_t = range_to_elem_t;\n using coordinate_t = range_to_elem_t;\n\n auto dim = boost::size(*std::begin(cluster));\n for(auto idx : irange(dim)) {\n coordinate_t res{};\n for (auto && point : cluster) {\n res += std::begin(point)[idx];\n }\n *out = res / boost::size(cluster);\n ++out;\n }\n}\n\n/**\n * @brief centroid minimize within cluster sum of squares\n * @param clusters\n * @param out\n * @tparam Clusters\n * @tparam OutputIterator\n */\ntemplate \nvoid centroids_minimalize_w_c_s_s(Clusters && clusters, OutputIterator out) {\n assert(!boost::empty(clusters));\n assert(!boost::empty(*std::begin(clusters)));\n\n using cluster_t = range_to_elem_t;\n using point_t = range_to_elem_t;\n using coordinate_t = range_to_elem_t;\n\n auto size = boost::size(*std::begin(*begin(clusters)));\n for (auto && cluster : clusters) {\n std::vector point(size);\n centroid_minimalize_w_c_s_s(cluster, point.begin());\n *out = point;\n ++out;\n }\n}\n\n/**\n * @brief this is solve k_means_clustering problem\n * and return vector of cluster\n * example:\n * \\snippet k_means_clustering_example.cpp K Means Clustering Example\n *\n * complete example is k_means_clustering_example.cpp\n * @param points\n * @param centers\n * @param result pairs of point and id of cluster\n * (number form 0,1,2 ...,number_of_cluster-1)\n * @param visitor\n * @tparam Points\n * @tparam OutputIterator\n * @tparam CoordinateType\n * @tparam Visitor\n */\ntemplate \nauto k_means(Points &&points, Centers &¢ers, OutputIterator result,\n Visitor visitor = Visitor{}) {\n using point_t = range_to_elem_t;\n using center_t = range_to_elem_t;\n\n center_t center{ *std::begin(centers) };\n\n return k_means(\n points, centers,\n [&](std::vector const & points)->center_t const & {\n centroid_minimalize_w_c_s_s(points, std::begin(center));\n return center;\n },\n [&](point_t const &point) { return closest_to(point, centers); },\n result, utils::equal_to{}, visitor);\n}\n\n} //!paal\n\n#endif /* PAAL_K_MEANS_CLUSTERING_HPP */\n", "meta": {"hexsha": "c471a468c3c84a3e2ba65efa6ed6ced815717b58", "size": 3015, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/clustering/k_means_clustering.hpp", "max_stars_repo_name": "Kommeren/AA", "max_stars_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/paal/clustering/k_means_clustering.hpp", "max_issues_repo_name": "Kommeren/AA", "max_issues_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/paal/clustering/k_means_clustering.hpp", "max_forks_repo_name": "Kommeren/AA", "max_forks_repo_head_hexsha": "e537b58d50e93d4a72709821b9ea413008970c6b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-02-24T06:23:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-24T06:23:56.000Z", "avg_line_length": 28.7142857143, "max_line_length": 77, "alphanum_fraction": 0.6815920398, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8418256631249077, "lm_q2_score": 0.7956581049086031, "lm_q1q2_score": 0.6698054117853922}} {"text": "\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\nnamespace bindings = boost::numeric::bindings;\n\n// solves the equation Ax = B, and puts the solution in B\n// A is mutated by this routine\ntemplate \nvoid InPlaceSolve(MatrA& a, MatrB& b)\n{\n // if the matrix has kl lower and ku upper diagonals, then we should have\n // allocated kl lower and kl+ku upper diagonals\n fortran_int_t const kl = bindings::bandwidth_lower(a);\n fortran_int_t const ku = bindings::bandwidth_upper(a) - kl;\n std::vector piv(a.size1());\n int ret = lapack::gbtrf(/*kl, ku, */a, piv);\n if(ret < 0)\n {\n //CStdString err;\n //err.Format(\"banded::Solve: argument %d in DGBTRF had an illegal value\", -ret);\n //throw RuntimeError(err);\n throw std::runtime_error(\"banded::Solve: argument %d in DGBTRF had an illegal value\");\n }\n if(ret > 0)\n {\n //CStdString err;\n //err.Format(\"banded::Solve: the (%d,%d) diagonal element is 0 after DGBTRF\", ret, ret);\n //throw RuntimeError(err);\n throw std::runtime_error(\"banded::Solve: the (%d,%d) diagonal element is 0 after DGBTRF\");\n }\n\n ret = lapack::gbtrs(/*kl, ku, */a, piv, b);\n if(ret < 0)\n {\n //CStdString err;\n //err.Format(\"banded::Solve: argument %d in DGBTRS had an illegal value\", -ret);\n //throw RuntimeError(err);\n throw std::runtime_error(\"banded::Solve: argument %d in DGBTRS had an illegal value\");\n }\n}\n\ntemplate\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 a(sz, sz, kl, kl+ku);\n ublas::vector b(sz);\n // fill values in a and b\n for(size_t i = 0; i < sz; ++i)\n {\n a(i,i) = i;\n b(i) = i;\n }\n for(size_t i = 1; i < sz; ++i)\n {\n a(i,i-1) = i;\n a(i-1,i) = 1;\n }\n InPlaceSolve(a, b);\n}\n\nint main()\n{\n do_typename();\n do_typename();\n do_typename >();\n do_typename >();\n return 0;\n}\n", "meta": {"hexsha": "6d6d81539a091d0daf54aa98ea4c8e69019cefce", "size": 2505, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gbsv.cpp", "max_stars_repo_name": "fperignon/sandbox", "max_stars_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gbsv.cpp", "max_issues_repo_name": "fperignon/sandbox", "max_issues_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gbsv.cpp", "max_forks_repo_name": "fperignon/sandbox", "max_forks_repo_head_hexsha": "649f09d6db7bbd84c2418de74eb9453c0131f070", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 30.5487804878, "max_line_length": 94, "alphanum_fraction": 0.6686626747, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6697998385653774}} {"text": "#include \n#include \n#include \n#include \n#include \"mex.h\"\n\nconst std::complex i1(0.0, 1.0);\n\nEigen::Matrix3cd T;\n\n\nvoid update_T(double a, double p)\n{\n T(0,0) = pow(cos(a/2),2);\n T(0,1) = pow(sin(a/2),2)*(cos(2*p)+1.0*i1*sin(2*p));\n T(0,2) = sin(a)*(sin(p)-1.0*i1*cos(p));\n T(1,0) = std::conj(T(0,1));\n T(1,1) = T(0,0);\n T(1,2) = std::conj(T(0,2));\n T(2,0) = -0.5*sin(a)*(sin(p)+1.0*i1*cos(p));\n T(2,1) = std::conj(T(2,0));\n T(2,2) = cos(a);\n}\n\nvoid EPG_GRE(double *signal_real, double *signal_imag, double *path_real, double *path_imag, double *N, double *FA, double *RF, double *TR, double *T1, double *T2, double *M0)\n{\n int n = (int) N[0];\n\n //max order of EPG simulation\n int KMAX = n;\n if(n>25){KMAX = 25;}\n\n ///// MEMORY ALLOCATION\t\n // relaxation operators\n double E1 = exp(-TR[0]/T1[0]);\n double E2 = exp(-TR[0]/T2[0]);\n\n // signal vectors\n Eigen::VectorXcd F_plus(KMAX);\n F_plus.setZero();\n\n Eigen::VectorXcd F_minus(KMAX);\n F_minus.setZero();\n\n Eigen::VectorXcd Z(KMAX);\n Z.setZero();\n\n Eigen::Vector3cd aux_states(0, 0, 0);\n\n\n /////SIGNAL SIMULATION\n Z(0) = M0[0];\n \n // transition matrix\n update_T(FA[0], RF[0]);\n\n //apply first pulse\n aux_states(0) = F_plus(0);\n aux_states(1) = F_minus(0);\n aux_states(2) = Z(0);\n aux_states = T * aux_states;\n F_plus(0) = aux_states(0);\n F_minus(0) = aux_states(1);\n Z(0) = aux_states(2);\n\n //save F_minus_zero >> this is the measured signal\n signal_real[0] = F_minus(0).real();\n signal_imag[0] = F_minus(0).imag();\n\n //simulate rest of the sequence\n for (int j=1; j0; k--){ F_plus(k) = F_plus(k-1); }\n \tF_plus(0) = std::conj(F_minus(1));\n \tfor (int k=0; k<(std::min(KMAX-1,j)); k++){ F_minus(k) = F_minus(k+1); }\n \tF_minus(std::min(KMAX-1,j)) = 0.0 + 0.0*i1;\n\t\n \t//apply T\n update_T(FA[j], RF[j]);\n \tfor (int k=0; k<(std::min(KMAX,j+1)); k++) \n \t{\n \t\taux_states(0) = F_plus(k);\n \t\taux_states(1) = F_minus(k);\n \t\taux_states(2) = Z(k);\n \t\taux_states = T * aux_states;\n \n \t\tF_plus(k) = aux_states(0);\n \t\tF_minus(k) = aux_states(1);\n \t\tZ(k) = aux_states(2);\n \t}\n\n \n \t//save F_minus_zero\n \tsignal_real[j] = F_minus(0).real();\n signal_imag[j] = F_minus(0).imag();\n\n //save last states \n if(j==(n-1))\n {\n for (int k=0; k\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"GPs.h\"\n\n#include \n\n// Specify the target function for Gaussian process regression\ndouble targetFunc(Eigen::MatrixXd X)\n{\n\n if ( X.size() == 1 )\n {\n // Define the target function to be an oscillatory, non-periodic function\n double oscillation = 30.0;\n double xshifted = 0.5*(X(0) + 1.0);\n return std::sin(oscillation*(xshifted-0.1))*(0.5-(xshifted-0.1))*15.0;\n }\n else\n {\n // Define the target function to be the Marr wavelet (a.k.a \"Mexican Hat\" wavelet)\n // ( see https://en.wikipedia.org/wiki/Mexican_hat_wavelet )\n double sigma = 0.25;\n double pi = std::atan(1)*4;\n double radialTerm = std::pow(X.squaredNorm()/sigma,2);\n return 2.0 / (std::sqrt(pi*sigma) * std::pow(pi,1.0/4.0)) * (1.0 - radialTerm) * std::exp(-radialTerm);\n }\n}\n\n\n// Example use of CppGPs code for Gaussian process regression\nint main(int argc, char const *argv[])\n{\n\n // Retrieve aliases from GP namescope\n using Matrix = Eigen::MatrixXd;\n using Vector = Eigen::VectorXd;\n\n // Convenience using-declarations\n using std::cout;\n using std::endl;\n using GP::GaussianProcess;\n using GP::linspace;\n using GP::sampleNormal;\n using GP::sampleUnif;\n using GP::RBF;\n \n // Used for timing code with chrono\n using GP::high_resolution_clock;\n using GP::time;\n using GP::getTime;\n \n // Set random seed based on system clock\n std::srand(static_cast(high_resolution_clock::now().time_since_epoch().count()));\n\n // Fix random seed for debugging and testing\n //std::srand(static_cast(0));\n\n\n //\n // [ Define Training Data ]\n //\n\n // Specify the input dimensions\n //int inputDim = 1;\n int inputDim = 2;\n \n // Specify observation data count\n int obsCount;\n if ( inputDim == 1 )\n obsCount = 250;\n else\n obsCount = 1000;\n \n // Specify observation noise level\n auto noiseLevel = 1.0;\n\n // Define random noise to add to target observations\n auto noise = sampleNormal(obsCount) * noiseLevel;\n\n // Define observations by sampling random uniform distribution\n Matrix X = sampleUnif(-1.0, 1.0, obsCount, inputDim);\n Matrix y; y.resize(obsCount, 1);\n \n // Define target observations 'y' by applying 'targetFunc'\n // to the input observations 'X' and adding a noise vector\n for ( auto i : boost::irange(0,obsCount) )\n y(i) = targetFunc(X.row(i)) + noise(i);\n\n\n \n //\n // [ Construct Gaussian Process Model ]\n //\n\n // Initialize Gaussian process model\n GaussianProcess model;\n \n // Specify training observations for GP model\n model.setObs(X,y);\n\n // Fix noise level [ noise level is fit to the training data by default ]\n //model.setNoise(0.33);\n \n // Initialize a RBF covariance kernel and assign it to the model\n RBF kernel;\n model.setKernel(kernel);\n\n // Specify hyperparameter bounds [ including noise bounds (index 0) ]\n // Vector lbs(2); lbs << 0.0001 , 0.01;\n // Vector ubs(2); ubs << 5.0 , 100.0;\n // model.setBounds(lbs, ubs);\n\n // Specify hyperparameter bounds [ excluding noise bounds ]\n Vector lbs(1); lbs << 0.01;\n Vector ubs(1); ubs << 100.0;\n model.setBounds(lbs, ubs);\n \n\n // Fit covariance kernel hyperparameters to the training data\n time start = high_resolution_clock::now();\n model.fitModel(); \n time end = high_resolution_clock::now();\n auto computationTime = getTime(start, end);\n\n // Display computation time required for fitting the GP model\n cout << \"\\nComputation Time: \";\n cout << computationTime << \" s\" << endl;\n\n // Retrieve the tuned/optimized kernel hyperparameters\n auto optParams = model.getParams();\n cout << \"\\nOptimized Hyperparameters:\" << endl << optParams.transpose() << \" \";\n auto noiseL = model.getNoise();\n cout << \"(Noise = \" << noiseL << \")\\n\" << endl;\n\n // Display the negative log marginal likelihood (NLML) of the optimized model\n cout << \"NLML: \" << std::fixed << std::setprecision(4) << model.computeNLML() << endl << endl;\n\n\n //double eps = std::numeric_limits::min();\n //cout << \"Epsilon: \" << eps << endl;\n \n //\n // [ Posterior Predictions and Samples ]\n //\n\n // Define test mesh for GP model predictions\n int predCount;\n if ( inputDim == 1 )\n predCount = 100;\n else\n predCount = 1000;\n //int predRes = static_cast(std::sqrt(predCount));\n int predRes = static_cast(std::pow(predCount,1.0/inputDim));\n //auto testMesh = linspace(0.0, 1.0, predCount);\n auto testMesh = linspace(-1.0, 1.0, predRes, inputDim);\n model.setPred(testMesh);\n\n // Reset predCount to account for rounding\n predCount = std::pow(predRes,inputDim);\n\n // Compute predicted means and variances for the test points\n model.predict();\n Matrix pmean = model.getPredMean();\n Matrix pvar = model.getPredVar();\n Matrix pstd = pvar.array().sqrt().matrix();\n\n // Get sample paths from the posterior distribution of the model\n int sampleCount;\n Matrix samples;\n if ( inputDim == 1 )\n {\n sampleCount = 25;\n samples = model.getSamples(sampleCount);\n }\n\n \n //\n // [ Save Results for Plotting ]\n //\n \n // Save true and predicted means/variances to file\n std::string outputFile = \"predictions.csv\";\n //Matrix trueSoln = testMesh.unaryExpr(std::ptr_fun(targetFunc));\n\n Matrix trueSoln(predCount,1);\n for ( auto i : boost::irange(0,predCount) )\n trueSoln(i,0) = targetFunc(testMesh.row(i));\n\n std::ofstream fout;\n fout.open(outputFile);\n for ( auto i : boost::irange(0,predCount) )\n {\n for ( auto j : boost::irange(0,inputDim) )\n fout << testMesh(i,j) << \",\";\n \n fout << trueSoln(i) << \",\" << pmean(i) << \",\" << pstd(i) << \"\\n\";\n }\n fout.close();\n\n // Save observations to file\n std::string outputObsFile = \"observations.csv\";\n fout.open(outputObsFile);\n for ( auto i : boost::irange(0,obsCount) )\n {\n for ( auto j : boost::irange(0,inputDim) )\n fout << X(i,j) << \",\";\n \n fout << y(i) << \"\\n\";\n }\n fout.close();\n\n\n if ( inputDim == 1 )\n {\n // Save samples to file\n std::string outputSampleFile = \"samples.csv\";\n fout.open(outputSampleFile);\n for ( auto j : boost::irange(0,sampleCount) )\n {\n for ( auto i : boost::irange(0,predCount) )\n fout << samples(i,j) << ((i\n#include \n\nusing namespace std;\nusing namespace arma;\nvoid setZeroMean(mat& A)\n\n{\n int n_rows;\n int D;\n n_rows=A.n_rows;\n cout<<\"number row:\"<(4,5); //random matrix 4 rows 5 cols\n setZeroMean(A);\n mat Mean=mean(A);\n cout<<\" centered data new Mean =\"<(4,5);\n\n// cout << A*B.t() << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "95d45a9c3bb8c81ddf509f8fc6974c5b35c34d3b", "size": 705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "armadilloexample.cpp", "max_stars_repo_name": "lyase/barnes-hut-sne", "max_stars_repo_head_hexsha": "dff66e307877de3f205621ac4da86e5c8159f878", "max_stars_repo_licenses": ["BSD-4-Clause-UC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "armadilloexample.cpp", "max_issues_repo_name": "lyase/barnes-hut-sne", "max_issues_repo_head_hexsha": "dff66e307877de3f205621ac4da86e5c8159f878", "max_issues_repo_licenses": ["BSD-4-Clause-UC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "armadilloexample.cpp", "max_forks_repo_name": "lyase/barnes-hut-sne", "max_forks_repo_head_hexsha": "dff66e307877de3f205621ac4da86e5c8159f878", "max_forks_repo_licenses": ["BSD-4-Clause-UC"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.7352941176, "max_line_length": 58, "alphanum_fraction": 0.5957446809, "num_tokens": 217, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505428129513, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6695991332098471}} {"text": "//\n// diff.cpp\n//\n// Copyright (c) 2021 Izadori\n//\n// This software is released under the MIT License.\n// http://opensource.org/licenses/mit-license.php\n//\n\n#include \n\ntemplate \nconst Eigen::MatrixXd Diff(const Eigen::MatrixBase & m, const unsigned int n = 1)\n{\n Eigen::MatrixXd mr = m;\n\n for(unsigned int i = 0; i < n; i++)\n {\n mr = (mr.topRows(mr.rows() - 1) - mr.bottomRows(mr.rows() - 1)).eval();\n }\n\n return mr;\n}\n\ntemplate \nconst Eigen::SparseMatrix Diff(const Eigen::SparseMatrixBase & m, const unsigned int n = 1)\n{\n Eigen::SparseMatrix mr = m;\n\n for(unsigned int i = 0; i < n; i++)\n {\n mr = (mr.topRows(mr.rows() - 1) - mr.bottomRows(mr.rows() - 1)).eval();\n }\n\n return mr;\n}\n", "meta": {"hexsha": "8d0d77fc47a7cd6dcaf019814154dc72d2139044", "size": 812, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "diff.cpp", "max_stars_repo_name": "Izadori/cpp_eigen", "max_stars_repo_head_hexsha": "61ce61a675ff2ad16d36f70fcecd80f5742d36a5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-01-25T08:30:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-25T08:30:07.000Z", "max_issues_repo_path": "diff.cpp", "max_issues_repo_name": "Izadori/cpp_eigen", "max_issues_repo_head_hexsha": "61ce61a675ff2ad16d36f70fcecd80f5742d36a5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "diff.cpp", "max_forks_repo_name": "Izadori/cpp_eigen", "max_forks_repo_head_hexsha": "61ce61a675ff2ad16d36f70fcecd80f5742d36a5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9459459459, "max_line_length": 108, "alphanum_fraction": 0.6145320197, "num_tokens": 235, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7690802370707281, "lm_q1q2_score": 0.6695591639092547}} {"text": "/**************************************\n * Class Name: PRNG, PrimeGen\n * Function: 伪随机数与伪随机素数比特生成器\n * Introduction: PrimeGen 继承于 PRNG 类\n * ***********************************/\n\n#include \"Random.h\"\n#include \"TDES.h\"\n#include \n#include \n#include \n#include \n \nusing namespace std;\nusing namespace NTL;\n\ntypedef unsigned long long size_ul;\n\n/*---------------------------------\n * Class: PRNG\n *-------------------------------*/\n\n// 构造函数,进行初始化操作\nPRNG::PRNG(int n) {\n m = n;\n x = new bitset<64>[m];\n s = \"\";\n}\n\n// 析构函数,释放内存空间\nPRNG::~PRNG() {\n delete [] x;\n}\n\n// 通过外界修改 m 的数值\nvoid PRNG::SetM(int n) {\n m = n;\n delete [] x;\n x = new bitset<64>[m];\n}\n\n// 伪随机数比特生成函数\nZZ PRNG::GenerateRandom() {\n // 获取本地时间日期\n time_t now = time(0);\n bitset<64> Date(now);\n\n // 产生 64 比特随机种子 s\n size_ul ss = size_ul(random()) << 32 + random();\n bitset<64> s(ss);\n\n TDES td;\n td.plain = Date;\n bitset<64> Im = td.TDESEncrypt();\n for (int i = 0; i < m; i++) {\n td.plain = Im ^ s;\n x[i] = td.TDESEncrypt();\n td.plain = x[i] ^ Im;\n s = td.TDESEncrypt();\n }\n\n // 生成字符串类型保存\n bitsToString();\n ZZ res = bitsToNumber();\n return res;\n}\n\n// 将比特数转化为 ZZ 型数字\nZZ PRNG::bitsToNumber() {\n ZZ res(0);\n for (int i = 0; i < m; i++) {\n string str = x[i].to_string();\n for (int j = 0; j < 64; j++) {\n res = res * 2;\n if (str[j] == '1') {\n res = res + 1;\n }\n }\n }\n return res;\n}\n\n// 比特位转为字符串类型(01字符串)\nvoid PRNG::bitsToString() {\n s = \"\";\n for (int i = 0; i < m; i++) {\n s += x[i].to_string();\n }\n}\n\n// 以十六进制打印比特数值\nvoid PRNG::PrintInDER() {\n cout << \"modulus:\";\n string pairstr = \"\";\n for (size_t i = 0; i < s.length(); i += 4) {\n int index = 0;\n \n for (size_t j = i; j < i + 4; j++) {\n index = index << 1;\n if (s[j] == '1') {\n index += 1;\n }\n }\n pairstr += DERTable[index];\n if (pairstr.length() == 2) {\n cout << pairstr;\n if (i + 4 < s.length()) {\n cout << \":\";\n }\n pairstr = \"\";\n }\n if (i % 120 == 0) {\n cout << endl << '\\t';\n }\n }\n cout << endl;\n}\n\n\n/*---------------------------------\n * Class: PrimeGen\n *-------------------------------*/\n\nPrimeGen::PrimeGen(int n) : PRNG(n) {\n cout << \"Create a pseudorandom number generator.\\n\";\n}\n\n// 生成随机素数,使用 NTL 中库函数检验\n// 素性检测算法为 Miller-Rabin 检测\nZZ PrimeGen::GeneratePrime() {\n ZZ res(0);\n // 此处进行 srandom,为产生 64 比特随机种子\n srandom((unsigned)time(NULL));\n do {\n res = GenerateRandom();\n } while(!ProbPrime(res, m * 32));\n\n return res;\n}", "meta": {"hexsha": "c2c59e3de767f1acef373193b01c88b784d71a01", "size": 2776, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Random.cpp", "max_stars_repo_name": "yuanyangwangTJ/RSA", "max_stars_repo_head_hexsha": "384423bf33d555047755bb253a3531e35870ffd6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Random.cpp", "max_issues_repo_name": "yuanyangwangTJ/RSA", "max_issues_repo_head_hexsha": "384423bf33d555047755bb253a3531e35870ffd6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Random.cpp", "max_forks_repo_name": "yuanyangwangTJ/RSA", "max_forks_repo_head_hexsha": "384423bf33d555047755bb253a3531e35870ffd6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.9712230216, "max_line_length": 56, "alphanum_fraction": 0.4398414986, "num_tokens": 938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6695591581885}} {"text": "/****************************************\n * Creator : Léo Gaspard *\n * Mail : leo.gaspard@outlook.fr *\n * Git : https://github.com/NehZio *\n * *\n * Date : 26/08/2019 *\n * *\n * File : main.cpp *\n ****************************************/\n\n\n#include \n#include \n#include \n#include \n#include \n\nint main()\n{\n\tint norb(3);\n\tint nvec(3);\n\n\n\tEigen::MatrixXcd c(nvec,nvec);\n\tEigen::MatrixXcd d(norb,nvec);\n\tEigen::MatrixXcd p(nvec,nvec);\n\tEigen::MatrixXcd s(nvec,nvec);\n\tEigen::MatrixXcd invSqrtS(nvec,nvec);\n\tEigen::MatrixXcd pON(nvec,nvec);\n\tEigen::MatrixXcd heff(nvec,nvec);\n\tEigen::MatrixXd e(nvec,nvec);\n\n\n\tEigen::FullPivLU lu;\n\tEigen::ComplexEigenSolver eig;\n\n\tstd::cout << std::fixed << std::setprecision(6);\n\tstd::cout << std::endl << \"This program will perform Heff calculations using the method described in : \\n Chem. Rev. 2014, 114, 1, 429-492\" << std::endl;\n\n\n//*************************************************\n/*\n * Manual initialization of c\n */\n\n\tc(0,1) = {-0.4867551E+00,0.0000E-10};\n\tc(0,0) = {-0.2653160E+00,0.0000E-10};\n\tc(0,2) = { 0.7520712E+00,0.0000E-10};\n\n\tc(1,1) = { 0.6126111E+00,0.0000E-10};\n\tc(1,0) = {-0.7456646E+00,0.0000E-10};\n\tc(1,2) = { 0.1330535E+00,0.0000E-10};\n\n\tc(2,1) = {-0.5748099E+00,0.0000E-10};\n\tc(2,0) = {-0.5748095E+00,0.0000E-10};\n\tc(2,2) = {-0.5748079E+00,0.0000E-10};\n\n/*\n * Manual initializaion of e\n */\n\te(0,0) =-715.10E+00;\n\te(1,1) =-231.20E+00;\n\te(2,2) = 0.00E+00;\n//*************************************************\n\n\n\t\t\n\n\tstd::cout << std::endl << \"c Matrix : \" << std::endl << c << std::endl;\n\tstd::cout << std::endl << \"e Matrix : \" << std::endl << e << std::endl << std::endl; \n\n\n\t/***********************\n\t * Calculation of the *\n\t * projection operator *\n\t ***********************/\n\n\tstd::cout << std::endl << \"Projection matrix P = |I>* basis : \" << std::endl;\n\tstd::cout << std::endl << heff << std::endl;\n\n\t/***********************\n\t * Diagonalization of *\n\t * the effective *\n\t * Hamiltonian *\n\t ***********************/\n\n\teig.compute(heff);\n\n\tstd::cout << std::endl << \"Eigenvalues of the effective Hamiltonian :\" << std::endl;\n\tstd::cout << std::endl << eig.eigenvalues() << std::endl;\n\n\tstd::cout << std::endl << \"Eigenvectors of the effective Hamiltonian :\" << std::endl;\n\tstd::cout << std::endl << eig.eigenvectors() << std::endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "baf9ce6160669b73fa0120cfacc01232a9aa1acf", "size": 4129, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "NehZio/Heff", "max_stars_repo_head_hexsha": "59fd0fc8d287d7328c98c92145e969cdedaba48c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "NehZio/Heff", "max_issues_repo_head_hexsha": "59fd0fc8d287d7328c98c92145e969cdedaba48c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "NehZio/Heff", "max_forks_repo_head_hexsha": "59fd0fc8d287d7328c98c92145e969cdedaba48c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1329113924, "max_line_length": 154, "alphanum_fraction": 0.4945507387, "num_tokens": 1271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425333801889, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6694771914979003}} {"text": "#include \n#include \n#include \n#include \n#include \n\nusing Eigen::Vector3d;\nusing std::runtime_error;\n\nnamespace lambert {\n struct LambertResults {\n Vector3d v0;\n Vector3d v;\n };\n\n double c2(double psi) {\n double res;\n auto eps = 1.0;\n if (psi > eps) {\n res = (1 - cos(sqrt(psi))) / psi;\n } else if (psi < -eps) {\n res = (cosh(sqrt(-psi)) - 1) / (-psi);\n } else {\n res = 1.0 / 2.0;\n auto delta = (-psi) / tgamma(2 + 2 + 1);\n auto k = 1;\n while (res + delta != res) {\n res += delta;\n k += 1;\n delta = pow(-psi, k) / tgamma(2*k + 2 + 1);\n }\n }\n return res;\n }\n\n double c3(double psi) {\n double res;\n auto eps = 1.0;\n if (psi > eps) {\n res = (sqrt(psi) - sin(sqrt(psi))) / (psi * sqrt(psi));\n } else if (psi < -eps) {\n res = (sinh(sqrt(-psi)) - sqrt(-psi)) / (-psi * sqrt(-psi));\n } else {\n res = 1.0 / 6.0;\n auto delta = (-psi) / tgamma(2 + 3 + 1);\n int k = 1;\n while (res + delta != res) {\n res += delta;\n k += 1;\n delta = pow(-psi, k) / tgamma(2*k + 3 + 1);\n }\n }\n return res;\n }\n\n LambertResults lambert(double k, Vector3d r0, Vector3d r, double tof,\n bool shortway=true, int numiter=35, double rtol=1e-8) {\n int t_m;\n if (shortway) {\n t_m = 1;\n } else {\n t_m = -1;\n }\n auto norm_r0 = r0.norm();\n auto norm_r = r.norm();\n auto cos_dnu = r0.dot(r) / (norm_r * norm_r0);\n\n auto A = t_m * sqrt(norm_r * norm_r0 * (1 + cos_dnu));\n\n if (A == 0.0) {\n throw runtime_error(\"Cannot compute orbit, phase angle is 180 degrees\");\n }\n\n auto psi = 0.0;\n auto psi_low = -4*M_PI;\n auto psi_up = 4*M_PI;\n\n auto count = 0;\n double y;\n while (count < numiter) {\n y = norm_r0 + norm_r + A * (psi * c3(psi) - 1) / sqrt(c2(psi));\n if (A > 0.0 & y < 0.0) {\n while (y < 0.0) {\n psi_low = psi;\n psi = (0.8 * (1.0 / c3(psi)) *\n (1.0 - (norm_r0 + norm_r) * sqrt(c2(psi)) / A));\n y = norm_r0 + norm_r + A * (psi * c3(psi) - 1) / sqrt(c2(psi));\n }\n }\n auto xi = sqrt(y / c2(psi));\n auto tof_new = (pow(xi, 3) * c3(psi) + A * sqrt(y)) / sqrt(k);\n\n if (fabs((tof_new - tof) / tof) < rtol) {\n break;\n } else {\n count += 1;\n if (tof_new <= tof) {\n psi_low = psi;\n } else {\n psi_up = psi;\n }\n psi = (psi_up + psi_low) / 2;\n }\n }\n if (count > numiter) {\n throw runtime_error(\"Maximum number of iterations reached\");\n }\n auto f = 1 - y / norm_r0;\n auto g = A * sqrt(y / k);\n auto gdot = 1 - y / norm_r;\n auto v0 = (r - f * r0) / g;\n auto v = (gdot * r - r0) / g;\n LambertResults results = {v, v0};\n return results;\n }\n\n void benchmark(int times) {\n auto mu = 3.986004418e5;\n Vector3d r0(5000.0, 10000.0, 2100.0);\n Vector3d r(-14600.0, 2500.0, 7000.0);\n auto tof = 3600.0;\n\n auto best = std::numeric_limits::infinity();\n auto worst = -std::numeric_limits::infinity();\n double all = 0;\n for (auto i=0; i < times; i++) {\n auto begin = std::chrono::high_resolution_clock::now();\n\n lambert(mu, r0, r, tof);\n\n auto end = std::chrono::high_resolution_clock::now();\n auto current = std::chrono::duration_cast(end-begin).count()/1e9;\n all += current;\n if (current < best) {\n best = current;\n }\n if (current > worst) {\n worst = current;\n }\n }\n std::cout << \"[\" << all/times << \",\" << best << \",\" << worst << \"]\" << std::endl;\n }\n}\n", "meta": {"hexsha": "c12ab7a9d981cbf430b4c1d9a17b0c9927c5f217", "size": 4327, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/lambert.cpp", "max_stars_repo_name": "helgee/icatt-2016", "max_stars_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-05-07T19:09:15.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-06T14:31:44.000Z", "max_issues_repo_path": "cpp/src/lambert.cpp", "max_issues_repo_name": "OpenAstrodynamics/benchmarks", "max_issues_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-05-05T14:36:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T09:18:55.000Z", "max_forks_repo_path": "cpp/src/lambert.cpp", "max_forks_repo_name": "OpenAstrodynamics/benchmarks", "max_forks_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T12:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T14:19:13.000Z", "avg_line_length": 30.0486111111, "max_line_length": 103, "alphanum_fraction": 0.4201525306, "num_tokens": 1254, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425245706047, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6694771796573123}} {"text": "#include \n#include \n#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\nMatrixXf computeLinkPos(MatrixXf L, MatrixXf P, Matrix3f R, MatrixXf s, MatrixXf pb);\nMatrixXf computeActuation(MatrixXf L, float lc);\n\nMatrixXf computeSliderControl(float re,float rb,float lc,float D,float Pz,float xd, float yd, float zd,float phi,float theta,float psi) {\n// float* computeSliderControl(float re,float rb,float lc,float D,float Pz,float xd, float yd, float zd,float phi,float theta,float psi) {\n // void computeSliderControl(float re,float rb,float lc,float D,float Pz,float xd, float yd, float zd,float phi,float theta,float psi) {\n // - スライダー間距離D[mm] : 56+(12/2)*2=68mm\n // - ロッド長さlc[mm] : 262+(8/2)*2=268mm\n // - スライダー設置半径rb[mm] : sqrt(269.7^2-200.5^2)=180.38248\n // - テーブル半径re[mm] :90mm\n // - テーブル初期高さPz[mm] :438.17mm\n // float re = 90;\n // float Pz = 438.17;\n // float D = 68;\n // float lc = 268;\n // float rb = 180.38;\n\n float th = asin(D/(2*rb)); //% theta1: angle (linear actuator)\n float th2 = asin(D/(2*re)); //% theta2: angle (end effector)\n\n MatrixXf pb(6,3);\n pb << \n rb*cos(th),rb*sin(th),0,\n rb*cos(-th),rb*sin(-th),0,\n rb*cos(2*M_PI/3+th),rb*sin(2*M_PI/3+th),0,\n rb*cos(2*M_PI/3-th),rb*sin(2*M_PI/3-th),0,\n rb*cos(4*M_PI/3+th),rb*sin(4*M_PI/3+th),0,\n rb*cos(4*M_PI/3-th),rb*sin(4*M_PI/3-th),0;\n\n MatrixXf s_local(6,3);\n s_local << \n re*cos(th2),re*sin(th2),0,\n re*cos(-th2),re*sin(-th2),0,\n re*cos(2*M_PI/3+th2),re*sin(2*M_PI/3+th2),0,\n re*cos(2*M_PI/3-th2),re*sin(2*M_PI/3-th2),0,\n re*cos(4*M_PI/3+th2),re*sin(4*M_PI/3+th2),0,\n re*cos(4*M_PI/3-th2),re*sin(4*M_PI/3-th2),0;\n\n MatrixXf sliders(6,3);\n sliders <<\n rb*cos(th),rb*sin(th),Pz,\n rb*cos(-th),rb*sin(-th),Pz,\n rb*cos(2*M_PI/3+th),rb*sin(2*M_PI/3+th),Pz,\n rb*cos(2*M_PI/3-th),rb*sin(2*M_PI/3-th),Pz,\n rb*cos(4*M_PI/3+th),rb*sin(4*M_PI/3+th),Pz,\n rb*cos(4*M_PI/3-th),rb*sin(4*M_PI/3-th),Pz;\n\n // float phi = M_PI/24; //% rotation around X axis\n // float theta = M_PI/12; //% rotation around Y axis\n // float psi = M_PI/16; //% rotation around Z axis\n\n Matrix3f R;\n R << \n cos(phi)*cos(theta),cos(phi)*sin(theta)*sin(psi)-sin(phi)*cos(psi),cos(phi)*sin(theta)*cos(psi)+sin(phi)*sin(psi),\n sin(phi)*cos(theta),sin(phi)*sin(theta)*sin(psi)+cos(phi)*cos(psi),sin(phi)*sin(theta)*cos(psi)-cos(phi)*sin(psi),\n -sin(theta),cos(theta)*sin(psi),cos(theta)*cos(psi);\n\n Vector3f a;\n a << 0,0,1;\n\n MatrixXf s(6,3);\n s = s_local*R;//6x3 x 3x3 => 6x3\n\n MatrixXf P(1,3);\n P << xd,yd,zd; //% Position Vector of the end effector\n // P << 50,50,height; //% Position Vector of the end effector\n\n // cout << \"*** re: \" << endl << s << endl;\n // cout << \"*** rb: \" << endl << rb << endl;\n // cout << \"*** pb: \" << endl << pb << endl;\n // cout << \"*** R: \" << endl<< R << endl;\n\n MatrixXf L(6,3);\n L << computeLinkPos(L, P, R, s, pb); \n // cout << \"*** L: \" << endl << L << endl;\n\n MatrixXf C(1,6);\n C << computeActuation(L,lc);\n cout << \"*** C: \" << endl << C << endl;\n\n return C;\n // float* arrayf = C.data();\n} \n\n// %% compute position vector of rod end of end effector\nMatrixXf computeLinkPos(MatrixXf L, MatrixXf P, Matrix3f R, MatrixXf s, MatrixXf pb){\n // L = P + R*s - pb;\n for(int i=0;i<6;i++){\n L.block(i,0,1,3) << P + (s.block(i,0,1,3))*R - pb.block(i,0,1,3);\n }\n return L;\n}\n\nMatrixXf computeActuation(MatrixXf L, float lc){\n MatrixXf C(1,6); \n for (int i=0;i<6;i++){\n float lxi = L(i,0);\n float lyi = L(i,1);\n float lzi = L(i,2);\n C.block(0,i,1,1) << lzi - sqrt(lc*lc-lxi*lxi-lyi*lyi);\n }\n return C;\n}\n\n\nextern \"C\" {\n void solveInverseMechanism(float* arrayf, float re,float rb,float lc,float D,float Pz,float xd, float yd, float zd,float phi,float theta,float psi){\n MatrixXf C(1,6);\n C << computeSliderControl(re,rb,lc,D,Pz,xd,yd,zd,phi,theta,psi);\n memcpy(arrayf,C.data(),C.size()*sizeof(float));\n }\n}\n", "meta": {"hexsha": "7db077a830ece347110d1e70effc54720ff5cc33", "size": 4008, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "frontend/six_axes_parallel/src/solve_inverse_kinematics.cpp", "max_stars_repo_name": "shohei/6axes-nanokontrol", "max_stars_repo_head_hexsha": "731c33b21d444dba30e31eed0e4c75c51c366700", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "frontend/six_axes_parallel/src/solve_inverse_kinematics.cpp", "max_issues_repo_name": "shohei/6axes-nanokontrol", "max_issues_repo_head_hexsha": "731c33b21d444dba30e31eed0e4c75c51c366700", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2016-06-04T02:34:35.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-04T02:48:17.000Z", "max_forks_repo_path": "frontend/six_axes_parallel/src/solve_inverse_kinematics.cpp", "max_forks_repo_name": "shohei/6axes-nanokontrol", "max_forks_repo_head_hexsha": "731c33b21d444dba30e31eed0e4c75c51c366700", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4, "max_line_length": 150, "alphanum_fraction": 0.5953093812, "num_tokens": 1554, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632896242073, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6693181596065171}} {"text": "#ifndef CANNON_MATH_MULTIVARIATE_NORMAL_H\n#define CANNON_MATH_MULTIVARIATE_NORMAL_H \n\n/*!\n * \\file cannon/math/multivariate_normal.hpp\n * \\brief File containing MultivariateNormal class definition.\n */\n\n#include \n\n#include \n\nusing namespace Eigen;\n\nnamespace cannon {\n namespace math {\n\n /*!\n * \\brief Class representing a multivariate normal distribution of\n * arbitrary dimensionality.\n */\n class MultivariateNormal {\n public:\n MultivariateNormal() = delete;\n\n /*!\n * \\brief Constructor taking a covariance matrix. The distribution is\n * assumed to be centered at zero.\n */\n MultivariateNormal(const Ref& covar) :\n MultivariateNormal(VectorXd::Zero(covar.rows()), covar) {}\n\n /*!\n * \\brief Constructor taking a mean and covariance matrix.\n */\n MultivariateNormal(const Ref &mean, const Ref &covar)\n : mean_(mean),\n transform_(MatrixXd::Zero(mean.size(), mean.size())) {\n SelfAdjointEigenSolver eigen_solver(covar);\n transform_ = eigen_solver.eigenvectors() *\n eigen_solver.eigenvalues().cwiseSqrt().asDiagonal();\n }\n\n /*!\n * \\brief Sample a point from this distribution.\n *\n * \\returns A sample from the multivariate normal distribution\n * represented by this object.\n */\n VectorXd sample() const {\n return mean_ + (transform_ * VectorXd::NullaryExpr(mean_.size(),\n [&](){return dist(gen);}));\n }\n\n /*!\n * \\brief Set the seed for all normal distributions.\n *\n * \\param seed The new seed to use.\n */ \n static void set_seed(int seed);\n\n static std::random_device rd; //!< Physical random number generator.\n static std::mt19937 gen; //!< Pseudo-random number generator.\n static std::normal_distribution dist; //!< 1D normal distribution for sampling\n\n private:\n VectorXd mean_; //!< Mean of this normal distribution\n MatrixXd transform_; //!< Transform used to compute multivariate samples\n\n };\n\n }\n}\n\n#endif /* ifndef CANNON_MATH_MULTIVARIATE_NORMAL_H */\n", "meta": {"hexsha": "35993cb83d8252c6fedb5ecc512e7c1acd310ea0", "size": 2285, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/math/multivariate_normal.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/math/multivariate_normal.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/math/multivariate_normal.hpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0657894737, "max_line_length": 94, "alphanum_fraction": 0.6249452954, "num_tokens": 479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6692449369358631}} {"text": "// smooth: Lie Theory for Robotics\n// https://github.com/pettni/smooth\n//\n// Licensed under the MIT License .\n//\n// Copyright (c) 2021 Petter Nilsson\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#ifndef SMOOTH__INTERNAL__SO3_HPP_\n#define SMOOTH__INTERNAL__SO3_HPP_\n\n#include \n\n#include \"common.hpp\"\n\nnamespace smooth {\n\n/**\n * @brief SO(3) Lie group represented as S^3\n *\n * Memory layout\n * -------------\n * Group: qx qy qz qw (same as Eigen quaternion)\n * Tangent: Ωx Ωy Ωz\n *\n * Lie group Matrix form\n * ---------------------\n * 3x3 rotation matrix\n *\n * Lie algebra Matrix form\n * -----------------------\n * [ 0 -Ωz Ωy ]\n * [ Ωz 0 -Ωx ]\n * [ -Ωy Ωx 0 ]\n *\n * Constraints\n * -----------\n * Group: qx * qx + qy * qy + qz * qz + qw * qw = 1\n * Tangent: -pi < Ωx, Ωy, Ωz <= pi\n */\ntemplate\nclass SO3Impl\n{\npublic:\n using Scalar = _Scalar;\n\n static constexpr Eigen::Index RepSize = 4;\n static constexpr Eigen::Index Dim = 3;\n static constexpr Eigen::Index Dof = 3;\n static constexpr bool IsCommutative = false;\n\n SMOOTH_DEFINE_REFS;\n\n static void setIdentity(GRefOut g_out) { g_out << Scalar(0), Scalar(0), Scalar(0), Scalar(1); }\n\n static void setRandom(GRefOut g_out)\n {\n g_out = Eigen::Quaternion::UnitRandom().coeffs();\n if (g_out[3] < Scalar(0)) { g_out *= Scalar(-1); }\n }\n\n static void matrix(GRefIn g_in, MRefOut m_out)\n {\n Eigen::Map> q(g_in.data());\n m_out = q.toRotationMatrix();\n }\n\n static void composition(GRefIn g_in1, GRefIn g_in2, GRefOut g_out)\n {\n Eigen::Map> q1(g_in1.data());\n Eigen::Map> q2(g_in2.data());\n g_out = (q1 * q2).coeffs();\n if (g_out[3] < Scalar(0)) { g_out *= Scalar(-1); }\n }\n\n static void inverse(GRefIn g_in, GRefOut g_out)\n {\n Eigen::Map> q(g_in.data());\n g_out = q.inverse().coeffs();\n }\n\n static void log(GRefIn g_in, TRefOut a_out)\n {\n using std::atan2, std::sqrt;\n const Scalar xyz2 = g_in[0] * g_in[0] + g_in[1] * g_in[1] + g_in[2] * g_in[2];\n\n const auto phi = [&]() -> Scalar {\n if (xyz2 < Scalar(eps2)) {\n // https://www.wolframalpha.com/input/?i=series+atan%28y%2Fx%29+%2F+y+at+y%3D0\n return Scalar(2) / g_in[3] - Scalar(2) * xyz2 / (Scalar(3) * g_in[3] * g_in[3] * g_in[3]);\n } else {\n const Scalar xyz = sqrt(xyz2);\n return Scalar(2) * atan2(xyz, g_in[3]) / xyz;\n }\n }();\n\n a_out << g_in[0], g_in[1], g_in[2];\n a_out *= phi;\n }\n\n static void Ad(GRefIn g_in, TMapRefOut A_out)\n {\n Eigen::Map> q(g_in.data());\n A_out = q.toRotationMatrix();\n }\n\n static void exp(TRefIn a_in, GRefOut g_out)\n {\n using std::sqrt, std::cos, std::sin;\n\n const Scalar th2 = a_in.squaredNorm();\n\n const auto [A, B] = [&]() -> std::array {\n if (th2 < Scalar(eps2)) {\n return {\n // https://www.wolframalpha.com/input/?i=series+sin%28x%2F2%29%2Fx+at+x%3D0\n Scalar(1) / Scalar(2) - th2 / Scalar(48),\n // https://www.wolframalpha.com/input/?i=series+cos%28x%2F2%29+at+x%3D0\n Scalar(1) - th2 / Scalar(8),\n };\n } else {\n const Scalar th = sqrt(th2);\n return {\n sin(th / Scalar(2)) / th,\n cos(th / Scalar(2)),\n };\n }\n }();\n\n g_out << A * a_in.x(), A * a_in.y(), A * a_in.z(), B;\n if (g_out[3] < Scalar(0)) { g_out *= Scalar(-1); }\n }\n\n static void hat(TRefIn a_in, MRefOut A_out)\n {\n A_out << Scalar(0), -a_in(2), a_in(1), a_in(2), Scalar(0), -a_in(0), -a_in(1), a_in(0),\n Scalar(0);\n }\n\n static void vee(MRefIn A_in, TRefOut a_out)\n {\n a_out << (A_in(2, 1) - A_in(1, 2)) / Scalar(2), (A_in(0, 2) - A_in(2, 0)) / Scalar(2),\n (A_in(1, 0) - A_in(0, 1)) / Scalar(2);\n }\n\n static void ad(TRefIn a_in, TMapRefOut A_out) { hat(a_in, A_out); }\n\n static void dr_exp(TRefIn a_in, TMapRefOut A_out)\n {\n using std::sqrt, std::sin, std::cos;\n const Scalar th2 = a_in.squaredNorm();\n\n const auto [A, B] = [&]() -> std::array {\n if (th2 < Scalar(eps2)) {\n return {\n // https://www.wolframalpha.com/input/?i=series+%281-cos+x%29+%2F+x%5E2+at+x%3D0\n Scalar(1) / Scalar(2) - th2 / Scalar(24),\n // https://www.wolframalpha.com/input/?i=series+%28x+-+sin%28x%29%29+%2F+x%5E3+at+x%3D0\n Scalar(1) / Scalar(6) - th2 / Scalar(120),\n };\n } else {\n const Scalar th = sqrt(th2);\n return {\n (Scalar(1) - cos(th)) / th2,\n (th - sin(th)) / (th2 * th),\n };\n }\n }();\n\n using TangentMap = Eigen::Matrix;\n TangentMap ad_a;\n ad(a_in, ad_a);\n A_out.noalias() = TangentMap::Identity() - A * ad_a + B * ad_a * ad_a;\n }\n\n static void dr_expinv(TRefIn a_in, TMapRefOut A_out)\n {\n using std::sqrt, std::sin, std::cos;\n const Scalar th2 = a_in.squaredNorm();\n\n const auto A = [&]() -> Scalar {\n if (th2 < Scalar(eps2)) {\n // https://www.wolframalpha.com/input/?i=series+1%2Fx%5E2-%281%2Bcos+x%29%2F%282*x*sin+x%29+at+x%3D0\n return Scalar(1) / Scalar(12) + th2 / Scalar(720);\n } else {\n const Scalar th = sqrt(th2);\n return Scalar(1) / th2 - (Scalar(1) + cos(th)) / (Scalar(2) * th * sin(th));\n }\n }();\n\n using TangentMap = Eigen::Matrix;\n TangentMap ad_a;\n ad(a_in, ad_a);\n A_out.noalias() = TangentMap::Identity() + ad_a / Scalar(2) + A * ad_a * ad_a;\n }\n\n static void d2r_exp(TRefIn a_in, THessRefOut H_out)\n {\n const auto [A, B, dA_over_th, dB_over_th] = [&]() -> std::array {\n using std::sqrt;\n\n const Scalar th2 = a_in.squaredNorm();\n const Scalar th = sqrt(th2);\n\n if (th2 < Scalar(eps2)) {\n return {\n Scalar(0.5) - th2 / 24,\n Scalar(1. / 6) - th2 / 120,\n -Scalar(1) / 48,\n -Scalar(1) / 60,\n };\n } else {\n const Scalar sTh = sin(th);\n const Scalar cTh = cos(th);\n const Scalar th3 = th2 * th;\n const Scalar th4 = th2 * th2;\n const Scalar th5 = th3 * th2;\n return {\n (Scalar(1) - cTh) / th2,\n (th - sTh) / th3,\n sTh / th3 + 2 * cTh / th4 - 2 / th4,\n -cTh / th4 - 2 / th4 + 3 * sTh / th5,\n };\n }\n }();\n\n // -A * d(ad) + B * d(ad^2)\n // clang-format off\n H_out <<\n 0., -2 * B * a_in.y(), -2 * B * a_in.z(), B * a_in.y(), B * a_in.x(), -A, B * a_in.z(), A, B * a_in.x(),\n B * a_in.y(), B * a_in.x(), A, -2 * B * a_in.x(), 0., -2 * B * a_in.z(), -A, B * a_in.z(), B * a_in.y(),\n B * a_in.z(), -A, B * a_in.x(), A, B * a_in.z(), B * a_in.y(), -2 * B * a_in.x(), -2 * B * a_in.y(), 0.;\n // clang-format on\n\n // add -dA * ad + dB * ad^2\n Eigen::Matrix3 ad_a;\n ad(a_in, ad_a);\n const Eigen::Matrix3 ad_a2 = ad_a * ad_a;\n\n for (auto i = 0u; i < 3; ++i) {\n const Scalar dA_dxi = dA_over_th * a_in(i);\n const Scalar dB_dxi = dB_over_th * a_in(i);\n for (auto j = 0u; j < 3; ++j) {\n H_out.col(i + 3 * j) -= dA_dxi * ad_a.row(j).transpose();\n H_out.col(i + 3 * j) += dB_dxi * ad_a2.row(j).transpose();\n }\n }\n }\n\n static void d2r_expinv(TRefIn a_in, THessRefOut H_out)\n {\n const auto [A, dA_over_th] = [&]() -> std::array {\n using std::sqrt;\n\n const Scalar th2 = a_in.squaredNorm();\n const Scalar th = sqrt(th2);\n if (th2 < Scalar(eps2)) {\n return {\n Scalar(1) / Scalar(12) + th2 / Scalar(720),\n Scalar(1) / Scalar(360),\n };\n } else {\n const Scalar th3 = th2 * th;\n const Scalar th4 = th2 * th2;\n const Scalar sTh = sin(th);\n const Scalar cTh = cos(th);\n return {\n Scalar(1) / th2 - (Scalar(1) + cTh) / (Scalar(2) * th * sTh),\n 1 / (2 * th2) + cTh * cTh / (2 * th2 * sTh * sTh) + cTh / (2 * th2 * sTh * sTh)\n + cTh / (2 * th3 * sTh) + 1 / (2 * th3 * sTh) - 2 / th4,\n };\n }\n }();\n\n // A * d(ad^2)\n // clang-format off\n H_out <<\n 0, -2 * A * a_in.y(), -2 * A * a_in.z(), A * a_in.y(), A * a_in.x(), 0.5, A * a_in.z(), -0.5, A * a_in.x(),\n A * a_in.y(), A * a_in.x(), -0.5, -2 * A * a_in.x(), 0, -2 * A * a_in.z(), 0.5, A * a_in.z(), A * a_in.y(),\n A * a_in.z(), 0.5, A * a_in.x(), -0.5, A * a_in.z(), A * a_in.y(), -2 * A * a_in.x(), -2 * A * a_in.y(), 0;\n // clang-format on\n\n // add dA * ad^2\n Eigen::Matrix3 ad_a;\n ad(a_in, ad_a);\n const Eigen::Matrix3 ad_a2 = ad_a * ad_a;\n for (auto i = 0u; i < 3; ++i) {\n const Scalar dA_dxi = dA_over_th * a_in(i);\n for (auto j = 0u; j < 3; ++j) { H_out.col(i + 3 * j) += dA_dxi * ad_a2.row(j).transpose(); }\n }\n }\n};\n\n} // namespace smooth\n\n#endif // SMOOTH__INTERNAL__SO3_HPP_\n", "meta": {"hexsha": "dbe2a1702fdb504c2e6c390ccf94abc1fc5545fb", "size": 10007, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/smooth/internal/so3.hpp", "max_stars_repo_name": "tgurriet/smooth", "max_stars_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/smooth/internal/so3.hpp", "max_issues_repo_name": "tgurriet/smooth", "max_issues_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/smooth/internal/so3.hpp", "max_forks_repo_name": "tgurriet/smooth", "max_forks_repo_head_hexsha": "c19e35e23c8e0084314726729d0cf6729192240f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8694267516, "max_line_length": 113, "alphanum_fraction": 0.5516138703, "num_tokens": 3417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.900529778109184, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6692449167711142}} {"text": "// inverse_chi_squared_distribution_example.cpp\n\n// Copyright Paul A. Bristow 2010.\n// Copyright Thomas Mang 2010.\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// Example 1 of using inverse chi squared distribution\n#include \nusing boost::math::inverse_chi_squared_distribution; // inverse_chi_squared_distribution.\nusing boost::math::inverse_chi_squared; //typedef for nverse_chi_squared_distribution double.\n\n#include \nusing std::cout; using std::endl;\n#include \nusing std::setprecision;\nusing std::setw;\n#include \nusing std::sqrt;\n\ntemplate \nRealType naive_pdf1(RealType df, RealType x)\n{ // Formula from Wikipedia http://en.wikipedia.org/wiki/Inverse-chi-square_distribution\n // definition 1 using tgamma for simplicity as a check.\n using namespace std; // For ADL of std functions.\n using boost::math::tgamma;\n RealType df2 = df / 2;\n RealType result = (pow(2., -df2) * pow(x, (-df2 -1)) * exp(-1/(2 * x) ) )\n / tgamma(df2); //\n return result;\n}\n\ntemplate \nRealType naive_pdf2(RealType df, RealType x)\n{ // Formula from Wikipedia http://en.wikipedia.org/wiki/Inverse-chi-square_distribution\n // Definition 2, using tgamma for simplicity as a check.\n // Not scaled, so assumes scale = 1 and only uses nu aka df.\n using namespace std; // For ADL of std functions.\n using boost::math::tgamma;\n RealType df2 = df / 2;\n RealType result = (pow(df2, df2) * pow(x, (-df2 -1)) * exp(-df/(2*x) ) )\n / tgamma(df2);\n return result;\n}\n\ntemplate \nRealType naive_pdf3(RealType df, RealType scale, RealType x)\n{ // Formula from Wikipedia http://en.wikipedia.org/wiki/Scaled-inverse-chi-square_distribution\n // *Scaled* version, definition 3, df aka nu, scale aka sigma^2\n // using tgamma for simplicity as a check.\n using namespace std; // For ADL of std functions.\n using boost::math::tgamma;\n RealType df2 = df / 2;\n RealType result = (pow(scale * df2, df2) * exp(-df2 * scale/x) )\n / (tgamma(df2) * pow(x, 1+df2));\n return result;\n}\n\ntemplate \nRealType naive_pdf4(RealType df, RealType scale, RealType x)\n{ // Formula from http://mathworld.wolfram.com/InverseChi-SquaredDistribution.html\n // Weisstein, Eric W. \"Inverse Chi-Squared Distribution.\" From MathWorld--A Wolfram Web Resource.\n // *Scaled* version, definition 3, df aka nu, scale aka sigma^2\n // using tgamma for simplicity as a check.\n using namespace std; // For ADL of std functions.\n using boost::math::tgamma;\n RealType nu = df; // Wolfram uses greek symbols nu,\n RealType xi = scale; // and xi.\n RealType result =\n pow(2, -nu/2) * exp(- (nu * xi)/(2 * x)) * pow(x, -1-nu/2) * pow((nu * xi), nu/2)\n / tgamma(nu/2);\n return result;\n}\n\nint main()\n{\n\n cout << \"Example (basic) using Inverse chi squared distribution. \" << endl;\n\n // TODO find a more practical/useful example. Suggestions welcome?\n\n#ifdef BOOST_NO_CXX11_NUMERIC_LIMITS\n int max_digits10 = 2 + (boost::math::policies::digits >() * 30103UL) / 100000UL;\n cout << \"BOOST_NO_CXX11_NUMERIC_LIMITS is defined\" << endl;\n#else\n int max_digits10 = std::numeric_limits::max_digits10;\n#endif\n cout << \"Show all potentially significant decimal digits std::numeric_limits::max_digits10 = \"\n << max_digits10 << endl;\n cout.precision(max_digits10); //\n\n inverse_chi_squared ichsqdef; // All defaults - not very useful!\n cout << \"default df = \" << ichsqdef.degrees_of_freedom()\n << \", default scale = \" << ichsqdef.scale() << endl; // default df = 1, default scale = 0.5\n\n inverse_chi_squared ichsqdef4(4); // Unscaled version, default scale = 1 / degrees_of_freedom\n cout << \"default df = \" << ichsqdef4.degrees_of_freedom()\n << \", default scale = \" << ichsqdef4.scale() << endl; // default df = 4, default scale = 2\n\n inverse_chi_squared ichsqdef32(3, 2); // Scaled version, both degrees_of_freedom and scale specified.\n cout << \"default df = \" << ichsqdef32.degrees_of_freedom()\n << \", default scale = \" << ichsqdef32.scale() << endl; // default df = 3, default scale = 2\n\n {\n cout.precision(3);\n double nu = 5.;\n //double scale1 = 1./ nu; // 1st definition sigma^2 = 1/df;\n //double scale2 = 1.; // 2nd definition sigma^2 = 1\n inverse_chi_squared ichsq(nu, 1/nu); // Not scaled\n inverse_chi_squared sichsq(nu, 1/nu); // scaled\n\n cout << \"nu = \" << ichsq.degrees_of_freedom() << \", scale = \" << ichsq.scale() << endl;\n\n int width = 8;\n\n cout << \" x pdf pdf1 pdf2 pdf(scaled) pdf pdf cdf cdf\" << endl;\n for (double x = 0.0; x < 1.; x += 0.1)\n {\n cout\n << setw(width) << x\n << ' ' << setw(width) << pdf(ichsq, x) // unscaled\n << ' ' << setw(width) << naive_pdf1(nu, x) // Wiki def 1 unscaled matches graph\n << ' ' << setw(width) << naive_pdf2(nu, x) // scale = 1 - 2nd definition.\n << ' ' << setw(width) << naive_pdf3(nu, 1/nu, x) // scaled\n << ' ' << setw(width) << naive_pdf4(nu, 1/nu, x) // scaled\n << ' ' << setw(width) << pdf(sichsq, x) // scaled\n << ' ' << setw(width) << cdf(sichsq, x) // scaled\n << ' ' << setw(width) << cdf(ichsq, x) // unscaled\n << endl;\n }\n }\n\n cout.precision(max_digits10);\n\n inverse_chi_squared ichisq(2., 0.5);\n cout << \"pdf(ichisq, 1.) = \" << pdf(ichisq, 1.) << endl;\n cout << \"cdf(ichisq, 1.) = \" << cdf(ichisq, 1.) << endl;\n\n return 0;\n} // int main()\n\n/*\n\nOutput is:\n Example (basic) using Inverse chi squared distribution.\n Show all potentially significant decimal digits std::numeric_limits::max_digits10 = 17\n default df = 1, default scale = 1\n default df = 4, default scale = 0.25\n default df = 3, default scale = 2\n nu = 5, scale = 0.2\n x pdf pdf1 pdf2 pdf(scaled) pdf pdf cdf cdf\n 0 0 -1.#J -1.#J -1.#J -1.#J 0 0 0\n 0.1 2.83 2.83 3.26e-007 2.83 2.83 2.83 0.0752 0.0752\n 0.2 3.05 3.05 0.00774 3.05 3.05 3.05 0.416 0.416\n 0.3 1.7 1.7 0.121 1.7 1.7 1.7 0.649 0.649\n 0.4 0.941 0.941 0.355 0.941 0.941 0.941 0.776 0.776\n 0.5 0.553 0.553 0.567 0.553 0.553 0.553 0.849 0.849\n 0.6 0.345 0.345 0.689 0.345 0.345 0.345 0.893 0.893\n 0.7 0.227 0.227 0.728 0.227 0.227 0.227 0.921 0.921\n 0.8 0.155 0.155 0.713 0.155 0.155 0.155 0.94 0.94\n 0.9 0.11 0.11 0.668 0.11 0.11 0.11 0.953 0.953\n 1 0.0807 0.0807 0.61 0.0807 0.0807 0.0807 0.963 0.963\n pdf(ichisq, 1.) = 0.30326532985631671\n cdf(ichisq, 1.) = 0.60653065971263365\n\n\n*/\n", "meta": {"hexsha": "0fb6a6de08c6a9ec6d7aab1458488b528c12de9a", "size": 7092, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/inverse_chi_squared_example.cpp", "max_stars_repo_name": "Bpowers4/turicreate", "max_stars_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/inverse_chi_squared_example.cpp", "max_issues_repo_name": "Bpowers4/turicreate", "max_issues_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "src/external/boost/boost_1_68_0/libs/math/example/inverse_chi_squared_example.cpp", "max_forks_repo_name": "Bpowers4/turicreate", "max_forks_repo_head_hexsha": "73dad213cc1c4f74337b905baea2b3a1e5a0266c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 41.4736842105, "max_line_length": 122, "alphanum_fraction": 0.6122391427, "num_tokens": 2372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357494949105, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6692159101920716}} {"text": "#include \"core/BezierCurve.h\"\n\n#include \"core/Util.h\"\n#include \n\nBezierCurve::BezierCurve(const vector_t& control0, const vector_t& control1, const vector_t& control2, const vector_t& control3)\n : _control0(control0), _control1(control1), _control2(control2), _control3(control3) {\n\n}\n\nvector_t BezierCurve::Position(float t) const {\n if (t <= 0) {\n return _control0;\n } else if (t >= 1) {\n return _control3;\n } else {\n return (1 - t) * (1 - t) * (1 - t) * _control0 +\n 3 * (1 - t) * (1 - t) * t * _control1 +\n 3 * (1 - t) * t * t * _control2 +\n t * t * t * _control3;\n }\n}\n\nvector_t BezierCurve::Heading(float t) const {\n if (t <= 0) {\n return (_control1 - _control0).normalized();\n } else if (t >= 1) {\n return (_control3 - _control2).normalized();\n } else {\n return (3 * (1 - t) * (1 - t) * (_control1 - _control0) +\n 6 * (1 - t) * t * (_control2 - _control1) +\n 3 * t * t * (_control3 - _control2)).normalized();\n }\n}\n\nfloat BezierCurve::Length(float start, float end) const {\n if (start >= end) {\n return 0;\n } else {\n return boost::math::quadrature::trapezoidal(\n [this](float t) {\n vector_t grad = -3 * (1 - t) * (1 - t) * _control0 +\n 3 * (1 - t) * (1 - 3 * t) * _control1 +\n 3 * t * (2 - 3 * t) * _control2 +\n 3 * t * t * _control3;\n return grad.norm();\n },\n std::max(start, 0.0f), std::min(end, 1.0f), 1e-12f);\n }\n}\n", "meta": {"hexsha": "70d1539acd1b2eac8044f07212060ce559690bcb", "size": 1506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/core/BezierCurve.cpp", "max_stars_repo_name": "modanesh/magic", "max_stars_repo_head_hexsha": "2eec5c7a1e45a4594b02d8df1e7f2880d7fc8422", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-03-13T22:12:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-06T03:29:03.000Z", "max_issues_repo_path": "cpp/src/core/BezierCurve.cpp", "max_issues_repo_name": "modanesh/magic", "max_issues_repo_head_hexsha": "2eec5c7a1e45a4594b02d8df1e7f2880d7fc8422", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-07-17T01:34:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-17T04:58:54.000Z", "max_forks_repo_path": "cpp/src/core/BezierCurve.cpp", "max_forks_repo_name": "modanesh/magic", "max_forks_repo_head_hexsha": "2eec5c7a1e45a4594b02d8df1e7f2880d7fc8422", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-05-25T07:44:33.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T08:40:29.000Z", "avg_line_length": 29.5294117647, "max_line_length": 128, "alphanum_fraction": 0.5484727756, "num_tokens": 515, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094145755219, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6691666698212935}} {"text": "/* MonteCarlo.hpp\r\n-Description:\r\n\t*Declare and define MonteCarlo template class that calculates the price of a financial option using the Euler-Maruyama scheme.\r\n-State Objects:\r\n\t*variate_generator rng: Boost implemented normal random number generator for Monte Carlo path generation.\r\n-Class Methods:\r\n\t// Constructors/Destructors:\r\n\t*MonteCarlo(double t, double s, double k, double b, double r, double sigma, unsigned long NSIM, unsigned long NT, bool isCall): Overloaded Constructor.\r\n\t*MonteCarlo(const MonteCarlo&): Copy constructor.\r\n\t*~MonteCarlo(): Destructor.\r\n\t// Accessors:\r\n\t*unsigned long NSIM() const: Return the number of trials to be run in Monte Carlo.\r\n\t*unsigned long NT() const: Return number of sub-intervals in time to be used in generating each path.\r\n\t// Mutators:\r\n\t*void NSIM(unsigned long): Set number of trials.\r\n\t*void NT(unsigned long): Set number of time sub-intervals.\r\n\t// Misc. Methods:\r\n\t*double Price() const: Calculate price of associated option using Monte Carlo method with Euler-Maruyama scheme.\r\n*/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"MonteCarlo.hpp\"\r\n#include \"MonteCarloExcept.hpp\"\r\n#include \"Option.hpp\"\r\n#include \"OptionExcept.hpp\"\r\n\r\nnamespace Options\r\n{\r\n\t////////////////////////////\r\n\t// Constructors/Destructor:\r\n\t////////////////////////////\r\n\tMonteCarlo::MonteCarlo(double t, double s, double k, double b, double r, double sigma, bool isCall, unsigned long NSIM_in, unsigned long NT_in) : /* Overloaded Constructor. Set all parameters. */\r\n\t\tOption(t, s, k, b, r, sigma, isCall), nT(NT_in), nSIM(NSIM_in)\t\r\n\t{\r\n\t\tmainRNG = new boost::variate_generator >(boost::mt19937(time(0)), boost::normal_distribution<>(0, 1));\r\n\t}\r\n\tMonteCarlo::MonteCarlo(const MonteCarlo &in) : Option(in), nT(in.nT), nSIM(in.nSIM) /* Copy Constructor. */\r\n\t{\r\n\t\t\tmainRNG = new boost::variate_generator >(boost::mt19937(time(0)), boost::normal_distribution<>(0, 1));\r\n\t}\r\n\tMonteCarlo::MonteCarlo(const Option &in, unsigned long NSIM, unsigned long NT): \t\t\t\t\t\t\t/* Copy Constructor 2, with NT and NSIM setting*/\r\n\t\tOption(in), nSIM(NSIM), nT(NT)\r\n\t{\r\n\t\tmainRNG = new boost::variate_generator >(boost::mt19937(time(0)), boost::normal_distribution<>(0, 1));\r\n\t}\r\n\tMonteCarlo::~MonteCarlo()\t\t\t\t\t\t\t\t\t\t\t\t\t/* Destructor. */\r\n\t{\r\n\t\tdelete mainRNG;\r\n\t}\r\n\t////////////////////////////\r\n\t// Accessors:\r\n\t////////////////////////////\r\n\tunsigned long MonteCarlo::NSIM() const\t\t\t\t\t\t\t/* Return number of simulations run in the Monte Carlo. */\r\n\t{\r\n\t\treturn nSIM;\r\n\t}\r\n\tunsigned long MonteCarlo::NT() const\t\t\t\t\t\t\t\t/* Return number of time intervals run in the Monte Carlo path generation. */\r\n\t{\r\n\t\treturn nT;\r\n\t}\r\n\t////////////////////////////\r\n\t// Mutators:\r\n\t////////////////////////////\r\n\tvoid MonteCarlo::NSIM(unsigned long NSIM_in)\t\t\t\t\t\t/* Set the number of simulations to run in the Monte Carlo. */\r\n\t{\r\n\t\tnSIM = NSIM_in;\r\n\t}\r\n\tvoid MonteCarlo::NT(unsigned long NT_in)\t\t\t\t\t\t\t/* Set the number of time intervals to run in the Monte Carlo path generation. */\r\n\t{\r\n\t\tnT = NT_in;\r\n\t}\r\n\t////////////////////////////\r\n\t// Misc. Methods:\r\n\t////////////////////////////\r\n\tdouble MonteCarlo::Price() const\t\t/* Get price of option using Monte Carlo method with Euler-Maruyama pdf. */\r\n\t{\r\n\t\t// NSIM is number of paths to generate, 1/NT is the time divisor (discretizes \"t\" into number of subintervals).\r\n\t\t// As NSIM AND NT approach infinity, GeneratePrice approaches the exact price given by the Black-Scholes equation or the American Perpetual Option pricing method. \r\n\t\tdouble S, output = 0, payoff = 0;\r\n\t\tfor (unsigned long currTrial = 0; currTrial < nSIM; currTrial++)\r\n\t\t{\r\n\t\t\t// Reset the path:\r\n\t\t\tS = Param(\"s\");\r\n\t\t\t// Generate path using Euler-Maruyama partial differentiation scheme:\r\n\t\t\tfor (double currTimeInterval = 0; currTimeInterval < Param(\"t\"); currTimeInterval += 1.0 / (double) nT)\r\n\t\t\t{\r\n\t\t\t\tS += (Param(\"r\") * S * (((double) 1.0 / (double) nT))) + (Param(\"sigma\") * S * std::sqrt((double) 1.0 / (double) nT) * (*mainRNG)());\r\n\t\t\t}\r\n\t\t\t// Calculate payoff of option at expiry depending on type:\r\n\t\t\tif (Option::Type())\r\n\t\t\t{\r\n\t\t\t\tpayoff = std::max(S - Param(\"k\"), 0.0);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tpayoff = std::max(Param(\"k\") - S, 0.0);\r\n\t\t\t}\r\n\t\t\t// Discount the payoff back to present and accumulate:\r\n\t\t\toutput += payoff / (double) nSIM;\r\n\t\t}\r\n\t\t// Return the average discounted payoff:\r\n\t\treturn output * exp(-Param(\"r\") * Param(\"t\"));\r\n\t}\r\n\t////////////////////////////\r\n\t// Overloaded Operators:\r\n\t////////////////////////////\r\n\tMonteCarlo& MonteCarlo::operator=(const MonteCarlo &in)\t\t\t\t\t\t\t\t\t/* Assignment Operator. */\r\n\t{\r\n\t\tif (this != &in)\r\n\t\t{\r\n\t\t\tOption::operator=(in);\r\n\t\t}\r\n\t\treturn *this;\r\n\t}\r\n}", "meta": {"hexsha": "4e41b6972b1eaf262275b852c7ef9180f9f2d844", "size": 4986, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Options/Files/MonteCarlo.cpp", "max_stars_repo_name": "BRutan/Cpp", "max_stars_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Options/Files/MonteCarlo.cpp", "max_issues_repo_name": "BRutan/Cpp", "max_issues_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Options/Files/MonteCarlo.cpp", "max_forks_repo_name": "BRutan/Cpp", "max_forks_repo_head_hexsha": "8acbc6c341f49d6d83168ccd5ba49bd6824214f9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.2066115702, "max_line_length": 197, "alphanum_fraction": 0.6385880465, "num_tokens": 1325, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6691666541789066}} {"text": "// EigenConsoleApplication1.cpp : Defines the entry point for the console application.\r\n//\r\n\r\n\r\n//#include \"stdafx.h\"\r\n#include \r\n#include \r\n#include \r\n#include // std::complex\r\n\r\n//using Eigen::MatrixXd;\r\n//using Eigen::Matrix3cd;\r\n\r\nvoid rf_pulse_matrix(Eigen::Matrix3cd *rfpulse, double alpha, double phi)\r\n{\r\n\tconst double PI = 3.1415926535897932384626433832795;\r\n\r\n\tdouble alpha_half = alpha / 2.0;\r\n\tdouble c_a_h = cos(alpha_half);\r\n\tdouble c_a_h2 = c_a_h * c_a_h;\r\n\tdouble s_a_h = sin(alpha_half);\r\n\tdouble s_a_h2 = s_a_h * s_a_h;\r\n\tdouble c_a = cos(alpha);\r\n\tdouble s_a = sin(alpha);\r\n\r\n\tstd::complex i_phi = std::complex(0.0, phi);\r\n\tstd::complex i_half = std::complex(0.0, 0.5);\r\n\r\n\t(*rfpulse)(0, 0) = c_a_h2;\r\n\t(*rfpulse)(0, 1) = exp(i_phi*2.0)*s_a_h2;\r\n\t(*rfpulse)(0, 2) = -1.0*std::complex(0.0, 1.0)*exp(i_phi)*s_a;\r\n\r\n\t(*rfpulse)(1, 0) = exp(-2.0 * i_phi)*s_a_h2;\r\n\t(*rfpulse)(1, 1) = c_a_h2;\r\n\t(*rfpulse)(1, 2) = std::complex(0.0, 1.0) * exp(-1.0*i_phi)*s_a;\r\n\r\n\t(*rfpulse)(2, 0) = -1.0*i_half*exp(-1.0*i_phi)*s_a;\r\n\t(*rfpulse)(2, 1) = 1.0*i_half*exp(1.0*i_phi)*s_a;\r\n\t(*rfpulse)(2, 2) = c_a;\r\n\r\n\t//std::cout << *rfpulse << std::endl;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nvoid epg_grad(Eigen::MatrixXcd *FpFmZ, int num_cols)\r\n{\r\n\r\n\tfor (int i = 0; i < num_cols - 1; i++)\r\n\t{\r\n\t\t//std::cout << i << \"\\t\" << num_cols - 1 - i << \"\\t\" << num_cols - 1 - i - 1 << \"\\t\" << (*FpFmZ)(0,i) << std::endl;\r\n\t\t(*FpFmZ)(0, num_cols - 1 - i) = (*FpFmZ)(0, num_cols - 1 - i - 1);\r\n\t}\r\n\r\n\r\n\t(*FpFmZ)(0, 0) = std::complex(0.0, 0.0);\r\n\r\n\tfor (int i = 0; i < num_cols - 1; i++)\r\n\t\t(*FpFmZ)(1, i) = (*FpFmZ)(1, i + 1);\r\n\r\n\t(*FpFmZ)(1, num_cols - 1) = std::complex(0.0, 0.0);\r\n\r\n\t(*FpFmZ)(0, 0) = conj((*FpFmZ)(1, 0));\r\n}\r\n\r\n\r\nvoid cpmg_epg(double *signal, int Nechos, double rf_180, double T1, double T2, double Techo)\r\n{\r\n\tconst double PI = 3.1415926535897932384626433832795;\r\n\tint num_cols = 2 * Nechos;\r\n\r\n\tEigen::MatrixXcd FpFmZ(3, 34);\r\n\tEigen::Matrix3cd rfpulse90y = Eigen::Matrix3cd::Zero();\r\n\tEigen::Matrix3cd rfpulse180x = Eigen::Matrix3cd::Zero();\r\n\tEigen::Matrix3d ee = Eigen::Matrix3d::Zero();\r\n\t//Eigen::MatrixXd signal(1, 17);\r\n\r\n\r\n\r\n\r\n\tFpFmZ = FpFmZ.Zero(3, 34);\r\n\r\n\r\n\r\n\t// ****************************************\r\n\t// Initialize diagonal of relaxation matrix\r\n\t// ****************************************\r\n\r\n\tee(0, 0) = exp(-Techo / 2.0 / T2);\r\n\tee(1, 1) = exp(-Techo / 2.0 / T2);\r\n\tee(2, 2) = exp(-Techo / 2.0 / T1);\r\n\r\n\r\n\t// ********************************\r\n\t// Set Z magnetization to 1.0 +0.0j\r\n\t// ********************************\r\n\r\n\tFpFmZ(0, 0) = 0.0;\r\n\tFpFmZ(1, 0) = 0.0;\r\n\tFpFmZ(2, 0) = 1.0;\r\n\r\n\t// *********************************\r\n\t// Create 90(y) rotation matrix\r\n\t// *********************************\r\n\r\n\trf_pulse_matrix(&rfpulse90y, PI / 2.0, PI / 2.0);\r\n\r\n\t// *********************************\r\n\t// Create 180(x) rotation matrix\r\n\t// *********************************\r\n\r\n\trf_pulse_matrix(&rfpulse180x, rf_180*PI / 180.0, 0.0);\r\n\r\n\t// *********************************\r\n\t// Apply 90 degree pulse\r\n\t// *********************************\r\n\r\n\tFpFmZ = rfpulse90y * FpFmZ;\r\n\r\n\t// ****************************************\r\n\t// Apply 180 pulses of CPMG sequence\r\n\t// ****************************************\r\n\r\n\tfor (int i = 0; i < Nechos; i++)\r\n\t{\r\n\r\n\t\tFpFmZ = ee * FpFmZ;\r\n\t\tFpFmZ(2, 0) = FpFmZ(2, 0) + 1.0 - ee(2, 2);\r\n\t\tepg_grad(&FpFmZ, 34);\r\n\r\n\t\tFpFmZ = rfpulse180x * FpFmZ;\r\n\r\n\t\tFpFmZ = ee * FpFmZ;\r\n\t\tFpFmZ(2, 0) = FpFmZ(2, 0) + 1.0 - ee(2, 2);\r\n\t\tepg_grad(&FpFmZ, 34);\r\n\r\n\t\tsignal[i] = real(FpFmZ(0, 0));\r\n\t}\r\n\r\n\r\n}\r\n\r\n\r\n\r\n//int main()\r\n//{\r\n//\tconst double PI = 3.1415926535897932384626433832795;\r\n//\tstd::clock_t start;\r\n//\r\n//\tdouble T1 = 3000.0;\r\n//\tdouble T2 = 50.0;\r\n//\tdouble Techo = 10.0;\r\n//\tint Nechos = 17;\r\n//\tint num_cols = 2 * Nechos;\r\n//\r\n//\tEigen::MatrixXcd FpFmZ(3, num_cols);\r\n//\tEigen::Matrix3cd rfpulse90y = Eigen::Matrix3cd::Zero();\r\n//\tEigen::Matrix3cd rfpulse180x = Eigen::Matrix3cd::Zero();\r\n//\tEigen::Matrix3d ee = Eigen::Matrix3d::Zero();\r\n//\r\n//\tdouble *signal = new double [Nechos] { 0.0 };\r\n//\r\n//\tstart = std::clock();\r\n//\r\n//\tfor (int j = 0; j < 10000; j++)\r\n//\t\tcpmg_epg(signal, Nechos, PI, T1, T2, Techo);\r\n//\r\n//\tstd::cout << \"Time: \" << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << \" ms\" << std::endl;\r\n//\r\n//\tfor (int i = 0; i\n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main()\n{\n Matrix3f m = Matrix3f::Random();\n m = (m + Matrix3f::Constant(1.2)) * 50;\n cout << \"m =\" << endl << m << endl;\n Vector3f v(1,2,3);\n \n cout << \"m * v =\" << endl << m * v << endl;\n}\n", "meta": {"hexsha": "edf3268cde0336ba805765aa7b72cda651fc0d7a", "size": 289, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SoftRender/eigen3/eigen3/doc/examples/QuickStart_example2_fixed.cpp", "max_stars_repo_name": "LEEZHEHUI/QT-SoftRender", "max_stars_repo_head_hexsha": "4321356bc51c564ac911e32f4927ce7f3fe5b7ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2015-03-12T00:12:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-26T08:56:31.000Z", "max_issues_repo_path": "SoftRender/eigen3/eigen3/doc/examples/QuickStart_example2_fixed.cpp", "max_issues_repo_name": "LEEZHEHUI/QT-SoftRender", "max_issues_repo_head_hexsha": "4321356bc51c564ac911e32f4927ce7f3fe5b7ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "SoftRender/eigen3/eigen3/doc/examples/QuickStart_example2_fixed.cpp", "max_forks_repo_name": "LEEZHEHUI/QT-SoftRender", "max_forks_repo_head_hexsha": "4321356bc51c564ac911e32f4927ce7f3fe5b7ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2019-07-04T12:54:29.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:04:38.000Z", "avg_line_length": 18.0625, "max_line_length": 45, "alphanum_fraction": 0.5605536332, "num_tokens": 98, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9230391579526934, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6690836493471927}} {"text": "//============================================================================\n//\n// This file is part of the Thea toolkit.\n//\n// This software is distributed under the BSD license, as detailed in the\n// accompanying LICENSE.txt file. Portions are derived from other works:\n// their respective licenses and copyright information are reproduced in\n// LICENSE.txt and/or in the relevant source files.\n//\n// Author: Siddhartha Chaudhuri\n// First version: 2011\n//\n//============================================================================\n\n#include \"Math.hpp\"\n#include \"../../Array.hpp\"\n#include \"../../MatVec.hpp\"\n#include \"../../Ray3.hpp\"\n#include \"../../Triangle3.hpp\"\n#include \n\nnamespace Browse3D {\n\nMatrix3\northonormalBasisMatrix(Vector3 const & u, Vector3 const & v, Vector3 const & w)\n{\n Vector3 w2 = w.normalized();\n Vector3 u2 = v.cross(w2).normalized();\n Vector3 v2 = w2.cross(u2);\n\n Matrix3 ret; ret << u2, v2, w2;\n return ret;\n}\n\nMatrix3\northonormalBasisMatrix(Matrix3 const & m)\n{\n return orthonormalBasisMatrix(m.col(0), m.col(1), m.col(2));\n}\n\nReal\nestimateScalingFactor(Matrix3 const & m)\n{\n return (m.col(0).norm() + m.col(1).norm() + m.col(2).norm()) / 3.0f;\n}\n\nVector3\nreflectPoint(Vector3 const & p, Plane3 const & mirror_plane)\n{\n // Assume Plane3::normal() is unit\n return p - 2 * (p - mirror_plane.getPoint()).dot(mirror_plane.getNormal()) * mirror_plane.getNormal();\n}\n\nVector3\nreflectVector(Vector3 const & v, Plane3 const & mirror_plane)\n{\n // Assume Plane3::normal() is unit\n return v - 2 * v.dot(mirror_plane.getNormal()) * mirror_plane.getNormal();\n}\n\nbool\nlineIntersectsTriangle(Line3 const & line, Vector3 const & v0, Vector3 const & edge01, Vector3 const & edge02, Real * time)\n{\n // The code is taken from the ray-triangle intersection test in Dave Eberly's Wild Magic library, v5.3, released under the\n // Boost license: http://www.boost.org/LICENSE_1_0.txt .\n\n static Real const EPS = 1e-30f;\n\n Vector3 diff = line.getPoint() - v0;\n Vector3 normal = edge01.cross(edge02);\n\n // Solve Q + t*D = b1*E1 + b2*E2 (Q = diff, D = line direction, E1 = edge01, E2 = edge02, N = Cross(E1,E2)) by\n // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))\n // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))\n // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)\n\n Real DdN = line.getDirection().dot(normal);\n int sign;\n if (DdN > EPS)\n sign = 1;\n else if (DdN < -EPS)\n {\n sign = -1;\n DdN = -DdN;\n }\n else\n {\n // Line and triangle are parallel, call it a \"no intersection\" even if the line does intersect\n return false;\n }\n\n Real DdQxE2 = sign * line.getDirection().dot(diff.cross(edge02));\n if (DdQxE2 >= 0)\n {\n Real DdE1xQ = sign * line.getDirection().dot(edge01.cross(diff));\n if (DdE1xQ >= 0)\n {\n if (DdQxE2 + DdE1xQ <= DdN)\n {\n // Line intersects triangle\n Real QdN = -sign * diff.dot(normal);\n if (time) *time = QdN / DdN;\n return true;\n }\n // else: b1 + b2 > 1, no intersection\n }\n // else: b2 < 0, no intersection\n }\n // else: b1 < 0, no intersection\n\n return false;\n}\n\n#define CLOSEST_PT_SEGMENT_SEGMENT(VecType) \\\nReal \\\nclosestPtSegmentSegment(VecType const & p1, VecType const & q1, VecType const & p2, VecType const & q2, Real & s, Real & t, \\\n VecType & c1, VecType & c2) \\\n{ \\\n static Real const EPSILON = 1e-20f; \\\n \\\n VecType d1 = q1 - p1; /* Direction vector of segment S1 */ \\\n VecType d2 = q2 - p2; /* Direction vector of segment S2 */ \\\n VecType r = p1 - p2; \\\n Real a = d1.squaredNorm(); /* Squared length of segment S1, always nonnegative */ \\\n Real e = d2.squaredNorm(); /* Squared length of segment S2, always nonnegative */ \\\n Real f = d2.dot(r); \\\n \\\n /* Check if either or both segments degenerate into points */ \\\n if (a <= EPSILON && e <= EPSILON) \\\n { \\\n /* Both segments degenerate into points */ \\\n s = t = 0; \\\n c1 = p1; \\\n c2 = p2; \\\n return (c1 - c2).dot(c1 - c2); \\\n } \\\n if (a <= EPSILON) \\\n { \\\n /* First segment degenerates into a point */ \\\n s = 0; \\\n t = f / e; /* s = 0 => t = (b*s + f) / e = f / e */ \\\n t = Math::clamp(t, (Real)0, (Real)1); \\\n } \\\n else \\\n { \\\n Real c = d1.dot(r); \\\n if (e <= EPSILON) \\\n { \\\n /* Second segment degenerates into a point */ \\\n t = 0; \\\n s = Math::clamp(-c / a, (Real)0, (Real)1); /* t = 0 => s = (b*t - c) / a = -c / a */ \\\n } \\\n else \\\n { \\\n /* The general nondegenerate case starts here */ \\\n Real b = d1.dot(d2); \\\n Real denom = a * e - b * b; /* Always nonnegative */ \\\n \\\n /* If segments not parallel, compute closest point on L1 to L2, and */ \\\n /* clamp to segment S1. Else pick arbitrary s (here 0) */ \\\n if (denom != 0) \\\n s = Math::clamp((b * f - c * e) / denom, (Real)0, (Real)1); \\\n else \\\n s = 0; \\\n \\\n /* Compute point on L2 closest to S1(s) using */ \\\n /* t = Dot((P1+D1*s)-P2,D2) / Dot(D2,D2) = (b*s + f) / e */ \\\n t = (b * s + f) / e; \\\n \\\n /* If t in [0,1] done. Else clamp t, recompute s for the new value */ \\\n /* of t using s = Dot((P2+D2*t)-P1,D1) / Dot(D1,D1)= (t*b - c) / a */ \\\n /* and clamp s to [0, 1] */ \\\n if (t < 0) \\\n { \\\n t = 0; \\\n s = Math::clamp(-c / a, (Real)0, (Real)1); \\\n } \\\n else if (t > 1) \\\n { \\\n t = 1; \\\n s = Math::clamp((b - c) / a, (Real)0, (Real)1); \\\n } \\\n } \\\n } \\\n \\\n c1 = p1 + s * d1; \\\n c2 = p2 + t * d2; \\\n return (c1 - c2).squaredNorm(); \\\n}\n\nCLOSEST_PT_SEGMENT_SEGMENT(Vector2)\nCLOSEST_PT_SEGMENT_SEGMENT(Vector3)\n\n#define CLOSEST_PT_SEGMENT_LINE(VecType) \\\nReal \\\nclosestPtSegmentLine(VecType const & p1, VecType const & q1, VecType const & p2, VecType const & q2, Real & s, Real & t, \\\n VecType & c1, VecType & c2) \\\n{ \\\n static Real const EPSILON = 1e-20f; \\\n \\\n VecType d1 = q1 - p1; /* Direction vector of segment S1 */ \\\n VecType d2 = q2 - p2; /* Direction vector of line L2 */ \\\n VecType r = p1 - p2; \\\n Real a = d1.squaredNorm(); /* Squared length of segment S1, always nonnegative */ \\\n Real e = d2.squaredNorm(); /* Squared length of segment supporting L2, always nonnegative and assumed to be non-zero */ \\\n Real f = d2.dot(r); \\\n \\\n if (a <= EPSILON) \\\n { \\\n /* Segment degenerates into a point */ \\\n s = 0; \\\n t = f / e; /* s = 0 => t = (b*s + f) / e = f / e */ \\\n } \\\n else \\\n { \\\n /* The general nondegenerate case starts here */ \\\n Real c = d1.dot(r); \\\n Real b = d1.dot(d2); \\\n Real denom = a * e - b * b; /* Always nonnegative */ \\\n\\\n /* If segments not parallel, compute closest point on L1 to L2, and */ \\\n /* clamp to segment S1. Else pick arbitrary s (here 0) */ \\\n if (denom != 0) \\\n s = Math::clamp((b * f - c * e) / denom, (Real)0, (Real)1); \\\n else \\\n s = 0; \\\n\\\n /* Compute point on L2 closest to S1(s) using */ \\\n /* t = Dot((P1+D1*s)-P2,D2) / Dot(D2,D2) = (b*s + f) / e */ \\\n t = (b * s + f) / e; \\\n } \\\n \\\n c1 = p1 + s * d1; \\\n c2 = p2 + t * d2; \\\n return (c1 - c2).squaredNorm(); \\\n}\n\nCLOSEST_PT_SEGMENT_LINE(Vector2)\nCLOSEST_PT_SEGMENT_LINE(Vector3)\n\nReal\nclosestPtLineTriangle(Line3 const & line, Vector3 const & v0, Vector3 const & edge01, Vector3 const & edge02, Real & s,\n Vector3 & c1, Vector3 & c2)\n{\n if (lineIntersectsTriangle(line, v0, edge01, edge02, &s))\n {\n c1 = c2 = line.getPoint() + s * line.getDirection();\n return 0;\n }\n\n // Either (1) the line is not parallel to the triangle and the point of\n // intersection of the line and the plane of the triangle is outside the\n // triangle or (2) the line and triangle are parallel. Regardless, the\n // closest point on the triangle is on an edge of the triangle. Compare\n // the line to all three edges of the triangle.\n Real min_sqdist = -1;\n Vector3 v[3] = { v0, v0 + edge01, v0 + edge02 };\n Vector3 tmp_c1, tmp_c2;\n float tmp_s, t;\n for (int i0 = 2, i1 = 0; i1 < 3; i0 = i1++)\n {\n Real sqdist = closestPtSegmentLine(v[i0], v[i1], line.getPoint(), line.getPoint() + line.getDirection(),\n t, tmp_s, tmp_c2, tmp_c1);\n if (min_sqdist < 0 || sqdist < min_sqdist)\n {\n min_sqdist = sqdist;\n s = tmp_s;\n c1 = tmp_c1;\n c2 = tmp_c2;\n }\n }\n\n return min_sqdist;\n}\n\nReal\nclosestPtRayTriangle(Ray3 const & ray, Vector3 const & v0, Vector3 const & edge01, Vector3 const & edge02, Real & s,\n Vector3 & c1, Vector3 & c2)\n{\n Real sqdist = closestPtLineTriangle(Line3::fromPointAndDirection(ray.getOrigin(), ray.getDirection()), v0, edge01, edge02,\n s, c1, c2);\n if (s >= 0)\n return sqdist;\n\n // Not the most efficient way but the most convenient\n LocalTriangle3 tri(v0, v0 + edge01, v0 + edge02);\n s = 0;\n c1 = ray.getOrigin();\n c2 = tri.closestPoint(c1);\n\n return (c1 - c2).squaredNorm();\n}\n\nRigidTransform3\nclosestRigidTransform(std::vector const & src, std::vector const & dst)\n{\n alwaysAssertM(src.size() == dst.size(), \"Source and destination sets must have same number of frames\");\n\n if (src.empty())\n return RigidTransform3::identity();\n else if (src.size() == 1)\n return RigidTransform3(dst[0]) * RigidTransform3(src[0].inverse());\n else if (src.size() == 2)\n {\n // First map line segment to line segment...\n Vector3 src_mean = 0.5f * (src[0].getTranslation() + src[1].getTranslation());\n Vector3 dst_mean = 0.5f * (dst[0].getTranslation() + dst[1].getTranslation());\n\n static Real const MIN_SQLEN = 1.0e-8f;\n\n Vector3 src_axis = src[1].getTranslation() - src[0].getTranslation();\n Vector3 dst_axis = dst[1].getTranslation() - dst[0].getTranslation();\n\n if (src_axis.squaredNorm() > MIN_SQLEN && dst_axis.squaredNorm() > MIN_SQLEN)\n {\n Matrix3 rot = Math::rotationArc(src_axis, dst_axis);\n\n // Now rotate around the mapped segment to align the z axes of the frames...\n Vector3 src_dir = rot * (src[0].getRotation().col(2) + src[1].getRotation().col(2));\n Vector3 dst_dir = dst[0].getRotation().col(2) + dst[1].getRotation().col(2);\n\n // Transform src_dir and dst_dir to be perpendicular to dst_axis\n dst_axis = dst_axis.normalized();\n src_dir = src_dir - src_dir.dot(dst_axis) * dst_axis;\n dst_dir = dst_dir - dst_dir.dot(dst_axis) * dst_axis;\n\n if (src_dir.squaredNorm() > MIN_SQLEN && dst_dir.squaredNorm() > MIN_SQLEN)\n {\n src_dir = src_dir.normalized();\n dst_dir = dst_dir.normalized();\n\n Vector3 src_perp = dst_axis.cross(src_dir);\n Vector3 dst_perp = dst_axis.cross(dst_dir);\n\n Matrix3 src_basis; src_basis << src_dir, src_perp, dst_axis;\n Matrix3 dst_basis; dst_basis << dst_dir, dst_perp, dst_axis;\n Matrix3 extra_rot = dst_basis * src_basis.transpose(); // inverse == tranpose for rotation matrices\n\n rot = extra_rot * rot;\n }\n\n CoordinateFrame3 cf(RigidTransform3::_fromAffine(AffineTransform3(rot, dst_mean - rot * src_mean)));\n // THEA_CONSOLE.nospace() << \"R = \" << toString(cf.getRotation()) << \", T = \" << toString(cf.getTranslation());\n\n return RigidTransform3(cf);\n }\n else\n return RigidTransform3::translation(dst_mean - src_mean);\n }\n\n // ICP algorithm of Arun et al. 1987.\n\n size_t num_frames = src.size();\n Vector3 src_mean = Vector3::Zero(), dst_mean = Vector3::Zero();\n for (size_t i = 0; i < num_frames; ++i)\n {\n CoordinateFrame3 const & src_frame = src[i];\n CoordinateFrame3 const & dst_frame = dst[i];\n\n // THEA_CONSOLE.nospace() << \"src[\" << i << \"] = R: \" << toString(src_frame.getRotation()) << \", T: \"\n // << toString(src_frame.getTranslation());\n // THEA_CONSOLE.nospace() << \"dst[\" << i << \"] = R: \" << toString(dst_frame.getRotation()) << \", T: \"\n // << toString(dst_frame.getTranslation());\n\n src_mean += src_frame.getTranslation();\n dst_mean += dst_frame.getTranslation();\n }\n\n src_mean /= num_frames;\n dst_mean /= num_frames;\n\n Matrix3 corr = Matrix3::Zero();\n Vector3 src_pt, dst_pt;\n for (size_t i = 0; i < num_frames; ++i)\n {\n CoordinateFrame3 const & src_frame = src[i];\n CoordinateFrame3 const & dst_frame = dst[i];\n\n src_pt = src_frame.getTranslation() - src_mean;\n dst_pt = dst_frame.getTranslation() - dst_mean;\n\n for (int r = 0; r < 3; ++r)\n for (int c = 0; c < 3; ++c)\n corr(r, c) += src_pt[r] * dst_pt[c];\n }\n\n Eigen::JacobiSVD svd(corr, Eigen::ComputeFullU | Eigen::ComputeFullV);\n Matrix3 U_T = svd.matrixU().transpose();\n Matrix3 V = svd.matrixV();\n Matrix3 rotation = V * U_T;\n\n if (rotation.determinant() < 0)\n {\n // FIXME: One of the columns (which?) of V should be negated. See Eggert et al. '97, \"Estimating 3D rigid transformations: a\n // comparison of four major algorithms\".\n //\n // For now, we'll do the dumb but safe thing and test each option for the minimum error.\n\n THEA_WARNING << \"Estimated rigid transform involves reflection, fixing by negating a column of V\";\n\n Real min_sqerr = -1;\n for (int i = 0; i < 3; ++i)\n {\n // Swap i'th column of V\n Matrix3 V_i = V;\n V_i(0, i) = -V_i(0, i);\n V_i(1, i) = -V_i(1, i);\n V_i(2, i) = -V_i(2, i);\n\n Matrix3 candidate_rot = V_i * U_T;\n Real sqerr = 0;\n for (size_t j = 0; j < num_frames; ++j)\n {\n CoordinateFrame3 const & src_frame = src[j];\n CoordinateFrame3 const & dst_frame = dst[j];\n\n src_pt = src_frame.getTranslation() - src_mean;\n dst_pt = dst_frame.getTranslation() - dst_mean;\n sqerr += (candidate_rot * src_pt - dst_pt).squaredNorm();\n }\n\n if (min_sqerr < 0 || sqerr < min_sqerr)\n {\n rotation = candidate_rot;\n min_sqerr = sqerr;\n }\n }\n }\n\n Vector3 translation = dst_mean - rotation * src_mean;\n\n CoordinateFrame3 cf(RigidTransform3::_fromAffine(AffineTransform3(rotation, translation)));\n // THEA_CONSOLE.nospace() << \"R = \" << toString(rotation) << \", T = \" << toString(translation);\n\n return RigidTransform3(cf);\n}\n\nint\nbvhDepth(intx num_elems, int max_elems_in_leaf)\n{\n alwaysAssertM(num_elems >= 0, \"Can't compute BVH depth for negative number of elements\");\n alwaysAssertM(max_elems_in_leaf > 0, \"Can't compute BVH depth for non-positive number of elements at leaf\");\n\n int max_depth = (num_elems > 0 ? (int)std::ceil(Math::fastLog2(num_elems / (double)max_elems_in_leaf)) : 0);\n return max_depth;\n}\n\nvoid\ngetBarycentricCoordinates2(Real qx, Real qy, Real x0, Real y0, Real x1, Real y1, Real x2, Real y2,\n Real & bc0, Real & bc1, Real & bc2)\n{\n Real a = y1 - y2;\n Real b = x0 - x2;\n Real c = y2 - y0;\n Real d = x2 - x1;\n\n Real det = a * b - c * d;\n if (std::abs(det) < 1.0e-30f)\n bc0 = bc1 = bc2 = 1.0f / 3;\n else\n {\n Real qx_rel_3 = qx - x2;\n Real qy_rel_3 = qy - y2;\n\n bc0 = (a * qx_rel_3 + d * qy_rel_3) / det;\n bc1 = (c * qx_rel_3 + b * qy_rel_3) / det;\n bc2 = 1 - bc0 - bc1;\n }\n}\n\nvoid\ngetBarycentricCoordinates2(Vector2 const & q, Vector2 const & v0, Vector2 const & v1, Vector2 const & v2,\n Real & bc0, Real & bc1, Real & bc2)\n{\n getBarycentricCoordinates2(q.x(), q.y(), v0.x(), v0.y(), v1.x(), v1.y(), v2.x(), v2.y(), bc0, bc1, bc2);\n}\n\nvoid\ngetBarycentricCoordinates3(Vector3 const & q, Vector3 const & v0, Vector3 const & v1, Vector3 const & v2,\n Real & bc0, Real & bc1, Real & bc2)\n{\n switch (Math::maxAbsAxis((v1 - v0).cross(v2 - v0)))\n {\n case 0: getBarycentricCoordinates2(q.tail<2>(), v0.tail<2>(), v1.tail<2>(), v2.tail<2>(), bc0, bc1, bc2); break;\n case 1: getBarycentricCoordinates2(Vector2( q[0], q[2]),\n Vector2(v0[0], v0[2]),\n Vector2(v1[0], v1[2]),\n Vector2(v2[0], v2[2]), bc0, bc1, bc2); break;\n default /* 2 */: getBarycentricCoordinates2(q.head<2>(), v0.head<2>(), v1.head<2>(), v2.head<2>(), bc0, bc1, bc2);\n }\n}\n\nVector3\ntriRandomPoint(Vector3 const & v0, Vector3 const & v1, Vector3 const & v2)\n{\n return triRandomPointFromEdges(v0, v1 - v0, v2 - v0);\n}\n\nVector3\ntriRandomPointFromEdges(Vector3 const & v0, Vector3 const & edge01, Vector3 const & edge02)\n{\n // From G3D::Triangle\n\n // Choose a random point in the parallelogram\n\n float s = Random::common().uniform01();\n float t = Random::common().uniform01();\n\n if (t > 1.0f - s)\n {\n // Outside the triangle; reflect about the diagonal of the parallelogram\n t = 1.0f - t;\n s = 1.0f - s;\n }\n\n return s * edge01 + t * edge02 + v0;\n}\n\nVector3\nquadRandomPoint(Vector3 const & v0, Vector3 const & v1, Vector3 const & v2, Vector3 const & v3)\n{\n Vector3 edge01 = v1 - v0;\n Vector3 edge03 = v3 - v0;\n Vector3 edge21 = v1 - v2;\n Vector3 edge23 = v3 - v2;\n\n Real tri0_double_area = edge01.cross(edge03).norm();\n Real tri1_double_area = edge21.cross(edge23).norm();\n\n float tri = Random::common().uniform(0, tri0_double_area + tri1_double_area);\n if (tri <= tri0_double_area)\n return triRandomPointFromEdges(v0, edge01, edge03);\n else\n return triRandomPointFromEdges(v2, edge21, edge23);\n}\n\nReal\nraySphereIntersectionTime(Ray3 const & ray, Vector3 const & center, Real radius)\n{\n Vector3 pmc = ray.getOrigin() - center;\n\n double s[3];\n s[2] = ray.getDirection().squaredNorm();\n s[1] = 2 * pmc.dot(ray.getDirection());\n s[0] = pmc.squaredNorm() - radius * radius;\n\n double roots[2];\n int num_roots = Math::solveQuadratic(s[0], s[1], s[2], roots);\n\n double min_root = -1;\n for (int i = 0; i < num_roots; ++i)\n if (roots[i] >= 0 && (min_root < 0 || roots[i] < min_root))\n min_root = roots[i];\n\n#if 0\n if (min_root >= 0)\n THEA_CONSOLE << \"min_root =\" << min_root;\n#endif\n\n return (Real)min_root;\n}\n\nReal\nrayTorusIntersectionTime(Ray3 const & ray, Real torus_radius, Real torus_width)\n{\n double r2pw2 = torus_radius * torus_radius + torus_width * torus_width;\n double r2mw2 = r2pw2 - 2 * torus_width * torus_width;\n\n Vector3 p2 = ray.getOrigin().cwiseProduct(ray.getOrigin());\n Vector3 pu = ray.getOrigin().cwiseProduct(ray.getDirection());\n Vector3 u2 = ray.getDirection().cwiseProduct(ray.getDirection());\n\n double s[5];\n s[4] = u2[0] * (u2[0] + 2 * u2[1]) + u2[1] * (u2[1] + 2 * u2[2]) + u2[2] * (u2[2] + 2 * u2[0]);\n s[3] = 4 * (pu[0] + pu[1] + pu[2]) * (u2[0] + u2[1] + u2[2]);\n s[2] = 2 * (r2mw2 * u2[2] - r2pw2 * (u2[0] + u2[1]))\n + 8 * (pu[0] * pu[1] + pu[1] * pu[2] + pu[2] * pu[0])\n + 6 * (pu[0] * pu[0] + pu[1] * pu[1] + pu[2] * pu[2])\n + 2 * (p2[0] * (u2[1] + u2[2]) + p2[1] * (u2[2] + u2[0]) + p2[2] * (u2[0] + u2[1]));\n s[1] = 4 * (r2mw2 * pu[2] - r2pw2 * (pu[0] + pu[1]) + (p2[0] + p2[1] + p2[2]) * (pu[0] + pu[1] + pu[2]));\n s[0] = 2 * (r2mw2 * p2[2] - r2pw2 * (p2[0] + p2[1]) + p2[0] * p2[1] + p2[1] * p2[2] + p2[2] * p2[0])\n + p2[0] * p2[0] + p2[1] * p2[1] + p2[2] * p2[2] + r2mw2 * r2mw2;\n\n double roots[4];\n int num_roots = Math::solveQuartic(s[0], s[1], s[2], s[3], s[4], roots);\n\n double min_root = -1;\n for (int i = 0; i < num_roots; ++i)\n if (roots[i] >= 0 && (min_root < 0 || roots[i] < min_root))\n min_root = roots[i];\n\n#if 0\n if (min_root >= 0)\n THEA_CONSOLE << \"min_root =\" << min_root;\n#endif\n\n return (Real)min_root;\n}\n\n} // namespace Browse3D\n", "meta": {"hexsha": "a7f9e77989399457beae9a2e313d3f0326b2cfb3", "size": 19503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/Source/Tools/Browse3D/Math.cpp", "max_stars_repo_name": "sidch/Thea", "max_stars_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2016-11-06T17:25:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T16:30:34.000Z", "max_issues_repo_path": "Code/Source/Tools/Browse3D/Math.cpp", "max_issues_repo_name": "sidch/Thea", "max_issues_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-04-22T16:47:04.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-22T16:47:04.000Z", "max_forks_repo_path": "Code/Source/Tools/Browse3D/Math.cpp", "max_forks_repo_name": "sidch/Thea", "max_forks_repo_head_hexsha": "d5ea3e3f1bd7389255cfabf1d55a6fe88c3c7db7", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2015-10-17T20:38:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-18T09:56:27.000Z", "avg_line_length": 32.4509151414, "max_line_length": 128, "alphanum_fraction": 0.583397426, "num_tokens": 6433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.6690530293862523}} {"text": "/**\n * Discrete time LQR controller implementation\n * @author: Haoguang Yang\n * @date: 09-27-2021\n * \n * Copyright (c) 2021-2022, Haoguang Yang\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef _DLQR_H_\n#define _DLQR_H_\n\n#include \n#include \n#include \n#include \n//#include \n\nnamespace control\n{\n /// @class dLQR\n /// @brief A discrete time LQR controller class. The LQR controller minimizes the Hinf control cost,\n /// as defined by: J = \\sum_t[(Xd(t)-X(t))'Q(Xd(t)-X(t)) + u(t)'Ru(t) + 2*(Xd(t)-X(t))'Nu(t)].\n class dLQR\n {\n public:\n /// @brief Constructor\n /// @param[in] K is the LQR gain matrix for u=K(Xd-X), which drives X to Xd.\n dLQR(const Eigen::MatrixXd& K);\n\n /// @brief Constructor using system x[n+1]=Ax[n]+Bu[n]\n /// @param[in] A specifies the discrete-time state space equation.\n /// @param[in] B specifies the discrete-time state space equation.\n /// @param[in] Q specifies the state space error penalty.\n /// @param[in] R specifies the control effort penalty.\n /// @param[in] N specifies the error-effort cross penalty.\n /// @param[in] dt specifies the control interval.\n dLQR(const Eigen::MatrixXd& A,\n const Eigen::MatrixXd& B,\n const Eigen::MatrixXd& Q,\n const Eigen::MatrixXd& R,\n const Eigen::MatrixXd& N);\n\n dLQR(){};\n\n ~dLQR(){ initialized = false; };\n\n /// @brief Calculate the ARE solution given A, B, Q, R, N matrices. This algorithm is based\n /// on the work of https://github.com/TakaHoribe/Riccati_Solver/ and W. F. Arnold and A. J. Laub, \n /// \"Generalized eigenproblem algorithms and software for algebraic Riccati equations,\" in \n /// Proceedings of the IEEE, vol. 72, no. 12, pp. 1746-1754, Dec. 1984, doi: 10.1109/PROC.1984.13083.\n /// The DARE solver is based on: https://github.com/arunabh1904/LQR-ROS/blob/master/lqr_obsavoid/src/are_solver.cpp\n /// The WIP DARE solver with N term used is based on: https://github.com/scipy/scipy/blob/v1.7.1/scipy/linalg/_solvers.py#L529-L734\n Eigen::MatrixXd care(const Eigen::MatrixXd& A,\n const Eigen::MatrixXd& B,\n const Eigen::MatrixXd& Q,\n const Eigen::MatrixXd& R,\n const Eigen::MatrixXd& N);\n\n Eigen::MatrixXd dare(const Eigen::MatrixXd& A,\n const Eigen::MatrixXd& B,\n const Eigen::MatrixXd& Q,\n const Eigen::MatrixXd& R,\n const Eigen::MatrixXd& N);\n\n /// @brief Input the current states and desired states, output the control values\n /// @param X is the most recently state space\n /// @param Xd is the most recently desired state space\n /// @return the control value from the LQR algorithm\n const Eigen::VectorXd& calculateControl(const Eigen::VectorXd& X, const Eigen::VectorXd& Xd);\n \n void balance_matrix(const Eigen::MatrixXd &A, Eigen::MatrixXd &Aprime, Eigen::VectorXd &D);\n\n /// @brief Get the current LQR gain.\n /// @return The current K matrix.\n inline const Eigen::MatrixXd& getK() const { return K_; };\n\n /// @brief Get the current value of the control error\n inline const Eigen::VectorXd& CurrentError() const { return e_; };\n\n /// @brief Get the current control value (calculated based on most recent errors)\n /// @return the current control value\n inline const Eigen::VectorXd& CurrentControl() const { return u_; };\n inline bool isInitialized() const { return initialized; };\n \n private:\n /// @brief is initialized\n bool initialized = false;\n\n /// @brief LQR gain.\n Eigen::MatrixXd K_;\n\n /// @brief Current state space error used in LQR control algorithm\n Eigen::VectorXd e_;\n\n /// @brief Current control value\n Eigen::VectorXd u_;\n\n }; // End class dLQR\n\n} // End namespace control\n\n#endif", "meta": {"hexsha": "4d2038ac278ee1a47f50bd91f3b2a70cd33084ea", "size": 5448, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/LQR.hpp", "max_stars_repo_name": "HaoguangYang/lqgController", "max_stars_repo_head_hexsha": "78bcc3636354a010729f91e5f828a432866f8855", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/LQR.hpp", "max_issues_repo_name": "HaoguangYang/lqgController", "max_issues_repo_head_hexsha": "78bcc3636354a010729f91e5f828a432866f8855", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/LQR.hpp", "max_forks_repo_name": "HaoguangYang/lqgController", "max_forks_repo_head_hexsha": "78bcc3636354a010729f91e5f828a432866f8855", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 42.5625, "max_line_length": 135, "alphanum_fraction": 0.6749265786, "num_tokens": 1315, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7853085909370422, "lm_q1q2_score": 0.6690458544585989}} {"text": "#ifndef INTEGRALS_HPP_\n#define INTEGRALS_HPP_\n/**\n * @file integrals.hpp\n * @author Adam Lamson\n * @brief Probility Density Function integrals for KMC algorithm. Used to create\n * lookup tables\n * @version 0.1\n * @date 2019-04-15\n *\n * @copyright Copyright (c) 2019\n *\n */\n\n#include \n#include \n#include \n#include \n#include \n\n/*! \\brief Integrate exponential factor with the form of\n * e^{-M * (\\sqrt{ s^2 + lm^2}-ell0 -1)^2}\n * from sbound0 to sbound1 with respect to the variable s.\n *\n * \\param lm Physically, this is the perpendicular distance above rod\n * \\param sbound lowerr limit of integral\n * \\param sbound Upper limit of integral\n * \\param M exponential constant factor. Physically, this is the product of\n (1-load_sensitivity)*spring_const/(k_B * Temperature)\n * \\param ell0 Shift of the integrands mean. Physically, protein rest length\n * \\return result The value of the integration\n\n */\ninline double integral(double lm, double sbound0, double sbound1, double M,\n double ell0) {\n if (sbound0 >= sbound1) {\n return 0;\n }\n auto integrand = [&](double s) {\n // lambda capture variabls ell0 and M\n const double exponent = sqrt(s * s + lm * lm) - ell0 - 1;\n return exp(-M * exponent * exponent);\n };\n double error = 0;\n double result =\n boost::math::quadrature::gauss_kronrod::integrate(\n integrand, sbound0, sbound1, 10, 1e-6, &error);\n return result;\n}\n\n#endif /* INTEGRALS_HPP_ */\n", "meta": {"hexsha": "c2e1695d2e32149961f57a424b25a2fda8e6ae3f", "size": 1570, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "KMC/integrals.hpp", "max_stars_repo_name": "jeffmm/KMC", "max_stars_repo_head_hexsha": "d4744bd6a2fe86efb7ee45eb00a0448185b3ae4c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "KMC/integrals.hpp", "max_issues_repo_name": "jeffmm/KMC", "max_issues_repo_head_hexsha": "d4744bd6a2fe86efb7ee45eb00a0448185b3ae4c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "KMC/integrals.hpp", "max_forks_repo_name": "jeffmm/KMC", "max_forks_repo_head_hexsha": "d4744bd6a2fe86efb7ee45eb00a0448185b3ae4c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1923076923, "max_line_length": 80, "alphanum_fraction": 0.6700636943, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6689148123345399}} {"text": "#include \r\n#include \r\n//#include \r\n#include \r\n//#include \r\n//#include \r\n//#include \r\n\r\n// [[Rcpp::depends(RcppArmadillo)]]\r\n// [[Rcpp::depends(RcppEigen)]]\r\n\r\ntypedef Eigen::Triplet T; //tripleta para rellenar matrices sparse\r\ntypedef Eigen::MappedSparseMatrix MSpMat; //alias para matriz sparse\r\ntypedef Eigen::Matrix VectorXd; //alias para vector sparse\r\nusing namespace Rcpp;\r\n//using namespace RcppArmadillo;\r\n\r\n// [[Rcpp::export]]\r\nfloat KernelGauss (arma::cube x, arma::cube y, int dimension, double sigJ, double sigd, float distancia)\r\n{\r\n //Calculo individual del kernel entre dos observaciones\r\n // input: x observaciones\r\n // y observaciones\r\n // dimension: numero de canales\r\n //sigJ: sd de la imagen\r\n //sigd: sd de la posicion\r\n //distancia: distancia L_2 entre los dos pixeles\r\n float kernel_value = 0;\r\n float siJ = (float)sigJ;\r\n float sid = (float)sigd;\r\n for (int i = 0; i < dimension; i++ )\r\n {\r\n kernel_value +=(float)pow( (float)(x[i] - y[i]),2);\r\n }\r\n kernel_value = exp(-(kernel_value/(2*pow(siJ,2)) ) - distancia/(2*pow(sid, 2)));\r\n return( kernel_value );\r\n}\r\n\r\n\r\n \r\n// [[Rcpp::export]]\r\nEigen::SparseMatrix Kernel_RGB ( arma::cube M, int h, int w, double distancia, double sigJ, double sigd, int dimension)\r\n{\r\n // Funcion para calcular la matriz de similaridades de todos los puntos de una imagen \r\n // input: w: altura en pixeles de la imagen//SINO NO ME SALIAN LAS MULTIPLICACIONES\r\n // h: ancho en pixeles de la imagen//SINO NO ME SALIAN LAS MULTIPLICACIONES\r\n // distancia: limite de la vecindad del pixel a considerar\r\n // M: imagen de 'dimension' dimensiones (numero de canales)\r\n // sigJ: sigma para kernel gaussiano, de la imagen\r\n // sigd: sigma para kernell gaussiano, de las distancias\r\n // dimension: numero de canales\r\n //output: W, similaridad calculada \r\n int i, j, k, l = 0 ;\r\n float vecindad = distancia;\r\n float d2 = 0.;\r\n float calculo = 0.;\r\n std::vector tripletList; //inicializamos tripleta\r\n tripletList.reserve((int)floor(h*h*w*w*.1));\r\n \r\n //comienza calculo de matriz de similaridades\r\n for(i=0; i < h; i++)\r\n {\r\n for(j=0; j< w; j++ )\r\n {\r\n for(k=0; k W(h*w, h*w); //construccion de matriz de similaridades\r\n W.setFromTriplets(tripletList.begin(), tripletList.end());\r\n return(W);\r\n}\r\n\r\n\r\n\r\n// [[Rcpp::export]]\r\nEigen::SparseMatrix Kernel_float ( NumericMatrix M, int h, int w, double distancia, double sigJ, double sigd)\r\n{\r\n // Funcion para calcular la matriz de similaridades de todos los puntos de una imagen \r\n // input: w: altura en pixeles de la imagen//SINO NO ME SALIAN LAS MULTIPLICACIONES\r\n // h: ancho en pixeles de la imagen//SINO NO ME SALIAN LAS MULTIPLICACIONES\r\n // distancia: limite de la vecindad del pixel a considerar\r\n // M: imagen de 2 dimensiones (EN ESCALA DE GRISES)\r\n // sigJ: sigma para kernel gaussiano, de la imagen\r\n // sigd: sigma para kernell gaussiano, de las distancias\r\n //output: W, similaridad calculada, sparse \r\n int i, j, k, l = 0 ;\r\n float vecindad = (float)distancia;\r\n float d2 = 0.;\r\n float calculo = 0.;\r\n std::vector tripletList; //inicializamos tripleta\r\n tripletList.reserve((int)(h*h*w*w*.1));\r\n //comienza calculo de matriz de similaridades\r\n for(i=0; i < h; i++)\r\n {\r\n for(j=0; j< w; j++ )\r\n {\r\n for(k=0; k W(h*w, h*w); //construccion de matriz de similaridades\r\n W.setFromTriplets(tripletList.begin(), tripletList.end());\r\n return(W);\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "c41a26c351a2406e965ad04af49b6e7e6c9d215c", "size": 4536, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Second/Numerico/Miniproyecto/W_RGB_float.cpp", "max_stars_repo_name": "fou-foo/MCE", "max_stars_repo_head_hexsha": "a279ed86fa31f89b0233257313ff3f72da9aab92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Second/Numerico/Miniproyecto/W_RGB_float.cpp", "max_issues_repo_name": "fou-foo/MCE", "max_issues_repo_head_hexsha": "a279ed86fa31f89b0233257313ff3f72da9aab92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Second/Numerico/Miniproyecto/W_RGB_float.cpp", "max_forks_repo_name": "fou-foo/MCE", "max_forks_repo_head_hexsha": "a279ed86fa31f89b0233257313ff3f72da9aab92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8923076923, "max_line_length": 128, "alphanum_fraction": 0.6071428571, "num_tokens": 1352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009549929799, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.6688461863835468}} {"text": "#include \"iris/geometry.h\"\n#include \n#include \n#include \n#include \"iris_cdd.h\"\n\nnamespace iris {\n\nint factorial(int n) {\n return n == 0 ? 1 : factorial(n - 1) * n;\n}\n\ndouble nSphereVolume(int dim, double radius) {\n double v;\n int k = std::floor(dim / 2);\n if (dim % 2 == 0) {\n v = std::pow(M_PI, k) / static_cast(factorial(k));\n } else {\n v = (2.0 * factorial(k) * std::pow(4 * M_PI, k)) / static_cast(factorial(2 * k + 1));\n }\n return v * std::pow(radius, dim);\n}\n\nEllipsoid::Ellipsoid(int dim) :\n C_(Eigen::MatrixXd(dim, dim)),\n d_(Eigen::VectorXd(dim)) {}\nEllipsoid::Ellipsoid(Eigen::MatrixXd C, Eigen::VectorXd d):\n C_(C),\n d_(d) {}\nconst Eigen::MatrixXd& Ellipsoid::getC() const {\n return C_;\n}\nconst Eigen::VectorXd& Ellipsoid::getD() const {\n return d_;\n}\nvoid Ellipsoid::setC(const Eigen::MatrixXd &C) {\n C_ = C;\n}\nvoid Ellipsoid::setCEntry(Eigen::DenseIndex row, \n Eigen::DenseIndex col, double value) {\n C_(row, col) = value;\n}\nvoid Ellipsoid::setD(const Eigen::VectorXd &d) {\n d_ = d;\n}\nvoid Ellipsoid::setDEntry(Eigen::DenseIndex index, double value) {\n d_(index) = value;\n}\nint Ellipsoid::getDimension() const {\n return C_.cols();\n}\ndouble Ellipsoid::getVolume() const {\n return C_.determinant() * nSphereVolume(this->getDimension(), 1.0);\n}\nEllipsoid Ellipsoid::fromNSphere(Eigen::VectorXd ¢er, double radius) {\n const int dim = center.size();\n Eigen::MatrixXd C = Eigen::MatrixXd::Zero(dim, dim);\n C.diagonal().setConstant(radius);\n Ellipsoid ellipsoid(C, center);\n return ellipsoid;\n}\n\nPolyhedron::Polyhedron(int dim):\n A_(0, dim),\n b_(0, 1),\n dd_representation_dirty_(true) {}\nPolyhedron::Polyhedron(Eigen::MatrixXd A, Eigen::VectorXd b):\n A_(A),\n b_(b),\n dd_representation_dirty_(true) {}\nvoid Polyhedron::setA(const Eigen::MatrixXd &A) {\n A_ = A;\n dd_representation_dirty_ = true;\n}\nconst Eigen::MatrixXd& Polyhedron::getA() const {\n return A_;\n}\nvoid Polyhedron::setB(const Eigen::VectorXd &b) {\n b_ = b;\n dd_representation_dirty_ = true;\n}\nconst Eigen::VectorXd& Polyhedron::getB() const {\n return b_;\n}\nint Polyhedron::getDimension() const {\n return A_.cols();\n}\nint Polyhedron::getNumberOfConstraints() const {\n return A_.rows();\n}\nvoid Polyhedron::appendConstraints(const Polyhedron &other) {\n A_.conservativeResize(A_.rows() + other.getA().rows(), A_.cols());\n A_.bottomRows(other.getA().rows()) = other.getA();\n b_.conservativeResize(b_.rows() + other.getB().rows());\n b_.tail(other.getB().rows()) = other.getB();\n dd_representation_dirty_ = true;\n}\nvoid Polyhedron::updateDDRepresentation() {\n generator_points_.clear();\n generator_rays_.clear();\n getGenerators(A_, b_, generator_points_, generator_rays_);\n dd_representation_dirty_ = false;\n}\nstd::vector Polyhedron::generatorPoints() {\n if (dd_representation_dirty_) {\n updateDDRepresentation();\n }\n return generator_points_;\n}\nstd::vector Polyhedron::generatorRays() {\n if (dd_representation_dirty_) {\n updateDDRepresentation();\n }\n return generator_rays_;\n}\nbool Polyhedron::contains(Eigen::VectorXd point, double tolerance) {\n return (A_ * point - b_).maxCoeff() <= tolerance;\n}\n\n}", "meta": {"hexsha": "6190849ec95ad832207ec3879332de6364beca37", "size": 3246, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cxx/geometry.cpp", "max_stars_repo_name": "tardani95/iris-distro", "max_stars_repo_head_hexsha": "dbb1ebbde2e52b4cc747b4aa2fe88518b238071a", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 82.0, "max_stars_repo_stars_event_min_datetime": "2016-03-30T15:32:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T03:03:08.000Z", "max_issues_repo_path": "src/cxx/geometry.cpp", "max_issues_repo_name": "tardani95/iris-distro", "max_issues_repo_head_hexsha": "dbb1ebbde2e52b4cc747b4aa2fe88518b238071a", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 49.0, "max_issues_repo_issues_event_min_datetime": "2015-01-21T16:13:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T02:47:52.000Z", "max_forks_repo_path": "src/cxx/geometry.cpp", "max_forks_repo_name": "tardani95/iris-distro", "max_forks_repo_head_hexsha": "dbb1ebbde2e52b4cc747b4aa2fe88518b238071a", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 61.0, "max_forks_repo_forks_event_min_datetime": "2015-03-20T18:49:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-27T12:35:38.000Z", "avg_line_length": 27.05, "max_line_length": 97, "alphanum_fraction": 0.6823783118, "num_tokens": 937, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122238669026, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6688326171154351}} {"text": "/**\n * Kalman Filter \n * Skeleton code for teaching \n * A3M33MKR\n * Czech Technical University \n * Faculty of Electrical Engineering\n * Intelligent and Mobile Robotics group\n *\n * Authors: Zdeněk Kasl, Karel Košnar kosnar@labe.felk.cvut.cz\n *\n * this code is inspired by tutorial on Kalman Filter by Greg Czerniak \n *\n * Licence: MIT (see LICENSE file)\n **/\n\n#include\n#include\n#include\n#include\n#include\n#include \n\n#include \"gui/gui.h\"\n#include \"systemSimulator/system.h\"\nusing namespace imr;\nusing namespace gui;\nusing namespace Eigen;\n\nPoint KalmanFilter(Point measuredPosition);\n\n// float v0 = 149;\n// float alpha = (float) (M_PI / 4 - 0.007);\n float v0 = 150;\n float alpha = (float) (M_PI / 4);\n float dt = 0.1;\n float g = (float) (9.8 * dt);\n\n Matrix4f A,R,Sigma;\n Matrix B;\n Matrix2f Q;\n Matrix C;\n Vector4f X;\n\n\n\nvoid help(char** argv)\n{\n std::cout << \"\\nUsage of the program \" << argv[0]+2 << std::endl\n << \"Parameter [-h or -H] displays this message.\" < HELP\n case 'H' : case 'h' :\n help(argv);\n break;\n\t\tcase 'N': case 'n':\n assert(i+1 < argc);\n assert(atoi(argv[i+1])>1);\n nSteps = atoi(argv[i+1]);\n\t\t break;\n default :\n std::cout << \"Parameter \\033[1;31m\" << argv[i] << \"\\033[0m is not valid!\\n\"\n << \"Use parameter -h or -H for help.\" << std::endl;\n break;\n }\n }\n }\n // All parameters parsed\n\n Gui gui;\n System system;\n \n //> comment line below in order to let the program\n //> continue right away\n// gui.startInteractor();\n\n Point measurement;\n Point truth;\n Point kfPosition;\n\n for(int i=1; i comment line below in order to let the program\n //> continue right away\n if (i%40 == 0) gui.startInteractor();\n \n }\n gui.startInteractor();\n\n return EXIT_SUCCESS;\n}\n\n\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n// implement Kalman Filter here\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\nPoint KalmanFilter(const Point measuredPosition)\n{\n Point ret;\n Vector2f Z;\n Z << measuredPosition.x,\n measuredPosition.y;\n Matrix input = g * B;\n Vector4f X_ = A * X + input;\n Matrix4f Sigma_ = A * Sigma * A.transpose() + R;\n Matrix K = Sigma_ * C.transpose() * (C * Sigma_ * C.transpose() + Q).inverse();\n X = X_ + 1*K * (Z - C * X_);\n\n ret.x = X(0);\n ret.y = X(1);\n return ret;\n}\n\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n/// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n\n\n\n", "meta": {"hexsha": "a47052ebe3148cf2bc65510dc45f30ef3ae9c2e2", "size": 3974, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kf_main.cpp", "max_stars_repo_name": "kralma/mkr_kf", "max_stars_repo_head_hexsha": "f8079150d27cfa12483bdab37be141f651c4a78b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kf_main.cpp", "max_issues_repo_name": "kralma/mkr_kf", "max_issues_repo_head_hexsha": "f8079150d27cfa12483bdab37be141f651c4a78b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kf_main.cpp", "max_forks_repo_name": "kralma/mkr_kf", "max_forks_repo_head_hexsha": "f8079150d27cfa12483bdab37be141f651c4a78b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.5308641975, "max_line_length": 95, "alphanum_fraction": 0.4632611978, "num_tokens": 1116, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122313857378, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6688326121796766}} {"text": "/*\n Copyright (C) 2015-2021 by Synge Todo \n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\n// Free energy, energy, and specific heat of square lattice Ising model\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace ising {\nnamespace free_energy {\nnamespace square {\n\nnamespace {\n\ntemplate\nstruct functor {\n functor(T Jx, T Jy, FVAR beta) {\n using std::cosh; using std::sinh;\n c_ = 1 / (2 * boost::math::constants::pi());\n chab_ = cosh(2 * beta * Jx) * cosh(2 * beta * Jy);\n k_ = 1.0 / (sinh(2 * beta * Jx) * sinh(2 * beta * Jy));\n }\n FVAR operator()(T t) const {\n using std::cos; using std::log; using std::sqrt;\n return c_ * log(chab_ + sqrt(1 + k_ * k_ - 2 * k_ * cos(2 * t)) / k_);\n }\n T c_;\n FVAR chab_, k_;\n};\n\ntemplate\nfunctor func(T Jx, T Jy, FVAR beta) { return functor(Jx, Jy, beta); }\n \n}\n\ntemplate\ninline std::tuple infinite(T Jx, T Jy, T beta) {\n typedef T real_t;\n using std::log;\n if (Jx <= 0 || Jy <= 0) throw(std::invalid_argument(\"Jx and Jy should be positive\"));\n if (beta <= 0) throw(std::invalid_argument(\"beta should be positive\"));\n const real_t pi = boost::math::constants::pi();\n auto beta_fvar = boost::math::differentiation::make_fvar(beta);\n auto logZ = log(real_t(2)) / 2 + standards::simpson_1d(func(Jx, Jy, beta_fvar), real_t(0), pi, 8);\n real_t d2 = logZ.derivative(2);\n for (unsigned long n = 16; n < 1024; n *= 2) {\n logZ = log(real_t(2)) / 2 + standards::simpson_1d(func(Jx, Jy, beta_fvar), real_t(0), pi, n);\n if (beta * beta * abs((logZ.derivative(2) - d2) / logZ.derivative(0)) <\n 2 * std::numeric_limits::epsilon()) break;\n d2 = logZ.derivative(2);\n }\n real_t free_energy = - logZ.derivative(0) / beta;\n real_t energy = - logZ.derivative(1);\n real_t specific_heat = beta * beta * logZ.derivative(2);\n return std::make_tuple(free_energy, energy, specific_heat);\n}\n\ntemplate\ninline std::tuple finite(I Lx, I Ly, T Jx, T Jy, T beta) {\n typedef T real_t;\n using std::exp; using std::log;\n if (Lx <= 0 || Ly <= 0) throw(std::invalid_argument(\"Lx and Ly should be positive\"));\n if (Jx <= 0 || Jy <= 0) throw(std::invalid_argument(\"Jx and Jy should be positive\"));\n if (beta <= 0) throw(std::invalid_argument(\"beta should be positive\"));\n const real_t pi = boost::math::constants::pi();\n auto beta_fvar = boost::math::differentiation::make_fvar(beta);\n auto a = beta_fvar * Jx;\n auto b = beta_fvar * Jy;\n decltype(beta_fvar) lp0(0), lp1(0), lp2(0), lp3(0);\n for (std::size_t k = 0; k < 2 * Lx; ++k) {\n auto cosh_g = (cosh(2*a) * cosh(2*b) - cos(pi * k / Lx) * sinh(2*b)) / sinh(2*a);\n auto gamma_abs = log(cosh_g + sqrt(cosh_g * cosh_g - 1));\n if ((k & 1) == 1) {\n lp0 += (Ly * gamma_abs/2) + log(1 + exp(-(Ly*gamma_abs)));\n lp1 += (Ly * gamma_abs/2) + log(1 - exp(-(Ly*gamma_abs)));\n } else {\n lp2 += (Ly * gamma_abs/2) + log(1 + exp(-(Ly*gamma_abs)));\n lp3 += (Ly * gamma_abs/2) + log(1 - exp(-(Ly*gamma_abs)));\n }\n }\n auto logZ = -log(real_t(2)) / (Lx * Ly) + a + real_t(1)/2 * log(1 - exp(-4*a));\n if (sinh(2*a) * sinh(2*b) < real_t(1)) {\n logZ += (lp0 + log(1 + exp(lp1-lp0) + exp(lp2-lp0) - exp(lp3-lp0))) / (Lx * Ly);\n } else {\n logZ += (lp0 + log(1 + exp(lp1-lp0) + exp(lp2-lp0) + exp(lp3-lp0))) / (Lx * Ly);\n }\n real_t free_energy = - logZ.derivative(0) / beta;\n real_t energy = - logZ.derivative(1);\n real_t specific_heat = beta * beta * logZ.derivative(2);\n return std::make_tuple(free_energy, energy, specific_heat);\n}\n\n} // end namespace square\n} // end namespace free_energy\n} // end namespace ising\n", "meta": {"hexsha": "03710c13e206a33640875d107286bd30b424b9b2", "size": 4417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ising/free_energy/square_count.hpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "ising/free_energy/square_count.hpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "ising/free_energy/square_count.hpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.7456140351, "max_line_length": 100, "alphanum_fraction": 0.6359520036, "num_tokens": 1484, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.6688326029420584}} {"text": "/*\n// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a\n// component of the Texas A&M University System.\n\n// All rights reserved.\n\n// The information and source code contained herein is the exclusive\n// property of TEES and may not be disclosed, examined or reproduced\n// in whole or in part without explicit written authorization from TEES.\n*/\n\n////////////////////////////////////////////////////////////////////////////////\n/// @file\n/// Solution of the Euler Problem #3\n/// (link).\n////////////////////////////////////////////////////////////////////////////////\n\n#include \n#include \n#include \n#include \n\n////////////////////////////////////////////////////////////////////////////////\n/// @brief Returns truncated integer square root of given number.\n/// @tparam IntType Integral type of the number.\n////////////////////////////////////////////////////////////////////////////////\ntemplate \ninline IntType sqrt_int(IntType n)\n{\n return static_cast( std::sqrt(n) );\n}\n\n////////////////////////////////////////////////////////////////////////////////\n/// @brief Functor that returns the larger of @p n and @p x/n that is both a\n/// factor of @p x and a prime number (0 if neither satisfies these\n/// conditions).\n/// @tparam IntType Integral type of the dividend @p x.\n////////////////////////////////////////////////////////////////////////////////\ntemplate \nstruct largest_prime_factors_filter\n{\n static_assert(std::is_integral::value, \"Integer required.\");\n\n typedef IntType result_type;\n\n largest_prime_factors_filter(IntType x)\n : m_x(x)\n { }\n\n IntType operator()(IntType n)\n {\n if ((m_x % n) != 0) // n is not a factor of x\n return 0;\n\n if (is_prime(m_x/n)) // x/n (which is larger than n) is prime\n return m_x/n;\n\n return is_prime(n) ? n : 0;\n }\n\n void define_type(stapl::typer& t)\n {\n t.member(m_x);\n }\n\nprivate:\n IntType m_x;\n\n static bool is_prime(IntType n)\n {\n IntType sqrt_n = sqrt_int(n);\n\n for (IntType i = 2; i <= sqrt_n; ++i)\n {\n if ((n % i) == 0)\n return false;\n }\n\n return true;\n }\n};\n\nstapl::exit_code stapl_main(int argc, char** argv)\n{\n using value_t = std::size_t;\n\n if (argc < 2)\n {\n stapl::do_once( [] {\n std::cout << \"Run as: mpirun -n pe_3b \" << std::endl;\n });\n return EXIT_FAILURE;\n }\n\n stapl::counter exec_timer;\n exec_timer.start();\n\n // Read the dividend from command line.\n value_t num = boost::lexical_cast (argv[1]);\n\n // Create a generator of consecutive values from 2 to sqrt(num).\n auto c_vw = stapl::counting_view(sqrt_int(num)-1, 2);\n\n // Apply the filter that effectively replaces each generated number by zero\n // if it is not prime factor of and accumulate a maximum of these\n // numbers.\n value_t max_prime_factor = stapl::map_reduce(\n largest_prime_factors_filter(num),\n stapl::max(),\n c_vw);\n\n double t = exec_timer.stop();\n\n stapl::do_once( [&] {\n std::cout << \"Computation finished (time taken: \" << t << \" s).\"\n << std::endl\n << \"Largest prime factor of \" << num << \" is: \"\n << max_prime_factor << std::endl;\n });\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "b80efa289045a68d168dd39d151affd9c8f8fecc", "size": 3462, "ext": "cc", "lang": "C++", "max_stars_repo_path": "stapl_release/examples/project_euler/pe_3b.cc", "max_stars_repo_name": "parasol-ppl/PPL_utils", "max_stars_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stapl_release/examples/project_euler/pe_3b.cc", "max_issues_repo_name": "parasol-ppl/PPL_utils", "max_issues_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stapl_release/examples/project_euler/pe_3b.cc", "max_forks_repo_name": "parasol-ppl/PPL_utils", "max_forks_repo_head_hexsha": "92728bb89692fda1705a0dee436592d97922a6cb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1463414634, "max_line_length": 80, "alphanum_fraction": 0.5589254766, "num_tokens": 817, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6687687987885138}} {"text": "#include \"resection.h\"\n\n#include \n#include \n#include \"sfm_utils.h\"\n#include \"defines.h\"\n\nnamespace {\n\n matrix34d canonicalizeP(const matrix34d &P)\n {\n matrix3d RR = P.get_minor<3, 3>(0, 0);\n vector3d tt;\n tt[0] = P(0, 3);\n tt[1] = P(1, 3);\n tt[2] = P(2, 3);\n\n if (cv::determinant(RR) < 0) {\n RR *= -1;\n tt *= -1;\n }\n\n double sc = 0;\n for (int i = 0; i < 9; i++) {\n sc += RR.val[i] * RR.val[i];\n }\n sc = std::sqrt(3 / sc);\n\n Eigen::MatrixXd RRe;\n copy(RR, RRe);\n Eigen::JacobiSVD svd(RRe, Eigen::ComputeFullU | Eigen::ComputeFullV);\n RRe = svd.matrixU() * svd.matrixV().transpose();\n copy(RRe, RR);\n\n tt *= sc;\n\n matrix34d result;\n for (int i = 0; i < 9; ++i) {\n result(i / 3, i % 3) = RR(i / 3, i % 3);\n }\n result(0, 3) = tt(0);\n result(1, 3) = tt(1);\n result(2, 3) = tt(2);\n\n return result;\n }\n\n // (см. Hartley & Zisserman p.178)\n cv::Matx34d estimateCameraMatrixDLT(const cv::Vec3d *Xs, const cv::Vec3d *xs, int count)\n {\n using mat = Eigen::MatrixXd;\n using vec = Eigen::VectorXd;\n\n mat A(2 * count, 12);\n\n for (int i = 0; i < count; ++i) {\n\n double x = xs[i][0];\n double y = xs[i][1];\n double w = xs[i][2];\n\n double X = Xs[i][0];\n double Y = Xs[i][1];\n double Z = Xs[i][2];\n double W = 1.0;\n\n A.row(i * 2 + 0) << 0, 0, 0, 0, -w*X, -w*Y, -w*Z, -w*W, y*X, y*Y, y*Z, y*W;\n A.row(i * 2 + 1) << w*X, w*Y, w*Z, w*W, 0, 0, 0, 0, -x*X, -x*Y, -x*Z, -x*W;\n }\n\n Eigen::JacobiSVD svd(A, Eigen::ComputeFullU | Eigen::ComputeFullV);\n Eigen::VectorXd null_space = svd.matrixV().col(11);\n\n matrix34d result;\n for (int i = 0; i < 12; ++i) {\n result(i / 4, i % 4) = null_space(i);\n }\n\n return canonicalizeP(result);\n }\n\n\n cv::Matx34d estimateCameraMatrixRANSAC(const phg::Calibration &calib, const std::vector &X, const std::vector &x, bool verbose)\n {\n if (X.size() != x.size()) {\n throw std::runtime_error(\"estimateCameraMatrixRANSAC: X.size() != x.size()\");\n }\n\n const int n_points = X.size();\n\n // https://en.wikipedia.org/wiki/Random_sample_consensus#Parameters\n // будет отличаться от случая с гомографией\n const int n_trials = 10000;\n\n const double threshold_px = 3;\n\n const int n_samples = 6;\n uint64_t seed = 1;\n\n int best_support = 0;\n cv::Matx34d best_P;\n\n std::vector sample;\n for (int i_trial = 0; i_trial < n_trials; ++i_trial) {\n phg::randomSample(sample, n_points, n_samples, &seed);\n\n cv::Vec3d ms0[n_samples];\n cv::Vec3d ms1[n_samples];\n for (int i = 0; i < n_samples; ++i) {\n ms0[i] = X[sample[i]];\n ms1[i] = calib.unproject(x[sample[i]]);\n }\n\n cv::Matx34d P = estimateCameraMatrixDLT(ms0, ms1, n_samples);\n\n int support = 0;\n for (int i = 0; i < n_points; ++i) {\n cv::Vec3d pt = calib.project(P * cv::Vec4d(X[i][0], X[i][1], X[i][2], 1.0));\n if (pt[2] == 0) {\n continue;\n }\n cv::Vec2d px = {pt[0] / pt[2], pt[1] / pt[2]};\n if (cv::norm(px - x[i]) < threshold_px) {\n ++support;\n }\n }\n\n if (support > best_support) {\n best_support = support;\n best_P = P;\n\n if (verbose) std::cout << \"estimateCameraMatrixRANSAC : support: \" << best_support << \"/\" << n_points << std::endl;\n\n if (best_support == n_points) {\n break;\n }\n }\n }\n\n if (verbose) std::cout << \"estimateCameraMatrixRANSAC : best support: \" << best_support << \"/\" << n_points << std::endl;\n\n if (best_support == 0) {\n throw std::runtime_error(\"estimateCameraMatrixRANSAC : failed to estimate camera matrix\");\n }\n\n return best_P;\n }\n\n\n}\n\ncv::Matx34d phg::findCameraMatrix(const Calibration &calib, const std::vector &X, const std::vector &x, bool verbose) {\n return estimateCameraMatrixRANSAC(calib, X, x, verbose);\n}\n", "meta": {"hexsha": "a0374c5ac6c973e27d7c15e1e99ac17fae93f57a", "size": 4538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phg/sfm/resection.cpp", "max_stars_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_stars_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/phg/sfm/resection.cpp", "max_issues_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_issues_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/phg/sfm/resection.cpp", "max_forks_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_forks_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.2774193548, "max_line_length": 153, "alphanum_fraction": 0.4832525342, "num_tokens": 1403, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.896251362048962, "lm_q2_score": 0.746138993030751, "lm_q1q2_score": 0.6687280887816516}} {"text": "#pragma once\n#include \n#include \n#include \"serializer.hpp\"\n\nnamespace tomoto\n{\n\tnamespace math\n\t{\n\t\ttemplate\n\t\tstruct MultiNormalDistribution\n\t\t{\n\t\t\tstatic constexpr _Ty log2pi = (_Ty)1.83787706641;\n\t\t\tEigen::Matrix<_Ty, -1, 1> mean;\n\t\t\tEigen::Matrix<_Ty, -1, -1> cov, l;\n\t\t\t_Ty logDet = 0;\n\n\t\t\tMultiNormalDistribution(size_t k = 0) :\n\t\t\t\tmean{ Eigen::Matrix<_Ty, -1, 1>::Zero(k) },\n\t\t\t\tcov{ Eigen::Matrix<_Ty, -1, -1>::Identity(k, k) },\n\t\t\t\tl{ Eigen::Matrix<_Ty, -1, -1>::Identity(k, k) }\n\t\t\t{\n\t\t\t}\n\n\t\t\t_Ty getLL(const Eigen::Matrix<_Ty, -1, 1>& x) const\n\t\t\t{\n\t\t\t\t_Ty ll = -((x - mean).transpose() * cov.inverse() * (x - mean))[0] / 2;\n\t\t\t\tll -= log2pi * mean.size() / 2 + logDet;\n\t\t\t\treturn ll;\n\t\t\t}\n\n\t\t\tconst Eigen::Matrix<_Ty, -1, -1>& getCovL() const\n\t\t\t{\n\t\t\t\treturn l;\n\t\t\t}\n\n\t\t\ttemplate\n\t\t\tstatic MultiNormalDistribution<_Ty> estimate(_List list, size_t len)\n\t\t\t{\n\t\t\t\tMultiNormalDistribution<_Ty> newDist;\n\t\t\t\tif (len)\n\t\t\t\t{\n\t\t\t\t\tnewDist.mean = list(0);\n\t\t\t\t\tfor (size_t i = 1; i < len; ++i) newDist.mean += list(i);\n\t\t\t\t\tnewDist.mean /= len;\n\t\t\t\t\tnewDist.cov = Eigen::Matrix<_Ty, -1, -1>::Identity(newDist.mean.size(), newDist.mean.size());\n\t\t\t\t\tfor (size_t i = 0; i < len; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tEigen::Matrix<_Ty, -1, 1> o = list(i) - newDist.mean;\n\t\t\t\t\t\tnewDist.cov += o * o.transpose();\n\t\t\t\t\t}\n\t\t\t\t\tif (len > 1) newDist.cov /= len - 1;\n\t\t\t\t}\n\t\t\t\tEigen::MatrixXd l = newDist.cov.template cast().llt().matrixL();\n\t\t\t\tnewDist.l = l.template cast();\n\t\t\t\tnewDist.logDet = l.diagonal().array().log().sum();\n\t\t\t\treturn newDist;\n\t\t\t}\n\n\t\t\tDEFINE_SERIALIZER_CALLBACK(onRead, mean, cov);\n\t\tprivate:\n\t\t\tvoid onRead() \n\t\t\t{\n\t\t\t\tl = cov.llt().matrixL();\n\t\t\t\tlogDet = l.diagonal().array().log().sum();\n\t\t\t}\n\t\t};\n\n\t}\n}", "meta": {"hexsha": "8e0d96c7c4bd88039fbd5c12734115c4a2a6e40d", "size": 1790, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Utils/MultiNormalDistribution.hpp", "max_stars_repo_name": "bab2min/tomotopy", "max_stars_repo_head_hexsha": "20a44b03dc67b90730edfb9e21623c9bed9f17ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 393.0, "max_stars_repo_stars_event_min_datetime": "2019-05-11T16:43:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T12:54:28.000Z", "max_issues_repo_path": "src/Utils/MultiNormalDistribution.hpp", "max_issues_repo_name": "bab2min/tomotopy", "max_issues_repo_head_hexsha": "20a44b03dc67b90730edfb9e21623c9bed9f17ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 122.0, "max_issues_repo_issues_event_min_datetime": "2019-05-22T07:08:31.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-21T11:58:01.000Z", "max_forks_repo_path": "src/Utils/MultiNormalDistribution.hpp", "max_forks_repo_name": "bab2min/tomotopy", "max_forks_repo_head_hexsha": "20a44b03dc67b90730edfb9e21623c9bed9f17ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 49.0, "max_forks_repo_forks_event_min_datetime": "2019-06-05T09:04:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T18:04:20.000Z", "avg_line_length": 25.5714285714, "max_line_length": 98, "alphanum_fraction": 0.5832402235, "num_tokens": 611, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095292, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6687235625052518}} {"text": "#ifndef POLYTOPE_H\n#define POLYTOPE_H\n\n#include \n#include \n#include \n\n#include \n\n\nnamespace integrator_chains {\n\n\n/** Basic half-space representation of polytopes.\n\n \\ingroup integrator_chains */\nclass Polytope {\n public:\n Polytope( Eigen::MatrixXd incoming_H, Eigen::VectorXd incoming_K );\n Polytope( const Polytope &other );\n\n /** Check that defining matrices have consistent dimensions.\n\n The \"defining matrices\" are those involved in the inequality providing\n the half-space representation, i.e., H and K in {x | Hx <= K}.\n N.B., this check does not occur during instantiation of Polytope. */\n bool is_consistent() const;\n\n /** Is X contained in this polytope?\n\n The polytope is a closed set. No numerical tolerance is used. */\n bool is_in( Eigen::VectorXd X ) const;\n\n /** Intersect two polytopes that are defined in the same dimension space. */\n Polytope operator&( const Polytope &P2 );\n\n // Factory functions\n /** Create random Polytope in R^n using Eigen::MatrixXd::Random().\n\n \\param n dimension of the containing space.\n\n Random matrices as provided by Eigen::MatrixXd::Random() are used to\n instantiate Polytope in half-space representation. The matrices have\n \\c n+1 rows, corresponding to \\c n+1 inequalities.\n */\n static Polytope * randomH( int n );\n\n /** Construct Polytope that is an axis-aligned rectangle.\n\n \\param bounds an array of the form\n \\code\n [x1_min, x1_max, x2_min, x2_max, ..., xn_min, xn_max],\n \\endcode\n which defines a polytope in terms of intervals along each axis in R^n.\n The interval along the first axis is [x1_min, x1_max], the interval along\n the second axis is [x2_min, x2_max], etc. Thus the length of the given\n array is 2n.\n\n E.g., a unit square in R^2 can be created using\n \\code\n Eigen::Vector4d bounds;\n bounds << 0, 1,\n 0, 1;\n Polytope *square = Polytope::box( bounds );\n \\endcode\n */\n static Polytope * box( const Eigen::VectorXd &bounds );\n\n /** Output this polytope in JSON to given stream. */\n friend std::ostream & operator<<( std::ostream &out, const Polytope &P );\n\n /** Output this polytope in JSON excluding opening { and closing }.\n\n This method facilitates inheritance from Polytope without crowding the\n JSON representations of other classes. */\n void dumpJSONcore( std::ostream &out ) const;\n\n private:\n // { x \\in R^n | Hx \\leq K }\n Eigen::MatrixXd H;\n Eigen::VectorXd K;\n};\n\nstd::ostream & operator<<( std::ostream &out, const Polytope &P )\n{\n out << \"{ \";\n P.dumpJSONcore( out );\n out << \" }\";\n return out;\n}\n\nvoid Polytope::dumpJSONcore( std::ostream &out ) const\n{\n int i, j;\n out << \"\\\"H\\\": [\";\n for (i = 0; i < H.rows(); i++) {\n if (i > 0) {\n out << \", \";\n }\n out << \"[\";\n for (j = 0; j < H.cols(); j++) {\n if (j > 0)\n out << \", \";\n out << H(i,j);\n }\n out << \"]\";\n }\n out << \"], \\\"K\\\": [\";\n for (i = 0; i < K.rows(); i++) {\n if (i > 0) {\n out << \", \";\n }\n out << K(i);\n }\n out << \"]\";\n}\n\nPolytope * Polytope::randomH( int n )\n{\n return new Polytope( Eigen::MatrixXd::Random( n+1, n ),\n Eigen::VectorXd::Random( n+1 ) );\n}\n\nPolytope * Polytope::box( const Eigen::VectorXd &bounds )\n{\n assert( bounds.size() % 2 == 0 );\n\n int n = bounds.size()/2;\n Eigen::MatrixXd H = Eigen::MatrixXd::Zero( 2*n, n );\n Eigen::VectorXd K( 2*n );\n for (int i = 0; i < n; i++) {\n H(2*i, i) = -1;\n K(2*i) = -bounds(2*i);\n H(2*i+1, i) = 1;\n K(2*i+1) = bounds(2*i+1);\n }\n return new Polytope( H, K );\n}\n\nbool Polytope::is_consistent() const\n{\n if (H.rows() == K.size()) {\n return true;\n } else {\n return false;\n }\n}\n\nbool Polytope::is_in( Eigen::VectorXd X ) const\n{\n assert( H.cols() == X.size() );\n\n if ((H*X-K).maxCoeff() <= 0) {\n return true;\n } else {\n return false;\n }\n}\n\nPolytope Polytope::operator&( const Polytope &P2 )\n{\n assert( this->H.cols() == P2.H.cols() );\n\n Eigen::MatrixXd H( this->H.rows() + P2.H.rows(), this->H.cols() );\n Eigen::VectorXd K( this->H.rows() + P2.H.rows(), 1 );\n\n H.topRows( this->H.rows() ) = this->H;\n K.topRows( this->H.rows() ) = this->K;\n H.bottomRows( P2.H.rows() ) = P2.H;\n K.bottomRows( P2.H.rows() ) = P2.K;\n\n return Polytope( H, K );\n}\n\nPolytope::Polytope( Eigen::MatrixXd incoming_H, Eigen::VectorXd incoming_K )\n : H(incoming_H), K(incoming_K)\n{ }\n\nPolytope::Polytope( const Polytope &other )\n : H(other.H), K(other.K)\n{ }\n\n\n/** Extension of Polytope to have label (string).\n\n This class provides a basis for labeling trajectories. E.g., the labeling of\n the state can be a set of strings corresponding to the labels of polytopes\n containing the state.\n\n \\ingroup integrator_chains */\nclass LabeledPolytope : public Polytope {\npublic:\n std::string label;\n\n LabeledPolytope( const Polytope &other );\n\n /** Polytope::box() but including a label. */\n static LabeledPolytope * box( const Eigen::VectorXd &bounds, std::string label=\"\" );\n\n /** Output this labeled polytope in JSON to given stream. */\n friend std::ostream & operator<<( std::ostream &out, const LabeledPolytope &P );\n};\n\nLabeledPolytope::LabeledPolytope( const Polytope &other )\n : label(\"\"), Polytope( other )\n{ }\n\nLabeledPolytope * LabeledPolytope::box( const Eigen::VectorXd &bounds, std::string label )\n{\n Polytope *P = Polytope::box( bounds );\n LabeledPolytope *Q = new LabeledPolytope( *P );\n delete P;\n Q->label = label;\n return Q;\n}\n\nstd::ostream & operator<<( std::ostream &out, const LabeledPolytope &P )\n{\n out << \"{ \\\"label\\\": \\\"\" << P.label << \"\\\", \";\n P.dumpJSONcore( out );\n out << \" }\";\n return out;\n}\n\n\n} // namespace integrator_chains\n\n\n#endif // ifndef POLYTOPE_H\n", "meta": {"hexsha": "c94b10d56f13ff1ab1e3ede4cbd36148363b5523", "size": 6090, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "domains/integrator_chains/dynamaestro/include/polytope.hpp", "max_stars_repo_name": "fmrchallenge/fmrbenchmark", "max_stars_repo_head_hexsha": "529520a2b254f7da366b681983182c9e25555b6c", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2015-05-28T22:52:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T00:21:12.000Z", "max_issues_repo_path": "domains/integrator_chains/dynamaestro/include/polytope.hpp", "max_issues_repo_name": "fmrchallenge/fmrbenchmark", "max_issues_repo_head_hexsha": "529520a2b254f7da366b681983182c9e25555b6c", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 15.0, "max_issues_repo_issues_event_min_datetime": "2016-02-07T20:57:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-30T23:42:06.000Z", "max_forks_repo_path": "domains/integrator_chains/dynamaestro/include/polytope.hpp", "max_forks_repo_name": "fmrchallenge/fmrbenchmark", "max_forks_repo_head_hexsha": "529520a2b254f7da366b681983182c9e25555b6c", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2015-12-28T20:53:26.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-08T23:30:44.000Z", "avg_line_length": 26.4782608696, "max_line_length": 90, "alphanum_fraction": 0.5866995074, "num_tokens": 1724, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6687235552796125}} {"text": "#include \"vio/eigen_utils.h\"\n#include \n#include \n\nnamespace vio {\n\nEigen::Vector3d rotro2eu(Eigen::Matrix3d R) {\n Eigen::Vector3d euler;\n euler[0] = atan2(R(2, 1), R(2, 2));\n euler[1] = -(atan2(R(2, 0), sqrt(1 - R(2, 0) * R(2, 0))));\n euler[2] = atan2(R(1, 0), R(0, 0));\n return euler;\n}\n\nEigen::Matrix3d roteu2ro(Eigen::Vector3d eul) {\n double cr = cos(eul[0]);\n double sr = sin(eul[0]); // roll\n double cp = cos(eul[1]);\n double sp = sin(eul[1]); // pitch\n double ch = cos(eul[2]);\n double sh = sin(eul[2]); // heading\n Eigen::Matrix3d dcm;\n dcm(0, 0) = cp * ch;\n dcm(0, 1) = (sp * sr * ch) - (cr * sh);\n dcm(0, 2) = (cr * sp * ch) + (sh * sr);\n\n dcm(1, 0) = cp * sh;\n dcm(1, 1) = (sr * sp * sh) + (cr * ch);\n dcm(1, 2) = (cr * sp * sh) - (sr * ch);\n\n dcm(2, 0) = -sp;\n dcm(2, 1) = sr * cp;\n dcm(2, 2) = cr * cp;\n return dcm;\n}\n// input: lat, long in radians, height is immaterial\n// output: Ce2n\nEigen::Matrix3d llh2dcm(const Eigen::Vector3d llh) {\n double sL = sin(llh[0]);\n double cL = cos(llh[0]);\n double sl = sin(llh[1]);\n double cl = cos(llh[1]);\n\n Eigen::Matrix3d Ce2n;\n Ce2n << -sL * cl, -sL * sl, cL, -sl, cl, 0, -cL * cl, -cL * sl, -sL;\n return Ce2n;\n}\n\nEigen::MatrixXd nullspace(const Eigen::MatrixXd &A) {\n Eigen::HouseholderQR qr(A);\n // ColPivHouseholderQR qr(A); //don't use column pivoting because in\n // that case Q*R-A!=0\n Eigen::MatrixXd nullQ = qr.householderQ();\n\n int rows = A.rows(), cols = A.cols();\n assert(rows >\n cols); // \"Rows should be greater than columns in computing nullspace\"\n nullQ = nullQ.block(0, cols, rows, rows - cols).eval();\n return nullQ;\n}\n\nvoid leftNullspaceAndColumnSpace(const Eigen::MatrixXd &A, Eigen::MatrixXd *Q2,\n Eigen::MatrixXd *Q1) {\n int rows = A.rows(), cols = A.cols();\n assert(rows > cols); // \"Rows should be greater than columns in computing\n // left nullspace\"\n Eigen::HouseholderQR qr(A);\n // don't use column pivoting because in that case Q*R-A!=0\n Eigen::MatrixXd Q = qr.householderQ();\n\n Q2->resize(rows, rows - cols);\n *Q2 = Q.block(0, cols, rows, rows - cols);\n\n Q1->resize(rows, cols);\n *Q1 = Q.block(0, 0, rows, cols);\n}\n\nEigen::Matrix superdiagonal(\n const Eigen::Matrix &M) {\n const int numElements = std::min(M.rows(), M.cols()) - 1;\n Eigen::Matrix r(numElements, 1);\n for (int jack = 0; jack < numElements; ++jack) r[jack] = M(jack, jack + 1);\n return r;\n}\n\nEigen::Matrix subdiagonal(\n const Eigen::Matrix &M) {\n const int numElements = std::min(M.rows(), M.cols()) - 1;\n Eigen::Matrix r(numElements, 1);\n for (int jack = 0; jack < numElements; ++jack) r[jack] = M(jack + 1, jack);\n return r;\n}\n\nvoid reparameterize_AIDP(const Eigen::Matrix3d &Ri, const Eigen::Matrix3d &Rj,\n const Eigen::Vector3d &abrhoi,\n const Eigen::Vector3d &pi, const Eigen::Vector3d &pj,\n Eigen::Vector3d &abrhoj,\n Eigen::Matrix *jacobian) {\n Eigen::Matrix Tci2cj = Eigen::Matrix::Identity();\n Tci2cj.topLeftCorner<3, 3>() = Rj.transpose() * Ri;\n Tci2cj.block<3, 1>(0, 3).noalias() = Rj.transpose() * (pi - pj);\n Eigen::Matrix homogi;\n homogi << abrhoi.head<2>(), 1, abrhoi[2];\n double rhoj_drhoi = 1 / (Tci2cj.row(2) * homogi); //\\rho_j divided by \\rho_i\n abrhoj.head<2>() = rhoj_drhoi * Tci2cj.topLeftCorner<2, 4>() * homogi;\n abrhoj[2] = abrhoi[2] * rhoj_drhoi;\n if (jacobian) {\n Eigen::Matrix3d lhs;\n lhs.setIdentity();\n lhs.col(2) = -abrhoj;\n //{\\alpha, \\beta, \\rho}_i\n Eigen::Matrix subrhs;\n subrhs << Tci2cj.topLeftCorner<3, 2>(), Tci2cj.block<3, 1>(0, 3);\n jacobian->topLeftCorner<3, 3>() = rhoj_drhoi * lhs * subrhs;\n (*jacobian)(2, 2) =\n rhoj_drhoi * rhoj_drhoi * Tci2cj.block<1, 3>(2, 0) * homogi.head<3>();\n //{pi, pj}\n Eigen::Matrix rhs;\n rhs.topLeftCorner<3, 3>() = abrhoi[2] * Rj.transpose(),\n rhs.block<3, 3>(0, 3) = -rhs.topLeftCorner<3, 3>();\n jacobian->block<3, 6>(0, 3) = rhoj_drhoi * lhs * rhs;\n }\n}\n\nvoid reparameterizeNumericalJacobian(const Eigen::Matrix3d &Ri,\n const Eigen::Matrix3d &Rj,\n const Eigen::Vector3d &abrhoi,\n const Eigen::Vector3d &pi,\n const Eigen::Vector3d &pj,\n Eigen::Vector3d &abrhoj,\n Eigen::Matrix &jacobian) {\n // numerical differentation\n Eigen::Vector3d abrhojp;\n reparameterize_AIDP(Ri, Rj, abrhoi, pi, pj, abrhoj);\n double h = 1e-8;\n for (int jack = 0; jack < 3; ++jack) {\n Eigen::Vector3d abrhoip = abrhoi;\n abrhoip[jack] = abrhoi[jack] + h;\n reparameterize_AIDP(Ri, Rj, abrhoip, pi, pj, abrhojp);\n Eigen::Vector3d subJacobian = (abrhojp - abrhoj) / h;\n jacobian.col(jack) = subJacobian;\n }\n\n for (int jack = 0; jack < 3; ++jack) {\n Eigen::Vector3d pip = pi;\n pip[jack] = pi[jack] + h;\n reparameterize_AIDP(Ri, Rj, abrhoi, pip, pj, abrhojp);\n Eigen::Vector3d subJacobian = (abrhojp - abrhoj) / h;\n jacobian.col(jack + 3) = subJacobian;\n }\n\n for (int jack = 0; jack < 3; ++jack) {\n Eigen::Vector3d pjp = pj;\n pjp[jack] = pj[jack] + h;\n reparameterize_AIDP(Ri, Rj, abrhoi, pi, pjp, abrhojp);\n Eigen::Vector3d subJacobian = (abrhojp - abrhoj) / h;\n jacobian.col(jack + 6) = subJacobian;\n }\n}\n\n\nEigen::Vector3d unskew3d(const Eigen::Matrix3d &Omega) {\n return 0.5 * Eigen::Vector3d(Omega(2, 1) - Omega(1, 2),\n Omega(0, 2) - Omega(2, 0),\n Omega(1, 0) - Omega(0, 1));\n}\n\n// https://github.com/ethz-asl/maplab_lightweight_filtering/blob/28417454164b08d5483754f0c0d250b84f2ce951/include/lightweight_filtering/Update.hpp\ndouble getConditionNumberOfMatrix(const Eigen::MatrixXd &matrix) {\n Eigen::JacobiSVD svd(matrix);\n return svd.singularValues()(0) /\n svd.singularValues()(svd.singularValues().size() - 1);\n}\n} // namespace vio\n", "meta": {"hexsha": "ca391984d77a364939cf5ba3902efa9a0437530f", "size": 6445, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/eigen_utils.cpp", "max_stars_repo_name": "stellarpower/vio_common", "max_stars_repo_head_hexsha": "5508203cbcc166cbcd34dc0a6f7852c73e2cff55", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-06-02T07:22:31.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T02:39:39.000Z", "max_issues_repo_path": "src/eigen_utils.cpp", "max_issues_repo_name": "stellarpower/vio_common", "max_issues_repo_head_hexsha": "5508203cbcc166cbcd34dc0a6f7852c73e2cff55", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-08-10T04:01:35.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-18T08:21:17.000Z", "max_forks_repo_path": "src/eigen_utils.cpp", "max_forks_repo_name": "stellarpower/vio_common", "max_forks_repo_head_hexsha": "5508203cbcc166cbcd34dc0a6f7852c73e2cff55", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2017-08-03T02:23:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-22T02:17:46.000Z", "avg_line_length": 36.8285714286, "max_line_length": 146, "alphanum_fraction": 0.5851047324, "num_tokens": 2280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6686988797681043}} {"text": "#include \"engine/math/hcMatrix.h\"\n#include \"engine/hcImageFITS.h\"\n//#include \"engine/math/coordTransform.h\"\n\n#include \"src/pfss.h\"\n\n//#include \"extern/soil/SOIL.h\"\n\n#include \n#include \n#include \n\n#include \n#include \"boost/lexical_cast.hpp\"\n#include \n\nusing namespace std;\nusing namespace boost;\n\n/*! returns the magnetic field vector at given position (spherical coordinates) for a dipole\n * at the origin oriented along the positive z-axis. Return value given in spherical coordinates.\n * mathematics found at http://www.physicsinsights.org/dipole_field_1.html\n */\nVec3D getDipoleField(Vec3D pos, hcFloat dipole, bool debug)\n{\n\thcFloat r\t\t= pos[0] / r_sol;\n\thcFloat theta\t= pos[1];\n\thcFloat stheta\t= sin(theta);\n\thcFloat ctheta\t= cos(theta);\n\thcFloat fac\t\t= dipole / (r * r * r);\n\thcFloat Br\t\t= fac * 2 * ctheta;\n\thcFloat Bt\t\t= fac * stheta;\n\n\tVec3D retval((hcFloat)Br, (hcFloat)Bt, (hcFloat)0.0f);\n\n\tif(debug)\n\t\tprintf(\"r: %E, t: %E, fac: %E, Br: %E, Bt: %E\\n\", r, theta, fac, Br, Bt);\n\n\treturn retval;\n}\n\n/*! mathematics found in \"The Model Magnetic Configuration of the Extended Corona\nin the Solar Wind Formation Region - Igor Veselovsky and Olga Panasenco\"\n */\nVec3D getDipoleCurrentField(Vec3D pos, hcFloat dipole, bool debug)\n{\n\thcFloat r\t\t= pos[0] / r_sol;\n\thcFloat theta\t= pos[1];\n\thcFloat stheta\t= sin(theta);\n\thcFloat ctheta\t= cos(theta);\n\thcFloat fac\t\t= dipole / (r * r * r);\n\n\thcFloat mu0\t\t= 4*PI*1E-7;\n\thcFloat mu\t\t= mu0 * dipole;\n\thcFloat r0\t\t= 2.5;\n\thcFloat B0\t\t= -1E-8;\n\thcFloat Ba\t\t= (B0*r0*r0) * (B0*r0*r0) * (B0*r0*r0) / (4 * mu * mu);\n\thcFloat a\t\t= 2 * mu / (B0*r0*r0);\n\thcFloat rho\t\t= r / a;\n\n\thcFloat Br\t\t= Ba / (rho * rho) * (ctheta / rho + (theta - PI/2.0 < 0 ? -1.0 : 1.0));\n\thcFloat Bt\t\t= 1 / (2 * rho * rho * rho) * Ba * stheta;\n\n\tif(debug)\n\t{\n\t\tprintf(\"r: %E, t: %E, Ba: %E, a: %E, rho: %E, Br: %E, Bt: %E\\n\", r, theta, Ba, a, rho, Br, Bt);\n\t\t//printf(\"(B0*r0*r0): %E, ^3: %E, denom: %E, ba: %E\\n\", (B0*r0*r0), (B0*r0*r0) * (B0*r0*r0) * (B0*r0*r0), (4 * dipole * dipole), Ba);\n\t}\n\n\tVec3D retval((hcFloat)Br, (hcFloat)Bt, (hcFloat)0.0f);\n\n\treturn retval;\n}\n\nPFSSsolution_SHC::PFSSsolution_SHC(const char *filename, bool WSOfile, hcFloat r_ss)\n{\n\tinitNULL();\n\timportCoefficients(filename, WSOfile, r_ss);\n}\n\nPFSSsolution_SHC::PFSSsolution_SHC()\n{\n initNULL();\n}\n\nPFSSsolution_SHC::~PFSSsolution_SHC()\n{\n clear();\n}\n\nPFSSsolution_SHC::PFSSsolution_SHC(const PFSSsolution_SHC &other)\n{\n\tprintf(\"PFSS_magfield: cpy constructor not implemented!\\n\");\n\tinitNULL();\n}\n\nPFSSsolution_SHC &PFSSsolution_SHC::operator=(const PFSSsolution_SHC &other)\n{\n\tif(this == &other)\n\t\treturn *this;\n\n\tprintf(\"PFSSsolution_SHC: assignment operator not implemented!\\n\");\n\n\treturn *this;\n}\n\nvoid PFSSsolution_SHC::initNULL()\n{\n\tg \t\t\t\t\t= NULL;\n\th \t\t\t\t\t= NULL;\n\tassLegPoly \t\t\t= NULL;\n\tcoeffOrder \t\t\t= 0;\n}\n\nvoid PFSSsolution_SHC::clear()\n{\n\tif(g!=NULL)\n\t{\n\t\tfor(uint i=0;i highestOrder)\n highestOrder = atoi(tempstr);\n }\n\n init((uint)highestOrder, r_ss);\n\n fseek(coeffFile,0, SEEK_SET);\n uint j=0;\n while (fgets(str, 1000, coeffFile) != NULL)\n {\n if(j==0) // load g's\n {\n if(str[0] == '\\n')\n ++j;\n else\n {\n i = 0;\n\n tempstr[0] = '\\0';\n while(str[i++] != ' ');\n z = i;\n strncpy(tempstr, str, i-1);\n tempstr[i-1] = '\\0';\n order=(uint)atoi(tempstr);\n k=0;\n\n while(k<=order)\n {\n while(str[i] == ' ' || str[i] == '\\t')\n ++i;\n z=i;\n while(str[i] != ' ' && str[i++] != '\\n');\n strncpy(tempstr, str+z, i-1);\n tempstr[i-z] = '\\0';\n g[order][k++] = strtof(tempstr, NULL);\n tempstr[0] = '\\0';\n z=i;\n }\n ++order;\n }\n }\n else // load h's\n {\n if(str[0] == '\\n')\n break;\n else\n {\n i = 0;\n\n tempstr[0] = '\\0';\n while(str[i++] != ' ');\n z = i;\n strncpy(tempstr, str, i-1);\n tempstr[i-1] = '\\0';\n order=(uint)atoi(tempstr);\n k=0;\n\n while(k<=order)\n {\n while(str[i] == ' ' || str[i] == '\\t')\n ++i;\n z=i;\n while(str[i] != ' ' && str[i++] != '\\n');\n strncpy(tempstr, str+z, i-1);\n tempstr[i-1-z] = '\\0';\n h[order][k++] = strtof(tempstr, NULL);\n tempstr[0] = '\\0';\n z=i;\n }\n\n ++order;\n }\n }\n\n }\n fclose(coeffFile);\n\n if(WSOfile)\t\t\t\t// WSO files employ microTesla as units\n {\n \tfor(uint l=0; l<=coeffOrder; ++l)\n \t\tfor(uint m=0; m<=l; ++m)\n \t\t{\n \t\t\tg[l][m] /= 100;\n \t\t\th[l][m] /= 100;\n \t\t}\n }\n\n return true;\n}\n\nvoid PFSSsolution_SHC::exportCoefficients(const char *filename)\n{\n char tempstr[10000];\n char tmp[100];\n\n FILE *outfile = fopen(filename, \"w\");\n for(uint l=0;l<=coeffOrder;++l)\n {\n tempstr[0] = '\\0';\n sprintf(tempstr, \"%u \", l);\n for(uint m=0;m<=l;++m)\n {\n tmp[0] = '\\0';\n sprintf(tmp, \"%f \", g[l][m]);\n strcat(tempstr, tmp);\n }\n if(l==0)\n strcat(tempstr, \"\\t\\t g's\");\n strcat(tempstr, \"\\n\");\n fprintf(outfile, \"%s\", tempstr);\n }\n fprintf(outfile, \"\\n\");\n for(uint l=0;l<=coeffOrder;++l)\n {\n tempstr[0] = '\\0';\n sprintf(tempstr, \"%u \", l);\n for(uint m=0;m<=l;++m)\n {\n tmp[0] = '\\0';\n sprintf(tmp, \"%f \", h[l][m]);\n strcat(tempstr, tmp);\n }\n if(l==0)\n strcat(tempstr, \"\\t\\t h's\");\n strcat(tempstr, \"\\n\");\n fprintf(outfile, \"%s\", tempstr);\n }\n fclose(outfile);\n}\n\n//---------------------------------------------------------------------------------------------------------------\n//--- PFSSsolution_SHC_sun\n//---------------------------------------------------------------------------------------------------------------\n\nPFSSsolution_SHC_sun::PFSSsolution_SHC_sun()\n{\n\tinitNULL();\n}\n\nPFSSsolution_SHC_sun::PFSSsolution_SHC_sun(const PFSSsolution_SHC_sun &other)\n{\n\tinitNULL();\n\toperator =(other);\n}\n\nPFSSsolution_SHC_sun::~PFSSsolution_SHC_sun()\n{\n\tclear();\n}\n\nPFSSsolution_SHC_sun &PFSSsolution_SHC_sun::operator=(const PFSSsolution_SHC_sun &other)\n{\n\tif(this == &other)\n\t\treturn *this;\n\n\tinit(other.coeffOrder, other.sourceSurfaceFactor*r_sol);\n\n\tfor(uint l=0; l<=coeffOrder; ++l)\n\t\tfor(uint m=0; m<=l; ++m)\n\t\t{\n\t\t\tg[l][m]\t= other.g[l][m];\n\t\t\th[l][m]\t= other.h[l][m];\n\t\t}\n\n\treturn *this;\n}\n\nPFSSsolution_SHC_sun PFSSsolution_SHC_sun::operator-(const PFSSsolution_SHC_sun &other)\n{\n\tPFSSsolution_SHC_sun retval;\n\n\tif(this->coeffOrder != other.coeffOrder || this->sourceSurfaceFactor != other.sourceSurfaceFactor)\n\t{\n\t\tprintf(\"PFSS_magfield::operator- order does not match (%u != %u) or r_ss is different.\\n\", this->coeffOrder, other.coeffOrder);\n\t\tretval.init(0, 2.5*r_sol);\n\t}\n\telse\n\t{\n\t\tretval.init(this->coeffOrder, this->sourceSurfaceFactor);\n\t\tfor(uint l=0; l<=coeffOrder; ++l)\n\t\t\tfor(uint m=0; m<=l; ++m)\n\t\t\t{\n\t\t\t\thcFloat g1 \t\t= fabs(this->g[l][m] - other.g[l][m]) / fabs(this->g[l][m]);\n\t\t\t\thcFloat g2 \t\t= fabs(this->g[l][m] - other.g[l][m]) / fabs(other.g[l][m]);\n\t\t\t\thcFloat h1 \t\t= fabs(this->h[l][m] - other.h[l][m]) / fabs(this->h[l][m]);\n\t\t\t\thcFloat h2 \t\t= fabs(this->h[l][m] - other.h[l][m]) / fabs(other.h[l][m]);\n\n\t\t\t\tretval.g[l][m] \t= this->g[l][m]==0 ? 0.0 : g1 < g2 ? g1 : g2;\n\t\t\t\tretval.h[l][m] \t= this->h[l][m]==0 ? 0.0 : h1 < h2 ? h1 : h2;\n\t\t\t}\n\t}\n\n\treturn retval;\n\n}\n\nvoid PFSSsolution_SHC_sun::init(uint order, hcFloat r_ss)\n{\n\tclear();\n\tcoeffOrder \t= order;\n\tsourceSurfaceFactor = r_ss/r_sol;\n\tg \t\t\t= new hcFloat*[coeffOrder + 1];\n\th \t\t\t= new hcFloat*[coeffOrder + 1];\n\tassLegPoly \t= new AssocLegendrePoly_sun*[coeffOrder + 1];\n\n\tfor(uint i=0;i<=coeffOrder;++i)\n\t{\n\t\tg[i] \t\t\t= new hcFloat[i+1];\n\t\th[i] \t\t\t= new hcFloat[i+1];\n\t\tassLegPoly[i] \t= new AssocLegendrePoly_sun[i+1];\n\n\t\tfor(uint j=0;j<=i;++j)\n\t\t{\n\t\t\tAssocLegendrePoly_sun temp(i, j);\n\t\t\tassLegPoly[i][j] = temp;\n\t\t}\n\t}\n}\n\nvoid PFSSsolution_SHC_sun::eval(const Vec3D &pos, Vec3D &result)\n{\n\thcFloat r\t\t\t= pos[0];\n\thcFloat theta\t\t= pos[1];\n\thcFloat phi\t\t\t= pos[2];\n\n\thcFloat r_ss \t\t= sourceSurfaceFactor * r_sol; // source surface\n\thcFloat retval_r \t= 0.0;\n\thcFloat retval_t \t= 0.0;\n\thcFloat retval_p \t= 0.0;\n\n\tfor(uint l=0;l<=coeffOrder;++l)\n\t\tfor(uint m=0;m<=l;++m)\n\t\t{ // equation 16 from Notes on PFSS Extrapolation, Xudong Sun\n\t\t\tretval_r += assLegPoly[l][m](cos(theta))\n\t\t\t\t\t * ( g[l][m] * cos(m*phi) + h[l][m] * sin(m*phi) )\n\t\t\t\t\t * pow(r_sol / r, (hcFloat)(l+2))\n\t\t\t\t\t * (l+1+l*pow(r / r_ss, (hcFloat)(2*l+1))) / (l+1+l*pow(r_sol / r_ss, (hcFloat)(2*l+1)));\n\n\t\t\t// equation 17\n\t\t\tretval_t += -assLegPoly[l][m].getDeriv(theta)\n\t\t\t\t\t * ( g[l][m] * cos(m*phi) + h[l][m] * sin(m*phi) )\n\t\t\t\t\t * pow(r_sol / r, (hcFloat)(l+2))\n\t\t\t\t\t * (1 - pow(r / r_ss, (hcFloat)(2*l+1))) / (l+1+l*pow(r_sol / r_ss, (hcFloat)(2*l+1)));\n\n\t\t\t// equation 18\n\t\t\tretval_p += assLegPoly[l][m](cos(theta))\n\t\t\t\t\t * ( g[l][m] * sin(m*phi) - h[l][m] * cos(m*phi) )\n\t\t\t\t\t * pow(r_sol / r, (hcFloat)(l+2))\n\t\t\t\t\t * (1 - pow(r / r_ss, (hcFloat)(2*l+1))) / (l+1+l*pow(r_sol / r_ss, (hcFloat)(2*l+1)));\n\t\t}\n\n\tresult(0) = retval_r;\n\tresult(1) = retval_t;\n\tresult(2) = retval_p;\n}\n\n\n//---------------------------------------------------------------------------------------------------------------\n//--- PFSSsolution_SHC_hoek\n//---------------------------------------------------------------------------------------------------------------\n\nPFSSsolution_SHC_hoek::PFSSsolution_SHC_hoek()\n{\n\tinitNULL();\n}\n\nPFSSsolution_SHC_hoek::PFSSsolution_SHC_hoek(const PFSSsolution_SHC_hoek &other)\n{\n\tinitNULL();\n\toperator =(other);\n}\n\nPFSSsolution_SHC_hoek::~PFSSsolution_SHC_hoek()\n{\n\tclear();\n}\n\nPFSSsolution_SHC_hoek &PFSSsolution_SHC_hoek::operator=(const PFSSsolution_SHC_hoek &other)\n{\n\tif(this == &other)\n\t\treturn *this;\n\n\tprintf(\"PFSSsolution_SHC: assignment operator not implemented!\\n\");\n\n\treturn *this;\n}\n\nPFSSsolution_SHC_hoek PFSSsolution_SHC_hoek::operator-(const PFSSsolution_SHC_hoek &other)\n{\n\tPFSSsolution_SHC_hoek retval;\n\n\tif(this->coeffOrder != other.coeffOrder)\n\t{\n\t\tprintf(\"PFSS_magfield::operator- order does not match (%u != %u)\\n\", this->coeffOrder, other.coeffOrder);\n\t\tretval.init(0, 2.5*r_sol);\n\t}\n\telse\n\t{\n\t\tretval.init(this->coeffOrder, this->sourceSurfaceFactor);\n\t\tfor(uint l=0; l<=coeffOrder; ++l)\n\t\t\tfor(uint m=0; m<=l; ++m)\n\t\t\t{\n\t\t\t\tretval.g[l][m] = this->g[l][m]==0 ? 0.0 : (this->g[l][m] - other.g[l][m]) / this->g[l][m];\n\t\t\t\tretval.h[l][m] = this->h[l][m]==0 ? 0.0 : (this->h[l][m] - other.h[l][m]) / this->h[l][m];\n\t\t\t}\n\t}\n\n\treturn retval;\n\n}\n\nvoid PFSSsolution_SHC_hoek::init(uint order, hcFloat r_ss)\n{\n\tclear();\n\tcoeffOrder \t= order;\n\tsourceSurfaceFactor = r_ss / r_sol;\n\tg \t\t\t= new hcFloat*[coeffOrder + 1];\n\th \t\t\t= new hcFloat*[coeffOrder + 1];\n\tassLegPoly \t= new AssocLegendrePoly_sun*[coeffOrder + 1];\n\n\tfor(uint i=0;i<=coeffOrder;++i)\n\t{\n\t\tg[i] \t\t\t= new hcFloat[i+1];\n\t\th[i] \t\t\t= new hcFloat[i+1];\n\t\tassLegPoly[i] \t= new AssocLegendrePoly_sun[i+1];\n\n\t\tfor(uint j=0;j<=i;++j)\n\t\t{\n\t\t\tAssocLegendrePoly_sun temp(i, j);\n\t\t\tassLegPoly[i][j] = temp;\n\t\t}\n\t}\n}\n\nvoid PFSSsolution_SHC_hoek::eval(const Vec3D &pos, Vec3D &result)\n{\n\thcFloat r\t\t\t= pos[0];\n\thcFloat theta\t\t= pos[1];\n\thcFloat phi\t\t\t= pos[2];\n\n\thcFloat r_ss \t\t= sourceSurfaceFactor * r_sol; // source surface\n\thcFloat retval_r \t= 0.0;\n\thcFloat retval_t \t= 0.0;\n\thcFloat retval_p \t= 0.0;\n\n\tfor(uint l=0;l<=coeffOrder;++l)\n\t\tfor(uint m=0;m<=l;++m)\n\t\t{\n\t\t\thcFloat c\t= -pow(r_sol / r_ss, (hcFloat)(l+2));\n\n\t\t\tretval_r += assLegPoly[l][m](cos(theta))\n\t\t\t\t\t * ( g[l][m] * cos(m*phi) + h[l][m] * sin(m*phi) )\n\t\t\t\t\t * ((l+1) * pow(r_sol / r, (hcFloat)(l+2)) - c * l * pow(r / r_ss, (hcFloat)((int)l-1)));\n\n\t\t\tretval_t += -assLegPoly[l][m].getDeriv(theta)\n\t\t\t\t\t * ( g[l][m] * cos(m*phi) + h[l][m] * sin(m*phi) )\n\t\t\t\t\t * (pow(r_sol / r, (hcFloat)(l+2)) + c * pow(r / r_ss, (hcFloat)((int)l-1)));\n\n\t\t\tretval_p += assLegPoly[l][m](cos(theta))\n\t\t\t\t\t * ( g[l][m] * sin(m*phi) - h[l][m] * cos(m*phi) )\n\t\t\t\t\t * (pow(r_sol / r, (hcFloat)(l+2)) + c * pow(r / r_ss, (hcFloat)((int)l-1))) * m / sin(theta);\n\t\t}\n\n\tresult(0) = retval_r;\n\tresult(1) = retval_t;\n\tresult(2) = retval_p;\n}\n\n//---------------------------------------------------------------------------------------------------------------\n//--- CSSS\n//---------------------------------------------------------------------------------------------------------------\n\n\n\nCSSS_magfield::CSSS_magfield(const char *filename)\n{\n\tinitNULL();\n if(!load(filename))\n \tprintf(\"ERROR! CSSS_magfield constructor could not load file '%s'\\n\", filename);\n}\n\nCSSS_magfield::CSSS_magfield()\n{\n\tinitNULL();\n printf(\"ERROR! CSSS_magfield std constructor not implemented!\\n\");\n}\n\nCSSS_magfield::CSSS_magfield(const CSSS_magfield &other)\n{\n\tinitNULL();\n\tprintf(\"ERROR! CSSS_magfield cpy constructor not implemented!\\n\");\n}\n\nCSSS_magfield::~CSSS_magfield()\n{\n clear();\n}\n\nvoid CSSS_magfield::initNULL()\n{\n\tg \t\t\t\t\t= NULL;\n\th \t\t\t\t\t= NULL;\n\tassLegPoly \t\t\t= NULL;\n\tsourceSurfaceFactor = 2.5;\n\torder \t\t\t= 0;\n}\n\nvoid CSSS_magfield::clear()\n{\n\tif(g != NULL)\n\t{\n\t\tfor(uint i=0;i<=order;++i)\n\t\t{\n\t\t\tdelete [] g[i];\n\t\t\tdelete [] h[i];\n\t\t\tdelete [] assLegPoly[i];\n\t\t}\n\t\tdelete [] g;\n\t\tdelete [] h;\n\t\tdelete assLegPoly;\n\t}\n\n\tinitNULL();\n}\n\n\nvoid CSSS_magfield::init(uint order)\n{\n\tclear();\n\n this->order\t= order;\n g \t\t\t= new double*[order + 1];\n h \t\t\t= new double*[order + 1];\n assLegPoly \t= new AssocLegendrePoly_sun*[order + 1];\n\n for(uint l=0;l<=order;++l)\n {\n g[l] \t\t\t= new double[l+1];\n h[l] \t\t\t= new double[l+1];\n assLegPoly[l] \t= new AssocLegendrePoly_sun[l+1];\n for(uint m=0;m<=l;++m)\n {\n AssocLegendrePoly_sun temp(l, m);\n assLegPoly[l][m] \t= temp;\n g[l][m]\t\t\t\t= 0.0;\n h[l][m]\t\t\t\t= 0.0;\n }\n }\n}\n\nvoid CSSS_magfield::exportCoefficients(const char *filename)\n{\n char tempstr[10000];\n char tmp[100];\n FILE *outfile = fopen(filename, \"w\");\n for(uint l=0;l<=order;++l)\n {\n tempstr[0] = '\\0';\n sprintf(tempstr, \"%u \", l);\n for(uint m=0;m<=l;++m)\n {\n tmp[0] = '\\0';\n sprintf(tmp, \"%f \", g[l][m]);\n strcat(tempstr, tmp);\n }\n if(l==0)\n strcat(tempstr, \"\\t\\t g's\");\n strcat(tempstr, \"\\n\");\n fprintf(outfile, \"%s\", tempstr);\n }\n fprintf(outfile, \"\\n\");\n for(uint l=0;l<=order;++l)\n {\n tempstr[0] = '\\0';\n sprintf(tempstr, \"%u \", l);\n for(uint m=0;m<=l;++m)\n {\n tmp[0] = '\\0';\n sprintf(tmp, \"%f \", h[l][m]);\n strcat(tempstr, tmp);\n }\n if(l==0)\n strcat(tempstr, \"\\t\\t h's\");\n strcat(tempstr, \"\\n\");\n fprintf(outfile, \"%s\", tempstr);\n }\n fclose(outfile);\n}\n\n/*\nvoid CSSS_magfield::determineCoefficientsFromFITSsineLat(uint order, const char *FITS_filename,\n\t\tdouble maxSinLat, double minSinLat, bool accountForMissingFlux)\n{\n\n uint x, y, l, m;\n initArrays(order);\n hcImageFITS fitsIMG(FITS_filename);\n uint width \t= fitsIMG.width;\n uint height = fitsIMG.height;\n\n double dTheta = PI / (2 * height);\n double dSinTheta = (maxSinLat - minSinLat) / (height-1);\n double dPhi = 2*PI/(width);\n\n // compute missing-flux-term\n double delta = 0.0;\n double tempB;\n double theta;\n double cosecans;\n double numerator = 0.0;\n\n for(y=0;y(what[1]);\n\t\t\tbreak;\n\t\t}\n\n\t\tre.assign(\".*([0-9]{2}).*\", regex::icase);\n\t\tregex_search(line, what, re);\n\n\t\tif(what[0].matched)\n\t\t{\n\t\t\torder = boost::lexical_cast(what[1]);\n\t\t\tbreak;\n\t\t}\n\n\t\tre.assign(\".*([0-9]{1}).*\", regex::icase);\n\t\tregex_search(line, what, re);\n\n\t\tif(what[0].matched)\n\t\t{\n\t\t\torder = boost::lexical_cast(what[1]);\n\t\t\tbreak;\n\t\t}\n\n\t\tprintf(\"ERROR! loadCSSScoeff: Order of solution could not be found!\\n\");\n\t\treturn false;\n\t}\n\n\tinit(order);\n\n\tchar lstr[1000], mstr[1000], gstr[1000], hstr[1000];\n\n\twhile(file >> lstr >> mstr >> gstr >> hstr)\n\t{\n\t\tuint l \t\t= atoi(lstr);\n\t\tuint m \t\t= atoi(mstr);\n\t\tdouble gval = atof(gstr);\n\t\tdouble hval\t= atof(hstr);\n\n\t\tif((l>order) || (m>l))\n\t\t{\n\t\t\tprintf(\"Error! loadCSSScoeff: l: %u, m: %u\\n\", l, m);\n\t\t\treturn false;\n\t\t}\n\n\t\tg[l][m]\t= gval;\n\t\th[l][m]\t= hval;\n\t}\n\treturn true;\n}\n\nvoid CSSS_magfield::eval(const Vec3D &pos, Vec3D &result)\n{\n\thcFloat r\t\t\t= pos[0];\n\thcFloat theta\t\t= pos[1];\n\thcFloat phi\t\t\t= pos[2];\n\n double r_ss \t\t= sourceSurfaceFactor * r_sol; // source surface\n double retval_r \t= 0.0;\n double retval_t \t= 0.0;\n double retval_phi \t= 0.0;\n\n for(uint l=0;l<=order;++l)\n for(uint m=0;m<=l;++m)\n { // equation 16 from Notes on PFSS Extrapolation, Xudong Sun\n retval_r += assLegPoly[l][m](cos(theta))\n \t* ( g[l][m] * cos(m*phi) + h[l][m] * sin(m*phi) )\n \t* pow(r_sol / r, (double)(l+2))\n \t* (l+1+l*pow(r / r_ss, (double)(2*l+1))) / (l+1+l*pow(r_sol / r_ss, (double)(2*l+1)));\n\n // equation 17 (there has to be theta instead of cos(theta) below!)\n retval_t += -assLegPoly[l][m].getDeriv(theta)\n \t* ( g[l][m] * cos(m*phi) + h[l][m] * sin(m*phi) )\n \t* pow(r_sol / r, (double)(l+2))\n \t* (1 - pow(r / r_ss, (double)(2*l+1))) / (l+1+l*pow(r_sol / r_ss, (double)(2*l+1)));\n\n // equation 18\n retval_phi += assLegPoly[l][m](cos(theta))\n \t * ( g[l][m] * sin(m*phi) - h[l][m] * cos(m*phi) )\n \t * pow(r_sol / r, (double)(l+2))\n \t * (1 - pow(r / r_ss, (double)(2*l+1))) / (l+1+l*pow(r_sol / r_ss, (double)(2*l+1)));//*/\n\n }\n result(0) = retval_r;\n result(1) = retval_t;\n result(2) = retval_phi;\n}\n\nvoid CSSS_magfield::dump()\n{\n\tprintf(\"CSSS harmonic coefficients (up to order %u):\\n----------------------------------------------------------\\n\", order);\n\tfor(uint l=1; l<=order; ++l)\n\t\tfor(uint m=0; m<=l; ++m)\n\t\t\tprintf(\"l:\\t%u, m:\\t%u, g_lm:\\t%E, h_lm:\\t%E\\n\", m, l, g[l][m], h[l][m]);\n\n}\n\n//---------------------------------------------------------------------------------------------------------------\n//--- PFSS_visualization\n//---------------------------------------------------------------------------------------------------------------\n\n#ifdef GUI\n\nPFSS_visualization::PFSS_visualization(){\n\n\tdrawScale\t\t\t= 0.0;\n\tupperOrder \t\t\t= 0;\n\tlowerOrder\t\t\t= 0;\n\tupperSS\t\t\t\t= 0;\n\tlowerSS\t\t\t\t= 0;\n\ttextScreenID\t\t= 0;\n\tssAnimScreenID\t\t= 0;\n\tcontourProjScreenID\t= 0;\n\taccumulatedTimediff = 0;\n\tanimPointer\t\t\t= 0;\n\tanimationPlaying\t= false;\n\tfps\t\t\t\t\t= 0;\n\tnumFrames\t\t\t= 0;\n\tmagLines\t\t\t= NULL;\n}\n\nPFSS_visualization::PFSS_visualization(char *filename) : hcScene3D(){\n\n initFromCoeffFile(filename);\n}\n\nPFSS_visualization::~PFSS_visualization()\n{\n clear();\n}\n\nvoid PFSS_visualization::clear()\n{\n if(magLines != NULL)\n {\n delete [] magLines;\n magLines = NULL;\n }\n}\n\nvoid PFSS_visualization::init()\n{\n clear();\n hcScene3D::init();\n magLines \t\t\t\t= NULL;\n accumulatedTimediff \t= 0.0;\n drawScale \t\t\t\t= 1 / (1.5 * r_sol);\n double ssSize \t\t\t= magfield.sourceSurfaceFactor * r_sol * drawScale;\n double sunSize\t\t\t = r_sol * drawScale;\n sun.appendFragment(*(new hcDSphere3D(origin3D, 1.0)));\n sources.appendFragment(*(new hcDSphere3D(origin3D, 1.0)));\n sources.TFmodel.loadIdentity();\n sources.TFmodel.scaleHom(ssSize);\n sun.TFmodel.loadIdentity();\n sun.TFmodel.scaleHom(sunSize);\n animationPlaying = false;\n}\n\nvoid PFSS_visualization::initFromSynopticFITSsineLat(uint order, const char *filename, double maxSinLat, double minSinLat)\n{\n init();\n SynPhotMagfield synPhot;\n synPhot.load(filename);\n magfield.determineCoefficientsFromPhotMagfield(order, 2.5*r_sol, synPhot);\n\n sun.texContainer.rmTexture();\n sun.texContainer.addFITSTexFromFile(filename);\n\n sources.texContainer.rmTexture();\n sources.texContainer.addMonoTexture(char2RGBA8(255,255,255,50));\n\n initScene();\n\n}\n\nvoid PFSS_visualization::initFromSynopticWSO(uint order, const char *filename)\n{\n std::ifstream in(filename);\n\n char instrings[31][1000];\n in.getline(instrings[0], 1000);\n in.getline(instrings[0], 1000);\n\n uint ntheta \t\t= 30;\n uint nphi \t\t\t= 73;\n //hcFloat *imageData \t= new hcFloat[ntheta * nphi];\n hcImageFITS img(nphi, ntheta);\n\n uint i;\n uint j=0;\n while(in >> instrings[0] >> instrings[1] >> instrings[2] >> instrings[3] >> instrings[4] >> instrings[5] >> instrings[6] >> instrings[7] >> instrings[8] >> instrings[9] >> instrings[10] >> instrings[11] >> instrings[12] >> instrings[13] >> instrings[14] >> instrings[15] >> instrings[16] >> instrings[17] >> instrings[18] >> instrings[19] >> instrings[20] >> instrings[21] >> instrings[22] >> instrings[23] >> instrings[24] >> instrings[25] >> instrings[26] >> instrings[27] >> instrings[28] >> instrings[29] >> instrings[30])\n {\n if(strncmp(instrings[0], \"CTxxxxxxxx\", 2))\n {\n printf(\"ERROR! PFSS_visualization::initFromSynopticWSO: Data alignment mismatch! Check the WSO-file!\\n\");\n printf(\"j: %u, instrings[0]: %s\\n\", j, instrings[0]);\n exit(1);\n }\n\n for(i=0;i highestOrder1)\n highestOrder1 = atoi(tempstr);\n }\n\n coeffFile2 = fopen(infile2, \"r\");\n if(!coeffFile2)\n {\n printf(\"ERROR! PFSSsolution_SHC_sun::compareCoeffFiles: File %s does not exist!\\n\", infile1);\n return;\n }\n i=0;\n while(strcmp(fgets(str, 1000, coeffFile2), \"\\n\"))\n {\n while(str[i++] != ' ');\n strncpy(tempstr, str, --i);\n tempstr[i] = '\\0';\n if (atoi(tempstr) > highestOrder2)\n highestOrder2 = atoi(tempstr);\n }\n\n if(highestOrder1 != highestOrder2)\n {\n printf(\"ERROR! PFSSsolution_SHC_sun::compareCoeffFiles: Coefficient order does not match! (%i != %i)\\n\", highestOrder1, highestOrder2);\n return;\n }\n\n fseek(coeffFile1,0, SEEK_SET);\n fseek(coeffFile2,0, SEEK_SET);\n\n double **g1 = (double**)malloc(sizeof(double) * (highestOrder1+1));\n double **h1 = (double**)malloc(sizeof(double) * (highestOrder1+1));\n double **g2 = (double**)malloc(sizeof(double) * (highestOrder1+1));\n double **h2 = (double**)malloc(sizeof(double) * (highestOrder1+1));\n for(i=0;i<=highestOrder1;++i)\n {\n g1[i] = (double*) malloc(sizeof(double) * (i+1));\n h1[i] = (double*) malloc(sizeof(double) * (i+1));\n g2[i] = (double*) malloc(sizeof(double) * (i+1));\n h2[i] = (double*) malloc(sizeof(double) * (i+1));\n }\n\n j=0;\n while (fgets(str, 1000, coeffFile1) != NULL)\n {\n if(j==0) // load g's\n {\n if(str[0] == '\\n')\n ++j;\n else\n {\n i = 0;\n tempstr[0] = '\\0';\n while(str[i++] != ' ');\n z = i;\n strncpy(tempstr, str, i-1);\n tempstr[i-1] = '\\0';\n order=(uint)atoi(tempstr);\n k=0;\n\n while(k<=order)\n {\n while(str[i] == ' ' || str[i] == '\\t')\n ++i;\n z=i;\n while(str[i] != ' ' && str[i++] != '\\n');\n strncpy(tempstr, str+z, i-1);\n tempstr[i-1-z] = '\\0';\n g1[order][k++] = strtof(tempstr, NULL);\n tempstr[0] = '\\0';\n z=i;\n }\n ++order;\n }\n }\n else // load h's\n {\n if(str[0] == '\\n')\n break;\n else\n {\n i = 0;\n\n tempstr[0] = '\\0';\n while(str[i++] != ' ');\n z = i;\n strncpy(tempstr, str, i-1);\n tempstr[i-1] = '\\0';\n order=(uint)atoi(tempstr);\n k=0;\n\n while(k<=order)\n {\n while(str[i] == ' ' || str[i] == '\\t')\n ++i;\n z=i;\n while(str[i] != ' ' && str[i++] != '\\n');\n strncpy(tempstr, str+z, i-1);\n tempstr[i-1-z] = '\\0';\n h1[order][k++] = strtof(tempstr, NULL);\n tempstr[0] = '\\0';\n z=i;\n }\n ++order;\n }\n }\n }\n\n j=0;\n while (fgets(str, 1000, coeffFile2) != NULL)\n {\n if(j==0) // load g's\n {\n if(str[0] == '\\n')\n ++j;\n else\n {\n i = 0;\n\n tempstr[0] = '\\0';\n while(str[i++] != ' ');\n z = i;\n strncpy(tempstr, str, i-1);\n tempstr[i-1] = '\\0';\n order=(uint)atoi(tempstr);\n k=0;\n\n while(k<=order)\n {\n while(str[i] == ' ' || str[i] == '\\t')\n ++i;\n z=i;\n while(str[i] != ' ' && str[i++] != '\\n');\n strncpy(tempstr, str+z, i-1);\n tempstr[i-1-z] = '\\0';\n g2[order][k++] = strtof(tempstr, NULL);\n tempstr[0] = '\\0';\n z=i;\n }\n ++order;\n }\n }\n else // load h's\n {\n if(str[0] == '\\n')\n break;\n else\n {\n i = 0;\n\n tempstr[0] = '\\0';\n while(str[i++] != ' ');\n z = i;\n strncpy(tempstr, str, i-1);\n tempstr[i-1] = '\\0';\n order=(uint)atoi(tempstr);\n k=0;\n\n while(k<=order)\n {\n while(str[i] == ' ' || str[i] == '\\t')\n ++i;\n z=i;\n while(str[i] != ' ' && str[i++] != '\\n');\n strncpy(tempstr, str+z, i-1);\n tempstr[i-1-z] = '\\0';\n h2[order][k++] = strtof(tempstr, NULL);\n tempstr[0] = '\\0';\n z=i;\n }\n ++order;\n }\n }\n }\n\n fclose(coeffFile1);\n fclose(coeffFile2);\n compFile = fopen(outfile, \"w\");\n\n double error;\n double gAccum = 0.0;\n double hAccum = 0.0;\n for(i=0;i<=highestOrder1;++i)\n {\n fprintf(compFile, \"%i \", i);\n for(j=0;j<=i;++j)\n {\n error = fabs((g2[i][j]-g1[i][j])/g1[i][j]);\n fprintf(compFile, \"%f\\t\", error);\n if(!isnan((long double)error))\n gAccum += error;\n }\n fprintf(compFile, \"\\n\");\n }\n\n fprintf(compFile, \"\\n\");\n for(i=0;i<=highestOrder1;++i)\n {\n fprintf(compFile, \"%i \", i);\n for(j=0;j<=i;++j)\n {\n error = fabs((h2[i][j]-h1[i][j])/h1[i][j]);\n fprintf(compFile, \"%f\\t\", error);\n if(!isnan((long double)error))\n hAccum += error;\n }\n fprintf(compFile, \"\\n\");\n }\n\n fprintf(compFile, \"\\nAccumulated error in g: %f\\nAccumulated error in h: %f\\n\", gAccum, hAccum);\n fclose(compFile);\n\n for(i=0;i<=highestOrder1;++i)\n {\n free(g1[i]);\n free(h1[i]);\n free(g2[i]);\n free(h2[i]);\n }\n free(g1);\n free(h1);\n free(g2);\n free(h2);\n}\n\nvoid PFSS_visualization::initScene()\n{\n#define maxNumPointsPerMagLine 1000\n\n uint numTheta \t= 10;\n uint numPhi \t= 20;\n\n uint i,j,k;\n Vec3D temp;\n Vec3D pos;\n Vec3D temp_mag;\n Vec3D *posData;\n Vec3D gridPos;\n double theta, phi;\n\n appendObject(sun);\n\n magLines = new hcDObject3D[1];\n magLines[0].init();\n magLines[0].texContainer.init(3);\n magLines[0].texContainer.addMonoTexture(char2RGBA8(255, 0, 0, 255)); //downward maglines\n magLines[0].texContainer.addMonoTexture(char2RGBA8(0, 255, 0, 255)); //upward maglines\n magLines[0].texContainer.addMonoTexture(char2RGBA8(255, 255, 255, 30)); //source surface\n\n hcDLineStrip3D lineStrip;\n\n for(j=0;j<=numTheta;++j)\n for(k=0;k 0) \t\t\t// compute poles only for k=0\n break;\n bool upwards;\n theta \t\t\t\t= j * PI / numTheta;\t// TODO please review this\n phi \t\t\t\t= k * 2 * PI / numPhi;\t// TODO please review this\n gridPos.content[0] \t= r_sol;\n gridPos.content[1] \t= theta;\n gridPos.content[2] \t= phi;\n\n posData \t\t\t= new Vec3D[maxNumPointsPerMagLine];\n\n for(i=0;i magfield.sourceSurfaceFactor * r_sol))\n {\n lineStrip.init(i, posData);\n lineStrip.drawOptions.computeLighting = false;\n\n uint num = magLines[0].appendFragment(lineStrip);\n if(!upwards)\n magLines[0][num].texturePointer = 0;\n else\n magLines[0][num].texturePointer = 1;\n break;\n }\n\n temp = pos;\n temp.scale(1/drawScale);\n temp = temp.convCoordCart2Spher();\n magfield.eval(temp, temp_mag);\n }\n\n if(!upwards)\n {\n //temp.loadZeroes();\n //temp.minus(temp_mag);\n temp = -temp_mag;\n temp_mag = temp;\n }\n\n posData[i] = pos;\n temp_mag.scale(0.01 / temp_mag.length());\n //pos.plus(temp_mag);\n pos\t+= temp_mag;\n }\n delete [] posData;\n }\n appendObject(magLines[0]);\n appendObject(sources);\n}\n\nint PFSS_visualization::loadAnimation(const char *path)\n{\n uint i, j;\n numFrames \t= 1;\n lowerSS \t= 0;\n upperSS \t= 0;\n lowerOrder \t= 0;\n upperOrder \t= 0;\n\n char cfgFilename[1000];\n char inputFilename[1000];\n cfgFilename[0] = '\\0';\n sprintf(cfgFilename, \"%s%s\", path, \"config.cfg\");\n std::ifstream config(cfgFilename);\n\n char option[1000], argument[1000];\n option[0] = '\\0';\n argument[0] = '\\0';\n\n while(config >> option >> argument)\n {\n if (!strcmp(option, \"numFrames\"))\n numFrames = atof(argument);\n if (!strcmp(option, \"lowerSS\"))\n lowerSS = atof(argument);\n if (!strcmp(option, \"upperSS\"))\n upperSS = atof(argument);\n if (!strcmp(option, \"fps\"))\n fps = atof(argument);\n if (!strcmp(option, \"lowerOrder\"))\n lowerOrder = (uint)atoi(argument);\n if (!strcmp(option, \"upperOrder\"))\n upperOrder = (uint)atoi(argument);\n }\n\n clear();\n hcScene3D::init();\n //appendElement(sun);\n magLines = new hcDObject3D[numFrames];\n\n for(i=0;i relHeight)\n printf(\"ERROR: PFSS_visualization::loadAnimation(const char *path): Resolution of window too low for text rendering\\n(height = %E, required: %E)!\\n\", relHeight, reqRelHeight);\n if(reqRelWidth > relWidth)\n printf(\"ERROR: PFSS_visualization::loadAnimation(const char *path): Resolution of window too low for text rendering\\n(width = %e, required: %E)!\\n\", relWidth, reqRelWidth);\n\n ftHandler.printTextToImage(text, char2RGBA8(255, 255, 255, 255), 0, 0, pixelWidth, pixelHeight, textlayer);\n overlay[textScreenID].texContainer.addTexture2D(textlayer, false);\n\n }//*/\n //free(textlayer);\n\n Vec2D contourPosProj(0.38, 0.5);\n contourProjScreenID = overlay.createAnimationScreen(contourPosProj, 1.2, 0.3, numFrames);\n for(i=0;i\n#include \n#include \n#include \n\nusing namespace boost::math::quadrature;\n\nvoid TodaActionVariablesGK(std::vector & action_variables, \n integrable::TodaDiscriminant const & discriminant, \n int max_depth=5,double relative_error=1e-5){\n\n int matrix_size = discriminant.matrix_size();\n std::vector roots(2*matrix_size);\n discriminant.total_roots(roots);\n\n auto func = [&discriminant](double x){ \n if(discriminant(x) > 2) return std::acosh(0.5*discriminant(x));\n else if(discriminant(x) < -2) return std::acosh(-0.5*discriminant(x));\n else return 0.0;\n };\n\n for(int i = 0; i < matrix_size - 1; ++i){\n double error;\n if(roots[2*i+1] - roots[2*i+2] == 0)\n action_variables[i] = 0.0;\n else\n action_variables[i] = 2.0 / M_PI \n * gauss_kronrod::integrate(\n func, \n roots[2*i+1], \n roots[2*i+2], \n max_depth, \n relative_error, \n &error\n );\n }\n}\n\n#endif\n", "meta": {"hexsha": "4b47f27b8a6566585d5b8108fb1665a778a5d5a8", "size": 1594, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "clstatphys/clstatphys/physics/toda_action_variables_gk.hpp", "max_stars_repo_name": "FIshikawa/ClassicalStatPhys", "max_stars_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clstatphys/clstatphys/physics/toda_action_variables_gk.hpp", "max_issues_repo_name": "FIshikawa/ClassicalStatPhys", "max_issues_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T08:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T09:29:10.000Z", "max_forks_repo_path": "clstatphys/clstatphys/physics/toda_action_variables_gk.hpp", "max_forks_repo_name": "FIshikawa/ClassicalStatPhys", "max_forks_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-18T03:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-21T22:58:27.000Z", "avg_line_length": 37.0697674419, "max_line_length": 79, "alphanum_fraction": 0.4755332497, "num_tokens": 351, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802440252811, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6686310625350081}} {"text": "/*\nsource file to apply LinearModels header file\n*/\n\n#include \n#include \n#include \n#include \"LinearModels.hpp\"\nusing namespace std;\nusing namespace arma;\n\n// 1. Linear Regression\n//\tconstructors and destructors\nLinearRegression::LinearRegression() : fit_intercept(true) {};\nLinearRegression::LinearRegression(const LinearRegression& source) : fit_intercept(source.fit_intercept), theta(source.theta) {};\nLinearRegression::LinearRegression(bool fit_intercept1) : fit_intercept(fit_intercept1) {};\nLinearRegression::~LinearRegression() {};\n\n//\tassignment operation\nLinearRegression& LinearRegression::operator=(const LinearRegression& source) {\n\tif (this == &source) {\n\t\tcout << \"self-assignment checked\";\n\t}\n\telse {\n\t\tfit_intercept = source.fit_intercept;\n\t\ttheta = source.theta;\n\t}\n\treturn *this;\n}\n\n//\tfunctions\n// fit function to calculate the results and store to theta\nconst void LinearRegression::fit(mat X, const mat& y) {\n\t//\tadd an addtional column if fit intercept\n\tif (fit_intercept == true) X = join_rows(ones(X.n_rows), X);\n\t//\tipseduo inverse part of the equation\n\tmat ipseudo_inverse = (X.t() * X).i() * X.t();\n\n\ttheta = ipseudo_inverse * y;\t\t//\tsave results\n\treturn;\n}\n\n// return predicted values with trained model\nconst mat LinearRegression::predict(mat _X) {\n\t//\t_X is a test matrix with shape of (M, Z), pred_y will be the product of _X and theta\n\tif (fit_intercept == true) _X = join_rows(ones(_X.n_rows), _X);\n\t\n\tmat y_pred = _X * theta;\n\treturn y_pred;\n}\n\n\n//\t2. Ridge Regression\nRidgeRegression::RidgeRegression() : fit_intercept(true), lambda(1.0) {};\nRidgeRegression::RidgeRegression(const RidgeRegression& source) : fit_intercept(source.fit_intercept), theta(source.theta), lambda(source.lambda) {};\nRidgeRegression::RidgeRegression(double lambda1, bool fit_intercept1) : fit_intercept(fit_intercept1), lambda(lambda1) {};\nRidgeRegression::~RidgeRegression() {};\n\n//\tassignment operation\nRidgeRegression& RidgeRegression::operator=(const RidgeRegression& source) {\n\tif (this == &source) {\n\t\tcout << \"self-assignment checked\";\n\t}\n\telse {\n\t\tfit_intercept = source.fit_intercept;\n\t\tlambda = source.lambda;\n\t\ttheta = source.theta;\n\t}\n\treturn *this;\n}\n\n\n//\tfunctions\n// fit function to calculate the results and store to theta\nconst void RidgeRegression::fit(mat X, const mat& y) {\n\t//\tadd an addtional column if fit intercept\n\tif (fit_intercept == true) X = join_rows(ones(X.n_rows), X);\n\n\t//\tmatrix for alpha\n\n\tmat A = lambda * eye(X.n_cols, X.n_cols);\n\t//\tipseduo inverse part of the equation\n\tmat ipseudo_inverse = (X.t() * X + A).i() * X.t();\n\n\ttheta = ipseudo_inverse * y;\t\t//\tsave results\n\treturn;\n}\n\n// return predicted values with trained model\nconst mat RidgeRegression::predict(mat _X) {\n\t//\t_X is a test matrix with shape of (M, Z), pred_y will be the product of _X and theta\n\tif (fit_intercept == true) _X = join_rows(ones(_X.n_rows), _X);\n\tmat y_pred = _X * theta;\n\n\treturn y_pred;\n}\n\n\n// 3. Logistic Regression\n//\tconstructors and destructors\nLogisticRegression::LogisticRegression() : fit_intercept(true), lambda(0.0), penalty(\"l2\") {};\nLogisticRegression::LogisticRegression(const LogisticRegression& source) : fit_intercept(source.fit_intercept), theta(source.theta), lambda(source.lambda), penalty(source.penalty) {};\nLogisticRegression::LogisticRegression(double lambda1, bool fit_intercept1, string penalty1) : fit_intercept(fit_intercept1), penalty(penalty1), lambda(lambda1) {};\nLogisticRegression::~LogisticRegression() {};\n\n//\tassignment operation\nLogisticRegression& LogisticRegression::operator=(const LogisticRegression& source) {\n\tif (this == &source) {\n\t\tcout << \"self-assignment checked\";\n\t}\n\telse {\n\t\tfit_intercept = source.fit_intercept;\n\t\tlambda = source.lambda;\n\t\tpenalty = source.penalty;\n\t\ttheta = source.theta;\n\t}\n\treturn *this;\n}\n\n\n//\tfunctions\n// fit function to calculate the results and store to theta\nconst void LogisticRegression::fit(mat _X, const mat& y, double lr, double tol, long max_iter) {\n\t//\twhether to fit an intercept\n\tif (fit_intercept == true) _X = join_rows(ones(_X.n_rows), _X);\n\t//\tprevious loss value to store loss\n\tdouble loss, l_prev = 999999.0;\n\ttheta = vec(_X.n_cols, fill::randn);\n\n\t//\tset loss and y_pred\n\t//double loss;\n\tmat y_pred;\n\n\tfor (long i = 0; i < max_iter; i++) {\n\t\ty_pred = sigmoid(_X * theta);\n\t\tloss = _NLL(_X, y, y_pred);\n\t\t//\tstop if change is less than tol\n\t\tif (l_prev - loss < tol) return;\n\t\tl_prev = loss;\n\t\ttheta = theta - lr * _NLL_grad(_X, y, y_pred);\n\t}\n}\n\n// supplemental function to calculate negative log likelihood under current model\ndouble LogisticRegression::_NLL(const mat& X, const mat& y, const mat& y_pred) {\n\t//\tfor X with M rows (number of examples), and N cols (number of features)\n\tauto M = X.n_rows, N = X.n_cols;\n\tint order; // type of penalty depending on value of penalty\n\tif (penalty == \"l2\") order = 2;\n\telse order = 1;\n\n\tdouble norm_theta = arma::norm(theta, order);\n\n\tdouble nll, penalty_val;\n\tnll = sum(-arma::log(y_pred.elem(find(y == 1)))) - sum(log(1 - y_pred.elem(find(y == 0))));\n\n\tif (order == 2) penalty_val = (lambda / 2) * pow(norm_theta, 2);\n\telse penalty_val = lambda * norm_theta;\n\n\treturn (nll + penalty_val) / double(M);\n}\n\n\n// supplemental function to calculate Gradient of the penalized negative log likelihood wrt theta\nvec LogisticRegression::_NLL_grad(const mat& X, const mat& y, const mat& y_pred) {\n\t//\tfor X with N rows (number of examples), and M cols (number of features)\n\tauto M = X.n_rows, N = X.n_cols;\n\n\t// calculate delta penalty\n\tvec d_penalty;\n\tif (penalty == \"l2\") d_penalty = lambda * theta;\n\telse d_penalty = lambda * sign(theta);\n\n\treturn (((y - y_pred).t() * X).t() + d_penalty) / -double(M);\n}\n\n// return predicted values with trained model\nconst mat LogisticRegression::predict(mat _X) {\n\t//\t_X is a test matrix with shape of (M, Z), pred_y will be the product of _X and theta\n\tif (fit_intercept == true) _X = join_rows(ones(_X.n_rows), _X);\n\tmat y_pred = _X * theta;\n\n\treturn round(sigmoid(y_pred));\n}\n\n// supplemental functions\n\n//The logistic sigmoid function\nmat sigmoid(const mat& X) {\n\treturn 1 / (1 + exp(-X));\n};", "meta": {"hexsha": "7d6878e08ccd6d269c329159859ccffcc21c5f45", "size": 6123, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Machine Learning Algos/Machine Learning Algos/LinearModels/LinearModels.cpp", "max_stars_repo_name": "watermantle/ML_CPP", "max_stars_repo_head_hexsha": "76f82dad1eaea74098ad9f2b758bd0cd7a5e67d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Machine Learning Algos/Machine Learning Algos/LinearModels/LinearModels.cpp", "max_issues_repo_name": "watermantle/ML_CPP", "max_issues_repo_head_hexsha": "76f82dad1eaea74098ad9f2b758bd0cd7a5e67d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Machine Learning Algos/Machine Learning Algos/LinearModels/LinearModels.cpp", "max_forks_repo_name": "watermantle/ML_CPP", "max_forks_repo_head_hexsha": "76f82dad1eaea74098ad9f2b758bd0cd7a5e67d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.057591623, "max_line_length": 183, "alphanum_fraction": 0.7146823453, "num_tokens": 1654, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942171172603, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6685952157110956}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// declares a column-major sparse matrix type of double\ntypedef Eigen::SparseMatrix SparseMatrix;\ntypedef Eigen::Triplet Triplet;\n\ntypedef Eigen::Matrix RowMajorMatrixXf;\n\nconst float GRID_DX = 0.1;\nconst float GRID_DY = 1;\nconst float MIN_X = 0;\nconst float MAX_X = 359.9999;\nconst float MIN_Y = 30;\nconst float MAX_Y = 150;\n\ntemplate \nT clamp(const T& v, const T& min_v, const T& max_v)\n{\n return v < min_v ? min_v : (v > max_v ? max_v : v);\n}\n\nvoid saveAsBitmap(const Eigen::VectorXf& x, size_t rows, size_t cols, const char* fname)\n{\n std::ofstream ofs(fname);\n ofs << \"P2\\n\" << cols << \" \" << rows << \"\\n255\\n\";\n for(size_t rr = 0; rr < rows; rr++) {\n for(size_t cc = 0; cc < cols; cc++) {\n ofs << clamp((int)x[rr * cols + cc], 0, 255) << \" \";\n }\n ofs << \"\\n\";\n }\n}\n\ninline\nint wrap(int v, int min_v, int max_v)\n{\n int width = max_v - min_v + 1;\n while(v < min_v) v += width;\n while(v > max_v) v -= width;\n return v;\n}\n\ninline\nfloat sqr(float x)\n{\n return x*x;\n}\n\ninline\nfloat cube(float x)\n{\n return x*x*x;\n}\n\ninline\nfloat bspline(float x)\n{\n if(x < -2) {\n return 0;\n } else if(x < -1) {\n return (cube(x+2)/6.0);\n } else if(x < 0) {\n return (-3*cube(x+2-1)+3*sqr(x+2-1)+3*(x+2-1)+1)/6;\n } else if(x < 1) {\n return ((3*cube(x+2-2) - 6*sqr(x+2-2) + 4)/6);\n } else if(x < 2) {\n return cube(1 - (x + 2 - 3))/6.0;\n } else {\n return 0;\n }\n}\n\n\nfloat kernel(float x, float width=4)\n{\n // bspline width is 4\n width /= 4;\n return bspline(x / width ) / width;\n}\n\ninline\nsize_t grid_index(size_t width, size_t height, size_t grid_x, size_t grid_y)\n{\n return grid_y * width + grid_x;\n}\n\n\nstruct BSpline\n{\n float grid_dx = GRID_DX;\n float grid_dy = GRID_DY;\n float grid_min_x = MIN_Y;\n float grid_max_x = MAX_X;\n float grid_min_y = MIN_Y;\n float grid_max_y = MAX_Y;\n\n size_t x_knots = (grid_max_x - grid_min_x) / grid_dx;\n size_t y_knots = (grid_max_y - grid_min_y) / grid_dy;\n size_t n_knots = x_knots * y_knots;\n\n SparseMatrix getWeights(const Eigen::MatrixXf& points) const\n {\n assert(points.cols() >= 2);\n std::vector coeffs;\n coeffs.reserve(points.size()*5);\n\n for(size_t pp = 0; pp < points.rows(); pp++) {\n const auto& pt = points.row(pp);\n float c_xbin = x_knots * (pt.x() - grid_min_x)/(grid_max_x - grid_min_x);\n float c_ybin = y_knots * (pt.y() - grid_min_y)/(grid_max_y - grid_min_y);\n\n // add weights to adjacent knots\n for(int ii = -2; ii <= 2; ii++) {\n for(int jj = -2; jj <= 2; jj++) {\n int raw_xbin = (int)c_xbin + ii;\n int wrapped_xbin = wrap(raw_xbin, 0, x_knots - 1);\n\n int ybin = (int)c_ybin + jj;\n if(ybin < 0 || ybin >= y_knots)\n continue;\n\n float w = kernel(c_xbin - raw_xbin)*kernel(c_ybin - ybin);\n size_t grid_ind = grid_index(x_knots, y_knots, wrapped_xbin, ybin);\n coeffs.push_back(Triplet(pp, grid_ind, w));\n }\n }\n }\n\n size_t num_points = points.rows();\n SparseMatrix Bmat(num_points, n_knots);\n Bmat.setFromTriplets(coeffs.begin(), coeffs.end());\n return Bmat;\n }\n\n};\n\nEigen::VectorXf solve(const BSpline& spl, const Eigen::MatrixXf& points)\n{\n std::cerr << \"Filling Weights\" << std::endl;\n auto Bmat = spl.getWeights(points);\n Bmat.makeCompressed();\n std::cerr << \"Done\" << std::endl;\n\n //Eigen::SparseQR> qr;\n std::cerr << \"QR\" << std::endl;\n Eigen::SparseQR> qr(Bmat);\n std::cerr << \"Done\" << std::endl;\n //Eigen::SPQR qr;\n //qr.compute(Bmat);\n //Eigen::SparseLU qr(Bmat);\n std::cerr << \"Solving: \"<< std::endl;\n Eigen::VectorXf sol = qr.solve(points.col(2));\n std::cerr << \"Done\" << std::endl;\n return sol;\n};\n\nEigen::VectorXf interpolate(const BSpline& spl,\n const Eigen::VectorXf& knot_values, const Eigen::MatrixXf& points)\n{\n auto bmat = spl.getWeights(points);\n return bmat * knot_values;\n}\n\nvoid drawPoints(const BSpline& spl, const Eigen::MatrixXf& points, const char* fname)\n{\n size_t x_bins = spl.x_knots;\n size_t y_bins = spl.y_knots;\n Eigen::VectorXf raster(x_bins * y_bins);\n raster.fill(0);\n for(size_t rr = 0; rr < points.rows(); rr++) {\n float x = points(rr, 0);\n float y = points(rr, 1);\n float c_xbin = x_bins * (x - spl.grid_min_x) / (spl.grid_max_x - spl.grid_min_x);\n float c_ybin = y_bins * (y - spl.grid_min_y) / (spl.grid_max_y - spl.grid_min_y);\n raster[(int)c_xbin + (int)c_ybin * x_bins] = 255;\n }\n saveAsBitmap(raster, y_bins, x_bins, fname);\n}\n\nint main(int argc, char** argv)\n{\n size_t num_points = 30;\n Eigen::MatrixXf points = Eigen::MatrixXf::Random(num_points, 3); // x, y, value\n for(size_t rr = 0; rr < points.rows(); rr++) {\n points(rr, 0) = MIN_X + std::abs(points(rr, 0)) * (MAX_X - MIN_X);\n points(rr, 1) = MIN_Y + std::abs(points(rr, 1)) * (MAX_Y - MIN_Y);\n points(rr, 2) = 1;\n }\n\n BSpline spl;\n drawPoints(spl, points, \"orig.pgm\");\n\n // Matrix maps from knots to known points\n // v = Bx\n //\n // x is the value of the knots, B is the weights of values at each knot s.t.\n // the values reflect the positions of the input points and v is the value\n // at the input points\n Eigen::VectorXf knots = solve(spl, points);\n\n // Use the known knots to solve for the actual values at each knot location\n Eigen::MatrixXf grid_points(spl.x_knots*spl.y_knots, 2);\n for(size_t yy = 0; yy < spl.y_knots; yy++) {\n for(size_t xx = 0; xx < spl.x_knots; xx++) {\n grid_points(yy * spl.x_knots + xx, 0) = spl.grid_min_x + xx * spl.grid_dx;\n grid_points(yy * spl.x_knots + xx, 1) = spl.grid_min_y + yy * spl.grid_dy;\n }\n }\n\n Eigen::VectorXf interpolated = interpolate(spl, knots, grid_points);\n //Eigen::VectorXf interpolated = interpolate(spl, knots, points);\n\n saveAsBitmap(255*interpolated, spl.y_knots, spl.x_knots, \"smoothed.pgm\");\n return 0;\n}\n", "meta": {"hexsha": "2d64cc737f02d7478a6217ee3d71166f87225630", "size": 6620, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bspline_fit.cpp", "max_stars_repo_name": "micahcc/ctest", "max_stars_repo_head_hexsha": "af2a789a8c610f83a7e6ef55c371c64a41492e85", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bspline_fit.cpp", "max_issues_repo_name": "micahcc/ctest", "max_issues_repo_head_hexsha": "af2a789a8c610f83a7e6ef55c371c64a41492e85", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bspline_fit.cpp", "max_forks_repo_name": "micahcc/ctest", "max_forks_repo_head_hexsha": "af2a789a8c610f83a7e6ef55c371c64a41492e85", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.6860986547, "max_line_length": 95, "alphanum_fraction": 0.5904833837, "num_tokens": 2022, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6685952118572367}} {"text": "#include \n#include \n#include \n#include \n\nint main(int argc, char **argv)\n{\n\n {\n Eigen::Matrix3d m = Eigen::Matrix3d::Identity(); //生成单位矩阵\n std::cout << \"m^T:\" << std::endl\n << m.transpose() << std::endl; // transpose() 转置后输出\n\n Eigen::Vector3d v1(3, 0, 0);\n Eigen::Vector3d v2(0, 4, 0);\n Eigen::Vector3d v3(0, 0, 5);\n std::cout << \"v1^T:\" << std::endl\n << v1 << std::endl\n << \"v2^T:\" << std::endl\n << v2.transpose() << std::endl\n << \"v3^T:\" << std::endl\n << v3.transpose() << std::endl;\n\n // m.block<1, 3>(0, 0)\n // 分块每块大小<1行,3列>\n // 取出(第0行,第0列)个块\n m.block<1, 3>(0, 0) = v1.transpose();\n m.block<1, 3>(1, 0) = v2.transpose();\n m.block<1, 3>(2, 0) = v3.transpose();\n\n std::cout << \"m:\" << std::endl\n << m << std::endl;\n\n Eigen::Vector3d VecAll1;\n VecAll1.fill(1); //向量各个值全部填充为1\n std::cout << \"VecAll1^T:\" << std::endl\n << VecAll1.transpose() << std::endl;\n\n Eigen::Vector3d normal = m.inverse() * VecAll1;\n double NormalLen = normal.norm(); //向量的模\n normal = normal / NormalLen; //v1 v2 v3 构成平面的单位法向量\n double d_plane_o = 1 / NormalLen; //平面到原点的距离\n\n std::cout << \"normal^T:\" << std::endl\n << normal.transpose() << std::endl;\n std::cout << d_plane_o << std::endl;\n }\n return 0;\n}", "meta": {"hexsha": "2853914feb4a01a7cbfc2a25cd832b7aee344e81", "size": 1546, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Examples/eigen/useeigen.cc", "max_stars_repo_name": "2hanhan/LearnCpp", "max_stars_repo_head_hexsha": "99c7b92a2098ae3aedd5bcc5a2c26bfdd894b25b", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2022-03-16T08:51:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T08:51:21.000Z", "max_issues_repo_path": "Examples/eigen/useeigen.cc", "max_issues_repo_name": "2hanhan/LearnCpp", "max_issues_repo_head_hexsha": "99c7b92a2098ae3aedd5bcc5a2c26bfdd894b25b", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/eigen/useeigen.cc", "max_forks_repo_name": "2hanhan/LearnCpp", "max_forks_repo_head_hexsha": "99c7b92a2098ae3aedd5bcc5a2c26bfdd894b25b", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5510204082, "max_line_length": 69, "alphanum_fraction": 0.4676584735, "num_tokens": 534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9263037343628702, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.668553416156272}} {"text": "//!\n//! Contains the interface for the Gaussian distribution.\n//!\n//! \\file distrib/gaussian.hpp\n//! \\author Lachlan McCalman\n//! \\date February 2014\n//! \\license Affero General Public License version 3 or later\n//! \\copyright (c) 2014, NICTA\n//!\n\n#pragma once\n\n#include \n#include \n\nnamespace obsidian\n{\n namespace distrib\n {\n //! Compute the log Gaussian distribution PDF with a diagonal covariance matrix.\n //!\n //! \\param x The vector to evaluate the distribution at.\n //! \\param mu The mean vector containing the means of each dimension.\n //! \\param sigma The diagonal of the covariance matrix.\n //!\n double logGaussian(const Eigen::VectorXd& x, const Eigen::VectorXd& mu, const Eigen::VectorXd& sigma)\n {\n double coeff = -std::log(std::pow(2.0 * M_PI, x.size() * 0.5) * sigma.prod());\n return coeff - 0.5 * (x - mu).cwiseQuotient(sigma).squaredNorm();\n }\n }\n}\n", "meta": {"hexsha": "05790b954c57e558d31b60ba0dd4ee64d4729311", "size": 925, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/distrib/gaussian.hpp", "max_stars_repo_name": "divad-nhok/obsidian_fork", "max_stars_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2015-01-04T13:50:24.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-22T01:03:57.000Z", "max_issues_repo_path": "src/distrib/gaussian.hpp", "max_issues_repo_name": "divad-nhok/obsidian_fork", "max_issues_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-16T00:46:58.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-16T00:46:58.000Z", "max_forks_repo_path": "src/distrib/gaussian.hpp", "max_forks_repo_name": "divad-nhok/obsidian_fork", "max_forks_repo_head_hexsha": "e5bee2b706f78249564f06c88a18be086b17c895", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-08-31T05:42:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-21T21:37:47.000Z", "avg_line_length": 28.0303030303, "max_line_length": 105, "alphanum_fraction": 0.6648648649, "num_tokens": 238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473879530492, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6684742626069811}} {"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2007 François du Vignaud\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license. You should have received a\n copy of the license along with this program; if not, please email\n . The license is also available online at\n .\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n\n#ifndef quantlib_tap_correlations_hpp\n#define quantlib_tap_correlations_hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace QuantLib {\n\n //! Returns the Triangular Angles Parametrized correlation matrix\n /*! The matrix \\f$ m \\f$ is filled with values corresponding to angles\n given in the \\f$ angles \\f$ vector. See equation (24) in\n \"Parameterizing correlations: a geometric interpretation\"\n by Francesco Rapisarda, Damiano Brigo, Fabio Mercurio\n\n \\test\n - the correctness of the results is tested by reproducing\n known good data.\n - the correctness of the results is tested by checking\n returned values against numerical calculations.\n */\n Disposable\n triangularAnglesParametrization(const Array& angles,\n Size matrixSize,\n Size rank);\n\n Disposable\n lmmTriangularAnglesParametrization(const Array& angles,\n Size matrixSize,\n Size rank);\n\n // the same function using the angles parameterized by the following\n // transformation \\f[ \\teta_i = \\frac{\\Pi}{2} - arctan(x_i)\\f]\n Disposable\n triangularAnglesParametrizationUnconstrained(const Array& x,\n Size matrixSize,\n Size rank);\n\n Disposable\n lmmTriangularAnglesParametrizationUnconstrained(const Array& x,\n Size matrixSize,\n Size rank);\n\n\n //! Returns the rank reduced Triangular Angles Parametrized correlation matrix\n /*! The matrix \\f$ m \\f$ is filled with values corresponding to angles\n corresponding to the 3D spherical spiral paramterized by\n \\f$ alpha \\f$, \\f$ t0 \\f$, \\f$ epsilon \\f$ values. See equation (32) in\n \"Parameterizing correlations: a geometric interpretation\"\n by Francesco Rapisarda, Damiano Brigo, Fabio Mercurio\n\n \\test\n - the correctness of the results is tested by reproducing\n known good data.\n - the correctness of the results is tested by checking\n returned values against numerical calculations.\n */\n Disposable\n triangularAnglesParametrizationRankThree(Real alpha,\n Real t0,\n Real epsilon,\n Size nbRows);\n\n // the same function with parameters packed in an Array\n Disposable\n triangularAnglesParametrizationRankThreeVectorial(const Array& paramters,\n Size nbRows);\n\n // Cost function associated with Frobenius norm.\n // \n class FrobeniusCostFunction : public CostFunction{\n public:\n FrobeniusCostFunction(\n const Matrix& target,\n const boost::function(const Array&,\n Size,\n Size)>& f,\n Size matrixSize,\n Size rank)\n : target_(target), f_(f), matrixSize_(matrixSize), rank_(rank) {}\n Real value (const Array &x) const;\n Disposable values (const Array &x) const;\n private:\n Matrix target_;\n boost::function(const Array&, Size, Size)> f_;\n Size matrixSize_;\n Size rank_;\n };\n}\n\n/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2007 François du Vignaud\n\n This file is part of QuantLib, a free-software/open-source library\n for financial quantitative analysts and developers - http://quantlib.org/\n\n QuantLib is free software: you can redistribute it and/or modify it\n under the terms of the QuantLib license. You should have received a\n copy of the license along with this program; if not, please email\n . The license is also available online at\n .\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 \n\nnamespace QuantLib {\n\n inline Disposable triangularAnglesParametrization(const Array& angles,\n Size matrixSize,\n Size rank) {\n\n // what if rank == 1?\n QL_REQUIRE((rank-1) * (2*matrixSize - rank) == 2*angles.size(),\n \"rank-1) * (matrixSize - rank/2) == angles.size()\");\n Matrix m(matrixSize, matrixSize);\n\n // first row filling\n m[0][0] = 1.0;\n for (Size j=1; j lmmTriangularAnglesParametrization(const Array& angles,\n Size matrixSize,\n Size) {\n Matrix m(matrixSize, matrixSize);\n for (Size i=0; i0) {\n cosPhi = std::cos(angles[i-1]);\n sinPhi = std::sin(angles[i-1]);\n } else {\n cosPhi = 1.0;\n sinPhi = 0.0;\n }\n\n for (Size j=0; j triangularAnglesParametrizationUnconstrained(\n const Array& x,\n Size matrixSize,\n Size rank) {\n Array angles(x.size());\n //we convert the unconstrained parameters in angles\n for (Size i = 0; i < x.size(); ++i)\n angles[i] = M_PI*.5 - std::atan(x[i]);\n return triangularAnglesParametrization(angles, matrixSize, rank);\n }\n\n inline Disposable lmmTriangularAnglesParametrizationUnconstrained(\n const Array& x,\n Size matrixSize,\n Size rank) {\n Array angles(x.size());\n //we convert the unconstrained parameters in angles\n for (Size i = 0; i < x.size(); ++i)\n angles[i] = M_PI*.5 - std::atan(x[i]);\n return lmmTriangularAnglesParametrization(angles, matrixSize, rank);\n }\n\n inline Disposable triangularAnglesParametrizationRankThree(\n Real alpha, Real t0,\n Real epsilon, Size matrixSize) {\n Matrix m(matrixSize, 3);\n for (Size i=0; i triangularAnglesParametrizationRankThreeVectorial(\n const Array& parameters,\n Size nbRows) {\n QL_REQUIRE(parameters.size() == 3,\n \"the parameter array must contain exactly 3 values\" );\n return triangularAnglesParametrizationRankThree(parameters[0],\n parameters[1],\n parameters[2],\n nbRows);\n\n }\n\n inline Real FrobeniusCostFunction::value(const Array& x) const {\n Array temp = values(x);\n return DotProduct(temp, temp);\n }\n\n inline Disposable FrobeniusCostFunction::values(const Array& x) const {\n Array result((target_.rows()*(target_.columns()-1))/2);\n Matrix pseudoRoot = f_(x, matrixSize_, rank_);\n Matrix differences = pseudoRoot * transpose(pseudoRoot) - target_;\n Size k = 0;\n // then we store the elementwise differences in a vector.\n for (Size i=0; i\n#include \n#include \n#include \n#include \"bvp.hpp\"\n\nusing namespace std;\nusing namespace arma;\n\n// utility routine to map from physical/component space to linear algebra index space\n// interval: physical interval index [1 <= interval <= N]\n// location: location in interval [0=left, 1=midpoint, 2=right]\n// component: solution component at this location [0=u, 1=u']\nint idx(int interval, int location, int component) {\n return ( 4*(interval-1) + 2*location + component );\n}\n\n\n// main routine\nint main(int argc, char **argv) {\n\n // get lambda from the command line, otherwise set to -10\n double lambda;\n if (argc > 1)\n lambda = atof(argv[1]);\n if (lambda >= 0.0)\n lambda = -10.0;\n\n // define BVP object\n BVP bvp(lambda);\n\n // test 'idx' function by outputting mapping for small N\n cout << \"Test output from 'idx' function for N = 5, M = 22:\";\n for (int interval=1; interval<=5; interval++) {\n cout << \"\\n interval \" << interval << \", (loc,comp,idx):\";\n for (int location=0; location<=2; location++) {\n for (int component=0; component<=1; component++) {\n cout << \" (\" << location << \", \" << component << \", \"\n << idx(interval,location,component) << \")\";\n }\n }\n }\n\n // loop over spatial resolutions for tests\n vector N = {100, 1000, 10000};\n for (int i=0; i\n#include \n#include \"interp.h\"\n\n#define TOL 1e-2 // geometric tolerance on z (measure how far target point is w.r.t. interpolation plane)\n\nusing namespace std;\nusing namespace Eigen;\n\ndouble interp(double x0, double y0, double z0, double x1, double y1, double z1,\n double x2, double y2, double z2, double x3, double y3, double z3,\n double s0, double s1, double s2, double s3,\n double x, double y, double z) {\n\n //// Initialization\n Vector3d l, p, n; // unit vector\n Vector3d cg; // CG of planed formed by interpolation points\n Vector2d A, B, C, D, X; // (rotated) interpolation and interpolated points\n Vector2d E, F, G, H; // temporary vector\n double zd, avg; // distance between interpolated point and interpolation plane & plane diagonal\n double k2, k1, k0, Delta; // coefficients of k2*x^2 + k1*x + k0 and discriminant\n double u, v ;// inverse bilinear interpolation parameters\n double i0, i1, i ;// interpolated quantities\n\n //// Move change of coordinates out of file to improve CPU runtime\n //// Change of axes\n // Plane center\n cg(0) = 0.25*(x0 + x1 + x2 + x3);\n cg(1) = 0.25*(y0 + y1 + y2 + y3);\n cg(2) = 0.25*(z0 + z1 + z2 + z3);\n // Unit vectors\n l(0) = 0.5*(0.5*(x0+x3)-0.5*(x1+x2));\n l(1) = 0.5*(0.5*(y0+y3)-0.5*(y1+y2));\n l(2) = 0.5*(0.5*(z0+z3)-0.5*(z1+z2));\n n(0) = (y2-y0)*(z1-z3) - (z2-z0)*(y1-y3);\n n(1) = (z2-z0)*(x1-x3) - (x2-x0)*(z1-z3);\n n(2) = (x2-x0)*(y1-y3) - (y2-y0)*(x1-x3);\n p = n.cross(l);\n l = l / l.norm(); // normalize\n p = p / p.norm(); // normalize\n n = n / n.norm(); // normalize\n // Translation & Rotation\n A(0) = l(0)*(cg(0)-x0) + l(1)*(cg(1)-y0) + l(2)*(cg(2)-z0);\n A(1) = p(0)*(cg(0)-x0) + p(1)*(cg(1)-y0) + p(2)*(cg(2)-z0);\n B(0) = l(0)*(cg(0)-x1) + l(1)*(cg(1)-y1) + l(2)*(cg(2)-z1);\n B(1) = p(0)*(cg(0)-x1) + p(1)*(cg(1)-y1) + p(2)*(cg(2)-z1);\n C(0) = l(0)*(cg(0)-x2) + l(1)*(cg(1)-y2) + l(2)*(cg(2)-z2);\n C(1) = p(0)*(cg(0)-x2) + p(1)*(cg(1)-y2) + p(2)*(cg(2)-z2);\n D(0) = l(0)*(cg(0)-x3) + l(1)*(cg(1)-y3) + l(2)*(cg(2)-z3);\n D(1) = p(0)*(cg(0)-x3) + p(1)*(cg(1)-y3) + p(2)*(cg(2)-z3);\n X(0) = l(0)*(cg(0)-x) + l(1)*(cg(1)-y) + l(2)*(cg(2)-z);\n X(1) = p(0)*(cg(0)-x) + p(1)*(cg(1)-y) + p(2)*(cg(2)-z);\n // Error measure\n avg = sqrt((x2-x0)*(x2-x0) + (y2-y0)*(y2-y0) + (z2-z0)*(z2-z0));\n zd = n(0)*(x-cg(0)) + n(1)*(y-cg(1)) + n(2)*(z-cg(2));\n #ifdef VERBOSE\n if (abs(zd/avg) > TOL) {\n cout << endl << \"Interpolated point is far from interpolation plane; bilinear interpolation might be inaccurate!\" << endl;\n cout << \"Distance versus interpolation plane diagonal: \" << zd << \" / \" << avg << \" > \" << TOL << endl;\n cout << \"This might be caused by a coarse panelling of the body surface.\" << endl;\n }\n #endif\n\n //// Interpolation\n // Intermediate vectors\n E = B-A;\n F = D-A;\n G = (A-B) + (C-D);\n H = X-A;\n // Coefficients\n k2 = G(0)*F(1) - G(1)*F(0); //\n k1 = E(0)*F(1) - E(1)*F(0) + H(0)*G(1) - H(1)*G(0);\n k0 = H(0)*E(1) - H(1)*E(0);\n // Solve quadratic equation\n if (k2 == 0) {\n v = -k0/k1;\n }\n else {\n Delta = k1*k1 - 4*k2*k0;\n if (Delta < 0) {\n cout << endl << \"Discriminant of inverse bilinear interpolation is negative. Cannot interpolate!\" << endl;\n exit(EXIT_FAILURE);\n }\n else if (Delta == 0) {\n v = (-k1) / (2.0*k2);\n }\n else {\n Delta = sqrt(Delta);\n v = (-k1 - Delta) / (2.0*k2);\n }\n }\n u = (H(0) - F(0)*v) / (E(0) + G(0)*v);\n // Interpolation along l\n i0 = (1-u)*s0 + u*s1;\n i1 = (1-u)*s3 + u*s2;\n // Interpolation along p\n i = (1-v)*i0 + v*i1;\n return i;\n}", "meta": {"hexsha": "9cf8d2b50badeed80f445f7753d09aeacbfec91e", "size": 4909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/interp.cpp", "max_stars_repo_name": "acrovato/aero", "max_stars_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-16T15:24:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:36:09.000Z", "max_issues_repo_path": "src/interp.cpp", "max_issues_repo_name": "acrovato/aero", "max_issues_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/interp.cpp", "max_forks_repo_name": "acrovato/aero", "max_forks_repo_head_hexsha": "310e6840670f5a39ca015c61c9090f123da8cfd6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4732824427, "max_line_length": 130, "alphanum_fraction": 0.5483805256, "num_tokens": 1825, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6683577838223973}} {"text": "#pragma once\n\n#include \n\ntemplate \nconstexpr auto Stirling2nd()\n{\n if constexpr (K >= N || K <= 1)\n {\n return std::integral_constant {};\n }\n else\n {\n return std::integral_constant() + K * Stirling2nd()> {};\n }\n}\n\n// Set Partition\n//\n// A set partition of the set [n] = {1,2,3,...,n} is a collection B0,\n// B1, ... Bj of disjoint subsets of [n] whose union is [n]. Each Bj\n// is called a block. Below we show the partitions of [4]. The periods\n// separtate the individual sets so that, for example, 1.23.4 is the\n// partition {{1},{2,3},{4}}.\n// 1 block: 1234\n// 2 blocks: 123.4 124.3 134.2 1.234 12.34 13.24 14.23\n// 3 blocks: 1.2.34 1.24.3 14.2.3 13.2.4 12.3.4\n// 4 blocks: 1.2.3.4\n//\n// Each partition above has its blocks listed in increasing order of\n// smallest element; thus block 0 contains element 1, block1 contains\n// the smallest element not in block 0, and so on. A Restricted Growth\n// string (or RG string) is a sring a[1..n] where a[i] is the block in\n// whcih element i occurs. Restricted Growth strings are often called\n// restricted growth functions. Here are the RG strings corresponding\n// to the partitions shown above.\n//\n// 1 block: 0000\n// 2 blocks: 0001, 0010, 0100, 0111, 0011, 0101, 0110\n// 3 blocks: 0122, 0121, 0112, 0120, 0102,\n//\n// ...more\n//\n// Reference:\n// Frank Ruskey. Simple combinatorial Gray codes constructed by\n// reversing sublists. Lecture Notes in Computer Science, #762,\n// 201-208. Also downloadable from\n// http://webhome.cs.uvic.ca/~ruskey/Publications/SimpleGray/SimpleGray.html\n//\n#include \n#include \n#include \n#include \n#include \n#include \n\nclass set_partition_\n{\n using ret_t = std::tuple;\n using Fun = std::function;\n\n private:\n // int b[100 + 1]; /* maximum value of n */\n // int cnt{};\n Fun yield;\n\n public:\n /**\n * @brief Construct object\n *\n * @param[in] yield_\n */\n explicit set_partition_(Fun yield_)\n : yield(std::move(yield_))\n {\n }\n\n /**\n * @brief\n *\n * @param[in] n\n * @param[in] k\n */\n void run(int n, int k)\n {\n if (k % 2 == 0)\n {\n this->_GEN0_even(n, k);\n }\n else\n {\n this->_GEN0_odd(n, k);\n }\n }\n\n private:\n /**\n * @brief Move\n *\n * @param[in] x\n * @param[in] y\n */\n void _Move(int x, int y)\n {\n yield(std::tuple {x, y});\n }\n\n /**\n * @brief S(n,k,0) even k\n *\n * @param[in] n\n * @param[in] k\n */\n void _GEN0_even(int n, int k);\n\n /**\n * @brief S'(n,k,0) even k\n *\n * @param[in] n\n * @param[in] k\n */\n void _NEG0_even(int n, int k);\n\n /**\n * @brief S(n,k,1) even k\n *\n * @param[in] n\n * @param[in] k\n */\n void _GEN1_even(int n, int k);\n\n /**\n * @brief S'(n,k,1) even k\n *\n * @param[in] n\n * @param[in] k\n */\n void _NEG1_even(int n, int k);\n\n /**\n * @brief S(n,k,0) odd k\n *\n * @param[in] n\n * @param[in] k\n */\n void _GEN0_odd(int n, int k);\n\n /**\n * @brief S'(n,k,0) odd k\n *\n * @param[in] n\n * @param[in] k\n */\n void _NEG0_odd(int n, int k);\n\n /**\n * @brief S(n,k,1) odd k\n *\n * @param[in] n\n * @param[in] k\n */\n void _GEN1_odd(int n, int k);\n\n /**\n * @brief S'(n,k,1) odd k\n *\n * @param[in] n\n * @param[in] k\n */\n void _NEG1_odd(int n, int k);\n};\n\nusing ret_t = std::tuple;\nusing coro_t = boost::coroutines2::coroutine;\n\nextern coro_t::pull_type set_partition(int n, int k);\n", "meta": {"hexsha": "2bd34b927e9b4d0a2fb5c651bc7f2b5fc500bfba", "size": 3804, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/ckpttncpp/set_partition.hpp", "max_stars_repo_name": "luk036/ckpttncpp", "max_stars_repo_head_hexsha": "25898e331c5b114e5886b828fc68ec5512d409ee", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/include/ckpttncpp/set_partition.hpp", "max_issues_repo_name": "luk036/ckpttncpp", "max_issues_repo_head_hexsha": "25898e331c5b114e5886b828fc68ec5512d409ee", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-07-23T14:21:48.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-20T10:48:07.000Z", "max_forks_repo_path": "lib/include/ckpttncpp/set_partition.hpp", "max_forks_repo_name": "luk036/ckpttncpp", "max_forks_repo_head_hexsha": "25898e331c5b114e5886b828fc68ec5512d409ee", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-17T02:40:02.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-17T02:40:02.000Z", "avg_line_length": 21.3707865169, "max_line_length": 76, "alphanum_fraction": 0.5381177708, "num_tokens": 1260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961505, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.66821651787747}} {"text": "/*\n * stuart_landau.cpp\n *\n * This example demonstrates how one can use odeint can be used with state types consisting of complex variables.\n *\n * Copyright 2009-2012 Karsten Ahnert and Mario Mulansky.\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \n#include \n#include \n\n#include \n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n//[ stuart_landau_system_function\ntypedef complex< double > state_type;\n\nstruct stuart_landau\n{\n double m_eta;\n double m_alpha;\n\n stuart_landau( double eta = 1.0 , double alpha = 1.0 )\n : m_eta( eta ) , m_alpha( alpha ) { }\n\n void operator()( const state_type &x , state_type &dxdt , double t ) const\n {\n const complex< double > I( 0.0 , 1.0 );\n dxdt = ( 1.0 + m_eta * I ) * x - ( 1.0 + m_alpha * I ) * norm( x ) * x;\n }\n};\n//]\n\n\n/*\n//[ stuart_landau_system_function_alternative\ndouble eta = 1.0;\ndouble alpha = 1.0;\n\nvoid stuart_landau( const state_type &x , state_type &dxdt , double t )\n{\n const complex< double > I( 0.0 , 1.0 );\n dxdt[0] = ( 1.0 + m_eta * I ) * x[0] - ( 1.0 + m_alpha * I ) * norm( x[0] ) * x[0];\n}\n//]\n*/\n\n\nstruct streaming_observer\n{\n std::ostream& m_out;\n\n streaming_observer( std::ostream &out ) : m_out( out ) { }\n\n template< class State >\n void operator()( const State &x , double t ) const\n {\n m_out << t;\n m_out << \"\\t\" << x.real() << \"\\t\" << x.imag() ;\n m_out << \"\\n\";\n }\n};\n\n\n\n\nint main( int argc , char **argv )\n{\n //[ stuart_landau_integration\n state_type x = complex< double >( 1.0 , 0.0 );\n\n const double dt = 0.1;\n\n typedef runge_kutta4< state_type , double , state_type , double , \n vector_space_algebra > stepper_type;\n\n integrate_const( stepper_type() , stuart_landau( 2.0 , 1.0 ) , x , 0.0 , 10.0 , dt , streaming_observer( cout ) );\n //]\n\n return 0;\n}\n", "meta": {"hexsha": "10891b59686ca61c306cb93559e61a70ed161462", "size": 2048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/stuart_landau.cpp", "max_stars_repo_name": "473867143/Prometheus", "max_stars_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1217.0, "max_stars_repo_stars_event_min_datetime": "2020-07-02T13:15:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:17:44.000Z", "max_issues_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/stuart_landau.cpp", "max_issues_repo_name": "473867143/Prometheus", "max_issues_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 167.0, "max_issues_repo_issues_event_min_datetime": "2020-07-12T15:35:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T11:57:40.000Z", "max_forks_repo_path": "Modules/ego_planner/ego-planner-swarm/src/uav_simulator/so3_quadrotor_simulator/include/ode/libs/numeric/odeint/examples/stuart_landau.cpp", "max_forks_repo_name": "473867143/Prometheus", "max_forks_repo_head_hexsha": "df1e1b0d861490223ac8b94d8cc4796537172292", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 270.0, "max_forks_repo_forks_event_min_datetime": "2020-07-02T13:28:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:43:08.000Z", "avg_line_length": 23.2727272727, "max_line_length": 118, "alphanum_fraction": 0.611328125, "num_tokens": 622, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6682165150827575}} {"text": "#include \n#include \n#include \n\n\nPyObject* IFT_mat2tau(PyObject *f_mat_in, const int &Nmax, const double &beta, const double &asymp_coefs1, const double &asymp_coefs2)\n{\n PyArrayObject *f_mat = (PyArrayObject *) f_mat_in;\n import_array1(NULL);\n uint nfreq = f_mat->dimensions[0];\n npy_intp Nm = (npy_intp)Nmax;\n PyArrayObject *f_tau = (PyArrayObject *)PyArray_SimpleNew(1, &Nm, NPY_DOUBLE);\n Py_INCREF(f_tau);\n double *buf = (double *)PyArray_DATA(f_tau);\n std::complex *f_matsubara = (std::complex *)PyArray_DATA(f_mat);\n double C[2] = {asymp_coefs1, asymp_coefs2};\n\n for (int i = 0; i < Nmax; i++) {\n double tau=double(i)*beta/double(Nmax - 1);\n buf[i] = -C[0]/2. + C[1]/4.*(-beta+2*tau);\n for (uint k = 0; k < nfreq; ++k) {\n double wt((2*k+1)*double(i)*M_PI/double(Nmax - 1));\n std::complex iomegan(0,(2*k+1)*M_PI/beta);\n std::complex f_matsubara_nomodel = f_matsubara[k] - C[0]/iomegan - C[1]/(iomegan*iomegan);\n buf[i] += 2./beta*(cos(wt)*f_matsubara_nomodel.real() + sin(wt)*f_matsubara_nomodel.imag());\n }\n }\n return PyArray_Return(f_tau);\n}\n\nPyObject* FT_tau2mat(PyObject *f_tau_py_in, const double &beta, const int &Nmax)\n{\n PyArrayObject *f_tau_py = (PyArrayObject *) f_tau_py_in;\n import_array1(NULL);\n double *f_tau = (double *)PyArray_DATA(f_tau_py);\n int nfreq = f_tau_py->dimensions[0] - 1;\n PyArrayObject *f_mat;\n npy_intp Nm = (npy_intp)Nmax;\n f_mat = (PyArrayObject *)PyArray_SimpleNew(1, &Nm, NPY_CDOUBLE);\n Py_INCREF(f_mat);\n std::complex *f_matsubara = (std::complex *)PyArray_DATA(f_mat);\n \n // trapezoidal rule for integration\n for (int n = 0; n < Nmax; n++) {\n double wn = (2*n + 1)*M_PI/beta;\n f_matsubara[n] = 0;\n for (int p = 1; p < nfreq; p++) {\n double tau = beta/double(nfreq)*p;\n f_matsubara[n] += f_tau[p]*(cos(wn*tau) + std::complex(0,1)*sin(wn*tau));\n }\n f_matsubara[n] = beta/2./double(nfreq)*(f_tau[0] - f_tau[nfreq]) + beta/double(nfreq)*f_matsubara[n];\n } \n return PyArray_Return(f_mat);\n}\n\n", "meta": {"hexsha": "85d9801ef786a2476544d95c7dabe22337a3eeb9", "size": 2241, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppext/fourier.cpp", "max_stars_repo_name": "hungdt/scf_dmft", "max_stars_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2015-06-05T17:44:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-10T11:55:13.000Z", "max_issues_repo_path": "cppext/fourier.cpp", "max_issues_repo_name": "hungdt/scf_dmft", "max_issues_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppext/fourier.cpp", "max_forks_repo_name": "hungdt/scf_dmft", "max_forks_repo_head_hexsha": "845a2e144268350af0340927bba0044d538c34db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.0178571429, "max_line_length": 134, "alphanum_fraction": 0.6224899598, "num_tokens": 761, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190939, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.668216499468966}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"numeric_utils.h\"\n\nnamespace numeric_utils {\nEigen::MatrixXd corr_to_cov(const Eigen::MatrixXd& corr,\n const Eigen::VectorXd& std_dev) {\n Eigen::MatrixXd cov_matrix = Eigen::MatrixXd::Zero(corr.rows(), corr.cols());\n\n for (unsigned int i = 0; i < cov_matrix.rows(); ++i) {\n for (unsigned int j = 0; j < cov_matrix.cols(); ++j) {\n cov_matrix(i, j) = corr(i, j) * std_dev(i) * std_dev(j);\n }\n }\n\n return cov_matrix;\n}\n \nbool convolve_1d(const std::vector& input_x,\n const std::vector& input_y,\n std::vector& response) {\n bool status = true;\n response.resize(input_x.size() + input_y.size() - 1);\n\n // Create convolution status and task pointer\n int conv_status;\n VSLConvTaskPtr conv_task;\n // Construct convolution task, with solution mode set to direct\n conv_status =\n vsldConvNewTask1D(&conv_task, VSL_CONV_MODE_DIRECT, input_x.size(),\n input_y.size(), response.size());\n\n // Check if convolution construction was successful\n if (conv_status != VSL_STATUS_OK) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::convolve_1d: Error in convolution \"\n \"construction\\n\");\n status = false;\n }\n\n // Set convolution to start at first element in input_y\n vslConvSetStart(conv_task, 0);\n\n // Execute convolution\n conv_status = vsldConvExec1D(conv_task, input_x.data(), 1, input_y.data(), 1,\n response.data(), 1);\n\n // Check if convolution exectution was successful\n if (conv_status != VSL_STATUS_OK) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::convolve_1d: Error in convolution \"\n \"execution\\n\");\n status = false;\n }\n\n // Delete convolution task\n vslConvDeleteTask(&conv_task);\n\n return status;\n}\n\nbool inverse_fft(std::vector> input_vector,\n std::vector& output_vector) {\n output_vector.resize(input_vector.size());\n\n // Create task descriptor and MKL status\n DFTI_DESCRIPTOR_HANDLE fft_descriptor;\n MKL_LONG fft_status;\n\n // Allocate the descriptor data structure and initializes it with default\n // configuration values\n fft_status = DftiCreateDescriptor(&fft_descriptor, DFTI_DOUBLE, DFTI_REAL, 1,\n input_vector.size());\n if (fft_status != DFTI_NO_ERROR) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::inverse_fft: Error in descriptor creation\\n\");\n return false;\n }\n \n // Set configuration value to not do inplace transformation\n fft_status = DftiSetValue(fft_descriptor, DFTI_PLACEMENT, DFTI_NOT_INPLACE);\n if (fft_status != DFTI_NO_ERROR) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::inverse_fft: Error in setting configuration\\n\");\n return false;\n }\n\n // Set the backward scale factor to be 1 divided by the size of the input vector\n // to make the backward tranform the inverse of the forward transform\n fft_status = DftiSetValue(fft_descriptor, DFTI_BACKWARD_SCALE,\n static_cast(1.0 / input_vector.size()));\n if (fft_status != DFTI_NO_ERROR) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::inverse_fft: Error in setting backward \"\n \"scale factor\\n\");\n return false;\n } \n\n // Perform all initialization for the actual FFT computation\n fft_status = DftiCommitDescriptor(fft_descriptor);\n if (fft_status != DFTI_NO_ERROR) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::inverse_fft: Error in committing descriptor\\n\");\n return false;\n }\n \n // Compute the backward FFT\n fft_status = DftiComputeBackward(fft_descriptor, input_vector.data(),\n output_vector.data());\n if (fft_status != DFTI_NO_ERROR) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::inverse_fft: Error in computing backward FFT\\n\");\n return false;\n }\n \n // Free the memory allocated for descriptor\n fft_status = DftiFreeDescriptor(&fft_descriptor);\n if (fft_status != DFTI_NO_ERROR) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::inverse_fft: Error in freeing FFT descriptor\\n\");\n return false;\n } \n\n return true;\n}\n\nbool inverse_fft(const Eigen::VectorXcd& input_vector,\n Eigen::VectorXd& output_vector) {\n // Convert input Eigen vector to std vector\n std::vector> input_vals(input_vector.size());\n std::vector outputs(input_vals.size());\n Eigen::VectorXcd::Map(&input_vals[0], input_vector.size()) = input_vector;\n \n try {\n inverse_fft(input_vals, outputs);\n } catch (const std::exception& e) {\n std::cerr << \"\\nERROR: In numeric_utils::inverse_fft (With Eigen Vectors):\"\n << e.what() << std::endl;\n }\n\n // Convert output from std vector to Eigen vector\n output_vector = Eigen::Map(outputs.data(), outputs.size());\n\n return true;\n}\n\nbool inverse_fft(const Eigen::VectorXcd& input_vector,\n std::vector& output_vector) {\n // Convert input Eigen vector to std vector\n std::vector> input_vals(input_vector.size());\n Eigen::VectorXcd::Map(&input_vals[0], input_vector.size()) = input_vector;\n output_vector.resize(input_vector.size()); \n \n try {\n inverse_fft(input_vals, output_vector);\n } catch (const std::exception& e) {\n std::cerr << \"\\nERROR: In numeric_utils::inverse_fft (With Eigen Vectors):\"\n << e.what() << std::endl;\n }\n\n return true; \n}\n\nbool fft(std::vector input_vector,\n std::vector>& output_vector) {\n // Convert input vector to complex values\n std::vector> input_complex(input_vector.size());\n std::copy(input_vector.begin(), input_vector.end(), input_complex.begin());\n \n output_vector.resize(input_vector.size());\n\n // Create task descriptor and MKL status\n DFTI_DESCRIPTOR_HANDLE fft_descriptor;\n MKL_LONG fft_status;\n\n // Allocate the descriptor data structure and initializes it with default\n // configuration values\n fft_status = DftiCreateDescriptor(&fft_descriptor, DFTI_DOUBLE, DFTI_COMPLEX,\n 1, input_complex.size());\n if (fft_status != DFTI_NO_ERROR) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::fft: Error in descriptor creation\\n\");\n return false;\n }\n \n // Set configuration value to not do inplace transformation\n fft_status = DftiSetValue(fft_descriptor, DFTI_PLACEMENT, DFTI_NOT_INPLACE);\n if (fft_status != DFTI_NO_ERROR) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::fft: Error in setting configuration\\n\");\n return false;\n }\n\n // Perform all initialization for the actual FFT computation\n fft_status = DftiCommitDescriptor(fft_descriptor);\n if (fft_status != DFTI_NO_ERROR) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::fft: Error in committing descriptor\\n\");\n return false;\n }\n \n // Compute the backward FFT\n fft_status = DftiComputeForward(fft_descriptor, input_complex.data(),\n output_vector.data());\n if (fft_status != DFTI_NO_ERROR) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::fft: Error in computing FFT\\n\");\n return false;\n }\n \n // Free the memory allocated for descriptor\n fft_status = DftiFreeDescriptor(&fft_descriptor);\n if (fft_status != DFTI_NO_ERROR) {\n throw std::runtime_error(\n \"\\nERROR: in numeric_utils::fft: Error in freeing FFT descriptor\\n\");\n return false;\n } \n\n return true;\n}\n\nbool fft(const Eigen::VectorXd& input_vector, Eigen::VectorXcd& output_vector) {\n // Convert input Eigen vector to std vector\n std::vector input_vals(input_vector.size());\n std::vector> outputs(input_vals.size());\n Eigen::VectorXd::Map(&input_vals[0], input_vector.size()) = input_vector;\n \n try {\n fft(input_vals, outputs);\n } catch (const std::exception& e) {\n std::cerr << \"\\nERROR: In numeric_utils::fft (With Eigen Vectors):\"\n << e.what() << std::endl;\n }\n\n // Convert output from std vector to Eigen vector\n output_vector = Eigen::Map(outputs.data(), outputs.size());\n\n return true;\n}\n\nbool fft(const Eigen::VectorXd& input_vector,\n std::vector>& output_vector) {\n // Convert input Eigen vector to std vector\n std::vector input_vals(input_vector.size());\n Eigen::VectorXd::Map(&input_vals[0], input_vector.size()) = input_vector;\n output_vector.resize(input_vector.size()); \n \n try {\n fft(input_vals, output_vector);\n } catch (const std::exception& e) {\n std::cerr << \"\\nERROR: In numeric_utils::fft (With Eigen Vector and STL vector):\"\n << e.what() << std::endl;\n }\n\n return true; \n} \n \ndouble trapazoid_rule(const std::vector& input_vector, double spacing) {\n double result = (input_vector[0] + input_vector[input_vector.size() - 1]) / 2.0;\n\n for (unsigned int i = 1; i < input_vector.size() - 1; ++i) {\n result = result + input_vector[i];\n }\n\n return result * spacing;\n}\n\ndouble trapazoid_rule(const Eigen::VectorXd& input_vector, double spacing) {\n double result = (input_vector[0] + input_vector[input_vector.size() - 1]) / 2.0;\n\n for (unsigned int i = 1; i < input_vector.size() - 1; ++i) {\n result = result + input_vector[i];\n }\n\n return result * spacing;\n}\n\nEigen::VectorXd polyfit_intercept(const Eigen::VectorXd& points,\n const Eigen::VectorXd& data,\n\t\t\t\t double intercept,\n unsigned int degree) {\n\n Eigen::MatrixXd coefficients =\n Eigen::MatrixXd::Zero(points.size(), degree - 1);\n \n for (unsigned int i = 0; i < degree - 1; ++i) {\n coefficients.col(i) = points.array().pow(degree - i);\n }\n\n // Solve system\n Eigen::VectorXd solution = coefficients.fullPivHouseholderQr().solve(\n (data.array() - intercept).matrix());\n\n // Set y-intercept to zero\n Eigen::VectorXd poly_fit(solution.size() + 2);\n\n for (unsigned int i = 0; i < solution.size(); ++i) {\n poly_fit(i) = solution(i);\n } \n poly_fit(poly_fit.size() - 1) = intercept;\n poly_fit(poly_fit.size() - 2) = 0.0;\n\n return poly_fit;\n}\n\nEigen::VectorXd polynomial_derivative(const Eigen::VectorXd& coefficients) {\n Eigen::VectorXd derivative(coefficients.size() - 1);\n\n for (unsigned int i = 0; i < derivative.size(); ++i) {\n derivative(i) = coefficients(i) * (coefficients.size() - 1 - i);\n }\n\n return derivative;\n}\n\nstd::vector derivative(const std::vector& coefficients,\n double constant_factor, bool add_zero) {\n\n if (add_zero) {\n std::vector derivative(coefficients.size());\n derivative[0] = coefficients[0] * constant_factor;\n\n for (unsigned int i = 1; i < derivative.size(); ++i) {\n derivative[i] = (coefficients[i] - coefficients[i - 1]) * constant_factor;\n }\n\n return derivative;\n } else {\n std::vector derivative(coefficients.size() - 1);\n\n for (unsigned int i = 0; i < derivative.size(); ++i) {\n derivative[i] = (coefficients[i + 1] - coefficients[i]) * constant_factor;\n }\n\n return derivative;\n }\n}\n\nEigen::VectorXd evaluate_polynomial(const Eigen::VectorXd& coefficients,\n const Eigen::VectorXd& points) {\n Eigen::VectorXd evaluations = Eigen::VectorXd::Zero(points.size());\n\n for (unsigned int i = 0; i < evaluations.size(); ++i) {\n for (unsigned int j = 0; j < coefficients.size(); ++j) {\n evaluations(i) +=\n coefficients(j) * std::pow(points(i), coefficients.size() - 1 - j);\n }\n }\n\n return evaluations;\n}\n\nEigen::VectorXd evaluate_polynomial(const Eigen::VectorXd& coefficients,\n const std::vector& points) {\n Eigen::VectorXd evaluations = Eigen::VectorXd::Zero(points.size());\n\n for (unsigned int i = 0; i < evaluations.size(); ++i) {\n for (unsigned int j = 0; j < coefficients.size(); ++j) {\n evaluations(i) +=\n coefficients(j) * std::pow(points[i], coefficients.size() - 1 - j);\n }\n }\n\n return evaluations;\n}\n\nstd::vector evaluate_polynomial(const std::vector& coefficients,\n const std::vector& points) {\n std::vector evaluations(points.size(), 0.0);\n\n for (unsigned int i = 0; i < evaluations.size(); ++i) {\n for (unsigned int j = 0; j < coefficients.size(); ++j) {\n evaluations[i] +=\n coefficients[j] * std::pow(points[i], coefficients.size() - 1 - j);\n }\n }\n\n return evaluations;\n} \n} // namespace numeric_utils\n", "meta": {"hexsha": "9cd9e43418772d7be4f6c204e83bd039420fecd5", "size": 12876, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/numeric_utils.cc", "max_stars_repo_name": "fmckenna/smelt", "max_stars_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-05-07T03:14:27.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-19T07:10:52.000Z", "max_issues_repo_path": "src/numeric_utils.cc", "max_issues_repo_name": "fmckenna/smelt", "max_issues_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-04-11T19:29:24.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-11T19:29:47.000Z", "max_forks_repo_path": "src/numeric_utils.cc", "max_forks_repo_name": "fmckenna/smelt", "max_forks_repo_head_hexsha": "4e8a786fc415fc99bd79ada885e8312ed0eb36e0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-03-25T20:08:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-04T13:02:31.000Z", "avg_line_length": 33.3575129534, "max_line_length": 85, "alphanum_fraction": 0.6546287667, "num_tokens": 3138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381843, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6681975076411579}} {"text": "\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"BaseChange.h\"\n#include \"MultipointEval.h\"\n#include \"Util.h\"\n#include \"HasseLift.h\"\n#include \"HasseLiftExt.h\"\n#include \"MultiComposeMod.h\"\n#include \"FrobComp.h\"\n#include \"SSFactoring.h\"\n\n\n\nusing namespace std;\n\n//void testBaseChange(long degree) {\n// cout << \"degree: \" << degree << \"\\n\";\n//\n// ZZ_pX f, g, h;\n//\n// random(f, degree - 1);\n// random(h, degree - 1);\n// \n// // build a square-free modulus\n// random(g, degree);\n// SetCoeff(g, degree, 1);\n// diff(h, g);\n// GCD(h, g, h);\n// div(g, g, h);\n// ZZ_pXModulus modulus;\n// build(modulus, g);\n// \n// CompMod(g, h, f, modulus);\n// BaseChange baseChane;\n// baseChane.changeBasis(f, f, g, modulus);\n//\n// if (f == h)\n// cout << \"ok\\n\";\n// else\n// cout << \"oops\\n\";\n//\n// f.kill();\n// g.kill();\n// h.kill();\n// modulus.f.kill();\n//}\n//\n\nvoid testCompose() {\n long k = 1;\n long n = 2000;\n ZZ_pX f;\n random(f, n);\n SetCoeff(f, n, 1);\n ZZ_pXModulus F;\n build(F, f);\n\n Vec result;\n Vec result1;\n Vec gVec;\n result.SetLength(k);\n result1.SetLength(k);\n gVec.SetLength(k);\n\n for (long i = 0; i < k; i++)\n random(gVec[i], n);\n\n ZZ_pX h;\n random(h, n);\n\n MultiComposeMod multiComposeMod;\n\n Util util;\n long start = util.getTimeMillis();\n multiComposeMod.compose(result, gVec, h, F);\n cout << util.getTimeMillis() - start << endl;\n\n start = util.getTimeMillis();\n for (long i = 0; i < k; i++) {\n CompMod(result1[i], gVec[i], h, F);\n }\n cout << util.getTimeMillis() - start << endl;\n\n for (long i = 0; i < k; i++) {\n if (result[i] != result1[i]) {\n cout << \"Failed\" << endl;\n break;\n }\n }\n}\n//\n//\n//void testMultipointEval() {\n// long numPoints = 100;\n// \n// long degree = 20;\n// ZZ_pX f;\n// random(f, degree);\n// SetCoeff(f, degree, 1);\n// \n// ZZ_pE::init(f);\n// \n// Vec points;\n// Vec results;\n// points.SetLength(numPoints);\n// results.SetLength(numPoints);\n// \n// for (long i = 0; i < numPoints; i++)\n// random(points[i]);\n// \n// ZZ_pEX g;\n// random(g, numPoints);\n// SetCoeff(g, numPoints + 1, 1);\n// \n// Util util;\n// long start = util.getTimeMillis();\n// MultipointEval multiPointEval;\n// multiPointEval.eval(results, g, points);\n// cout << (util.getTimeMillis() - start) << endl;\n// \n// start = util.getTimeMillis();\n// ZZ_pE temp;\n// for (long i = 0; i < numPoints; i++) {\n// eval(temp, g, points[i]);\n// if (temp != results[i]) {\n// cout << \"not equal\" << endl;\n// break;\n// }\n// }\n// cout << (util.getTimeMillis() - start) << endl;\n//}\n//\n\nvoid testFrob() {\n ZZ_pX f;\n long d = 100;\n random(f, d);\n SetCoeff(f, d, 1);\n ZZ_pXModulus F;\n build(F, f);\n\n long m = 20;\n\n Vec frobs;\n frobs.SetLength(m);\n ZZ_pX xq;\n SetX(xq);\n PowerMod(xq, xq, ZZ_p::modulus(), F);\n\n FrobComp frobComp;\n frobComp.computeFrobePowers(frobs, m, xq, F);\n\n Vec frobs1;\n frobs1.SetLength(m);\n frobs1[0] = xq;\n for (long i = 1; i < m; i++) {\n PowerMod(frobs1[i], frobs1[i - 1], ZZ_p::modulus(), F);\n }\n\n if (frobs == frobs1)\n cout << \"OK\" << endl;\n else\n cout << \"Failed\" << endl;\n}\n\nvoid testHasseLift() {\n ZZ_pX f, g, delta, lift1, lift2;\n\n long degree = 10000;\n\n // build a square-free modulus\n Util util;\n util.randomMonic(f, degree);\n diff(g, f);\n GCD(g, g, f);\n div(f, f, g);\n ZZ_pXModulus F;\n build(F, f);\n degree = deg(F);\n\n random(g, degree);\n random(delta, degree);\n\n HasseLiftExt hasseLiftExt(g, delta, F);\n long start = util.getTimeMillis();\n// hasseLiftExt.computeNaive(lift1, degree / 2);\n// cout << util.getTimeMillis() - start << endl;\n//\n// start = util.getTimeMillis();\n hasseLiftExt.compute(lift2, degree / 2, 1);\n cout << util.getTimeMillis() - start << endl;\n\n if (lift1 == lift2)\n cout << \"OK\" << endl;\n else\n cout << \"Failed\" << endl;\n}\n\nvoid testFactoring() {\n Util util;\n \n long n = 10;\n ZZ_pX f;\n util.randomMonic(f, n);\n cout << \"p: \" << ZZ_p::modulus() << endl;\n cout << \"f: \" << f << endl;\n \n Vec factors1;\n Vec factors2;\n \n SSFactoring sSfactoring;\n// long start = util.getTimeMillis();\n sSfactoring.factor(factors1, f);\n cout << factors1 << endl;\n// cout << util.getTimeMillis() - start << endl;\n// \n// start = util.getTimeMillis();\n// CanZass(factors2, f, 1);\n// cout << util.getTimeMillis() - start << endl;\n//\n// ZZ_pX g;\n// mul(g, factors1);\n// if (f == g)\n// cout << \"OK\" << endl;\n// else\n// cout << \"Failed\" << endl;\n}\n\nint main(int argc, char** argv) {\n\n ZZ p;\n NextPrime(p, to_ZZ(7));\n ZZ_p::init(p);\n \n testFactoring();\n \n return 0;\n}\n\n", "meta": {"hexsha": "260fd13dfe0b9fc65ffaff6ca425edf0d0538c6d", "size": 5188, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ss_drinfeld_impl/test.cpp", "max_stars_repo_name": "javad-doliskani/supersingular_drinfeld_factoring", "max_stars_repo_head_hexsha": "fe402f03f2cec57a36fdf83f9b9e2d72241e6568", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-05-31T17:36:46.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-18T03:04:49.000Z", "max_issues_repo_path": "ss_drinfeld_impl/test.cpp", "max_issues_repo_name": "javad-doliskani/supersingular_drinfeld_factoring", "max_issues_repo_head_hexsha": "fe402f03f2cec57a36fdf83f9b9e2d72241e6568", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ss_drinfeld_impl/test.cpp", "max_forks_repo_name": "javad-doliskani/supersingular_drinfeld_factoring", "max_forks_repo_head_hexsha": "fe402f03f2cec57a36fdf83f9b9e2d72241e6568", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9193548387, "max_line_length": 63, "alphanum_fraction": 0.5291056284, "num_tokens": 1674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6681975024168333}} {"text": "/*********************************************************************\n* Software License Agreement (BSD License)\n*\n* Copyright (c) 2015, University of Toronto\n* All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions\n* are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above\n* copyright notice, this list of conditions and the following\n* disclaimer in the documentation and/or other materials provided\n* with the distribution.\n* * Neither the name of the University of Toronto nor the names of its\n* contributors may be used to endorse or promote products derived\n* from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n* \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*********************************************************************/\n\n/* Author: Jonathan Gammell*/\n\n// This file's header\n#include \"ompl/util/GeometricEquations.h\"\n\n// For pre C++ 11 gamma function\n#include \n\n// OMPL exceptions\n#include \"ompl/util/Exception.h\"\n\ndouble ompl::nBallMeasure(unsigned int N, double r)\n{\n return std::pow(std::sqrt(boost::math::constants::pi()) * r, static_cast(N)) / boost::math::tgamma(static_cast(N)/2.0 + 1.0);\n}\n\ndouble ompl::unitNBallMeasure(unsigned int N)\n{\n // This is the radius version with r removed (as it is 1) for efficiency\n return std::pow(std::sqrt(boost::math::constants::pi()), static_cast(N)) / boost::math::tgamma(static_cast(N)/2.0 + 1.0);\n}\n\ndouble ompl::prolateHyperspheroidMeasure(unsigned int N, double dFoci, double dTransverse)\n{\n // Sanity check input\n if (dTransverse < dFoci)\n {\n throw Exception(\"Transverse diameter cannot be less than the minimum transverse diameter.\");\n }\n\n // Variable\n // The conjugate diameter:\n double conjugateDiameter;\n // The Lebesgue measure return value\n double lmeas;\n\n // Calculate the conjugate diameter:\n conjugateDiameter = std::sqrt(dTransverse * dTransverse - dFoci * dFoci);\n\n // Calculate the volume\n // First multiply together the radii, noting that the first radius is the transverse diameter/2.0, and the other N-1 are the conjugate diameter/2.0\n lmeas = dTransverse/2.0;\n for (unsigned int i = 1u; i < N; ++i)\n {\n lmeas = lmeas * conjugateDiameter/2.0;\n }\n\n // Then multiply by the volume of the unit n-ball.\n lmeas = lmeas * unitNBallMeasure(N);\n\n // Finally return:\n return lmeas;\n}\n", "meta": {"hexsha": "fc8244071e2bfc8713d6d256db045822864a3d0a", "size": 3473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/util/src/GeometricEquations.cpp", "max_stars_repo_name": "ivaROS/ivaOmplCore", "max_stars_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ompl/util/src/GeometricEquations.cpp", "max_issues_repo_name": "ivaROS/ivaOmplCore", "max_issues_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ompl/util/src/GeometricEquations.cpp", "max_forks_repo_name": "ivaROS/ivaOmplCore", "max_forks_repo_head_hexsha": "3f5f47bb8f20c5eb82e84564342dd45f39d0c5f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-16T14:01:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T09:46:59.000Z", "avg_line_length": 39.4659090909, "max_line_length": 153, "alphanum_fraction": 0.6945004319, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6681975024168333}} {"text": "#define EIGEN_USE_MKL_ALL\n\n#include \n\n#include \n\n#include \"../misc.hpp\"\n\n#include \"models/transformers/principal_components_analysis.hpp\"\n#include \"models/transformers/zero_components_analysis.hpp\"\n\nvoid pca_examples() {\n\tEigen::MatrixXd X(2, 6);\n\n\tX.row(0) << -1, -2, -3, 1, 2, 3;\n\tX.row(1) << -1, -1, -2, 1, 1, 2;\n\n\tmlt::models::transformers::PrincipalComponentsAnalysis pca;\n\tpca.fit(X);\n\n\tstd::cout << \"PCA: \" << std::endl;\n\tstd::cout << pca.explained_variance_ratio() << std::endl << std::endl;\n\tstd::cout << \"X2\" << std::endl << X << std::endl;\n\tstd::cout << \"PCA(X2)\" << std::endl << pca.transform(X) << std::endl;\n\tstd::cout << \"PCA-1(PCA(X2))\" << std::endl << pca.inverse_transform(pca.transform(X)) << std::endl;\n\tstd::cout << \"PCA(X2[:,1])\" << std::endl << pca.transform(X.leftCols(1)) << std::endl;\n\tstd::cout << \"PCA-1(PCA(X2[:,1]))\" << std::endl << pca.inverse_transform(pca.transform(X.leftCols(1))) << std::endl << std::endl;\n\n\tmlt::models::transformers::ZeroComponentsAnalysis zca;\n\tzca.fit(X);\n\n\tstd::cout << \"ZCA: \" << std::endl;\n\tstd::cout << zca.explained_variance_ratio() << std::endl << std::endl;\n\tstd::cout << \"X2\" << std::endl << X << std::endl;\n\tstd::cout << \"ZCA(X2)\" << std::endl << zca.transform(X) << std::endl;\n\tstd::cout << \"ZCA-1(ZCA(X2))\" << std::endl << zca.inverse_transform(zca.transform(X)) << std::endl;\n\tstd::cout << \"ZCA(X2[:,1])\" << std::endl << zca.transform(X.leftCols(1)) << std::endl;\n\tstd::cout << \"ZCA-1(ZCA(X2[:,1]))\" << std::endl << zca.inverse_transform(zca.transform(X.leftCols(1))) << std::endl << std::endl;\n}", "meta": {"hexsha": "8d708e2e960a7c8358beae24ef41b7d3fb508279", "size": 1586, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/examples/principal_components_analysis.cpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/examples/principal_components_analysis.cpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/examples/principal_components_analysis.cpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6666666667, "max_line_length": 130, "alphanum_fraction": 0.6191677175, "num_tokens": 519, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110540642805, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6680442671049004}} {"text": "#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 random_subset(int max_index, int subset_size);\n\n/*!\n \\brief Returns the output of the cross operator.\n For 3 x 1 input, cross(x) * y is equivalent to cross_product(x, y)\n For 6 x 1 input, x = [rho, phi]^T. out = [cross(phi), rho; 0 0 0 1]\n \\param x Input vector which can be 3 x 1 or 6 x 1.\n \\return If the input if 3 x 1, the output is 3 x 3, if the input is 6 x 1, the output is 4 x 4.\n*/\nEigen::MatrixXd cross(Eigen::VectorXd x);\n\n/*!\n \\brief Returns the output of the circledot operator. cross(epsilon) * p == circledot(p) * epsilon,\n where epsilon is 6x1 and p is 4 x 1 homogeneous.\n p = [rhobar, eta]^T circledot(p) = [eta * identity(3), -cross(rhobar); 0 0 0 0 0 0]\n \\param x Input is a 4 x 1 homogeneous 3D vector.\n \\return returns the 4 x 6 output of circledot(x)\n*/\nEigen::MatrixXd circledot(Eigen::VectorXd x);\n\n/*!\n \\brief This function converts from a lie vector to a 4 x 4 SE(3) transform.\n // Lie Vector xi = [rho, phi]^T (6 x 1) --> SE(3) T = [C, R; 0 0 0 1] (4 x 4)\n \\param x Input vector is 6 x 1\n \\return Output is 4 x SE(3) transform\n*/\nEigen::Matrix4d se3ToSE3(Eigen::MatrixXd xi);\n\n/*!\n \\brief This function converts from an SE(3) transform into a lie vector\n // SE(3) T = [C, R; 0 0 0 1] (4 x 4) --> Lie Vector xi = [rho, phi]^T (6 x 1)\n \\param T Input is a 4x4 SE(3) transform\n \\return Output is 6x1 lie vector\n*/\nEigen::VectorXd SE3tose3(Eigen::MatrixXd T);\n\n/*!\n \\brief Converts a vector of x-y-z euler parameters to a rotation matrix.\n \\param eul 3x1 vector of euler rotation parameters (x,y,z) == (roll, pitch, yaw)\n \\return Output is a 3x3 rotation matrix, equivalent to the given euler parameters.\n*/\nEigen::MatrixXd eulerToRot(Eigen::VectorXd eul);\n\n/*!\n \\brief Ensures that theta is within [0, 2 * pi)\n*/\ndouble wrapto2pi(double theta);\n\n//* Ransac\n/**\n* \\brief This class estimates a single rigid transform between two point clouds using RANSAC and singular value decomp\n*/\nclass Ransac {\npublic:\n // p1, p2 need to be either (x, y) x N or (x, y, z) x N (must be in homogeneous coordinates)\n Ransac(Eigen::MatrixXd p1_, Eigen::MatrixXd p2_, double tolerance_, double inlier_ratio_,\n int iterations_) : p1(p1_), p2(p2_), tolerance(tolerance_),\n inlier_ratio(inlier_ratio_), iterations(iterations_) {\n int dim = p1.rows();\n assert(p1.cols() == p2.cols() && p1.rows() == p2.rows() && (dim == 2 || dim == 3));\n T_best = Eigen::MatrixXd::Identity(dim + 1, dim + 1);\n }\n void setTolerance(double tolerance_) {tolerance = tolerance_;}\n void setInlierRatio(double inlier_ratio_) {inlier_ratio = inlier_ratio_;}\n void setMaxIterations(int iterations_) {iterations = iterations_;}\n void getTransform(Eigen::MatrixXd &Tf) {Tf = T_best;}\n\n /*!\n \\brief Computes the transform that best aligns the two pointclouds such at T * p1 = p2\n */\n double computeModel();\n\n /*!\n \\brief Retrieves the set of point pairs which are inliers given the current transform Tf.\n */\n void getInliers(Eigen::MatrixXd Tf, std::vector &inliers);\n\nprivate:\n Eigen::MatrixXd p1, p2;\n double tolerance = 0.05;\n double inlier_ratio = 0.9;\n int iterations = 40;\n Eigen::MatrixXd T_best;\n};\n\n//* MotionDistortedRansac\n/**\n* \\brief This class estimates the linear velocity and angular velocity of the sensor in the body-frame.\n*\n* Assuming constant velocity, the motion vector can be used to estimate the transform between any two pairs of points\n* if the delta_t between those points is known.\n*\n* A single transform between the two pointclouds can also be retrieved.\n*\n* All operations are done in SE(3) even if the input is 2D. The output motion and transforms are in 3D.\n*/\nclass MotionDistortedRansac {\npublic:\n MotionDistortedRansac(Eigen::MatrixXd p1, Eigen::MatrixXd p2, std::vector t1, std::vector t2,\n double tolerance_, double inlier_ratio_, int iterations_) : tolerance(tolerance_),\n inlier_ratio(inlier_ratio_), iterations(iterations_) {\n const int dim = p1.rows();\n assert(p1.cols() == p2.cols() && p1.rows() == p2.rows() && p1.cols() >= p1.rows() && (dim == 2 || dim == 3));\n p1bar = Eigen::MatrixXd::Zero(4, p1.cols());\n p2bar = Eigen::MatrixXd::Zero(4, p2.cols());\n p1bar.block(3, 0, 1, p1.cols()) = Eigen::MatrixXd::Ones(1, p1.cols());\n p2bar.block(3, 0, 1, p2.cols()) = Eigen::MatrixXd::Ones(1, p2.cols());\n if (dim == 2) {\n p1bar.block(0, 0, 2, p1.cols()) = p1;\n p2bar.block(0, 0, 2, p2.cols()) = p2;\n } else if (dim == 3) {\n p1bar.block(0, 0, 3, p1.cols()) = p1;\n p2bar.block(0, 0, 3, p2.cols()) = p2;\n }\n R_pol << pow(0.25, 2), 0, 0, 0, 0, pow(0.0157, 2), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1;\n delta_ts = std::vector(p1.cols(), 0.0);\n for (uint i = 0; i < p1bar.cols(); ++i) {\n int64_t delta_t = t2[i] - t1[i];\n delta_ts[i] = double(delta_t) / 1000000.0;\n if (delta_ts[i] > max_delta_t) {\n max_delta_t = delta_ts[i];\n }\n if (delta_ts[i] < min_delta_t) {\n min_delta_t = delta_ts[i];\n }\n }\n double delta_diff = (max_delta_t - min_delta_t) / (num_transforms - 1);\n for (int i = 0; i < num_transforms; ++i) {\n delta_vec.push_back(min_delta_t + i * delta_diff);\n }\n }\n void setTolerance(double tolerance_) {tolerance = tolerance_;}\n void setInlierRatio(double inlier_ratio_) {inlier_ratio = inlier_ratio_;}\n void setMaxIterations(int iterations_) {iterations = iterations_;}\n void setMaxGNIterations(int iterations_) {max_gn_iterations = iterations_;}\n void setConvergenceThreshold(double eps) {epsilon_converge = eps;}\n void correctForDoppler(bool doppler_) {doppler = doppler_;}\n void getTransform(double delta_t, Eigen::MatrixXd &Tf);\n void getMotion(Eigen::VectorXd &w) {w = w_best;}\n void setDopplerParameter(double beta_) {beta = beta_;}\n\n /*!\n \\brief Computes the ego-motion vector that best aligns the two pointclouds\n */\n double computeModel();\n\n /*!\n \\brief Retrieves the set of point pairs which are inliers given the current motion estimate.\n */\n void getInliers(Eigen::VectorXd wbar, std::vector &inliers);\n\nprivate:\n Eigen::MatrixXd p1bar, p2bar;\n std::vector delta_ts;\n double tolerance = 0.05;\n double inlier_ratio = 0.9;\n int iterations = 40;\n int max_gn_iterations = 10;\n double epsilon_converge = 0.0001;\n double error_converge = 0.01;\n int dim = 2;\n double beta = -0.049; // beta = (f_t / (df / dt))\n double r_observable_sq = 0.0625;\n bool doppler = false;\n int num_transforms = 21;\n double max_delta_t = 0.0;\n double min_delta_t = 0.5;\n std::vector delta_vec;\n Eigen::VectorXd w_best = Eigen::VectorXd::Zero(6);\n Eigen::Matrix4d R_pol = Eigen::Matrix4d::Identity();\n Eigen::MatrixXd get_jacobian(Eigen::Vector4d gbar);\n Eigen::MatrixXd get_inv_jacobian(Eigen::Vector4d gbar);\n Eigen::VectorXd to_cylindrical(Eigen::VectorXd gbar);\n Eigen::VectorXd from_cylindrical(Eigen::VectorXd ybar);\n\n /*!\n \\brief Given two sets of point pairs (p1small, p2small), this function computes the motion of the sensor\n (linear and angular velocity) in the body frame using nonlinear least squares.\n \\pre It's very important that the delt_t_local is accurate. Note that each azimuth in the radar scan is time\n stamped, this should be used to get the more accurate time differences.\n */\n void get_motion_parameters(std::vector subset, Eigen::VectorXd &wbar);\n\n /*!\n \\brief This function also computes the motion of the sensor, but it uses the linear least squares version of\n MDRANSAC. This is a lot less accurate, but it computes the motion vector in a single step.\n */\n void get_motion_parameters2(Eigen::MatrixXd& p1small, Eigen::MatrixXd& p2small, std::vector delta_t_local,\n Eigen::VectorXd &wbar);\n\n /*!\n \\brief Retrieve the number of inliers corresponding to body motion vector wbar. (6 x 1)\n */\n int getNumInliers(Eigen::VectorXd wbar);\n\n /*!\n \\brief Given a body motion vector wbar (6 x 1), adjust the position of point p to account\n for the Doppler distortion which may be present in the data.\n */\n void dopplerCorrection(Eigen::VectorXd wbar, Eigen::VectorXd &p);\n};\n\n/*!\n \\brief Retrieve a 4x4 homogeneous transformation matrix T_enu_sensor for this ground truth vector.\n \\param gt [GPSTime,x,y,z,vel_x,vel_y,vel_z,roll,pitch,heading,ang_vel_z]\n*/\nEigen::Matrix4d getTransformFromGT(std::vector gt);\n\n/*!\n \\brief This function removes motion distortion from a cloud of points.\n \\param pc The input point cloud should be 4 x N, as in homogeneous coordinates (x, y, z, 1) (z = 0 for 2D data)\n \\param times Timestamps associated with each point, in seconds.\n \\param T_enu_sensor A global transformation from the nominal sensor position to the ENU frame,\n used to transform the velocity vector from the ENU frame to the sensor frame.\n \\param gt [GPSTime,x,y,z,vel_x,vel_y,vel_z,roll,pitch,heading,ang_vel_z]\n \\param t_ref 0 (radar) --> use first time as reference, -1 (lidar) --> use last time as reference.\n*/\nvoid removeMotionDistortion(Eigen::MatrixXd &pc, std::vector ×, Eigen::Matrix4d T_enu_sensor,\n std::vector gt, int t_ref);\n\n// Return the inverse of a 4x4 homogeneous transformation matrix\nEigen::Matrix4d get_inverse_tf(Eigen::Matrix4d T);\n", "meta": {"hexsha": "5e6a3fb4ffbcda6f387f1074deaa9c39e4d66860", "size": 10964, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/association.hpp", "max_stars_repo_name": "carlschiller/yeti_radar_odometry", "max_stars_repo_head_hexsha": "339d37fd62b4895d87a0b9aed4aa1bc142d24670", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 72.0, "max_stars_repo_stars_event_min_datetime": "2020-11-13T01:22:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T02:34:48.000Z", "max_issues_repo_path": "include/association.hpp", "max_issues_repo_name": "carlschiller/yeti_radar_odometry", "max_issues_repo_head_hexsha": "339d37fd62b4895d87a0b9aed4aa1bc142d24670", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-27T08:02:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-29T01:36:55.000Z", "max_forks_repo_path": "include/association.hpp", "max_forks_repo_name": "carlschiller/yeti_radar_odometry", "max_forks_repo_head_hexsha": "339d37fd62b4895d87a0b9aed4aa1bc142d24670", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2020-12-20T08:48:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-17T07:32:52.000Z", "avg_line_length": 43.1653543307, "max_line_length": 119, "alphanum_fraction": 0.6700109449, "num_tokens": 3179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110339361275, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6680442470316679}} {"text": "#include \"scan_matching_skeleton/transform.h\"\n#include \n#include \"ros/ros.h\"\n#include \n#include \n\nusing namespace std;\n\n\nvoid transformPoints(const vector& points, Transform& t, vector& transformed_points) {\n transformed_points.clear();\n for (int i = 0; i < points.size(); i++) {\n transformed_points.push_back(t.apply(points[i]));\n //printf(\"%f %transformed_points.back().r, transformed_points.back().theta);\n }\n}\n\n// returns the largest real root to ax^3 + bx^2 + cx + d = 0\ncomplex get_cubic_root(float a, float b, float c, float d) {\n //std::cout<< \"a= \" << a<< \"; b= \" << b<< \"; c= \" << c<< \"; d= \" << d<<\";\"< xi(-.5, sqrt(3)/2);\n\n complex inside = sqrt(q*q/4 + p*p*p/27);\n\n complex root;\n\n for (float k = 0; k < 3; ++k) {\n // get root for 3 possible values of k\n root = -b/(3*a) + pow(xi, k) * pow(-q/2.f + inside, 1.f/3.f) + pow(xi, 2.f*k) * pow(-q/2.f - inside, 1.f/3.f);\n //std::cout<<\"RootTemp: \"<< root< m = get_cubic_root(8, 8*p, 2*p*p-8*r, -q*q);\n\n complex root1 = -b/(4*a) + ( sqrt(2.f*m) + sqrt(-(2*p + 2.f*m + sqrt(2.f)*q/sqrt(m))))/2.f;\n complex root2 = -b/(4*a) + ( sqrt(2.f*m) - sqrt(-(2*p + 2.f*m + sqrt(2.f)*q/sqrt(m))))/2.f;\n complex root3 = -b/(4*a) + (-sqrt(2.f*m) + sqrt(-(2*p + 2.f*m - sqrt(2.f)*q/sqrt(m))))/2.f;\n complex root4 = -b/(4*a) + (-sqrt(2.f*m) - sqrt(-(2*p + 2.f*m - sqrt(2.f)*q/sqrt(m))))/2.f;\n\n vector> roots { root1, root2, root3, root4 };\n\n float max_real_root = 0.f;\n\n for (complex root: roots) {\n if(root.imag()==0){\n max_real_root = max(max_real_root, root.real());\n }\n //std::cout<<\"Max real root:\" << max_real_root<& corresponds, Transform& curr_trans) {\n // Written with inspiration from: https://github.com/AndreaCensi/gpc/blob/master/c/gpc.c\n // You can use the helper functions which are defined above for finding roots and transforming points as and when needed.\n // use helper functions and structs in transform.h and correspond.h\n // input : corresponds : a struct vector of Correspondene struct object defined in correspond.\n // input : curr_trans : A Transform object refernece\n // output : update the curr_trans object. Being a call by reference function, Any changes you make to curr_trans will be reflected in the calling function in the scan_match.cpp program/\n\n// You can change the number of iterations here. More the number of iterations, slower will be the convergence but more accurate will be the results. You need to find the right balance.\nint number_iter = 1;\n\nfor(int i = 0; i\n#include \n\nnamespace DiscontinuousGalerkin1D {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::SparseMatrix compBmat(int Ml, int Mr, double h) {\n const int N = 2 * (Ml + Mr + 1);\n Eigen::SparseMatrix A(N, N);\n // Tell Eigen that the matrix is diagonal, which allows efficient\n // initialization\n A.reserve(Eigen::VectorXi::Ones(N));\n for (int i = 0; i < N; i += 2) {\n A.insert(i, i) = h;\n A.insert(i + 1, i + 1) = h * h * h / 12.0;\n }\n return A;\n}\n/* SAM_LISTING_END_1 */\n\n/* SAM_LISTING_BEGIN_2 */\ndouble Feo(double v, double w) {\n double result;\n auto f = [](double u) { return u * (1.0 - u); };\n auto I = [](double s) {\n double y = 0.25 - s * (1.0 - s);\n return s < 0.5 ? y : -y;\n };\n result = 0.5 * (f(v) + f(w)) - 0.5 * (I(v) - I(w));\n return result;\n}\n/* SAM_LISTING_END_2 */\n\n/* SAM_LISTING_BEGIN_3 */\nSolution solveTrafficFlow() {\n int Ml = 40;\n int Mr = 40;\n int N_half = Mr + Ml + 1;\n int N = 2 * N_half;\n\n double h = 0.05;\n double tau = h / 3;\n double T = 1.0;\n unsigned int m = (unsigned int)(T / tau);\n\n // Spatial mesh\n Eigen::VectorXd x = Eigen::VectorXd::LinSpaced(N_half, -2.0, 2.0);\n // Initial condition according to \\prbeqref{eq:u0}. Note that we just\n // initialize the cell averages; a more refined implementation would also\n // sample the local first moments of $u_0$.\n Eigen::VectorXd mu0 = Eigen::VectorXd::Zero(N);\n auto u0 = [](double x) { return 0.0 <= x && x <= 1.0 ? 1.0 : 0.0; };\n for (int i = 0; i < N_half; ++i) {\n mu0(2 * i) = u0(x(i));\n }\n // Flux function\n auto f = [](double u) { return u * (1.0 - u); };\n // Perform fully discrete evolution\n Eigen::VectorXd mu = dgcl(mu0, f, Feo, T, Ml, Mr, h, m);\n // Retrieve cell averages\n Eigen::VectorXd u(N_half);\n for (int i = 0; i < N_half; ++i) {\n u(i) = mu(2 * i);\n }\n\n return Solution(std::move(x), std::move(u));\n}\n/* SAM_LISTING_END_3 */\n\n} // namespace DiscontinuousGalerkin1D\n", "meta": {"hexsha": "6a1ea3b5f687bb62cb5002e0917761d475df248b", "size": 2187, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/DiscontinuousGalerkin1D/mastersolution/discontinuousgalerkin1d.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/DiscontinuousGalerkin1D/mastersolution/discontinuousgalerkin1d.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/DiscontinuousGalerkin1D/mastersolution/discontinuousgalerkin1d.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 27.0, "max_line_length": 75, "alphanum_fraction": 0.6049382716, "num_tokens": 770, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8080672135527632, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.6680386958458949}} {"text": "\n#include \"mesh_param.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nMatrixXd interpolate_field\n(\n const MatrixXd& V, // Vertices of the mesh\n const MatrixXi& F, // Faces\n const MatrixXi& TT, // Adjacency triangle-triangle\n const VectorXi& b, // Constrained faces id\n const MatrixXd& bc // Cosntrained faces representative vector\n) \n{\n // Lots of the codes below are based on the codes in tutorial_nrosy.cpp\n // However, there are a lot of modifications\n\n // Starter code, same as template\n assert(b.size() > 0); // One constraint is necessary to make the solution unique\n Matrix T1(F.rows(),3), T2(F.rows(),3);\n // Compute the local reference systems for each face\n for (unsigned i=0;i > > t;\n // The b vector is all zeroes so we do not need it here\n // std::vector< Triplet > > tb;\n\n // Handle the free part of matrix A; same as template\n unsigned count = 0;\n for (unsigned f=0;f g) continue;\n // Compute the complex representation of the common edge\n Vector3d e = (V.row(F(f,(ei+1)%3)) - V.row(F(f,ei)));\n Vector2d vef = Vector2d(e.dot(T1.row(f)),e.dot(T2.row(f))).normalized();\n std::complex ef(vef(0),vef(1));\n Vector2d veg = Vector2d(e.dot(T1.row(g)),e.dot(T2.row(g))).normalized();\n std::complex eg(veg(0),veg(1));\n // Add the term conj(f)^n*ui - conj(g)^n*uj to the energy matrix\n t.push_back(Triplet >(count,f, std::conj(ef)));\n t.push_back(Triplet >(count,g,-1.*std::conj(eg)));\n ++count;\n }\n }\n\n // Since tb is not used, comment out the codes related to tb\n // double lambda = 10e6;\n double lambda = 0;\n for (unsigned r=0; r c(v.dot(T1.row(f)),v.dot(T2.row(f)));\n t.push_back(Triplet >(count,f, sqrt(lambda)));\n // tb.push_back(Triplet >(count,0, c * std::complex(sqrt(lambda),0)));\n ++count;\n }\n\n const unsigned fr = F.rows();\n const unsigned bs = b.size();\n\n // Solve the linear system\n // Here the solving is based on the equation\n // Aff * u = - Afc * xc\n // (#f is the number of total faces)\n // (#b is number of constrained faces)\n // (so #f-#b is the number of free faces)\n // Where Aff is (#f-#b)*(#f-#b) matrix\n // u is our answer, (#f-#b)*#1 vector\n // Afc is (#f-#b)*#b matrix \n // xc is #b*#1 vector\n // Therefore, the right part is (#f-#b)*#1 vector\n // We need A to be a matrix of #count*#f\n // So that Q=A.adjoint()*A is #f*#f\n // Aff is the (#f-#b)*(#f-#b) part of Q\n // Afc is the (#f-#b)*#b part of Q\n typedef SparseMatrix> SparseMatrixXcd;\n // SparseMatrixXcd A(count,F.rows());\n SparseMatrixXcd A(count,fr); // #count*#f\n A.setFromTriplets(t.begin(), t.end());\n VectorXcd xc(bs,1); // #b*#1\n for (unsigned r=0; r c(v.dot(T1.row(f)),v.dot(T2.row(f)));\n xc(r) = c;\n }\n\n #ifdef DEBUG_3\n for (unsigned r=0; r constrained_set;\n for (unsigned r=0; r solver;\n solver.compute(Aff);\n // solver.compute(A.adjoint()*A);\n assert(solver.info()==Success);\n MatrixXcd u = solver.solve(mb);\n // MatrixXcd u = solver.solve(A.adjoint()*MatrixXcd(b));\n assert(solver.info()==Success);\n\n // Finally, rearrange u and store values in ua\n VectorXcd ua(fr);\n for (unsigned ui = 0; ui < u.size(); ui++) {\n ua(vf(ui)) = u(ui);\n }\n for (unsigned r=0; r& G // Gradient operator \n) \n{\n // Construct matrix A (areas)\n VectorXd A1(F.rows());\n igl::doublearea(V,F,A1);\n SparseMatrix A(F.rows()*3, F.rows()*3); // #3f*#3f\n for (unsigned f = 0; f < F.rows(); ++f) {\n A.insert(f,f) = A1(f);\n A.insert(f+F.rows(),f+F.rows()) = A1(f);\n A.insert(f+F.rows()*2,f+F.rows()*2) = A1(f);\n }\n\n // Construct matrix u (from R)\n VectorXd u(F.rows()*3); // #3f*#1\n for (unsigned f = 0; f < F.rows(); ++f) {\n u(f) = R(f,0);\n u(f+F.rows()) = R(f,1);\n u(f+2*F.rows()) = R(f,2);\n }\n\n // Construct K\n SparseMatrix K = G.transpose() * A * G; // #v*#v\n // Construct b\n VectorXd b = G.transpose() * A * u; // #v*#1\n\n // Row/col removal\n SparseMatrix Kff = K.bottomRightCorner(K.rows()-1, K.cols()-1);\n // SparseMatrix Kfc = K.bottomLeftCorner(K.rows()-1, 1);\n // VectorXd sc(1);\n // sc << 0;\n // VectorXd bt = b.bottomRows(b.rows()-1) - Kfc * sc;\n VectorXd bt = b.bottomRows(b.rows()-1);\n\n #ifdef DEBUG_7\n cout << \"--------------\" << endl;\n cout << \"V: \" << V.rows() << \" * \" << V.cols() << endl;\n cout << \"F: \" << F.rows() << \" * \" << F.cols() << endl;\n cout << \"R: \" << R.rows() << \" * \" << R.cols() << endl;\n cout << \"G: \" << G.rows() << \" * \" << G.cols() << endl;\n cout << \"A: \" << A.rows() << \" * \" << A.cols() << endl;\n cout << \"u: \" << u.rows() << \" * \" << u.cols() << endl;\n cout << \"K: \" << K.rows() << \" * \" << K.cols() << endl;\n cout << \"b: \" << b.rows() << \" * \" << b.cols() << endl;\n cout << \"--------------\" << endl;\n cout << \"G nonzeros: \" << G.nonZeros() << endl;\n cout << \"A nonzeros: \" << A.nonZeros() << endl;\n cout << \"K nonzeros: \" << K.nonZeros() << endl;\n #endif\n\n // Solve the system\n SimplicialLDLT> solver;\n // solver.compute(K);\n // assert(solver.info() == Success);\n // MatrixXd s = solver.solve(b);\n // assert(solver.info() == Success);\n solver.compute(Kff);\n assert(solver.info() == Success);\n MatrixXd sf = solver.solve(bt);\n assert(solver.info() == Success);\n VectorXd s(K.rows());\n s(0) = 0;\n for (unsigned i = 1; i < K.rows(); i++) {\n s(i) = sf(i-1);\n }\n\n // Debugging informations\n #ifdef DEBUG_7\n cout << \"s: \" << s.rows() << \" * \" << s.cols() << endl;\n cout << \"--------------\" << endl;\n #endif\n\n return s;\n}\n\nMatrixXd harmonic_param\n(\n const MatrixXd& V, // Vertices of the mesh\n const MatrixXi& F // Faces\n) \n{\n // Find the open boundary\n VectorXi bnd;\n igl::boundary_loop(F, bnd);\n // Map the boundary to a circle\n MatrixXd bnd_uv;\n igl::map_vertices_to_circle(V, bnd, bnd_uv);\n // Harmonic parameterizations\n MatrixXd V_uv;\n igl::harmonic(V,F,bnd,bnd_uv,1,V_uv);\n V_uv *= 8;\n\n #ifdef DEBUG_9\n cout << \"--------------\" << endl;\n cout << \"V: \" << V.rows() << \" * \" << V.cols() << endl;\n cout << \"F: \" << F.rows() << \" * \" << F.cols() << endl;\n cout << \"bnd: \" << bnd.rows() << \" * \" << bnd.cols() << endl;\n cout << \"bnd_uv: \" << bnd_uv.rows() << \" * \" << bnd_uv.cols() << endl;\n cout << \"V_uv: \" << V_uv.rows() << \" * \" << V_uv.cols() << endl;\n cout << \"--------------\" << endl;\n #endif\n\n return V_uv;\n}\n\nMatrixXd lscm_param\n(\n const MatrixXd& V, // Vertices of the mesh\n const MatrixXi& F // Faces\n) \n{\n // Fix two points on the boundary\n VectorXi bnd, b(2,1);\n igl::boundary_loop(F,bnd);\n b(0) = bnd(0);\n b(1) = bnd(round(bnd.size()/2));\n MatrixXd bc(2,2);\n bc << 0,0,1,0;\n // LSCM parametrizations\n MatrixXd V_uv;\n igl::lscm(V,F,b,bc,V_uv);\n V_uv *= 8;\n\n #ifdef DEBUG_9\n cout << \"--------------\" << endl;\n cout << \"V: \" << V.rows() << \" * \" << V.cols() << endl;\n cout << \"F: \" << F.rows() << \" * \" << F.cols() << endl;\n cout << \"bnd: \" << bnd.rows() << \" * \" << bnd.cols() << endl;\n cout << \"V_uv: \" << V_uv.rows() << \" * \" << V_uv.cols() << endl;\n cout << \"--------------\" << endl;\n #endif\n\n return V_uv;\n}\n\n", "meta": {"hexsha": "d6805a95732b038c4d8c81c5ab7e6cf058fea2a4", "size": 12807, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lab4/src/mesh_param.cpp", "max_stars_repo_name": "bambrow/geometric-modeling", "max_stars_repo_head_hexsha": "10c30f4254928d94f057f18e7542cccfa98ddb3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-11T05:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T05:20:52.000Z", "max_issues_repo_path": "lab4/src/mesh_param.cpp", "max_issues_repo_name": "bambrow/geometric-modeling", "max_issues_repo_head_hexsha": "10c30f4254928d94f057f18e7542cccfa98ddb3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab4/src/mesh_param.cpp", "max_forks_repo_name": "bambrow/geometric-modeling", "max_forks_repo_head_hexsha": "10c30f4254928d94f057f18e7542cccfa98ddb3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2649350649, "max_line_length": 107, "alphanum_fraction": 0.4991020536, "num_tokens": 4040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070158103778, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.667980507969872}} {"text": "/*\n * Copyright (c) 2015-, Filippo Basso \n *\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder(s) nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef UNIPD_CALIBRATION_IMPL_CALIBRATION_ALGORITHMS_CERES_PLANE_FIT_HPP_\n#define UNIPD_CALIBRATION_IMPL_CALIBRATION_ALGORITHMS_CERES_PLANE_FIT_HPP_\n\n#include \n#include \n\nnamespace unipd\n{\nnamespace calib\n{\n\ntemplate \n Plane3_\n plane_fit (const Cloud3_ & points)\n {\n assert(points.elements() > 1);\n\n Point3_ centroid = Point3_::Zero();\n typename Cloud3_::Container diff(3, points.elements());\n Size1 count = 0;\n for (Size1 i = 0; i < points.elements(); ++i)\n {\n if (points[i].allFinite())\n {\n centroid += points[i];\n diff.col(count++) = points[i];\n }\n }\n centroid /= count;\n diff.conservativeResize(3, count);\n diff.colwise() -= centroid;\n\n Eigen::Matrix covariance_matrix = diff * diff.transpose() / ScalarT_(count - 1);\n Eigen::SelfAdjointEigenSolver > solver(covariance_matrix, Eigen::ComputeEigenvectors);\n\n Point3_ eigen_vector = solver.eigenvectors().col(0);\n return Plane3_(eigen_vector, -eigen_vector.dot(centroid));\n }\n\n} // namespace calib\n} // namespace unipd\n#endif // UNIPD_CALIBRATION_IMPL_CALIBRATION_ALGORITHMS_CERES_PLANE_FIT_HPP_\n", "meta": {"hexsha": "0b5ef2333e2833531d012bcc1b3b1d01f9814a3b", "size": 2944, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "calibration_algorithms/include/impl/calibration_algorithms/plane_fit.hpp", "max_stars_repo_name": "pionex/calibration_toolkit", "max_stars_repo_head_hexsha": "ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2016-08-02T04:40:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T22:08:55.000Z", "max_issues_repo_path": "calibration_algorithms/include/impl/calibration_algorithms/plane_fit.hpp", "max_issues_repo_name": "pionex/calibration_toolkit", "max_issues_repo_head_hexsha": "ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-03-19T07:53:09.000Z", "max_issues_repo_issues_event_max_datetime": "2017-07-06T21:55:47.000Z", "max_forks_repo_path": "calibration_algorithms/include/impl/calibration_algorithms/plane_fit.hpp", "max_forks_repo_name": "pionex/calibration_toolkit", "max_forks_repo_head_hexsha": "ef9a6f7c6e83ac8c1a052f6f4f4887d60f001212", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2017-06-15T00:18:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-14T21:16:09.000Z", "avg_line_length": 41.4647887324, "max_line_length": 120, "alphanum_fraction": 0.7309782609, "num_tokens": 723, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765328159726, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6679510620543554}} {"text": "#include \"tetelem.hpp\"\r\n#include \r\n\r\n#define ZERO_DET_EPS 1e-14\r\n\r\n\r\nTetElem::TetElem(std::string& log_buf)\r\n : log_buf_(log_buf)\r\n{}\r\n\r\nbool TetElem::Init(const uint i_elem,\r\n const Mat &node_mat,\r\n const real e_modulus,\r\n const real nu)\r\n{\r\n node_mat_ = node_mat;\r\n e_modulus_ = e_modulus;\r\n nu_ = nu;\r\n\r\n A_ = Mat::Zero(4, 4);\r\n A_ << Vec::Ones(4, 1), node_mat_.block(0, 0, 4, 3);\r\n V6_ = A_.determinant();\r\n\r\n if (abs(V6_) == 0.0)\r\n {\r\n log_buf_ = \"Zero determinant for the \" + std::to_string(i_elem) + \"th element.\";\r\n return false;\r\n }\r\n\r\n const Mat tmp = V6_ * A_.inverse().transpose();\r\n a_ = tmp.col(0);\r\n b_ = tmp.col(1);\r\n c_ = tmp.col(2);\r\n d_ = tmp.col(3);\r\n\r\n D_ = Mat::Zero(6, 6);\r\n D_(0, 0) = D_(1, 1) = D_(2, 2) = e_modulus*(1.0 - nu) / ((1.0 + nu) * (1.0 - 2*nu));\r\n D_(0, 1) = D_(0, 2) = D_(1, 2) =\r\n D_(1, 0) = D_(2, 0) = D_(2, 1) = e_modulus*nu / ((1.0 + nu) * (1.0 - 2*nu));\r\n D_(3, 3) = D_(4, 4) = D_(5, 5) = e_modulus / (2.0 + 2.0*nu);\r\n\r\n return true;\r\n}\r\n\r\nMat TetElem::BuildStifMat() const\r\n{\r\n Mat B = Mat::Zero(6, 3*4);\r\n BuildShapeFuncDerMat(B);\r\n\r\n return (V6_/6.) * B.transpose() * D_ * B;\r\n}\r\n\r\nvoid TetElem::BuildShapeFuncDerMat(Mat& B) const\r\n{\r\n for(int i = 0; i < 4; ++i)\r\n {\r\n B(0, 0 + 3*i) = b_[i];\r\n B(1, 1 + 3*i) = c_[i];\r\n B(2, 2 + 3*i) = d_[i];\r\n B(3, 0 + 3*i) = c_[i];\r\n B(3, 1 + 3*i) = b_[i];\r\n B(4, 1 + 3*i) = d_[i];\r\n B(4, 2 + 3*i) = c_[i];\r\n B(5, 0 + 3*i) = d_[i];\r\n B(5, 2 + 3*i) = b_[i];\r\n }\r\n\r\n B /= V6_;\r\n}\r\n\r\nvoid TetElem::BuildShapeFuncDerRow(Vec& row, const int idx) const\r\n{\r\n switch(idx)\r\n {\r\n case 0: for(int i=0;i<4;++i) row(0 + 3*i) = b_[i]; break;\r\n case 1: for(int i=0;i<4;++i) row(1 + 3*i) = c_[i]; break;\r\n case 2: for(int i=0;i<4;++i) row(2 + 3*i) = d_[i]; break;\r\n case 3: for(int i=0;i<4;++i){row(0 + 3*i) = c_[i]; row(1 + 3*i) = b_[i];} break;\r\n case 4: for(int i=0;i<4;++i){row(1 + 3*i) = d_[i]; row(2 + 3*i) = c_[i];} break;\r\n case 5: for(int i=0;i<4;++i){row(0 + 3*i) = d_[i]; row(2 + 3*i) = b_[i];} break;\r\n default: return;\r\n }\r\n\r\n row /= V6_;\r\n}\r\n\r\nMat TetElem::BuildIsoMatHookeTensor(const real e_modulus,\r\n const real nu)\r\n{\r\n Mat m = Mat::Zero(6, 6);\r\n m(0, 0) = m(1, 1) = m(2, 2) = 1 - nu;\r\n m(3, 3) = m(4, 4) = m(5, 5) = 0.5 - nu;\r\n m(0, 1)=m(1, 0) = m(0, 2)=m(2, 0) = m(1, 2)=m(1, 2) = nu;\r\n\r\n return e_modulus / ((1 + nu)*(1 - 2*nu)) * m;\r\n}\r\n", "meta": {"hexsha": "89d2461f7912e7af45286676722548747eec5016", "size": 2632, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/solv_plug/tetelem.cpp", "max_stars_repo_name": "master-clown/ofeata", "max_stars_repo_head_hexsha": "306cbc3a402551fb62b3925d23a2d4f63f60d525", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T13:51:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T13:51:42.000Z", "max_issues_repo_path": "src/solv_plug/tetelem.cpp", "max_issues_repo_name": "master-clown/ofeata", "max_issues_repo_head_hexsha": "306cbc3a402551fb62b3925d23a2d4f63f60d525", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/solv_plug/tetelem.cpp", "max_forks_repo_name": "master-clown/ofeata", "max_forks_repo_head_hexsha": "306cbc3a402551fb62b3925d23a2d4f63f60d525", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-30T13:51:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-30T13:51:35.000Z", "avg_line_length": 27.1340206186, "max_line_length": 89, "alphanum_fraction": 0.4494680851, "num_tokens": 1123, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6679510570976502}} {"text": "#include \n#include \n#include \"admmSolver.hpp\"\n\nint main(int argc, char **argv)\n{\n Eigen::VectorXf mu = Eigen::VectorXf(4);\n const float regularization = 0.1f;\n const float volatility_target = 0.05; // 5% max vol\n\n // Vector of asset expected returns\n mu << 0.1, 0.3, -0.5, 0.6;\n\n Eigen::MatrixXf Sigma(4,4);\n // Sample covariance matrix (positive-definite)\n Sigma << 4.2, 0.3, 0.1, 1.25,\n 0.3, 5.95, 0.56, 1.56,\n 0.1, 0.56, 4.45, 0.25,\n 1.25, 1.56, 0.25, 4.56;\n\n Eigen::VectorXf x0 = Eigen::VectorXf::Zero(4);\n\n // Regularized markowitz optimization\n\n proxopp::ptfVolConstrainedL2 optim(mu, Sigma, x0, volatility_target, regularization);\n optim.setVerbose(1);\n\n Eigen::VectorXf ptf = optim.solve();\n std::cout << \"Solution: \\n\";\n std::cout << ptf << std::endl;\n std::cout << \"(ex-ante) Volatility :\" << ptf.dot(Sigma*ptf) << std::endl;\n return 0;\n}\n", "meta": {"hexsha": "b29a2b29316f23ee4a3f273a6ce904c93bcbfe3c", "size": 984, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "regularizedPortfolio.cpp", "max_stars_repo_name": "jopago/proxopp", "max_stars_repo_head_hexsha": "4eef17219f99591850bfbca26da2a4baf7e7268b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-17T21:20:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-17T21:20:15.000Z", "max_issues_repo_path": "regularizedPortfolio.cpp", "max_issues_repo_name": "Meloignon/proxopp", "max_issues_repo_head_hexsha": "e18d334ac714517b2bf166b12993495b0593bc39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "regularizedPortfolio.cpp", "max_forks_repo_name": "Meloignon/proxopp", "max_forks_repo_head_hexsha": "e18d334ac714517b2bf166b12993495b0593bc39", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-05-11T21:04:38.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-11T21:04:38.000Z", "avg_line_length": 28.9411764706, "max_line_length": 89, "alphanum_fraction": 0.5823170732, "num_tokens": 350, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765187126079, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6679510517439697}} {"text": "\n#include \"slamdunk/include/transformation_estimation.h\"\n#include \"slamdunk/include/pretty_printer.h\"\n\n#include \n#include \n#include \n#include \n#include // required for determinant computation\n\n#include \n\n#define LOG_TAG4\t\"slamdunk_app\"\n#define LOGI4(...)\t__android_log_print(ANDROID_LOG_INFO, LOG_TAG4, __VA_ARGS__)\n\nvoid SLAM_DUNK_API slamdunk::estimateTransformationSVD(const std::vector& reference,\n const std::vector& query,\n const std::vector< std::pair >& ref_query_ids,\n Eigen::Isometry3d& queryToRef)\n{\n const unsigned no_of_matches = ref_query_ids.size();\n Eigen::Vector3f mean_ref(0,0,0), mean_qry(0,0,0);\n for(unsigned rqidx = 0; rqidx < no_of_matches; ++rqidx)\n {\n mean_ref += reference[ ref_query_ids[rqidx].first ];\n mean_qry += query[ ref_query_ids[rqidx].second ];\n }\n mean_ref /= (float)no_of_matches;\n mean_qry /= (float)no_of_matches;\n\n Eigen::Matrix3d H = Eigen::Matrix3d::Zero();\n for(unsigned rqidx = 0; rqidx < no_of_matches; ++rqidx)\n {\n H.noalias() += (query[ ref_query_ids[rqidx].second ] - mean_qry).cast() *\n (reference[ ref_query_ids[rqidx].first ] - mean_ref).cast().transpose();\n }\n // SVD\n Eigen::JacobiSVD svd(H, Eigen::ComputeFullU | Eigen::ComputeFullV);\n Eigen::Matrix3d V = svd.matrixV();\n Eigen::Matrix3d R = V * svd.matrixU().transpose();\n if(R.determinant() < 0.0)\n {\n V.col(2) = V.col(2)*-1.0;\n R.noalias() = V * svd.matrixU().transpose();\n }\n\n queryToRef.setIdentity();\n queryToRef.rotate(R);\n queryToRef.translation() = (mean_ref.cast() - R*mean_qry.cast());\n}\n\n//////////////////////////////////////////////////////////////////////////////////////////////////////////\nbool slamdunk::RANSAC::findInliers(const std::vector& reference,\n const std::vector& query,\n const std::vector< std::pair >& ref_query_ids)\n{\n if(ref_query_ids.size() < 3)\n {\n if(m_verbose)\n std::cout << SLAM_DUNK_WARNING_STR(\"Less than 3 matches provided\") << std::endl;\n m_inlier_indices.clear();\n return false;\n }\n\n const unsigned no_of_matches = ref_query_ids.size();\n if(m_deterministic)\n m_rnd_eng.seed(42u);\n boost::variate_generator< boost::mt19937&, boost::uniform_int > rnd_gen(m_rnd_eng, boost::uniform_int(0, no_of_matches-1));\n unsigned current_max_iterations = m_max_iterations;\n\n unsigned a, b, c;\n Eigen::Matrix3d ref_mtx, qry_mtx;\n Eigen::Isometry3d current_transformation = Eigen::Isometry3d::Identity();\n unsigned best_score = 0;\n\n const double no_of_matches_inverse = 1.0/(double)no_of_matches;\n const double lognum = std::log(1-m_probability);\n\n /*std::stringstream sst;\n sst << \"RANSAC MATCHES NUMBER: \" << no_of_matches;\n LOGI4(sst.str().data());*/\n\n unsigned it = 0;\n int k = 0;\n for(; it < current_max_iterations; ++it)\n {\n a = rnd_gen();\n do b = rnd_gen(); while(a == b);\n do c = rnd_gen(); while(c == b || c == a);\n\n /*std::stringstream ss;\n ss << \"RANSAC IDS: (\" << a << \", \" << b << \", \" << c << \")\";\n LOGI4(ss.str().data());*/\n\n ref_mtx.row(0) = reference[ ref_query_ids[a].first ].cast();\n ref_mtx.row(1) = reference[ ref_query_ids[b].first ].cast();\n ref_mtx.row(2) = reference[ ref_query_ids[c].first ].cast();\n qry_mtx.col(0) = query[ ref_query_ids[a].second ].cast();\n qry_mtx.col(1) = query[ ref_query_ids[b].second ].cast();\n qry_mtx.col(2) = query[ ref_query_ids[c].second ].cast();\n\n /*Eigen::Vector3d ref1 = reference[ ref_query_ids[a].first ].cast();\n Eigen::Vector3d ref2 = reference[ ref_query_ids[b].first ].cast();\n Eigen::Vector3d ref3 = reference[ ref_query_ids[c].first ].cast();\n Eigen::Vector3d query1 = query[ ref_query_ids[a].second ].cast();\n Eigen::Vector3d query2 = query[ ref_query_ids[b].second ].cast();\n Eigen::Vector3d query3 = query[ ref_query_ids[c].second ].cast();\n\n std::stringstream ssx1;\n ssx1 << \"REF1: (\" << ref1.x() << \", \" << ref1.y() << \", \" << ref1.z() << \")\";\n LOGI4(ssx1.str().data());\n std::stringstream ssx2;\n ssx2 << \"REF2: (\" << ref2.x() << \", \" << ref2.y() << \", \" << ref2.z() << \")\";\n LOGI4(ssx2.str().data());\n std::stringstream ssx3;\n ssx3 << \"REF3: (\" << ref3.x() << \", \" << ref3.y() << \", \" << ref3.z() << \")\";\n LOGI4(ssx3.str().data());\n std::stringstream ssx4;\n ssx4 << \"QUERY1: (\" << query1.x() << \", \" << query1.y() << \", \" << query1.z() << \")\";\n LOGI4(ssx4.str().data());\n std::stringstream ssx5;\n ssx5 << \"QUERY2: (\" << query2.x() << \", \" << query2.y() << \", \" << query2.z() << \")\";\n LOGI4(ssx5.str().data());\n std::stringstream ssx6;\n ssx6 << \"QUERY3: (\" << query3.x() << \", \" << query3.y() << \", \" << query3.z() << \")\";\n LOGI4(ssx6.str().data());*/\n\n // compute centroids\n const Eigen::Vector3d cRef = (ref_mtx.row(0)+ref_mtx.row(1)+ref_mtx.row(2))*(0.33333333333333333333);\n const Eigen::Vector3d cQry = (qry_mtx.col(0)+qry_mtx.col(1)+qry_mtx.col(2))*(0.33333333333333333333);\n\n ref_mtx.row(0) -= cRef;\n ref_mtx.row(1) -= cRef;\n ref_mtx.row(2) -= cRef;\n qry_mtx.col(0) -= cQry;\n qry_mtx.col(1) -= cQry;\n qry_mtx.col(2) -= cQry;\n const Eigen::Matrix3d H = qry_mtx*ref_mtx;\n\n // SVD\n Eigen::JacobiSVD svd(H, Eigen::ComputeFullU | Eigen::ComputeFullV);\n Eigen::Matrix3d V = svd.matrixV();\n Eigen::Matrix3d R = V * svd.matrixU().transpose();\n if(R.determinant() < 0.0)\n {\n V.col(2) = V.col(2)*-1.0;\n R.noalias() = V * svd.matrixU().transpose();\n }\n current_transformation = Eigen::Isometry3d(R);\n current_transformation.translation() = cRef-R*cQry;\n\n // voting\n unsigned current_score = 0;\n for(unsigned rqidx = 0; rqidx < no_of_matches; ++rqidx)\n if((current_transformation * query[ ref_query_ids[rqidx].second ].cast()\n - reference[ ref_query_ids[rqidx].first ].cast()).squaredNorm() <= m_squared_threshold)\n ++current_score; // TODO: weight the actual distance\n\n // update\n if(current_score > best_score)\n {\n best_score = current_score;\n m_query2ref = current_transformation;\n\n if(best_score == no_of_matches)\n current_max_iterations = 0;\n else\n current_max_iterations = std::min((double)m_max_iterations, std::ceil(lognum / std::log(1.0 - std::pow((double)best_score * no_of_matches_inverse, 3.0))));\n }\n }\n\n if(m_verbose)\n std::cout << SLAM_DUNK_INFO_STR(\"No of iterations: \" << it) << std::endl;\n\n if(best_score < 4)\n {\n if(m_verbose)\n std::cout << SLAM_DUNK_WARNING_STR(\"Empty inlier set\") << std::endl;\n m_inlier_indices.clear();\n return false;\n }\n\n // store indices\n m_inlier_indices.clear();\n m_inlier_indices.reserve(best_score);\n for(unsigned rqidx = 0; rqidx < no_of_matches; ++rqidx)\n if((m_query2ref * query[ ref_query_ids[rqidx].second ].cast()\n - reference[ ref_query_ids[rqidx].first ].cast()).squaredNorm() <= m_squared_threshold)\n m_inlier_indices.push_back(rqidx);\n\n return true;\n}\n", "meta": {"hexsha": "681ddaba15fe5240d010740e2a6ed18d443d4184", "size": 7534, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jni/slamdunk/src/transformation_estimation.cpp", "max_stars_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_stars_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2018-01-18T15:50:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T23:07:15.000Z", "max_issues_repo_path": "jni/slamdunk/src/transformation_estimation.cpp", "max_issues_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_issues_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2019-01-31T05:53:49.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-26T14:06:53.000Z", "max_forks_repo_path": "jni/slamdunk/src/transformation_estimation.cpp", "max_forks_repo_name": "CVLAB-Unibo/Slam-Dunk-Android", "max_forks_repo_head_hexsha": "28343eb7d92cfd884e025dbaf510f4115199f58f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2017-08-08T12:18:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-07T08:07:55.000Z", "avg_line_length": 39.0362694301, "max_line_length": 163, "alphanum_fraction": 0.6140164587, "num_tokens": 2199, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898178450964, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6678577999460437}} {"text": "// functions to calculate X^2 (Pearson's cumulative test statistic)\n// and significance (1 - P(X^2/2, k/2)) for k categories. \n\n#include \n#include \n\n#include \n#include \n#include \n#include \"ChiSquared.hxx\"\n\ndouble ChiSquared::pearsonCTS(const std::vector & S, \n\t\t const std::vector & X)\n{\n // The inputs S[i] and X[i] are in the form of \"number of samples in\n // category [i] for the \"standard\" case (the histogram that fits\n // the null hypothesis) and the sample to be tested. \n \n // first make the p[i] (normative probability of an occurance in\n // bucket [i].\n int num_Ssamps = 0;\n int N = 0; \n for(int i = 0; i < S.size(); i++) {\n num_Ssamps += S[i];\n N += X[i]; \n }\n\n std::vector p; \n double rtsamps = 1.0 / ((double) num_Ssamps); \n for(int i = 0; i < S.size(); i++) {\n double v = (double) S[i]; \n p.push_back(v * rtsamps);\n }\n\n // check\n double sum_c = 0.0; \n for(double pi: p) {\n sum_c += pi; \n }\n std::cerr << \"sum_c = \" << sum_c << \" (1-sum_c) = \" << (1.0 - sum_c) << std::endl; \n\n double X2 = -1.0 * ((double) N);\n \n for(int i = 0; i < S.size(); i++) {\n double m = N * p[i]; \n double xi = ((double) X[i]); \n \n X2 += (xi * xi / m); \n }\n\n return X2; \n}\n\ndouble ChiSquared::test(const std::vector & S, const std::vector X)\n{\n int k = S.size(); \n \n return 1.0 - boost::math::gamma_p(((double) k) * 0.5, pearsonCTS(S, X) * 0.5);\n}\n\n\n", "meta": {"hexsha": "0b4ca778de25f4fae412d77a36b3f2aeb3f4ba6c", "size": 1510, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/ChiSquared.cxx", "max_stars_repo_name": "kb1vc/WSPRLog", "max_stars_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ChiSquared.cxx", "max_issues_repo_name": "kb1vc/WSPRLog", "max_issues_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ChiSquared.cxx", "max_forks_repo_name": "kb1vc/WSPRLog", "max_forks_repo_head_hexsha": "0c0121f9050a249905c3e72f2520479d60acba7c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3548387097, "max_line_length": 85, "alphanum_fraction": 0.5728476821, "num_tokens": 510, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206686206199, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6675785555060704}} {"text": "#ifndef SPLINE_SPLINE_HPP\n#define SPLINE_SPLINE_HPP\n\n#include \n#include \n#include \n#include \n\nclass QuadraticSplineSegment {\npublic:\n\n void setCtrlPointsAbscissa(double x_1, double x_2) {\n x1 = x_1;\n x2 = x_2;\n }\n\n void setCtrlPointsOrdinate(double y_1, double y_2) {\n y1 = y_1;\n y2 = y_2;\n }\n\n void setTangent(double tangent) {\n t1 = tangent;\n }\n\n bool computeParams() {\n Eigen::Matrix3d A;\n Eigen::Vector3d Y, X;\n\n A << pow(x1, 2), x1, 1,\n pow(x2, 2), x2, 1,\n 2 * x1, 1, 0;\n\n Y << y1, y2, t1;\n\n X = A.colPivHouseholderQr().solve(Y);\n\n a2 = X[0];\n a1 = X[1];\n a0 = X[2];\n std::cout << a2 << \" \" << a1 << \" \" << a0 << std::endl;\n }\n\n void getParams(double &a_2, double &a_1, double &a_0) const {\n a_2 = a2;\n a_1 = a1;\n a_0 = a0;\n }\n\n double getTangent() const {\n return t1;\n }\n\n double arcLength(double gamma) {\n computeParams();\n double yi = y1, yi1, xi = x1, xi1, len, ti;\n while (norm(xi - x2, yi - y2) > gamma * 3) {\n ti = evalDerivative(xi);\n yi = evalFunction(xi);\n xi1 = xi + gamma / norm(1, ti);\n yi1 = evalFunction(xi1);\n len += norm(xi1 - xi, yi1 - yi);\n std::cout << ((norm(xi - x2, yi - y2) - gamma) / gamma - 1.0) * 100 << \" \" << xi << std::endl;\n xi = xi1;\n }\n return len;\n }\n\n double evalFunction(double x) const {\n return a2 * pow(x, 2) + a1 * x + a0;\n }\n\n double evalDerivative(double x) const {\n return a2 * x + a1;\n }\n\nprotected:\n\n static inline double norm(double x, double y) {\n return sqrt(pow(x, 2) + pow(y, 2));\n }\n\n double t1, x1, x2, y1, y2;\n double a2, a1, a0;\n};\n\nclass QuadraticSplineCurve {\npublic:\n\n explicit QuadraticSplineCurve(std::vector> coordinates, double tangent) : coord(\n std::move(coordinates)), t(tangent) {}\n\n void compute() {\n QuadraticSplineSegment segment{};\n double x1, y1, x2, y2;\n\n for (int i = 0; i < coord.size() - 1; ++i) {\n auto pts1 = coord[i];\n auto pts2 = coord[i + 1];\n x1 = pts1[0];\n y1 = pts1[1];\n x2 = pts2[0];\n y2 = pts2[1];\n\n segment.setCtrlPointsAbscissa(x1, x2);\n segment.setCtrlPointsOrdinate(y1, y2);\n\n if (i == 0) {\n segment.setTangent(t);\n } else {\n segment.setTangent(curve[curve.size() - 1].evalDerivative(x2));\n }\n\n segment.computeParams();\n\n curve.push_back(segment);\n }\n }\n\n double evalFunction(double x) {\n double x1, x2;\n\n for (int i = 0; i < coord.size() - 1; ++i) {\n\n auto pts1 = coord[i];\n auto pts2 = coord[i + 1];\n\n x1 = pts1[0];\n x2 = pts2[0];\n\n if (x1 < x2) {\n if ((x >= x1) and (x <= x2)) {\n return curve[i].evalFunction(x);\n }\n } else {\n if ((x <= x1) and (x >= x2)) {\n return curve[i].evalFunction(x);\n }\n }\n }\n }\n\n double length(double gamma) {\n cLength = 0;\n for (auto segment : curve) {\n cLength += segment.arcLength(gamma/1000.0);\n }\n }\n\nprotected:\n std::vector> coord;\n std::vector curve;\n double t, cLength{};\n};\n\n#endif //SPLINE_SPLINE_HPP\n", "meta": {"hexsha": "7268666312ba8918aa46584c9445fcdfaa1a13ed", "size": 3662, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Spline.hpp", "max_stars_repo_name": "dcmde/spline", "max_stars_repo_head_hexsha": "3a4990c2d446651666115714c14c5265ed7f182d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/Spline.hpp", "max_issues_repo_name": "dcmde/spline", "max_issues_repo_head_hexsha": "3a4990c2d446651666115714c14c5265ed7f182d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Spline.hpp", "max_forks_repo_name": "dcmde/spline", "max_forks_repo_head_hexsha": "3a4990c2d446651666115714c14c5265ed7f182d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3248407643, "max_line_length": 106, "alphanum_fraction": 0.4751501912, "num_tokens": 1085, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569268, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6675785522880643}} {"text": "// g2o sphere\n// based on https://github.com/RainerKuemmerle/g2o/blob/master/g2o/examples/sphere/create_sphere.cpp\n// reference 1 : https://malcolmmielle.wordpress.com/2016/06/20/g2o-optimization/\n// reference 2 : http://fzheng.me/2016/03/15/g2o-demo/\n// Created by Seung-Chan Kim on 12/29/16.\n\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"g2o/types/slam3d/vertex_se3.h\"\n#include \"g2o/types/slam3d/edge_se3.h\"\n#include \"g2o/stuff/sampler.h\"\n#include \"g2o/stuff/command_args.h\"\n#include \"g2o/core/factory.h\"\n\n\n#include \"g2o/core/sparse_optimizer.h\"\n#include \"g2o/core/block_solver.h\"\n#include \"g2o/core/optimization_algorithm_gauss_newton.h\"\n#include \"g2o/core/optimization_algorithm_levenberg.h\"\n#include \"g2o/solvers/csparse/linear_solver_csparse.h\"\n\n\nusing namespace std;\nusing namespace g2o;\n\nint main(int argc, char** argv)\n{\n // command line parsing\n int nodesPerLevel;\n int numLaps;\n bool randomSeed;\n double radius;\n std::vector noiseTranslation;\n std::vector noiseRotation;\n string outFilename;\n CommandArgs arg;\n arg.param(\"o\", outFilename, \"-\", \"output filename\");\n arg.param(\"nodesPerLevel\", nodesPerLevel, 50, \"how many nodes per lap on the sphere\");\n arg.param(\"laps\", numLaps, 50, \"how many times the robot travels around the sphere\");\n arg.param(\"radius\", radius, 100., \"radius of the sphere\");\n arg.param(\"noiseTranslation\", noiseTranslation, std::vector(), \"set the noise level for the translation, separated by semicolons without spaces e.g: \\\"0.1;0.1;0.1\\\"\");\n arg.param(\"noiseRotation\", noiseRotation, std::vector(), \"set the noise level for the rotation, separated by semicolons without spaces e.g: \\\"0.001;0.001;0.001\\\"\");\n arg.param(\"randomSeed\", randomSeed, false, \"use a randomized seed for generating the sphere\");\n arg.parseArgs(argc, argv);\n\n if (noiseTranslation.size() == 0)\n {\n cerr << \"using default noise for the translation\" << endl;\n noiseTranslation.push_back(0.01);\n noiseTranslation.push_back(0.01);\n noiseTranslation.push_back(0.01);\n }\n cerr << \"Noise for the translation:\";\n for (size_t i = 0; i < noiseTranslation.size(); ++i)\n cerr << \" \" << noiseTranslation[i];\n cerr << endl;\n if (noiseRotation.size() == 0)\n {\n cerr << \"using default noise for the rotation\" << endl;\n noiseRotation.push_back(0.005);\n noiseRotation.push_back(0.005);\n noiseRotation.push_back(0.005);\n }\n cerr << \"Noise for the rotation:\";\n for (size_t i = 0; i < noiseRotation.size(); ++i)\n cerr << \" \" << noiseRotation[i];\n cerr << endl;\n\n Eigen::Matrix3d transNoise = Eigen::Matrix3d::Zero();\n /*\n 0 0 0\n 0 0 0\n 0 0 0\n */\n\n for (int i = 0; i < 3; ++i)\n transNoise(i, i) = std::pow(noiseTranslation[i], 2);\n\n\n Eigen::Matrix3d rotNoise = Eigen::Matrix3d::Zero();\n for (int i = 0; i < 3; ++i)\n rotNoise(i, i) = std::pow(noiseRotation[i], 2);\n cout << \"transNoise =\" < information = Eigen::Matrix::Zero();\n information.block<3,3>(0,0) = transNoise.inverse();\n information.block<3,3>(3,3) = rotNoise.inverse();\n\n // information matrix represents how reliable this measurement is. Therefore, the more precisely the measurement is made or the more you trust in this measurement, the larger values in the information matrix you can set. (see http://fzheng.me/2016/03/15/g2o-demo/ )\n cout << \"information =\" < vertices;\n vector odometryEdges;\n vector edges;\n \n // create the optimizer to load the data and carry out the optimization\n SparseOptimizer optimizer;\n \n int id = 0;\n FILE *fp = fopen(\"out_t.txt\", \"w+\");\n for (int f = 0; f < numLaps; ++f)\n {\n for (int n = 0; n < nodesPerLevel; ++n)\n {\n VertexSE3* v = new VertexSE3;\n v->setId(id++);\n \n if(id==1)\n v->setFixed( true );\n\n Eigen::AngleAxisd rotz(-M_PI + 2*n*M_PI / nodesPerLevel, Eigen::Vector3d::UnitZ());\n Eigen::AngleAxisd roty(-0.5*M_PI + id*M_PI / (numLaps * nodesPerLevel), Eigen::Vector3d::UnitY());\n Eigen::Matrix3d rot = (rotz * roty).toRotationMatrix();\n\n Eigen::Isometry3d t;\n t = rot;\n t.translation() = t.linear() * Eigen::Vector3d(radius, 0, 0);\n //cout << t.translation().transpose() <setEstimate(t);\n vertices.push_back(v);\n\n optimizer.addVertex(v);\n //row-wise\n fprintf(fp, \"%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\t%f\\n\",\n t(0,0), t(0,1),t(0,2), t(0,3),\n t(1,0), t(1,1),t(1,2), t(1,3),\n t(2,0), t(2,1),t(2,2), t(2,3),\n t(3,0), t(3,1),t(3,2), t(3,3) );\n }\n }\n fclose(fp);\n\n // generate odometry edges\n for (size_t i = 1; i < vertices.size(); ++i) {\n VertexSE3* prev = vertices[i-1];\n VertexSE3* cur = vertices[i];\n Eigen::Isometry3d t = prev->estimate().inverse() * cur->estimate();\n EdgeSE3* e = new EdgeSE3;\n e->setVertex(0, prev);\n e->setVertex(1, cur);\n e->setMeasurement(t);\n e->setInformation(information);\n odometryEdges.push_back(e);\n edges.push_back(e);\n optimizer.addEdge(e);\n }\n\n // generate loop closure edges\n fp = fopen(\"out_loopclosure_from+to.txt\", \"w+\");\n for (int f = 1; f < numLaps; ++f) {\n for (int nn = 0; nn < nodesPerLevel; ++nn) {\n VertexSE3* from = vertices[(f-1)*nodesPerLevel + nn];\n //row-wise\n Eigen::Isometry3d tf = from->estimate();\n\n for (int n = -1; n <= 1; ++n) // set three vertices\n {\n if (f == numLaps-1 && n == 1)\n continue;\n // VertexSE3* from = vertices[(f-1)*nodesPerLevel + nn];\n VertexSE3* to = vertices[f*nodesPerLevel + nn + n]; // one-level위에서 3개의 vertices와 연결\n Eigen::Isometry3d t = from->estimate().inverse() * to->estimate();\n EdgeSE3* e = new EdgeSE3;\n e->setVertex(0, from);\n e->setVertex(1, to);\n e->setMeasurement(t);\n e->setInformation(information);\n edges.push_back(e);\n optimizer.addEdge(e); // what happens if commented out?\n \n Eigen::Isometry3d tt = to->estimate();\n fprintf(fp, \"%f\\t%f\\t%f\\t%f\\t\\t\", tf(0,3),tf(1,3),tf(2,3),tf(3,3) );\n fprintf(fp, \"%f\\t%f\\t%f\\t%f\\n\", tt(0,3),tt(1,3),tt(2,3),tt(3,3) );\n }\n //fprintf(fp, \"\\n\");\n }\n }\n fclose(fp);\n\n GaussianSampler transSampler;\n transSampler.setDistribution(transNoise);\n GaussianSampler rotSampler;\n rotSampler.setDistribution(rotNoise);\n\n#if 0\n if (randomSeed)\n {\n std::random_device r;\n std::seed_seq seedSeq{r(), r(), r(), r(), r()};\n vector seeds(2);\n seedSeq.generate(seeds.begin(), seeds.end());\n cerr << \"using seeds:\";\n for (size_t i = 0; i < seeds.size(); ++i)\n cerr << \" \" << seeds[i];\n cerr << endl;\n transSampler.seed(seeds[0]); // error ?\n rotSampler.seed(seeds[1]);\n }\n#endif\n\n // noise for all the edges\n for (size_t i = 0; i < edges.size(); ++i)\n {\n EdgeSE3* e = edges[i];\n Eigen::Quaterniond gtQuat = (Eigen::Quaterniond)e->measurement().linear();\n Eigen::Vector3d gtTrans = e->measurement().translation();\n\n Eigen::Vector3d quatXYZ = rotSampler.generateSample();\n double qw = 1.0 - quatXYZ.norm();\n if (qw < 0)\n {\n qw = 0.;\n cerr << \"x\";\n }\n Eigen::Quaterniond rot(qw, quatXYZ.x(), quatXYZ.y(), quatXYZ.z());\n rot.normalize();\n Eigen::Vector3d trans = transSampler.generateSample();\n rot = gtQuat * rot;\n trans = gtTrans + trans;\n\n Eigen::Isometry3d noisyMeasurement = (Eigen::Isometry3d) rot;\n noisyMeasurement.translation() = trans;\n e->setMeasurement(noisyMeasurement);\n }\n\n\n // concatenate all the odometry constraints to compute the initial state\n // An hyper graph is a graph where an edge can connect one or more nodes.\n for (size_t i =0; i < odometryEdges.size(); ++i)\n {\n EdgeSE3* e = edges[i];\n VertexSE3* from = static_cast(e->vertex(0));\n VertexSE3* to = static_cast(e->vertex(1));\n HyperGraph::VertexSet aux;\n aux.insert(from);\n e->initialEstimate(aux, to);\n }\n\n // write output\n ofstream fileOutputStream;\n if (outFilename != \"-\")\n {\n //cerr << \"Writing into \" << outFilename << endl;\n //fileOutputStream.open(outFilename.c_str());\n }\n else\n {\n //cerr << \"writing to stdout\" << endl;\n outFilename = \"out_vertex+edge.g2o\";\n\n }\n cerr << \"Writing into \" << outFilename << endl;\n fileOutputStream.open(outFilename.c_str());\n\n string vertexTag = Factory::instance()->tag(vertices[0]);\n string edgeTag = Factory::instance()->tag(edges[0]);\n cout << \"vertexTag = \"<< vertexTag << endl;\n cout << \"edgeTag = \"<< edgeTag << endl;\n \n ostream& fout = outFilename != \"-\" ? fileOutputStream : cout;\n for (size_t i = 0; i < vertices.size(); ++i)\n {\n VertexSE3* v = vertices[i];\n fout << vertexTag << \" \" << v->id() << \" \";\n v->write(fout);\n fout << endl;\n }\n\n\n for (size_t i = 0; i < edges.size(); ++i)\n {\n EdgeSE3* e = edges[i];\n VertexSE3* from = static_cast(e->vertex(0));\n VertexSE3* to = static_cast(e->vertex(1));\n fout << edgeTag << \" \" << from->id() << \" \" << to->id() << \" \";\n e->write(fout);\n fout << endl;\n }\n\n // write output\n fp = fopen(\"out_vertices_before.txt\", \"w\");\n for(int i=0; iestimate();\n //cout<<\"vertex pose(before)=\"<();\n \n // create the block solver on top of the linear solver\n BlockSolverX* blockSolver = new BlockSolverX(linearSolver);\n\n \n // create the algorithm to carry out the optimization\n //OptimizationAlgorithmGaussNewton* optimizationAlgorithm = new OptimizationAlgorithmGaussNewton(blockSolver);\n OptimizationAlgorithmLevenberg* optimizationAlgorithm = new OptimizationAlgorithmLevenberg(blockSolver);\n\n \n optimizer.setVerbose(true);\n optimizer.setAlgorithm(optimizationAlgorithm);\n \n int maxIterations = 10;\n \n \n optimizer.initializeOptimization();\n optimizer.optimize(maxIterations);\n\n // Visulizing only points (w/o pose)\n fp = fopen(\"out_vertices_after.txt\", \"w\");\n for(size_t i=0; i( optimizer.vertex(i) );\n Eigen::Isometry3d t = v->estimate();\n //cout<<\"vertex pose(after)=\"<,\n * Copyright (c) 2020 Christian Eskil Vaugelade Berg\n * @author Christian Eskil Vaugelade Berg\n*/\n#pragma once\n\n#include \n\n#include \n\nnamespace orient {\n\n// \\brief Calculate rotation matrix from quaternion\n// Quaternion is expressed as a 4D-vector [w,a,b,c] such that\n// q = w + a*i + b*j + c*k\n// \\param q Source quaternion\n// \\return Rotation matrix\ntemplate\nEigen::Matrix rotationMatrixFromQuaternion(Eigen::Matrix const& q);\n\n// \\brief Calculate rotation matrix and partial derivatives from quaternion\n// See above for more detail\n// \\param q Source quaternion\n// \\return A pair containg first the rotation matrix then secondly the Jacobian matrix \ntemplate\nstd::pair, Eigen::Matrix> rotationMatrixFromQuaternionWD(Eigen::Matrix const& q);\n\n// \\brief Calculate angle axis derivatives from quaternion\n// See above for more detail\n// \\param q Source quaternion\n// \\return Angle axis\ntemplate\nEigen::Matrix angleAxisFromQuaternion(Eigen::Matrix const& q);\n\n// \\brief Calculate angle axis and partial derivatives from quaternion\n// See above for more detail\n// \\param q Source quaternion\n// \\return A pair containg first the angle axis secondly the Jacobian matrix \ntemplate\nstd::pair, Eigen::Matrix> angleAxisFromQuaternionWD(Eigen::Matrix const& q);\n\n}\n\n#include \n", "meta": {"hexsha": "65bac322ee6910fb4432736db2b1c01d0d5a4699", "size": 1713, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orient/from_quaternion.hpp", "max_stars_repo_name": "Eskilade/orient", "max_stars_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T07:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T09:23:29.000Z", "max_issues_repo_path": "include/orient/from_quaternion.hpp", "max_issues_repo_name": "Eskilade/orient", "max_issues_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-20T02:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T01:42:47.000Z", "max_forks_repo_path": "include/orient/from_quaternion.hpp", "max_forks_repo_name": "Eskilade/orient", "max_forks_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T11:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T04:26:22.000Z", "avg_line_length": 37.2391304348, "max_line_length": 137, "alphanum_fraction": 0.7238762405, "num_tokens": 431, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970904940927, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6674630774115037}} {"text": "#pragma once\n#include \n#include \n#include \"ear/common_types.hpp\"\n#include \"ear/metadata.hpp\"\n\nnamespace ear {\n\n template \n inline T radians(T d) {\n return d * static_cast(boost::math::constants::pi() / 180.0);\n }\n\n template \n inline T degrees(T r) {\n return r * static_cast(180.0 / boost::math::constants::pi());\n }\n\n /** @brief Assuming y is clockwise from x, increment y by 360 until it's not\n * less than x.\n *\n * @param x Start angle in degrees.\n * @param y End angle in degrees.\n *\n * @returns y shifted such that it represents the same angle but is greater\n * than x.\n */\n inline double relativeAngle(double x, double y) {\n while (y - 360.0 >= x) {\n y -= 360.0;\n }\n while (y < x) {\n y += 360.0;\n }\n return y;\n }\n\n /** @brief Assuming end is clockwise from start, is the angle x inside\n * [start,end] within some tolerance?\n *\n * @param x Angle to test, in degrees\n * @param start Start angle of range, in degrees\n * @param end End angle of range, in degrees\n * @param tol Tolerance in degrees to check within\n */\n bool insideAngleRange(double x, double start, double end, double tol = 0.0);\n\n /** @brief Order the vertices of a convex, approximately planar polygon.\n *\n * @param vertices Vertices to order (n, 3)\n *\n * @returns Indices to put the vertices into the right order.\n */\n Eigen::VectorXi ngonVertexOrder(Eigen::MatrixXd vertices);\n\n double azimuth(Eigen::Vector3d position);\n double elevation(Eigen::Vector3d position);\n double distance(Eigen::Vector3d position);\n\n Eigen::Vector3d cart(double azimuth, double elevation, double distance);\n\n inline Eigen::RowVector3d cartT(double azimuth, double elevation,\n double distance) {\n return cart(azimuth, elevation, distance).transpose();\n }\n\n PolarPosition toPolarPosition(CartesianPosition position);\n CartesianPosition toCartesianPosition(PolarPosition position);\n Eigen::Vector3d toNormalisedVector3d(PolarPosition position);\n\n Eigen::Vector3d toCartesianVector3d(PolarPosition position);\n Eigen::Vector3d toCartesianVector3d(CartesianPosition position);\n Eigen::Vector3d toCartesianVector3d(SpeakerPosition position);\n Eigen::Vector3d toCartesianVector3d(PolarSpeakerPosition position);\n Eigen::Vector3d toCartesianVector3d(CartesianSpeakerPosition position);\n\n Eigen::MatrixXd toPositionsMatrix(\n const std::vector& positions);\n\n /** @brief Calc local coordinate system\n *\n * @param azimuth: ADM format azimuth\n * @param elevation: ADM format elevation\n *\n * @return Vectors pointing along x, y and z, rotated so that +y points at\n * cart(az, el, 1).\n */\n inline Eigen::Matrix3d localCoordinateSystem(double azimuth,\n double elevation) {\n Eigen::Matrix3d ret;\n ret << cartT(azimuth - 90.0, 0.0, 1.0), //\n cartT(azimuth, elevation, 1.0), //\n cartT(azimuth, elevation + 90.0, 1.0);\n return ret;\n }\n\n} // namespace ear\n", "meta": {"hexsha": "17a1a5bb28a8def4c4277ae10b504b65d0ad8a4d", "size": 3122, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/common/geom.hpp", "max_stars_repo_name": "rsjtaylor/libear", "max_stars_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2019-07-30T17:58:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T15:33:36.000Z", "max_issues_repo_path": "src/common/geom.hpp", "max_issues_repo_name": "rsjtaylor/libear", "max_issues_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2019-07-30T18:01:58.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-14T10:24:52.000Z", "max_forks_repo_path": "src/common/geom.hpp", "max_forks_repo_name": "rsjtaylor/libear", "max_forks_repo_head_hexsha": "40a4000296190c3f91eba79e5b92141e368bd72a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-07-30T15:12:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-14T16:22:43.000Z", "avg_line_length": 31.8571428571, "max_line_length": 78, "alphanum_fraction": 0.6768097373, "num_tokens": 816, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970873650401, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6674630750403252}} {"text": "/** @file 38.cpp Problem 38: Pandigital multiples\n *\n * Take the number 192 and multiply it by each of 1, 2, and 3:\n *\n * 192 x 1 = 192\n * 192 x 2 = 384\n * 192 x 3 = 576\n *\n * By concatenating each product we get the 1 to 9 pandigital, 192384576. We\n * will call 192384576 the concatenated product of 192 and (1,2,3)\n *\n * The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4,\n * and 5, giving the pandigital, 918273645, which is the concatenated product\n * of 9 and (1,2,3,4,5).\n *\n * What is the largest 1 to 9 pandigital 9-digit number that can be formed as\n * the concatenated product of an integer with (1,2, ... , n) where n > 1?\n */\n\n// At most eight values of n, 2 through 9, are worth considering; n < 2 is\n// explicitly prohibited by the problem description, and n > 9 will produce a\n// number that exceeds the specified (9-digit) length.\n//\n// Similarly, we can limit the values of the multiplicand `m` to those that\n// produce 9-digit concatenated products.\n\n#include \"int_util.hpp\" // pandigital\n\n/// @cond\n#include // counting_iterator\n#include // cpp_int\n\n#include // all_of\n#include // cout\n#include \n/// @endcond\n\nusing boost::make_counting_iterator;\nusing boost::multiprecision::cpp_int;\nusing int_util::length;\nusing int_util::pandigital;\n\ncpp_int cat_prod(cpp_int const& m, std::vector const& v)\n{\n std::string s;\n for (auto const& x : v)\n s += cpp_int(m * x).str();\n return cpp_int(s);\n}\n\nint main()\n{\n cpp_int r = 0;\n for (int n = 2; n <= 9; ++n) {\n std::vector v(\n make_counting_iterator(1),\n make_counting_iterator(n + 1));\n cpp_int m = 1;\n auto p = cat_prod(m, v);\n while (p.str().size() < 9) { // Skip products that are too short.\n ++m;\n p = cat_prod(m, v);\n }\n while (p.str().size() == 9) {\n if (p > r && pandigital(p))\n r = p;\n p = cat_prod(++m, v);\n }\n }\n std::cout << r << std::endl;\n}\n", "meta": {"hexsha": "74cdaff659cb84271a6a1487af6ce826887eea8c", "size": 2217, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/38.cpp", "max_stars_repo_name": "jeffs/cpp-euler", "max_stars_repo_head_hexsha": "b42a8a70fad782569a699a028968bc1a60bd5c44", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/38.cpp", "max_issues_repo_name": "jeffs/cpp-euler", "max_issues_repo_head_hexsha": "b42a8a70fad782569a699a028968bc1a60bd5c44", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/38.cpp", "max_forks_repo_name": "jeffs/cpp-euler", "max_forks_repo_head_hexsha": "b42a8a70fad782569a699a028968bc1a60bd5c44", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.7916666667, "max_line_length": 77, "alphanum_fraction": 0.5886332882, "num_tokens": 631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.667463068002375}} {"text": "#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \nusing namespace std;\nusing Sophus::SE3;\nusing Sophus::SO3;\n\n/************************************************\n * 本程序演示如何用g2o solver进行位姿图优化\n * sphere.g2o是人工生成的一个Pose graph,我们来优化它。\n * 尽管可以直接通过load函数读取整个图,但我们还是自己来实现读取代码,以期获得更深刻的理解\n * 本节使用李代数表达位姿图,节点和边的方式为自定义\n * **********************************************/\n\ntypedef Eigen::Matrix Matrix6d;\n\n// 给定误差求J_R^{-1}的近似\nMatrix6d JRInv( SE3 e )\n{\n Matrix6d J;\n J.block(0,0,3,3) = SO3::hat(e.so3().log());\n J.block(0,3,3,3) = SO3::hat(e.translation());\n J.block(3,0,3,3) = Eigen::Matrix3d::Zero(3,3);\n J.block(3,3,3,3) = SO3::hat(e.so3().log());\n J = J*0.5 + Matrix6d::Identity();\n return J;\n}\n// 李代数顶点\ntypedef Eigen::Matrix Vector6d;\nclass VertexSE3LieAlgebra: public g2o::BaseVertex<6, SE3>\n{\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n bool read ( istream& is )\n {\n double data[7];\n for ( int i=0; i<7; i++ )\n is>>data[i];\n setEstimate ( SE3 (\n Eigen::Quaterniond ( data[6],data[3], data[4], data[5] ),\n Eigen::Vector3d ( data[0], data[1], data[2] )\n ));\n }\n\n bool write ( ostream& os ) const\n {\n os<\n{\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n bool read ( istream& is )\n {\n double data[7];\n for ( int i=0; i<7; i++ )\n is>>data[i];\n Eigen::Quaterniond q ( data[6], data[3], data[4], data[5] );\n q.normalize();\n setMeasurement (\n Sophus::SE3 ( q, Eigen::Vector3d ( data[0], data[1], data[2] ) ) \n );\n for ( int i=0; i> information() ( i,j );\n if ( i!=j )\n information() ( j,i ) =information() ( i,j );\n }\n return true;\n }\n bool write ( ostream& os ) const\n {\n VertexSE3LieAlgebra* v1 = static_cast (_vertices[0]);\n VertexSE3LieAlgebra* v2 = static_cast (_vertices[1]);\n os<id()<<\" \"<id()<<\" \";\n SE3 m = _measurement;\n Eigen::Quaterniond q = m.unit_quaternion();\n os< (_vertices[0]))->estimate();\n Sophus::SE3 v2 = (static_cast (_vertices[1]))->estimate();\n _error = (_measurement.inverse()*v1.inverse()*v2).log();\n }\n \n // 雅可比计算\n virtual void linearizeOplus()\n {\n Sophus::SE3 v1 = (static_cast (_vertices[0]))->estimate();\n Sophus::SE3 v2 = (static_cast (_vertices[1]))->estimate();\n Matrix6d J = JRInv(SE3::exp(_error));\n // 尝试把J近似为I?\n _jacobianOplusXi = - J* v2.inverse().Adj();\n _jacobianOplusXj = J*v2.inverse().Adj();\n }\n};\n\nint main ( int argc, char** argv )\n{\n if ( argc != 2 )\n {\n cout<<\"Usage: pose_graph_g2o_SE3_lie sphere.g2o\"<> Block; // BlockSolver为6x6\n Block::LinearSolverType* linearSolver = new g2o::LinearSolverCholmod(); // 线性方程求解器\n Block* solver_ptr = new Block ( linearSolver ); // 矩阵块求解器\n g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr );\n // 试试G-N或Dogleg?\n // g2o::OptimizationAlgorithmDogleg* solver = new g2o::OptimizationAlgorithmDogleg( solver_ptr );\n // g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton ( solver_ptr );\n \n g2o::SparseOptimizer optimizer; // 图模型\n optimizer.setAlgorithm ( solver ); // 设置求解器\n\n int vertexCnt = 0, edgeCnt = 0; // 顶点和边的数量\n \n vector vectices;\n vector edges;\n while ( !fin.eof() )\n {\n string name;\n fin>>name;\n if ( name == \"VERTEX_SE3:QUAT\" )\n {\n // 顶点\n VertexSE3LieAlgebra* v = new VertexSE3LieAlgebra();\n int index = 0;\n fin>>index;\n v->setId( index );\n v->read(fin);\n optimizer.addVertex(v);\n vertexCnt++;\n vectices.push_back(v);\n if ( index==0 )\n v->setFixed(true);\n }\n else if ( name==\"EDGE_SE3:QUAT\" )\n {\n // SE3-SE3 边\n EdgeSE3LieAlgebra* e = new EdgeSE3LieAlgebra();\n int idx1, idx2; // 关联的两个顶点\n fin>>idx1>>idx2;\n e->setId( edgeCnt++ );\n e->setVertex( 0, optimizer.vertices()[idx1] );\n e->setVertex( 1, optimizer.vertices()[idx2] );\n e->read(fin);\n optimizer.addEdge(e);\n edges.push_back(e);\n }\n if ( !fin.good() ) break;\n }\n\n cout<<\"read total \"<write(fout);\n }\n for ( EdgeSE3LieAlgebra* e:edges )\n {\n fout<<\"EDGE_SE3:QUAT \";\n e->write(fout);\n }\n fout.close();\n return 0;\n}\n", "meta": {"hexsha": "80ee9fe6eda018a598db59c2e38657a8d99c6690", "size": 7368, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch11/pose_graph_g2o_lie_algebra.cpp", "max_stars_repo_name": "seanleecn/learn_SLAM14", "max_stars_repo_head_hexsha": "d86501efcad7a95d545b53968864f4d61f0a4b8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch11/pose_graph_g2o_lie_algebra.cpp", "max_issues_repo_name": "seanleecn/learn_SLAM14", "max_issues_repo_head_hexsha": "d86501efcad7a95d545b53968864f4d61f0a4b8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch11/pose_graph_g2o_lie_algebra.cpp", "max_forks_repo_name": "seanleecn/learn_SLAM14", "max_forks_repo_head_hexsha": "d86501efcad7a95d545b53968864f4d61f0a4b8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.6223175966, "max_line_length": 112, "alphanum_fraction": 0.5571389794, "num_tokens": 2300, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767906859265, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6674532887833668}} {"text": "// (C) Copyright Matt Borland 2021.\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0. (See accompanying file\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_STATISTICS_Z_TEST_HPP\n#define BOOST_MATH_STATISTICS_Z_TEST_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace boost { namespace math { namespace statistics { namespace detail {\n\ntemplate\nReturnType one_sample_z_test_impl(T sample_mean, T sample_variance, T sample_size, T assumed_mean)\n{\n using Real = typename std::tuple_element<0, ReturnType>::type;\n using std::sqrt;\n using no_promote_policy = boost::math::policies::policy, boost::math::policies::promote_double>;\n\n Real test_statistic = (sample_mean - assumed_mean) / (sample_variance / sqrt(sample_size));\n auto z = boost::math::normal_distribution(sample_size - 1);\n Real pvalue;\n if(test_statistic > 0)\n {\n pvalue = 2*boost::math::cdf(z, -test_statistic);\n }\n else\n {\n pvalue = 2*boost::math::cdf(z, test_statistic);\n }\n\n return std::make_pair(test_statistic, pvalue);\n}\n\ntemplate\nReturnType one_sample_z_test_impl(ForwardIterator begin, ForwardIterator end, typename std::iterator_traits::value_type assumed_mean) \n{\n using Real = typename std::tuple_element<0, ReturnType>::type;\n std::pair temp = mean_and_sample_variance(begin, end);\n Real mu = std::get<0>(temp);\n Real s_sq = std::get<1>(temp);\n return one_sample_z_test_impl(mu, s_sq, Real(std::distance(begin, end)), Real(assumed_mean));\n}\n\ntemplate\nReturnType two_sample_z_test_impl(T mean_1, T variance_1, T size_1, T mean_2, T variance_2, T size_2)\n{\n using Real = typename std::tuple_element<0, ReturnType>::type;\n using std::sqrt;\n using no_promote_policy = boost::math::policies::policy, boost::math::policies::promote_double>;\n\n Real test_statistic = (mean_1 - mean_2) / sqrt(variance_1/size_1 + variance_2/size_2);\n auto z = boost::math::normal_distribution(size_1 + size_2 - 1);\n Real pvalue;\n if(test_statistic > 0)\n {\n pvalue = 2*boost::math::cdf(z, -test_statistic);\n }\n else\n {\n pvalue = 2*boost::math::cdf(z, test_statistic);\n }\n\n return std::make_pair(test_statistic, pvalue);\n}\n\ntemplate\nReturnType two_sample_z_test_impl(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2)\n{\n using Real = typename std::tuple_element<0, ReturnType>::type;\n using std::sqrt;\n auto n1 = std::distance(begin_1, end_1);\n auto n2 = std::distance(begin_2, end_2);\n\n ReturnType temp_1 = mean_and_sample_variance(begin_1, end_1);\n Real mean_1 = std::get<0>(temp_1);\n Real variance_1 = std::get<1>(temp_1);\n\n ReturnType temp_2 = mean_and_sample_variance(begin_2, end_2);\n Real mean_2 = std::get<0>(temp_2);\n Real variance_2 = std::get<1>(temp_2);\n\n return two_sample_z_test_impl(mean_1, variance_1, Real(n1), mean_2, variance_2, Real(n2));\n}\n\n} // detail\n\ntemplate::value, bool>::type = true>\ninline auto one_sample_z_test(Real sample_mean, Real sample_variance, Real sample_size, Real assumed_mean) -> std::pair\n{\n return detail::one_sample_z_test_impl>(sample_mean, sample_variance, sample_size, assumed_mean);\n}\n\ntemplate::value, bool>::type = true>\ninline auto one_sample_z_test(Real sample_mean, Real sample_variance, Real sample_size, Real assumed_mean) -> std::pair\n{\n return detail::one_sample_z_test_impl>(sample_mean, sample_variance, sample_size, assumed_mean);\n}\n\ntemplate::value_type, \n typename std::enable_if::value, bool>::type = true>\ninline auto one_sample_z_test(ForwardIterator begin, ForwardIterator end, Real assumed_mean) -> std::pair\n{\n return detail::one_sample_z_test_impl>(begin, end, assumed_mean);\n}\n\ntemplate::value_type, \n typename std::enable_if::value, bool>::type = true>\ninline auto one_sample_z_test(ForwardIterator begin, ForwardIterator end, Real assumed_mean) -> std::pair\n{\n return detail::one_sample_z_test_impl>(begin, end, assumed_mean);\n}\n\ntemplate::value, bool>::type = true>\ninline auto one_sample_z_test(Container const & v, Real assumed_mean) -> std::pair\n{\n return detail::one_sample_z_test_impl>(std::begin(v), std::end(v), assumed_mean);\n}\n\ntemplate::value, bool>::type = true>\ninline auto one_sample_z_test(Container const & v, Real assumed_mean) -> std::pair\n{\n return detail::one_sample_z_test_impl>(std::begin(v), std::end(v), assumed_mean);\n}\n\ntemplate::value_type, \n typename std::enable_if::value, bool>::type = true>\ninline auto two_sample_z_test(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2) -> std::pair\n{\n return detail::two_sample_z_test_impl>(begin_1, end_1, begin_2, end_2);\n}\n\ntemplate::value_type, \n typename std::enable_if::value, bool>::type = true>\ninline auto two_sample_z_test(ForwardIterator begin_1, ForwardIterator end_1, ForwardIterator begin_2, ForwardIterator end_2) -> std::pair\n{\n return detail::two_sample_z_test_impl>(begin_1, end_1, begin_2, end_2);\n}\n\ntemplate::value, bool>::type = true>\ninline auto two_sample_z_test(Container const & u, Container const & v) -> std::pair\n{\n return detail::two_sample_z_test_impl>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n}\n\ntemplate::value, bool>::type = true>\ninline auto two_sample_z_test(Container const & u, Container const & v) -> std::pair\n{\n return detail::two_sample_z_test_impl>(std::begin(u), std::end(u), std::begin(v), std::end(v));\n}\n\n}}} // boost::math::statistics\n\n#endif // BOOST_MATH_STATISTICS_Z_TEST_HPP\n", "meta": {"hexsha": "a8ef838e40bf1d04a9a39ac4c83e7e51c753d547", "size": 7597, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/statistics/z_test.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 310.0, "max_stars_repo_stars_event_min_datetime": "2017-02-02T09:14:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T06:50:11.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/statistics/z_test.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/math/statistics/z_test.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 46.8950617284, "max_line_length": 154, "alphanum_fraction": 0.7422666842, "num_tokens": 1930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563335, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6673745122571033}} {"text": "\n#pragma once\n\n#include \n\nnamespace ilqr\n{\n\n// Helper class to store the terms of the quadratic value function.\nclass QuadraticValue \n{\npublic:\n // Inititalizes the Value function terms V_, G_, W_ to zeros.\n QuadraticValue(const int state_dim);\n\n Eigen::MatrixXd& V() { return V_; }\n Eigen::MatrixXd& G() { return G_; }\n double& W() { return W_; }\n\n const Eigen::MatrixXd& V() const { return V_; }\n const Eigen::MatrixXd& G() const { return G_; }\n const double& W() const { return W_; }\n\nprivate:\n // Quadratic term [dim(x)] x [dim(x)]\n Eigen::MatrixXd V_;\n // Linear term [1] x [dim(x)]\n Eigen::MatrixXd G_;\n // Constant term [1] x [1]\n double W_;\n};\n\n// Dynamics Function Prototype. Takes state, control and returns the next state.\nusing DynamicsFunc = std::function; \n\n// Cost Function Prototype. Takes state, control and returns a real-valued cost.\nusing CostFunc = std::function; \n\n// Linearized dynamics parameters in terms of the state [x].\nstruct Dynamics\n{\n // Linear dynamics matrix. [dim(x)] x [dim(x)]\n // (extension is last row is [\\vec{0}, 1])\n Eigen::MatrixXd A;\n\n // Controls matrix. [dim(x)] x [dim(u)]\n // (extension is last row is [\\vec{0}])\n Eigen::MatrixXd B;\n};\n\n// Quadratic cost parameters in terms of the state x and control u.\nstruct Cost \n{\n // Quadratic state-cost matrix. [dim(x)] x [dim(x)]\n Eigen::MatrixXd Q;\n\n // Cost cross-term matrix. [dim(x)] x [dim(u)]\n Eigen::MatrixXd P;\n\n // Quadratic control-cost matrix. [dim(u)] x [dim(u)]\n Eigen::MatrixXd R;\n\n // Linear control-cost matrix. [dim(u)] x [1]\n Eigen::VectorXd g_u;\n\n // Linear control-cost matrix. [dim(x)] x [1]\n Eigen::VectorXd g_x;\n\n // Constant offset term\n double c;\n};\n\n\nilqr::Dynamics linearize_dynamics(const DynamicsFunc &dynamics_func, \n const Eigen::VectorXd &x, \n const Eigen::VectorXd &u);\n\nilqr::Cost quadraticize_cost(const CostFunc &cost_func, \n const Eigen::VectorXd &x, \n const Eigen::VectorXd &u);\n\n} // namespace ilqr\n\n", "meta": {"hexsha": "279055be4794c64372b5b1d9786c410ac7f02ccf", "size": 2251, "ext": "hh", "lang": "C++", "max_stars_repo_path": "src/ilqr/ilqr_taylor_expansions.hh", "max_stars_repo_name": "LAIRLAB/qr_trees", "max_stars_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-06-16T08:42:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-16T08:42:33.000Z", "max_issues_repo_path": "src/ilqr/ilqr_taylor_expansions.hh", "max_issues_repo_name": "LAIRLAB/qr_trees", "max_issues_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ilqr/ilqr_taylor_expansions.hh", "max_forks_repo_name": "LAIRLAB/qr_trees", "max_forks_repo_head_hexsha": "66eb7310daa1d9978158198a508d02bf2128a377", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2017-07-10T03:25:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-22T15:58:44.000Z", "avg_line_length": 26.7976190476, "max_line_length": 100, "alphanum_fraction": 0.6268325189, "num_tokens": 575, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253256, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6673437821496067}} {"text": "// (C) Copyright Nick Thompson 2020.\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0. (See accompanying file\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// Deliberately contains some unicode characters:\n// \n// boost-no-inspect\n//\n#include \n#include \n#include \n#include \n\nusing boost::math::constants::root_two;\nusing boost::math::constants::phi;\nusing boost::math::constants::pi;\nusing boost::math::constants::e;\nusing boost::math::constants::zeta_three;\nusing boost::math::tools::centered_continued_fraction;\nusing boost::multiprecision::mpfr_float;\n\nint main()\n{\n using Real = mpfr_float;\n int p = 10000;\n mpfr_float::default_precision(p);\n auto phi_cfrac = centered_continued_fraction(phi());\n std::cout << \"φ ≈ \" << phi_cfrac << \"\\n\";\n std::cout << \"Khinchin mean: \" << std::setprecision(10) << phi_cfrac.khinchin_geometric_mean() << \"\\n\\n\\n\";\n\n auto pi_cfrac = centered_continued_fraction(pi());\n std::cout << \"π ≈ \" << pi_cfrac << \"\\n\";\n std::cout << \"Khinchin mean: \" << std::setprecision(10) << pi_cfrac.khinchin_geometric_mean() << \"\\n\\n\\n\";\n\n auto rt_cfrac = centered_continued_fraction(root_two());\n std::cout << \"√2 ≈ \" << rt_cfrac << \"\\n\";\n std::cout << \"Khinchin mean: \" << std::setprecision(10) << rt_cfrac.khinchin_geometric_mean() << \"\\n\\n\\n\";\n\n auto e_cfrac = centered_continued_fraction(e());\n std::cout << \"e ≈ \" << e_cfrac << \"\\n\";\n std::cout << \"Khinchin mean: \" << std::setprecision(10) << e_cfrac.khinchin_geometric_mean() << \"\\n\\n\\n\";\n\n auto z_cfrac = centered_continued_fraction(zeta_three());\n std::cout << \"ζ(3) ≈ \" << z_cfrac << \"\\n\";\n std::cout << \"Khinchin mean: \" << std::setprecision(10) << z_cfrac.khinchin_geometric_mean() << \"\\n\\n\\n\";\n\n\n // http://jeremiebourdon.free.fr/data/Khintchine.pdf\n std::cout << \"The expected Khinchin mean for a random centered continued fraction is 5.45451724454\\n\";\n}\n", "meta": {"hexsha": "6d357d2b913531339b6d2c137d858e86535e3c29", "size": 2132, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/centered_continued_fraction.cpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "example/centered_continued_fraction.cpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "example/centered_continued_fraction.cpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 41.0, "max_line_length": 111, "alphanum_fraction": 0.6735459662, "num_tokens": 618, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6673437771408034}} {"text": "/**\n * @file finitevolumesineconslaw_main.cc\n * @brief NPDE homework \"FiniteVolumeSineConsLaw\" code\n * @author Oliver Rietmann\n * @date 25.04.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \n#include \n#include \n\n#include \"finitevolumesineconslaw.h\"\n\nusing namespace FiniteVolumeSineConsLaw;\n\nconst static Eigen::IOFormat CSVFormat(Eigen::FullPrecision,\n Eigen::DontAlignCols, \", \", \"\\n\");\n\nint main() {\n /* SAM_LISTING_BEGIN_1 */\n unsigned int N = 600;\n unsigned int M = 200;\n double h = 12.0 / N;\n Eigen::VectorXd x =\n Eigen::VectorXd::LinSpaced(N, -6.0 + 0.5 * h, 6.0 - 0.5 * h);\n\n std::ofstream file;\n\n // without reaction term\n Eigen::VectorXd ufinal = solveSineConsLaw(&sineClawRhs, N, M);\n#if SOLUTION\n file.open(\"ufinal.csv\");\n file << x.transpose().format(CSVFormat) << std::endl;\n file << ufinal.transpose().format(CSVFormat) << std::endl;\n file.close();\n\n std::cout << \"Generated \" CURRENT_BINARY_DIR \"/ufinal.csv\" << std::endl;\n std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot.py \" CURRENT_BINARY_DIR\n \"/ufinal.csv \" CURRENT_BINARY_DIR \"/ufinal.eps\");\n#else\n //====================\n // Your code goes here\n // Use std::ofstream to write the solution to\n // the file \"ufinal.csv\". To plot this\n // file you may uncomment the following line:\n // std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot.py \" CURRENT_BINARY_DIR\n // \"/ufinal.csv \" CURRENT_BINARY_DIR \"/ufinal.eps\");\n //====================\n#endif\n /* SAM_LISTING_END_1 */\n\n // with reaction term: -c * u(x, t), where c = 1.0\n double c = 1.0;\n auto bind_c = [c](const Eigen::VectorXd &mu) {\n return sineClawReactionRhs(mu, c);\n };\n Eigen::VectorXd ufinal_reaction = solveSineConsLaw(bind_c, N, M);\n#if SOLUTION\n file.open(\"ufinal_reaction.csv\");\n file << x.transpose().format(CSVFormat) << std::endl;\n file << ufinal_reaction.transpose().format(CSVFormat) << std::endl;\n file.close();\n\n std::cout << \"Generated \" CURRENT_BINARY_DIR \"/ufinal_reaction.csv\"\n << std::endl;\n std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot.py \" CURRENT_BINARY_DIR\n \"/ufinal_reaction.csv \" CURRENT_BINARY_DIR\n \"/ufinal_reaction.eps\");\n#else\n //====================\n // Your code goes here\n // Use std::ofstream to write the solution to\n // the file \"ufinal_reaction.csv\". To plot this\n // file you may uncomment the following line:\n // std::system(\"python3 \" CURRENT_SOURCE_DIR \"/plot.py \" CURRENT_BINARY_DIR\n // \"/ufinal_reaction.csv \" CURRENT_BINARY_DIR \"/ufinal_reaction.eps\");\n //====================\n#endif\n\n // Finding the optimal timestep (no reaction term)\n unsigned int M_small = findTimesteps();\n std::cout\n << \"The smallest number of timesteps keeping the solution in [0, 2] is \"\n << M_small << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "0f3be7fac6aba699b3abf462e6027cffcf53b8a7", "size": 2868, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/FiniteVolumeSineConsLaw/mastersolution/finitevolumesineconslaw_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/FiniteVolumeSineConsLaw/mastersolution/finitevolumesineconslaw_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/FiniteVolumeSineConsLaw/mastersolution/finitevolumesineconslaw_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 32.2247191011, "max_line_length": 78, "alphanum_fraction": 0.6440027894, "num_tokens": 779, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006920116079208, "lm_q2_score": 0.8333245953120233, "lm_q1q2_score": 0.6672363465427404}} {"text": "#ifndef QUAD_TANH_SINH_RULE_HPP\n#define QUAD_TANH_SINH_RULE_HPP\n\n#include \n\n#include \n\n#include \n\nnamespace quad\n{\n\n//==============================================================================\n// Double exponential formula for numerical integration\n//==============================================================================\n\n///\n/// ### DESinhTanhRule\n///\n/// \\brief Double exponential quadrature for finite interval [-1, 1]\n/// \\tparam T the scalar type for quadrature nodes and weights\n///\n/// This class computes nodes and weights of the sinh-tanh quadrature rule which\n/// can efficiently compute the integral over the finite interval. ///\n///\n/// \\f[\n/// I = \\int_{-1}^{1}f(x) dx \\approx \\sum_{k=N_{-}}^{N_{+}} w_{k} f(x_k)\n/// \\f]\n///\n/// This sinh-tanh rule is obtained by applying the change of variable in the\n/// form\n///\n/// \\f[\n/// x = \\phi(t)\n/// = \\tanh\\left(\\frac{\\pi}{2}\\sinh(t)\\right) ,\\quad t \\in (-\\infty,\\infty).\n/// \\f]\n///\n/// and discretizing the integral over \\f$ t \\f$ by the trapezoidal rule of the\n/// step width \\f$h\\f$. The integration nodes and weighs are given as\n///\n/// \\f[\n/// x_k = \\tanh\\left(\\frac{\\pi}{2}\\sinh(kh)\\right), \\\\\n/// w_k =\n/// \\frac{\\frac{1}{2}h\\pi\\cosh(kh)}{\\cosh^\\left(\\frac{1}{2}\\pi\\sinh(kh)\\right)}.\n/// \\f]\n///\ntemplate \nclass DESinhTanhRule\n{\npublic:\n constexpr static const T alpha = math::constant::pi / 2;\n\n using Scalar = T;\n using ArrayType = Eigen::Array;\n using Index = Eigen::Index;\n\nprivate:\n ArrayType m_node; // nodes\n ArrayType m_weight; // weights\n ArrayType m_dist_from_lower; // distance of nodes from lower bound\n ArrayType m_dist_from_upper; // distance of nodes from upper bound\n ArrayType m_adj_diff; // adjacent difference of nodes\npublic:\n /// Default constructor\n DESinhTanhRule() = default;\n /// Copy constructor\n DESinhTanhRule(const DESinhTanhRule&) = default;\n /// Move constructor\n DESinhTanhRule(DESinhTanhRule&&) = default;\n /// Destructor\n ~DESinhTanhRule() = default;\n\n /// Copy assignment operator\n DESinhTanhRule& operator=(const DESinhTanhRule&) = default;\n /// Move assignment operator\n DESinhTanhRule& operator=(DESinhTanhRule&&) = default;\n\n ///\n /// Construst `n`-points quadrature rule\n ///\n /// \\param[in] n number of integration points\n /// \\param[in] tiny A threshold value that the integration weights can be\n /// negligibly small. If the integrand is a regular function at\n /// boundaries,\n ///\n /// \\pre `n > 2` is required\n ///\n explicit DESinhTanhRule(Index n, T tiny)\n {\n compute(n, tiny);\n }\n\n ///\n /// \\return number of integration points.\n ///\n Index size() const\n {\n return m_node.size();\n }\n ///\n /// \\return const reference to the vector of integration points.\n ///\n const ArrayType& x() const\n {\n return m_node;\n }\n\n ///\n /// Get a node\n ///\n /// \\param[in] i index of integration point. `i < size()` required.\n /// \\return `i`-th integration point.\n ///\n Scalar x(Index i) const\n {\n assert(i < size());\n return m_node[i];\n }\n ///\n /// \\return const reference to the vector of integration weights.\n ///\n const ArrayType& w() const\n {\n return m_weight;\n }\n\n ///\n /// Get a weight\n ///\n /// \\parma[in] i index of integration point. `i < size()` required.\n /// \\return `i`-th integration weight.\n ///\n Scalar w(Index i) const\n {\n assert(i < size());\n return m_weight[i];\n }\n ///\n /// Get the distance of node from lower bound, \\f$ x + 1, \\f$ where \\f$ x\n /// \\in [-1,1].\\f$\n ///\n Scalar distanceFromLower(Index i) const\n {\n assert(i < size());\n return m_dist_from_lower[i];\n }\n ///\n /// Get the distance of node from upper bound, \\f$ 1 - x, \\f $where \\f$ x\n /// \\in [-1,1].\\f$\n ///\n Scalar distanceFromUpper(Index i) const\n {\n assert(i < size());\n return m_dist_from_upper[i];\n }\n ///\n /// Get the adjacent difference of nodes.\n ///\n /// \\param[in] i index of nodes\n ///\n /// \\return `x(0)` for `i=0`, `x(i)-x(i-1)` for `i=1,2,...,size()-1.`\n ///\n Scalar adjacentDifference(Index i) const\n {\n assert(i < size());\n return m_adj_diff[i];\n }\n\n ///\n /// Compute nodes and weights of the \\c n point Gauss-Legendre\n /// quadrature rule. Nodes are located in the interval [-1,1].\n ///\n /// \\param[in] n number of integration points\n /// \\param[in] tiny A threshold value that the integration weights can be\n /// negligibly small. If the integrand is a regular function at\n /// boundaries,\n ///\n /// \\pre `n > 2` is required\n ///\n void compute(Index n, T tiny)\n {\n using Eigen::numext::log;\n assert(T() < tiny && tiny < T(1));\n\n resize(n);\n\n const auto t_bound =\n log(log(T(2) / (alpha * tiny) * log(T(2) / tiny)) / alpha);\n const auto h = T(2) * t_bound / (n - 1);\n const auto w_pre = h * alpha;\n\n const auto sh_half = std::sinh(h / T(2));\n const auto ch_half = std::cosh(h / T(2));\n\n T di_pre;\n\n {\n const auto u0 = alpha * std::sinh(-t_bound);\n const auto d0 = std::cosh(u0);\n m_node[0] = std::tanh(u0);\n m_weight[0] = w_pre * std::cosh(-t_bound) / (d0 * d0);\n m_dist_from_lower[0] = std::exp(u0) / d0;\n m_dist_from_upper[0] = std::exp(-u0) / d0;\n m_adj_diff[0] = m_node[0];\n\n di_pre = d0;\n }\n\n for (Index i = 1; i < n; ++i)\n {\n const auto ti = -t_bound + T(i) * h;\n const auto si = alpha * std::sinh(ti);\n const auto ci = alpha * std::cosh(ti);\n const auto di = std::cosh(si);\n\n m_node[i] = std::tanh(si);\n m_weight[i] = w_pre * std::cosh(ti) / (di * di);\n m_dist_from_lower[i] = std::exp(si) / di;\n m_dist_from_upper[i] = std::exp(-si) / di;\n // alpha * (sinh(t[i]) - sinh(t[i-1]))\n const auto ui_diff = T(2) * sh_half * (ci * ch_half - si * sh_half);\n m_adj_diff[i] = std::sinh(ui_diff) / (di * di_pre);\n di_pre = di;\n }\n\n return;\n }\n\n ///\n /// Inverse of variable transformation\n ///\n /// \\return \\f$ t = \\phi^{-1}(x) \\f$\n ///\n static T inverse(T x)\n {\n return std::asinh(std::atanh(x) / alpha);\n }\n\nprivate:\n void resize(Index n)\n {\n m_node.resize(n);\n m_weight.resize(n);\n m_dist_from_lower.resize(n);\n m_dist_from_upper.resize(n);\n m_adj_diff.resize(n);\n }\n};\n\n} // namespace: quad\n\n#endif /* QUAD_TANH_SINH_RULE_HPP */\n", "meta": {"hexsha": "d50f6164dcf8e797b9f733a3fcf3e04de10e5564", "size": 7000, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/quad/tanh_sinh_rule.hpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "include/mxpfit/quad/tanh_sinh_rule.hpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "include/mxpfit/quad/tanh_sinh_rule.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.6679841897, "max_line_length": 82, "alphanum_fraction": 0.5298571429, "num_tokens": 1935, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6671890198345725}} {"text": "/*\n * Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n#include \n#include \n#include \n\n#include \n\n/**\n * Calculates the pseudoinverse of the Jacobian by using SVD technique.\n * This allows to get information about singular values and evaluate them.\n */\nEigen::MatrixXd PInvBySVD::calculate(const Eigen::MatrixXd& jacobian) const\n{\n Eigen::JacobiSVD svd(jacobian, Eigen::ComputeThinU | Eigen::ComputeThinV);\n double eps_truncation = DIV0_SAFE; // prevent division by 0.0\n Eigen::VectorXd singularValues = svd.singularValues();\n Eigen::VectorXd singularValuesInv = Eigen::VectorXd::Zero(singularValues.rows());\n\n // small change to ref: here quadratic damping due to Control of Redundant Robot Manipulators : R.V. Patel, 2005, Springer [Page 13-14]\n for (uint32_t i = 0; i < singularValues.rows(); ++i)\n {\n double denominator = singularValues(i) * singularValues(i);\n // singularValuesInv(i) = (denominator < eps_truncation) ? 0.0 : singularValues(i) / denominator;\n singularValuesInv(i) = (singularValues(i) < eps_truncation) ? 0.0 : singularValues(i) / denominator;\n }\n Eigen::MatrixXd result = svd.matrixV() * singularValuesInv.asDiagonal() * svd.matrixU().transpose();\n\n return result;\n}\n\n/**\n * Calculates the pseudoinverse of the Jacobian by using SVD technique.\n * This allows to get information about singular values and evaluate them.\n */\nEigen::MatrixXd PInvBySVD::calculate(const TwistControllerParams& params,\n boost::shared_ptr db,\n const Eigen::MatrixXd& jacobian) const\n{\n Eigen::JacobiSVD svd(jacobian, Eigen::ComputeThinU | Eigen::ComputeThinV);\n double eps_truncation = params.eps_truncation;\n Eigen::VectorXd singularValues = svd.singularValues();\n Eigen::VectorXd singularValuesInv = Eigen::VectorXd::Zero(singularValues.rows());\n Eigen::MatrixXd lambda = db->getDampingFactor(singularValues, jacobian);\n\n if (params.numerical_filtering)\n {\n // Formula 20 Singularity-robust Task-priority Redundandancy Resolution\n // Sum part\n for (uint32_t i = 0; i < singularValues.rows()-1; ++i)\n {\n // pow(beta, 2) << pow(lambda, 2)\n singularValuesInv(i) = singularValues(i) / (pow(singularValues(i), 2) + pow(params.beta, 2));\n }\n // Formula 20 - additional part - numerical filtering for least singular value m\n uint32_t m = singularValues.rows()-1;\n singularValuesInv(m) = singularValues(m) / (pow(singularValues(m), 2) + pow(params.beta, 2) + lambda(m, m));\n }\n else\n {\n // small change to ref: here quadratic damping due to Control of Redundant Robot Manipulators : R.V. Patel, 2005, Springer [Page 13-14]\n for (uint32_t i = 0; i < singularValues.rows(); ++i)\n {\n double denominator = (singularValues(i) * singularValues(i) + lambda(i, i) );\n // singularValuesInv(i) = (denominator < eps_truncation) ? 0.0 : singularValues(i) / denominator;\n singularValuesInv(i) = (singularValues(i) < eps_truncation) ? 0.0 : singularValues(i) / denominator;\n }\n\n //// Formula from Advanced Robotics : Redundancy and Optimization : Nakamura, Yoshihiko, 1991, Addison-Wesley Pub. Co [Page 258-260]\n // for(uint32_t i = 0; i < singularValues.rows(); ++i)\n // {\n // // damping is disabled due to damping factor lower than a const. limit\n // singularValues(i) = (singularValues(i) < eps_truncation) ? 0.0 : 1.0 / singularValues(i);\n // }\n }\n\n Eigen::MatrixXd result = svd.matrixV() * singularValuesInv.asDiagonal() * svd.matrixU().transpose();\n\n return result;\n}\n\n/**\n * Calculates the pseudoinverse by means of left/right pseudo inverse respectively.\n */\nEigen::MatrixXd PInvDirect::calculate(const Eigen::MatrixXd& jacobian) const\n{\n Eigen::MatrixXd result;\n Eigen::MatrixXd jac_t = jacobian.transpose();\n uint32_t rows = jacobian.rows();\n uint32_t cols = jacobian.cols();\n\n if (cols >= rows)\n {\n result = jac_t * (jacobian * jac_t).inverse();\n }\n else\n {\n result = (jac_t * jacobian).inverse() * jac_t;\n }\n\n return result;\n}\n\n/**\n * Calculates the pseudoinverse by means of left/right pseudo inverse respectively.\n */\nEigen::MatrixXd PInvDirect::calculate(const TwistControllerParams& params,\n boost::shared_ptr db,\n const Eigen::MatrixXd& jacobian) const\n{\n Eigen::MatrixXd result;\n Eigen::MatrixXd jac_t = jacobian.transpose();\n uint32_t rows = jacobian.rows();\n uint32_t cols = jacobian.cols();\n if (params.damping_method == LEAST_SINGULAR_VALUE)\n {\n ROS_ERROR(\"PInvDirect does not support SVD. Use PInvBySVD class instead!\");\n }\n\n Eigen::MatrixXd lambda = db->getDampingFactor(Eigen::VectorXd::Zero(1, 1), jacobian);\n if (cols >= rows)\n {\n Eigen::MatrixXd ident = Eigen::MatrixXd::Identity(rows, rows);\n Eigen::MatrixXd temp = jacobian * jac_t + lambda * ident;\n result = jac_t * temp.inverse();\n }\n else\n {\n Eigen::MatrixXd ident = Eigen::MatrixXd::Identity(cols, cols);\n Eigen::MatrixXd temp = jac_t * jacobian + lambda * ident;\n result = temp.inverse() * jac_t;\n }\n\n return result;\n}\n", "meta": {"hexsha": "656c4027b0af49684bd5d95f7345f2d8eabf9097", "size": 6130, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/inverse_jacobian_calculations/inverse_jacobian_calculation.cpp", "max_stars_repo_name": "nbfigueroa-rlic/robot_kinematics_kdl", "max_stars_repo_head_hexsha": "6f471c4e8f781e87c4309f348104a0fd299f66ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/inverse_jacobian_calculations/inverse_jacobian_calculation.cpp", "max_issues_repo_name": "nbfigueroa-rlic/robot_kinematics_kdl", "max_issues_repo_head_hexsha": "6f471c4e8f781e87c4309f348104a0fd299f66ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/inverse_jacobian_calculations/inverse_jacobian_calculation.cpp", "max_forks_repo_name": "nbfigueroa-rlic/robot_kinematics_kdl", "max_forks_repo_head_hexsha": "6f471c4e8f781e87c4309f348104a0fd299f66ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-06-02T17:31:42.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-02T17:31:42.000Z", "avg_line_length": 40.5960264901, "max_line_length": 143, "alphanum_fraction": 0.6610114192, "num_tokens": 1505, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523148, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6671889956252622}} {"text": "#include \n#include \n#include \n#include \n\nint binomial(int n, int k) {\n// if (c < 0)\n// std::cout << \"c: \" << c << std::endl;\n// if (n < 0)\n// std::cout << \"n: \" << n << std::endl;\n if (k > n)\n return 0;\n if (k == 0 || k == n)\n return 1;\n return binomial(n-1, k-1) + binomial(n-1, k);\n}\n\nint factorial(int n) {\n assert(n >= 0);\n return (n == 1 || n == 0) ? 1 : factorial(n-1) * n;\n}\n\ndouble k_pfac(double pfac, int n, int l, int m, double alpha,\n double beta, double gamma) {\n if (pfac == 0.0)\n return 0;\n double sum_term = 0.0;\n //std::cout << \"n,l,m: \" << n << \",\" << l << \",\" << m << std::endl;\n //std::cout << \"alpha: \" << alpha << \" beta: \" << beta << \" gamma: \" << gamma << std::endl;\n for (std::size_t a = 0; a != (n+2); ++a) {\n for (std::size_t b = 0; b != (l+2); ++b) {\n for (std::size_t c = 0; c != (m+2); ++c) {\n double sum_term_part = binomial(l + 1 - b + a, a) *\n binomial(m + 1 - c + b, b) * binomial(n + 1 - a + c, c)\n / (pow((alpha + beta)*2, l - b + a + 2)\n * pow((alpha + gamma)*2, n - a + c + 2)\n * pow((beta + gamma)*2, m - c + b + 2));\n //std::cout << \"a,b,c: \" << a << \",\" << b << \",\" << c << \" sum term contrib: \" << sum_term_part << std::endl;\n sum_term += sum_term_part;\n }\n }\n }\n\n return pfac * 16.0 * M_PI * M_PI * factorial(n+1) * factorial(l+1) * factorial(m+1) * sum_term;\n}\n\ndouble k(int n, int l, int m, double alpha,\n double beta, double gamma) {\n \n double sum_term = 0.0;\n for (std::size_t a = 0; a != n+2; ++a) {\n for (std::size_t b = 0; b != l+2; ++b) {\n for (std::size_t c = 0; c != m+2; ++c) {\n sum_term += binomial(l + 1 - b + a, a) * \n binomial(m + 1 - c + b, b) * binomial(n + 1 - a + c, c) \n / (pow((alpha + beta)*2, l - b + a + 2)\n * pow((alpha + gamma)*2, n - a + c + 2)\n * pow((beta + gamma)*2, m - c + b + 2));\n }\n }\n }\n\n return 16.0 * M_PI * M_PI * factorial(n+1) * factorial(l+1) * factorial(m+1) * sum_term;\n}\n\ndouble s(int ni, int li, int mi, int nj,\n int lj, int mj, double alpha, double beta, double gamma) {\n //std::cout << \"ni: \" << ni << \" nj: \" << nj << \" li: \" << li << \" lj: \" << lj << \" mi: \" <<\n //mi << \" mj: \" << mj << std::endl;\n //std::cout << \"alpha: \" << alpha << \" beta: \" << beta << \" gamma: \" << gamma << std::endl;\n return k_pfac(1, ni + nj, li + lj, mi + mj, alpha, beta, gamma);\n}\n\ndouble v_ne(int ni, int li, int mi, int nj,\n int lj, int mj, double alpha, double beta, double gamma,\n int z) {\n return -z * (k(ni + nj - 1, li + lj, mi + mj, alpha, beta, gamma)\n + k(ni + nj, li + lj - 1, mi + mj, alpha, beta, gamma));\n}\n\ndouble v_ee(int ni, int li, int mi, int nj,\n int lj, int mj, double alpha, double beta, double gamma) {\n return k(ni + nj, li + lj, mi + mj - 1, alpha, beta, gamma);\n}\n\ndouble t_e(int ni, int li, int mi, int nj,\n int lj, int mj, double alpha, double beta, double gamma) {\n return -((alpha*2.0) * (alpha*2.0) + (beta*2.0) * (beta*2.0) + 2.0 * (gamma*2.0) * (gamma*2.0)) * s(ni, li, mi, nj, lj, mj, alpha, beta, gamma) / 8.0\n + (nj * (alpha*2.0) / 2.0) * k(ni + nj - 1, li + lj, mi + mj, alpha, beta, gamma)\n + (lj * (beta*2.0) / 2.0) * k(ni + nj, li + lj - 1, mi + mj, alpha, beta, gamma)\n + (mj * (gamma*2.0)) * k(ni + nj, li + lj, mi + mj - 1, alpha, beta, gamma)\n// - (nj * (nj - 1) / 2) * k(ni + nj - 2, li + lj, mi + mj, alpha, beta, gamma)\n - k_pfac((nj * (nj - 1) / 2.0), ni + nj - 2, li + lj, mi + mj, alpha, beta, gamma)\n// - (lj * (lj - 1) / 2) * k(ni + nj, li + lj - 2, mi + mj, alpha, beta, gamma)\n - k_pfac((lj * (lj - 1) / 2.0), ni + nj, li + lj - 2, mi + mj, alpha, beta, gamma)\n//\n - k_pfac((mj * (mj - 1)), ni + nj, li + lj, mi + mj - 2, alpha, beta, gamma)\n + ((alpha*2.0) / 2.0) * k(ni + nj - 1, li + lj, mi + mj, alpha, beta, gamma)\n + ((beta*2.0) / 2.0) * k(ni + nj, li + lj - 1, mi + mj, alpha, beta, gamma)\n + ((gamma*2.0)) * k(ni + nj, li + lj, mi + mj - 1, alpha, beta, gamma)\n// - (nj) * k(ni + nj - 2, li + lj, mi + mj, alpha, beta, gamma)\n - k_pfac((nj), ni + nj - 2, li + lj, mi + mj, alpha, beta, gamma)\n// - (lj) * k(ni + nj, li + lj - 2, mi + mj, alpha, beta, gamma)\n - k_pfac((lj), ni + nj, li + lj - 2, mi + mj, alpha, beta, gamma)\n// - (2 * mj) * k(ni + nj, li + lj, mi + mj - 2, alpha, beta, gamma)\n - k_pfac((2.0 * mj), ni + nj, li + lj, mi + mj - 2, alpha, beta, gamma)\n - ((alpha*2.0) * (gamma*2.0) / 8.0) * (k(ni + nj - 1, li + lj, mi + mj + 1, alpha, beta, gamma)\n + k(ni + nj + 1, li + lj, mi + mj - 1, alpha, beta, gamma)\n - k(ni + nj - 1, li + lj + 2, mi + mj - 1, alpha, beta, gamma))\n - ((beta*2.0) * (gamma*2.0) / 8.0) * (k(ni + nj, li + lj - 1, mi + mj + 1, alpha, beta, gamma)\n + k(ni + nj, li + lj + 1, mi + mj - 1, alpha, beta, gamma)\n - k(ni + nj + 2, li + lj - 1, mi + mj - 1, alpha, beta, gamma))\n// + (nj * gamma / 4) * (k(ni + nj - 2, li + lj, mi + mj + 1, alpha, beta, gamma))\n + (k_pfac((nj * (gamma*2.0) / 4.0), ni + nj - 2, li + lj, mi + mj + 1, alpha, beta, gamma)\n + k_pfac((nj * (gamma*2.0) / 4.0), ni + nj, li + lj, mi + mj - 1, alpha, beta, gamma)\n - k_pfac((nj * (gamma*2.0) / 4.0), ni + nj - 2, li + lj + 2, mi + mj - 1, alpha, beta, gamma))\n// + (mj * alpha / 4) * (k(ni + nj - 1, li + lj, mi + mj, alpha, beta, gamma)\n + (k_pfac((mj * (alpha*2.0) / 4.0), ni + nj - 1, li + lj, mi + mj, alpha, beta, gamma)\n + k_pfac((mj * (alpha*2.0) / 4.0), ni + nj + 1, li + lj, mi + mj - 2, alpha, beta, gamma)\n - k_pfac((mj * (alpha*2.0) / 4.0), ni + nj - 1, li + lj + 2, mi + mj - 2, alpha, beta, gamma))\n// - (nj * mj / 2) * (k(ni + nj - 2, li + lj, mi + mj + 1, alpha, beta, gamma)\n - (k_pfac((nj * mj / 2.0), ni + nj - 2, li + lj, mi + mj, alpha, beta, gamma)\n + k_pfac((nj * mj / 2.0), ni + nj, li + lj, mi + mj - 2, alpha, beta, gamma)\n - k_pfac((nj * mj / 2.0), ni + nj - 2, li + lj + 2, mi + mj - 2, alpha, beta, gamma))\n// + (lj * gamma / 4) * (k(ni + nj, li + lj - 2, mi + mj + 1, alpha, beta, gamma)\n + (k_pfac((lj * (gamma*2.0) / 4.0), ni + nj, li + lj - 2, mi + mj + 1, alpha, beta, gamma)\n + k_pfac((lj * (gamma*2.0) / 4.0), ni + nj, li + lj, mi + mj - 1, alpha, beta, gamma)\n - k_pfac((lj * (gamma*2.0) / 4.0), ni + nj + 2, li + lj - 2, mi + mj - 1, alpha, beta, gamma))\n// + (mj * beta / 4) * (k(ni + nj, li + lj - 1, mi + mj, alpha, beta, gamma)\n + (k_pfac((mj * (beta*2.0) / 4.0), ni + nj, li + lj - 1, mi + mj, alpha, beta, gamma)\n + k_pfac((mj * (beta*2.0) / 4.0), ni + nj, li + lj + 1, mi + mj - 2, alpha, beta, gamma)\n - k_pfac((mj * (beta*2.0) / 4.0), ni + nj + 2, li + lj - 1, mi + mj - 2, alpha, beta, gamma))\n// - (lj * mj / 2) * (k(ni + nj, li + lj - 2, mi + mj, alpha, beta, gamma)\n - (k_pfac((lj * mj / 2.0), ni + nj, li + lj - 2, mi + mj, alpha, beta, gamma)\n + k_pfac((lj * mj / 2.0), ni + nj, li + lj, mi + mj - 2, alpha, beta, gamma)\n - k_pfac((lj * mj / 2.0), ni + nj + 2, li + lj - 2, mi + mj - 2, alpha, beta, gamma));\n}\n\nEigen::MatrixXd s_matrix_builder(std::vector, std::vector > > basis) {\n Eigen::MatrixXd result;\n result.setZero(basis.size(), basis.size());\n for (std::size_t i = 0; i != basis.size(); ++i) {\n for (std::size_t j = 0; j != basis.size(); ++j) {\n //std::vector q_nos_i, q_nos_j;\n //std::vector exp_i, exp_j;\n //auto [q_nos_i, exp_i] = basis[i];\n //auto [q_nos_j, exp_j] = basis[j];\n std::vector q_nos_i = basis[i].first;\n std::vector exp_i = basis[i].second;\n std::vector q_nos_j = basis[j].first;\n //std::cout << \"S(\" << i << \",\" << j << \") = s(\" << q_nos_i[0] << \",\" << q_nos_i[1] << \",\" << q_nos_i[2] << \",\" << q_nos_j[0] << \",\" << q_nos_j[1] << \",\" << q_nos_j[2] << \",\" << exp_i[0] << \",\" << exp_i[1] << \",\" << exp_i[2] << std::endl;\n result(i,j) = s(q_nos_i[0], q_nos_i[1], q_nos_i[2], q_nos_j[0], q_nos_j[1], q_nos_j[2], exp_i[0], exp_i[1], exp_i[2]);\n }\n }\n return result;\n}\n\nEigen::MatrixXd h_matrix_builder(std::vector, std::vector > > basis, int z) {\n Eigen::MatrixXd result;\n result.setZero(basis.size(), basis.size());\n for (std::size_t i = 0; i != basis.size(); ++i) {\n for (std::size_t j = 0; j != basis.size(); ++j) {\n //std::vector q_nos_i, q_nos_j;\n //std::vector exp_i, exp_j;\n //auto [q_nos_i, exp_i] = basis[i];\n //auto [q_nos_j, exp_j] = basis[j];\n std::vector q_nos_i = basis[i].first;\n std::vector exp_i = basis[i].second;\n std::vector q_nos_j = basis[j].first;\n result(i,j) = (v_ne(q_nos_i[0], q_nos_i[1], q_nos_i[2], q_nos_j[0], q_nos_j[1], q_nos_j[2], exp_i[0], exp_i[1], exp_i[2], z)\n + v_ee(q_nos_i[0], q_nos_i[1], q_nos_i[2], q_nos_j[0], q_nos_j[1], q_nos_j[2], exp_i[0], exp_i[1], exp_i[2])\n + t_e(q_nos_i[0], q_nos_i[1], q_nos_i[2], q_nos_j[0], q_nos_j[1], q_nos_j[2], exp_i[0], exp_i[1], exp_i[2]));\n// if (result(i,j) == nan(0)) {\n// result(i,j) = 0;\n// }\n }\n }\n return result;\n}\n\n//template\n//std::pair\nstd::pair hylleraas(std::vector, std::vector > > basis, int z) {\n auto H = h_matrix_builder(basis, z);\n auto S = s_matrix_builder(basis);\n\n Eigen::GeneralizedEigenSolver ges;\n ges.compute(H,S);\n\n Eigen::MatrixXd evecs = ges.eigenvectors().real();\n Eigen::MatrixXd evals = ges.eigenvalues().real();\n\n return std::pair(evecs, evals);\n}\n\nstd::vector, std::vector > > generate_basis(std::size_t N, double alpha, double gamma) {\n std::vector, std::vector > > result;\n for (int n = 0; n != N; ++n) {\n for (int l = 0; l != (N-n); ++l) {\n for (int m = 0; m != (N-n-l); ++m) {\n if ((n + l + m) <= N)\n result.push_back(std::pair, std::vector>{std::vector{n,l,m}, std::vector{alpha, alpha, gamma}});\n }\n }\n }\n return result;\n}\n\ntemplate\nstd::pair hylleraas_generic(int N, int z, double alpha, double gamma) {\n auto basis = generate_basis(N, alpha, gamma);\n auto [evecs, evals] = hylleraas(basis, z); //\n return std::pair(evecs, evals);\n}\n\nint main() {\n std::vector, std::vector > > basis =\n {std::pair(std::vector{0,0,0}, std::vector{1.6875, 1.6875, 0.0})};\n Eigen::MatrixXd S = s_matrix_builder(basis);\n std::cout << \"S with single basis fn: \\n\" << S << std::endl;\n\n Eigen::MatrixXd H = h_matrix_builder(basis, 2);\n std::cout << \"H with single basis fn: \\n\" << H << std::endl;\n\n// double k_test = k(0, 0, 0, 0.5, 0.5, 0.5);\n// std::cout << \"k(-1,-1,-1,0.5,0.5,0.5): \" << k_test << std::endl;\n\n// double k_test_pfac = k_pfac(1,0, 0, 0, 1, 1, 1);\n// std::cout << \"k(1,0,0,0,1,1,1): \" << k_test_pfac << std::endl;\n// double k_test_pfac2 = k_pfac(1,0, 0, 0, 1.6875, 1.6875, 0);\n// std::cout << \"k(1,0,0,0,1.6875,1.6875,0): \" << k_test_pfac2 << std::endl;\n\n// int binom_test = binomial(2,1);\n// std::cout << \"binom test C(2,1)\\n\" << binom_test;\n\n std::vector, std::vector > > func3_basis =\n {std::pair(std::vector{0,0,0}, std::vector{1.8, 1.8, 0.0}), std::pair(std::vector{1,1,0}, std::vector{1.8, 1.8, 0.0}), std::pair(std::vector{0,0,1}, std::vector{1.8, 1.8, 0.0})};\n Eigen::MatrixXd S_3func = s_matrix_builder(func3_basis);\n std::cout << \"S_3func: \\n\" << S_3func << std::endl;\n\n Eigen::MatrixXd H_3func = h_matrix_builder(func3_basis, 2);\n std::cout << \"H_3func: \\n\" << H_3func << std::endl;\n\n auto [evecs_3func, evals_3func] = hylleraas(func3_basis, 2);\n std::cout << \"3basis evecs: \\n\" << evecs_3func << \"\\n\\n3basis evals: \\n\" << evals_3func << std::endl;\n\n //hylleraas generic\n auto [evecs_gen_func, evals_gen_func] = hylleraas_generic(3, 2, 1.8, 0.0);\n std::cout << \"gen basis evecs: \\n\" << evecs_gen_func << \"\\n\\ngen basis evals: \\n\" << evals_gen_func << std::endl;\n\n// std::vector evals; //(15);\n// for (size_t i = 1; i != 16; ++i) {\n// auto [evecs_gen_func, evals_gen_func] = hylleraas_generic(i, 2, 1.8, 0.0);\n//\n// evals.push_back(evals_gen_func.minCoeff());\n// std::cout << \"Completed \" << i << \"th computation: \" << evals_gen_func.minCoeff() << \"\\n\";\n// }\n//\n// for (std::size_t i = 1; i != 16; ++i) {\n// std::cout << \"He energy computed with i=\" << i << \": \" << evals[i] << \"\\n\";\n// }\n\n auto [evecs_7_func, evals_7_func] = hylleraas_generic(8, 2, 1.8, 0.0);\n std::cout << \"7-basis evecs: \\n\" << evecs_7_func << \"\\n\\n7-basis evals: \\n\" << evals_7_func << std::endl;\n\n auto [evecs_8_func, evals_8_func] = hylleraas_generic(8, 2, 1.8, 0.0);\n std::cout << \"8-basis evecs: \\n\" << evecs_8_func << \"\\n\\n8-basis evals: \\n\" << evals_8_func << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "cd4773ecadc443c2267a62a6ffdfaff9a12fd6df", "size": 14059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "hylleraas.cpp", "max_stars_repo_name": "powellsr/hylleraas", "max_stars_repo_head_hexsha": "464c534a7d509edd8780218fe7529faed61c11c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "hylleraas.cpp", "max_issues_repo_name": "powellsr/hylleraas", "max_issues_repo_head_hexsha": "464c534a7d509edd8780218fe7529faed61c11c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "hylleraas.cpp", "max_forks_repo_name": "powellsr/hylleraas", "max_forks_repo_head_hexsha": "464c534a7d509edd8780218fe7529faed61c11c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.8782287823, "max_line_length": 252, "alphanum_fraction": 0.4932783271, "num_tokens": 5336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087985746093, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6671493622642348}} {"text": "/******************************************************************************\n * Copyright (C) 2014 by Jerome Maye *\n * jerome.maye@gmail.com *\n ******************************************************************************/\n\n#include \"aslam/calibration/car/geo/geodetic.h\"\n\n#include \n\n#include \n\n#include \n\nusing namespace sm::kinematics;\n\nnamespace aslam {\n namespace calibration {\n\n/******************************************************************************/\n/* Methods */\n/******************************************************************************/\n\n sm::kinematics::Transformation ecef2enu(double x, double y, double z, double\n latitude, double longitude) {\n return enu2ecef(x, y, z, latitude, longitude).inverse();\n }\n\n sm::kinematics::Transformation enu2ecef(double x, double y, double z, double\n latitude, double longitude) {\n\n const double slat = std::sin(latitude);\n const double clat = std::cos(latitude);\n const double slong = std::sin(longitude);\n const double clong = std::cos(longitude);\n\n Eigen::Matrix3d enu_R_ecef;\n enu_R_ecef << -slong, clong, 0,\n -slat * clong, -slat * slong, clat,\n clat * clong, clat * slong, slat;\n\n return Transformation(\n r2quat(enu_R_ecef.transpose()), Eigen::Vector3d(x, y, z));\n }\n\n sm::kinematics::Transformation ecef2ned(double x, double y, double z, double\n latitude, double longitude) {\n return ned2ecef(x, y, z, latitude, longitude).inverse();\n }\n\n sm::kinematics::Transformation ned2ecef(double x, double y, double z, double\n latitude, double longitude) {\n\n const double slat = std::sin(latitude);\n const double clat = std::cos(latitude);\n const double slong = std::sin(longitude);\n const double clong = std::cos(longitude);\n\n Eigen::Matrix3d ned_R_ecef;\n ned_R_ecef << -slat * clong, -slat * slong, clat,\n -slong, clong, 0,\n -clat * clong, -clat * slong, -slat;\n\n return Transformation(\n r2quat(ned_R_ecef.transpose()), Eigen::Vector3d(x, y, z));\n }\n\n void wgs84ToEcef(double latitude, double longitude, double altitude,\n double& x, double& y, double& z) {\n const double slat = std::sin(latitude);\n const double clat = std::cos(latitude);\n const double slong = std::sin(longitude);\n const double clong = std::cos(longitude);\n const double a = 6378137;\n const double e2 = 0.006694380004260827;\n const double R = a / std::sqrt(1 - e2 * slat * slat);\n x = (R + altitude) * clat * clong;\n y = (R + altitude) * clat * slong;\n z = (R * (1 - e2) + altitude) * slat;\n }\n\n }\n}\n", "meta": {"hexsha": "00eb481640cc574cb301fa4dae256f38c0c676fe", "size": 2887, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "incremental_calibration_examples/incremental_calibration_examples_car/src/geo/geodetic.cpp", "max_stars_repo_name": "ethz-asl/aslam_incremental_calibration", "max_stars_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-08-23T06:29:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T16:56:29.000Z", "max_issues_repo_path": "incremental_calibration_examples/incremental_calibration_examples_car/src/geo/geodetic.cpp", "max_issues_repo_name": "ethz-asl/aslam_incremental_calibration", "max_issues_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-02-14T16:02:18.000Z", "max_issues_repo_issues_event_max_datetime": "2017-02-14T16:02:18.000Z", "max_forks_repo_path": "incremental_calibration_examples/incremental_calibration_examples_car/src/geo/geodetic.cpp", "max_forks_repo_name": "ethz-asl/aslam_incremental_calibration", "max_forks_repo_head_hexsha": "16a44b86b6e7eb5ae4ee247f10c429494697ae0b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2017-01-23T09:01:30.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-10T05:13:23.000Z", "avg_line_length": 34.7831325301, "max_line_length": 80, "alphanum_fraction": 0.5226879113, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6671384184655587}} {"text": "// Copyright Yamaha 2021\n// MIT License\n// https://github.com/yamaha-bps/cbr_control/blob/master/LICENSE\n\n#ifndef PLANARQUAD_DYNAMICS_HPP_\n#define PLANARQUAD_DYNAMICS_HPP_\n\n#include \n\n// template here over some type\ntemplate\nauto planarquad_dynamics(const Eigen::MatrixBase & x, const Eigen::MatrixBase & u)\n{\n // Define nx, nu\n constexpr auto nx = T1::RowsAtCompileTime;\n constexpr auto nu = T2::RowsAtCompileTime;\n\n // Initialize Parameters\n constexpr double I = 0.2;\n constexpr double m = 0.5;\n constexpr double r = 0.25;\n constexpr double gr = 9.81;\n\n using T = typename decltype(x * u.transpose())::EvalReturnType::Scalar;\n\n // xDot = f(x) + g(x)*u\n Eigen::Matrix xDot;\n Eigen::Matrix f;\n\n Eigen::Matrix g;\n Eigen::Map> g1(g.data());\n Eigen::Map> g2(g.data() + nx);\n\n // Define States\n // const auto & X = x[0];\n // const auto & Y = x[1];\n const auto & theta = x[2];\n\n // Dynamics\n f[0] = x[3];\n f[1] = x[4];\n f[2] = x[5];\n f[3] = 0.;\n f[4] = -gr;\n f[5] = 0.;\n\n\n g1[0] = 0; g2[0] = 0;\n g1[1] = 0; g2[1] = 0;\n g1[2] = 0; g2[2] = 0;\n g1[3] = -sin(theta) / m; g2[3] = -sin(theta) / m;\n g1[4] = cos(theta) / m; g2[4] = cos(theta) / m;\n g1[5] = r / I; g2[5] = -r / I;\n\n xDot = f + g * u;\n\n return xDot;\n}\n\n#endif // PLANARQUAD_DYNAMICS_HPP_\n", "meta": {"hexsha": "1b947f6648f6e12ec0b5bd00dd7414f103d77c8f", "size": 1533, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/planarquad_dynamics.hpp", "max_stars_repo_name": "yamaha-bps/cbr_control", "max_stars_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/planarquad_dynamics.hpp", "max_issues_repo_name": "yamaha-bps/cbr_control", "max_issues_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/planarquad_dynamics.hpp", "max_forks_repo_name": "yamaha-bps/cbr_control", "max_forks_repo_head_hexsha": "c2faf79673d46c950dd7590f1072fc7decafad06", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.131147541, "max_line_length": 90, "alphanum_fraction": 0.5851272016, "num_tokens": 569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972684083609, "lm_q2_score": 0.766293653760418, "lm_q1q2_score": 0.6671331617624823}} {"text": "#include \n#include \n#include \n#include \n \nusing big_float = boost::multiprecision::cpp_dec_float_100;\n \nbig_float f(unsigned int n) {\n big_float pi(boost::math::constants::pi());\n return exp(sqrt(big_float(n)) * pi);\n}\n \nint main() {\n std::cout << \"Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\\n\"\n << std::setprecision(80) << f(163) << '\\n';\n std::cout << \"\\nResult with last four Heegner numbers:\\n\";\n std::cout << std::setprecision(30);\n for (unsigned int n : {19, 43, 67, 163}) {\n auto x = f(n);\n auto c = ceil(x);\n auto pc = 100.0 * (x/c);\n std::cout << \"f(\" << n << \") = \" << x << \" = \"\n << pc << \"% of \" << c << '\\n';\n }\n return 0;\n}", "meta": {"hexsha": "3e34d5667673350e82e0292124fc5ceb84e92b18", "size": 829, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "C++ Programs/Ramanujan's constant.cpp", "max_stars_repo_name": "Chibi-Shem/Hacktoberfest2020-Expert", "max_stars_repo_head_hexsha": "324843464aec039e130e85a16e74b76d310f1497", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 77.0, "max_stars_repo_stars_event_min_datetime": "2020-10-01T10:06:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T08:57:18.000Z", "max_issues_repo_path": "C++ Programs/Ramanujan's constant.cpp", "max_issues_repo_name": "Chibi-Shem/Hacktoberfest2020-Expert", "max_issues_repo_head_hexsha": "324843464aec039e130e85a16e74b76d310f1497", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2020-09-27T04:55:36.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T18:49:06.000Z", "max_forks_repo_path": "C++ Programs/Ramanujan's constant.cpp", "max_forks_repo_name": "Chibi-Shem/Hacktoberfest2020-Expert", "max_forks_repo_head_hexsha": "324843464aec039e130e85a16e74b76d310f1497", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 327.0, "max_forks_repo_forks_event_min_datetime": "2020-09-26T17:06:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-09T06:04:39.000Z", "avg_line_length": 31.8846153846, "max_line_length": 79, "alphanum_fraction": 0.5609167672, "num_tokens": 247, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6670994777640955}} {"text": "#include \"UtilEOL.h\"\n\n#include \"external\\ArcSim\\geometry.hpp\"\n\n#include \n\n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nMatrixXd deform_grad(const Face *f)\n{\n\tMatrixXd Dx(3, 2);\n\tDx(0, 0) = f->v[1]->node->x[0] - f->v[0]->node->x[0];\n\tDx(0, 1) = f->v[2]->node->x[0] - f->v[0]->node->x[0];\n\tDx(1, 0) = f->v[1]->node->x[1] - f->v[0]->node->x[1];\n\tDx(1, 1) = f->v[2]->node->x[1] - f->v[0]->node->x[1];\n\tDx(2, 0) = f->v[1]->node->x[2] - f->v[0]->node->x[2];\n\tDx(2, 1) = f->v[2]->node->x[2] - f->v[0]->node->x[2];\n\tMatrix2d DX;\n\tDX(0, 0) = f->v[1]->u[0] - f->v[0]->u[0];\n\tDX(0, 1) = f->v[2]->u[0] - f->v[0]->u[0];\n\tDX(1, 0) = f->v[1]->u[1] - f->v[0]->u[1];\n\tDX(1, 1) = f->v[2]->u[1] - f->v[0]->u[1];\n\treturn Dx * DX.inverse();\n}\n\nMatrixXd deform_grad_v(const Vert* v)\n{\n\tdouble tot_ang = 0.0;\n\tMatrix3d Q = Matrix3d::Zero();\n\tMatrix2d P = Matrix2d::Zero();\n\n\tfor (int f = 0; f < v->adjf.size(); f++) {\n\t\tFace* face = v->adjf[f];\n\n\t\tMatrixXd F = deform_grad(face);\n\t\tJacobiSVD svd(F, ComputeFullU | ComputeFullV);\n\n\t\tMatrixXd V3(2, 3);\n\t\tV3 << svd.matrixV(), Vector2d::Zero();\n\n\t\tMatrixXd Qx = svd.matrixU() * V3.transpose();\n\t\tMatrix3d Qxrot;\n\t\tQxrot << Qx.col(0), Qx.col(1), Qx.block<3,1>(0,0).cross(Qx.block<3,1>(0,1));\n\n\t\tMatrix2d S2;\n\t\tS2 << svd.singularValues(), svd.singularValues();\n\n\t\tMatrix2d Px = svd.matrixV() * S2 * svd.matrixV().transpose();\n\n\t\tQ += incedent_angle(v, face) * Qxrot.log();\n\t\t\n\t\tP += incedent_angle(v, face) * Px;\n\t\t\n\t\ttot_ang += incedent_angle(v, face);\n\t}\n\t\n\tQ /= tot_ang;\n\tQ = Q.exp();\n\n\tP /= tot_ang;\n\n\treturn Q.block<3, 2>(0, 0) * P;\n}", "meta": {"hexsha": "d9ed1f35d9fd6918ae1f5d06cdff3a2138032de1", "size": 1648, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/UtilEOL.cpp", "max_stars_repo_name": "sueda/eol-cloth", "max_stars_repo_head_hexsha": "cc8f24eef81283c541b859c05dd8ceed7813271f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 85.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T04:00:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-12T03:46:30.000Z", "max_issues_repo_path": "src/UtilEOL.cpp", "max_issues_repo_name": "sueda/eol-cloth", "max_issues_repo_head_hexsha": "cc8f24eef81283c541b859c05dd8ceed7813271f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-05-19T09:24:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-03-20T15:03:18.000Z", "max_forks_repo_path": "src/UtilEOL.cpp", "max_forks_repo_name": "sueda/eol-cloth", "max_forks_repo_head_hexsha": "cc8f24eef81283c541b859c05dd8ceed7813271f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 18.0, "max_forks_repo_forks_event_min_datetime": "2018-05-17T03:56:05.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T07:41:50.000Z", "avg_line_length": 24.5970149254, "max_line_length": 78, "alphanum_fraction": 0.5594660194, "num_tokens": 719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361604769414, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6670442825688918}} {"text": "\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \"covariance_visual.h\"\n\ntemplate\ninline bool isfinite(const Eigen::MatrixBase& x)\n{\n return ( (x - x).array() == (x - x).array()).all();\n}\n\n\ntemplate\ninline bool isnan(const Eigen::MatrixBase& x)\n{\n return !((x.array() == x.array())).all();\n}\n\nstd::pair computeEigenValuesAndVectors(const geometry_msgs::PoseWithCovariance& msg, unsigned offset)\n{\n Eigen::Matrix3d covariance = Eigen::Matrix3d::Zero();\n Eigen::Vector3d eigenValues = Eigen::Vector3d::Identity();\n Eigen::Matrix3d eigenVectors = Eigen::Matrix3d::Zero();\n\n for (size_t i = 0; i < 3; ++i)\n {\n for (size_t j = 0; j < 3; ++j)\n {\n covariance (i, j) = msg.covariance[(i + offset) * 6 + j + offset];\n }\n }\n\n // Compute eigen values and eigen vectors.\n Eigen::SelfAdjointEigenSolver eigensolver(covariance);\n\n if (eigensolver.info() == Eigen::Success)\n {\n eigenValues = eigensolver.eigenvalues();\n eigenVectors = eigensolver.eigenvectors();\n }\n else\n {\n ROS_WARN_THROTTLE(1, \"Failed to compute eigen vectors/values. Is the covariance matrix correct?\");\n }\n\n return std::make_pair(eigenVectors, eigenValues);\n}\n\nOgre::Quaternion computeRotation(const geometry_msgs::PoseWithCovariance& msg, std::pair& pair)\n{\n Ogre::Matrix3 rotation;\n\n for (size_t i = 0; i < 3; ++i)\n {\n for (size_t j = 0; j < 3; ++j)\n {\n rotation[i][j] = pair.first(i, j);\n }\n }\n\n return Ogre::Quaternion(rotation);\n}\n\nnamespace rviz_plugin_covariance\n{\n\nCovarianceVisual::CovarianceVisual(Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node)\n : frame_node_(parent_node->createChildSceneNode())\n , scene_manager_(scene_manager)\n , scale_(1.0)\n{\n axes_.reset(new rviz::Axes(scene_manager_, frame_node_));\n\n position_node_ = axes_->getSceneNode()->createChildSceneNode();\n orientation_node_ = axes_->getSceneNode()->createChildSceneNode();\n\n position_shape_.reset(new rviz::Shape(rviz::Shape::Sphere, scene_manager_, position_node_));\n orientation_shape_.reset(new rviz::Shape(rviz::Shape::Cone, scene_manager_, orientation_node_));\n\n axes_->getSceneNode()->setVisible(show_axis_);\n position_node_->setVisible(show_position_);\n orientation_node_->setVisible(use_6dof_ && show_orientation_);\n}\n\nCovarianceVisual::~CovarianceVisual()\n{\n scene_manager_->destroySceneNode(orientation_node_);\n scene_manager_->destroySceneNode(position_node_);\n scene_manager_->destroySceneNode(frame_node_);\n}\n\nvoid CovarianceVisual::setMessage(const geometry_msgs::PoseWithCovariance& msg)\n{\n // Construct pose position and orientation.\n const geometry_msgs::Point& p = msg.pose.position;\n Ogre::Vector3 position(p.x, p.y, p.z);\n Ogre::Quaternion orientation(msg.pose.orientation.w, msg.pose.orientation.x, msg.pose.orientation.y, msg.pose.orientation.z);\n\n // Set position and orientation for axes scene node.\n if (!position.isNaN())\n {\n axes_->setPosition(position);\n }\n else\n {\n ROS_WARN_STREAM_THROTTLE(1, \"Position contains NaN: \" << position);\n }\n\n if (!orientation.isNaN())\n {\n axes_->setOrientation(orientation);\n }\n else\n {\n ROS_WARN_STREAM_THROTTLE(1, \"Orientation contains NaN: \" << orientation);\n }\n\n if (use_6dof_)\n {\n // Check for NaN in covariance\n for (size_t i = 0; i < 3; ++i)\n {\n if (isnan(msg.covariance[i]))\n {\n ROS_WARN_THROTTLE(1, \"Covariance contains NaN\");\n return;\n }\n }\n\n // Compute eigen values and vectors for both shapes.\n std::pair positionEigenVectorsAndValues(computeEigenValuesAndVectors(msg, 0));\n std::pair orientationEigenVectorsAndValues(computeEigenValuesAndVectors(msg, 3));\n\n Ogre::Quaternion positionQuaternion(computeRotation(msg, positionEigenVectorsAndValues));\n Ogre::Quaternion orientationQuaternion(computeRotation(msg, orientationEigenVectorsAndValues));\n\n position_node_->setOrientation(positionQuaternion);\n orientation_node_->setOrientation(orientationQuaternion);\n\n // Compute scaling.\n Ogre::Vector3 positionScaling(\n std::sqrt(positionEigenVectorsAndValues.second[0]),\n std::sqrt(positionEigenVectorsAndValues.second[1]),\n std::sqrt(positionEigenVectorsAndValues.second[2]));\n positionScaling *= scale_;\n\n Ogre::Vector3 orientationScaling(\n std::sqrt(orientationEigenVectorsAndValues.second[0]),\n std::sqrt(orientationEigenVectorsAndValues.second[1]),\n std::sqrt(orientationEigenVectorsAndValues.second[2]));\n orientationScaling *= scale_;\n\n // Set the scaling.\n if (!positionScaling.isNaN())\n {\n position_node_->setScale(positionScaling);\n }\n else\n {\n ROS_WARN_STREAM_THROTTLE(1, \"PositionScaling contains NaN: \" << positionScaling);\n }\n\n if (!orientationScaling.isNaN())\n {\n orientation_node_->setScale(orientationScaling);\n }\n else\n {\n ROS_WARN_STREAM_THROTTLE(1, \"OrientationScaling contains NaN: \" << orientationScaling);\n }\n\n // Debugging.\n ROS_DEBUG_STREAM_THROTTLE(1,\n \"Position:\\n\"\n << position << \"\\n\"\n << \"Positional part 3x3 eigen values:\\n\"\n << positionEigenVectorsAndValues.second << \"\\n\"\n << \"Positional part 3x3 eigen vectors:\\n\"\n << positionEigenVectorsAndValues.first << \"\\n\"\n << \"Sphere orientation:\\n\"\n << positionQuaternion << \"\\n\"\n << positionQuaternion.getYaw() << \"\\n\"\n << \"Sphere scaling:\\n\"\n << positionScaling << \"\\n\"\n << \"Rotational part 3x3 eigen values:\\n\"\n << orientationEigenVectorsAndValues.second << \"\\n\"\n << \"Rotational part 3x3 eigen vectors:\\n\"\n << orientationEigenVectorsAndValues.first << \"\\n\"\n << \"Cone orientation:\\n\"\n << orientationQuaternion << \"\\n\"\n << orientationQuaternion.getRoll() << \" \"\n << orientationQuaternion.getPitch() << \" \"\n << orientationQuaternion.getYaw() << \"\\n\"\n << \"Cone scaling:\\n\"\n << orientationScaling);\n }\n else // 3DOF\n {\n // Take (x, y, th) part from the covariance matrix:\n // x y z R P Y\n // x * * x\n // y * * x\n // z\n // R\n // P\n // Y x x *\n //\n // Actually, we only take the elements marked with '*', although we could\n // also take a 3x3 matrix with the '*' and 'x' elements.\n Eigen::Matrix2d cov_xy; cov_xy << msg.covariance[0], msg.covariance[1],\n msg.covariance[6], msg.covariance[7];\n const double cov_yaw = msg.covariance[35];\n\n // Check for NaN in covariance\n if (isnan(cov_xy) || isnan(cov_yaw))\n {\n ROS_WARN_STREAM_THROTTLE(1, \"Covariance contains NaN: \" <<\n \"C_xy = \" << cov_xy << \", C_yaw = \" << cov_yaw);\n return;\n }\n\n // Compute eigen values and vectors for xy\n Eigen::Vector2d eigen_values = Eigen::Vector2d::Identity();\n Eigen::Matrix2d eigen_vectors = Eigen::Matrix2d::Zero();\n\n Eigen::SelfAdjointEigenSolver eigensolver(cov_xy);\n if (eigensolver.info() == Eigen::Success)\n {\n eigen_values = eigensolver.eigenvalues();\n eigen_vectors = eigensolver.eigenvectors();\n }\n else\n {\n ROS_WARN_THROTTLE(1, \"Failed to compute eigen values/vectors. Is the covariance matrix correct?\");\n }\n\n // Compute ellipsoid angle, and axes\n const double yaw = atan2(eigen_vectors(1, 0), eigen_vectors(0, 0));\n const double axis_major = sqrt(eigen_values[0]);\n const double axis_minor = sqrt(eigen_values[1]);\n const double axis_yaw = sqrt(cov_yaw);\n\n // Compute the ellipsoid orientation\n Ogre::Quaternion positionQuaternion;\n Ogre::Matrix3 R;\n R.FromEulerAnglesXYZ(Ogre::Radian(0.0), Ogre::Radian(0.0), Ogre::Radian(yaw));\n positionQuaternion.FromRotationMatrix(R);\n\n // Set the orientation\n position_node_->setOrientation(positionQuaternion);\n\n // Compute the ellipsoid scale\n Ogre::Vector3 positionScaling(\n std::isnormal(axis_major) ? axis_major : 0.001,\n std::isnormal(axis_minor) ? axis_minor : 0.001,\n std::isnormal(axis_yaw ) ? axis_yaw : 0.001);\n positionScaling *= scale_;\n\n // Set the scaling\n if (!positionScaling.isNaN())\n {\n position_node_->setScale(positionScaling);\n }\n else\n {\n ROS_WARN_STREAM_THROTTLE(1, \"PositionScaling contains NaN: \" << positionScaling);\n }\n\n // Debugging\n ROS_DEBUG_STREAM_THROTTLE(1,\n \"Position:\\n\"\n << position << \"\\n\"\n << \"C_xy:\\n\"\n << cov_xy << \"\\n\"\n << \"C_yaw:\\n\"\n << cov_yaw << \"\\n\"\n << \"axis (major, minor, yaw): (\" << axis_major << \", \" << axis_minor << \", \" << axis_yaw << \")\\n\"\n << \"yaw: \" << yaw << \"\\n\"\n << \"Positional part 2x2 eigen values:\\n\"\n << eigen_values << \"\\n\"\n << \"Positional part 2x2 eigen vectors:\\n\"\n << eigen_vectors << \"\\n\"\n << \"Sphere orientation:\\n\"\n << positionQuaternion << \"\\n\"\n << positionQuaternion.getRoll() << \" \"\n << positionQuaternion.getPitch() << \" \"\n << positionQuaternion.getYaw() << \"\\n\"\n << \"Sphere scaling:\\n\"\n << positionScaling);\n }\n}\n\nvoid CovarianceVisual::setMessage(const geometry_msgs::PoseWithCovarianceStampedConstPtr& msg)\n{\n setMessage(msg->pose);\n}\n\nvoid CovarianceVisual::setMessage(const nav_msgs::OdometryConstPtr& msg)\n{\n setMessage(msg->pose);\n}\n\nvoid CovarianceVisual::setFramePosition(const Ogre::Vector3& position)\n{\n frame_node_->setPosition(position);\n}\n\nvoid CovarianceVisual::setFrameOrientation(const Ogre::Quaternion& orientation)\n{\n frame_node_->setOrientation(orientation);\n}\n\nvoid CovarianceVisual::setColor(float r, float g, float b, float a)\n{\n position_shape_->setColor(r, g, b, a);\n orientation_shape_->setColor(r, g, b, a);\n}\n\nvoid CovarianceVisual::setScale(float scale)\n{\n scale_ = scale;\n}\n\nvoid CovarianceVisual::setShowAxis(bool show_axis)\n{\n show_axis_ = show_axis;\n\n axes_->getSceneNode()->setVisible(show_axis);\n position_node_->setVisible(show_position_);\n orientation_node_->setVisible(use_6dof_ && show_orientation_);\n}\n\nvoid CovarianceVisual::setShowPosition(bool show_position)\n{\n show_position_ = show_position;\n\n position_node_->setVisible(show_position_);\n}\n\nvoid CovarianceVisual::setShowOrientation(bool show_orientation)\n{\n show_orientation_ = show_orientation;\n\n orientation_node_->setVisible(use_6dof_ && show_orientation_);\n}\n\nvoid CovarianceVisual::setUse6DOF(bool use_6dof)\n{\n use_6dof_ = use_6dof;\n\n orientation_node_->setVisible(use_6dof && show_orientation_);\n}\n\n} // end namespace rviz_plugin_covariance\n", "meta": {"hexsha": "cbf4a7bdf84a32066f1511c8267fd617c20417ca", "size": 10888, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rviz_plugin_covariance/src/covariance_visual.cpp", "max_stars_repo_name": "hect1995/Robotics_intro", "max_stars_repo_head_hexsha": "1b687585c20db5f1114d8ca6811a70313d325dd6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-10-24T14:52:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-12T14:59:00.000Z", "max_issues_repo_path": "rviz_plugin_covariance/src/covariance_visual.cpp", "max_issues_repo_name": "hect1995/Robotics_intro", "max_issues_repo_head_hexsha": "1b687585c20db5f1114d8ca6811a70313d325dd6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rviz_plugin_covariance/src/covariance_visual.cpp", "max_forks_repo_name": "hect1995/Robotics_intro", "max_forks_repo_head_hexsha": "1b687585c20db5f1114d8ca6811a70313d325dd6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 17.0, "max_forks_repo_forks_event_min_datetime": "2019-09-29T10:22:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-08T12:38:37.000Z", "avg_line_length": 29.9944903581, "max_line_length": 136, "alphanum_fraction": 0.6708302719, "num_tokens": 2832, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.908617906830944, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6670341478957673}} {"text": "#pragma once\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"Bounds.hh\"\n#include \"../Math/math.hh\"\n#include \"../util/assert.hh\"\n#include \"../util/Maybe.hh\"\n\n#include \"LineSegment/linesegment.hh\"\n\nnamespace bold\n{\n /**\n * Line, specified using radius/distance-from-origin parameters (normal form.)\n *\n * Equations defining the line are:\n *\n * r = x*sin(theta) + y*cos(theta)\n *\n * x = (r - y*cos(theta))/sin(theta)\n * y = (r - x*sin(theta))/cos(theta)\n */\n class Line\n {\n // TODO rename to NormalLine2d?\n public:\n Line(double const radius, double const theta, const ushort votes = 0)\n : d_radius(radius),\n d_theta(theta)\n {\n ASSERT(theta >= 0);\n ASSERT(theta <= M_PI);\n ASSERT(!std::isnan(theta) && !std::isnan(radius) && !std::isinf(theta) && !std::isinf(radius));\n };\n\n double radius() const { return d_radius; }\n double theta() const { return d_theta; }\n double thetaDegrees() const { return Math::radToDeg(d_theta); }\n\n double gradient() const { return tanh(d_theta); }\n double yIntersection() const { return d_radius / cos(d_theta); }\n\n void draw(cv::Mat& mat, cv::Scalar const& color) const\n {\n Maybe> line(intersectWith(Bounds2i(Eigen::Vector2i::Zero(), Eigen::Vector2i(mat.cols, mat.rows))));\n\n if (line.hasValue())\n {\n Eigen::Vector2i const& p1 = line->p1();\n Eigen::Vector2i const& p2 = line->p2();\n cv::line(mat, cv::Point(p1.x(), p1.y()), cv::Point(p2.x(), p2.y()), color);\n }\n }\n\n template\n Maybe> intersectWith(Bounds bounds) const\n {\n ASSERT(d_theta >= 0 && d_theta <= M_PI);\n\n double tsin = sin(d_theta);\n double tcos = cos(d_theta);\n\n int minX = bounds.min().x();\n int minY = bounds.min().y();\n int maxX = bounds.max().x();\n int maxY = bounds.max().y();\n\n // r = x*sin(theta) + y*cos(theta)\n // x = (r - y*cos(theta))/sin(theta)\n // y = (r - x*sin(theta))/cos(theta)\n\n double xWhenYMin = (d_radius-minY*tcos)/tsin;\n double yWhenXMin = (d_radius-minX*tsin)/tcos;\n\n double xWhenYMax = (d_radius-maxY*tcos)/tsin;\n double yWhenXMax = (d_radius-maxX*tsin)/tcos;\n\n std::vector> edgeContactPoints;\n\n if (xWhenYMin >= minX && xWhenYMin <= maxX)\n edgeContactPoints.emplace_back(xWhenYMin, minY);\n\n if (xWhenYMax >= minX && xWhenYMax <= maxX)\n edgeContactPoints.emplace_back(xWhenYMax, maxY);\n\n if (yWhenXMin >= minY && yWhenXMin <= maxY)\n edgeContactPoints.emplace_back(minX, yWhenXMin);\n\n if (yWhenXMax >= minY && yWhenXMax <= maxY)\n edgeContactPoints.emplace_back(maxX, yWhenXMax);\n\n if (edgeContactPoints.size() == 0)\n return Maybe>::empty();\n\n ASSERT(edgeContactPoints.size() == 2);\n\n if (edgeContactPoints.size() != 2)\n return Maybe>::empty();\n\n return Maybe>(LineSegment(edgeContactPoints[0], edgeContactPoints[1]));\n }\n\n bool operator==(Line const& other) const\n {\n const double epsilon = 0.0000001;\n return fabs(d_radius - other.d_radius) < epsilon\n && fabs(d_theta - other.d_theta) < epsilon;\n }\n\n template\n static Line fromSegment(LineSegment2 const& segment)\n {\n double theta = atan2(segment.p2().y() - segment.p1().y(),\n segment.p1().x() - segment.p2().x());\n \n double radius = segment.p1().x() * std::sin(theta) +\n segment.p1().y() * std::cos(theta);\n\n while (theta < 0)\n {\n theta += M_PI;\n radius = -radius;\n }\n\n while (theta > M_PI)\n {\n theta -= M_PI;\n radius = -radius;\n }\n\n return Line(radius, theta);\n }\n\n friend std::ostream& operator<<(std::ostream& stream, Line const& line)\n {\n return stream << std::setprecision(13) << \"Line (radius=\" << line.radius() << \" theta=\" << line.theta() << \")\";\n }\n\n private:\n double d_radius;\n double d_theta;\n };\n}\n", "meta": {"hexsha": "1b9b6f7befe4a78f84618a9371aad184ba85ea8e", "size": 4161, "ext": "hh", "lang": "C++", "max_stars_repo_path": "geometry/Line.hh", "max_stars_repo_name": "drewnoakes/bold-humanoid", "max_stars_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "geometry/Line.hh", "max_issues_repo_name": "drewnoakes/bold-humanoid", "max_issues_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geometry/Line.hh", "max_forks_repo_name": "drewnoakes/bold-humanoid", "max_forks_repo_head_hexsha": "6025fcc92cdf3ce9486d4fe5af4f30ee7a7a3335", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.74, "max_line_length": 124, "alphanum_fraction": 0.5866378274, "num_tokens": 1146, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6669053055324907}} {"text": "/* Boost libs/numeric/odeint/examples/openmp/lorenz_ensemble_nested.cpp\r\n\r\n Copyright 2013 Karsten Ahnert\r\n Copyright 2013 Pascal Germroth\r\n Copyright 2013 Mario Mulansky\r\n\r\n Parallelized Lorenz ensembles using nested omp algebra\r\n\r\n Distributed under the Boost Software License, Version 1.0.\r\n(See accompanying file LICENSE_1_0.txt or\r\n copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"point_type.hpp\"\r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\n\r\ntypedef point point_type;\r\ntypedef vector< point_type > state_type;\r\n\r\nconst double sigma = 10.0;\r\nconst double b = 8.0 / 3.0;\r\n\r\n\r\nstruct sys_func {\r\n const vector &R;\r\n sys_func( vector &R ) : R(R) {}\r\n\r\n void operator()( const state_type &x , state_type &dxdt , double t ) const {\r\n# pragma omp parallel for\r\n for(size_t i = 0 ; i < x.size() ; i++) {\r\n dxdt[i][0] = -sigma * (x[i][0] - x[i][1]);\r\n dxdt[i][1] = R[i] * x[i][0] - x[i][1] - x[i][0] * x[i][2];\r\n dxdt[i][2] = -b * x[i][2] + x[i][0] * x[i][1];\r\n }\r\n }\r\n};\r\n\r\n\r\nint main(int argc, char **argv) {\r\n size_t n = 1024;\r\n if(argc > 1) n = boost::lexical_cast(argv[1]);\r\n\r\n vector R(n);\r\n const double Rmin = 0.1, Rmax = 50.0;\r\n# pragma omp parallel for\r\n for(size_t i = 0 ; i < n ; i++)\r\n R[i] = Rmin + (Rmax - Rmin) / (n - 1) * i;\r\n\r\n state_type state( n , point_type(10, 10, 10) );\r\n\r\n typedef runge_kutta4< state_type, double , state_type , double ,\r\n openmp_nested_algebra > stepper;\r\n\r\n const double t_max = 10.0, dt = 0.01;\r\n\r\n integrate_const(\r\n stepper(),\r\n sys_func(R),\r\n state,\r\n 0.0, t_max, dt\r\n );\r\n\r\n std::copy( state.begin(), state.end(), ostream_iterator(cout, \"\\n\") );\r\n\r\n return 0;\r\n}\r\n", "meta": {"hexsha": "578e71a5dad922bf9ebd6ed2707a5df3fa81cc3a", "size": 2099, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/openmp/lorenz_ensemble_nested.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/openmp/lorenz_ensemble_nested.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/numeric/odeint/examples/openmp/lorenz_ensemble_nested.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 27.6184210526, "max_line_length": 87, "alphanum_fraction": 0.595521677, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6667915064612215}} {"text": "#pragma once\n\n#include \n#include \n#include \n\n#define MAX_ITERS 100\n\nstruct KMedNode\n{\n\tKMedNode(size_t n, size_t k) : N(n), K(k), \n\t\t\t\t\t\tmedoids(K,arma::fill::zeros),\n\t\t\t\t\t\tmultiplicity(K,arma::fill::zeros),\n\t\t\t\t\t\tassignments(N,arma::fill::zeros) { }\n\tsize_t N;\n\tsize_t K;\n\tarma::uvec medoids;\n\tarma::uvec multiplicity;\n\tarma::uvec assignments;\n};\n\n\nvoid \nassign_to_medoids(const arma::mat& dists, KMedNode& kmn)\n{\n\tarma::mat sub_dists = dists.rows(kmn.medoids);\n\tkmn.multiplicity.zeros();\n\tfor(size_t i = 0; i < kmn.N; ++i)\n\t{\n\t\tarma::uvec idx = arma::find(kmn.medoids==i,1);\n\t\tif(idx.n_elem == 1)\n\t\t{\n\t\t\tsize_t loc = idx[0];\n\t\t\tkmn.multiplicity[loc]++;\n\t\t\tkmn.assignments[i] = kmn.medoids[loc];\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tsize_t min_idx = sub_dists.col(i).index_min();\n\t\tkmn.assignments[i] = kmn.medoids[min_idx];\n\t\tkmn.multiplicity[min_idx]++;\n\t}\n}\n\nvoid\nupdate_medoids(const arma::mat& dists, KMedNode& kmn)\n{\n\tarma::uvec set;\n\tfor(size_t k = 0; k < kmn.K; ++k)\n\t{\n\t\tset = arma::find(kmn.assignments == kmn.medoids[k]);\n\t\tarma::mat sub_dist = dists(set,set);\n\t\tarma::vec row_sums = arma::sum(sub_dist,1);\n\t\tsize_t min_idx = row_sums.index_min();\n\t\tif(kmn.medoids[k] != set[min_idx])\n\t\t\tprintf(\"Swapping %llu for %llu\\n\",set[min_idx],kmn.medoids[k]);\n\t\tkmn.medoids[k] = set[min_idx];\n\t}\n}\n\narma::uvec\nkmpp_init(const arma::mat& dists, size_t k, const arma::uvec& seeds)\n{\n\tarma::uvec medoids(k);\n\tsize_t start;\n\tprintf(\"Initializing random center\\n\");\n\tif(seeds.n_elem > k)\n\t\tthrow std::runtime_error(\"kmeans++ called with seed count greater than k\");\n\tif(seeds.n_elem > 0)\n\t{\n\t\tfor(size_t i = 0; i < seeds.n_elem; ++i)\n\t\t\tmedoids(i) = seeds(i);\n\t\tstart = seeds.n_elem;\n\t} else {\n\t\t// randomly initialize one value\n\t\tauto init = arma::randi(1,arma::distr_param(0,dists.n_rows-1));\n\t\tmedoids(0)=init(0);\n\t\tstart = 1;\n\t}\n\tfor(size_t i = start; i < k; ++i)\n\t{\n\t\t// Dsq(x) = min_i D(x,medoid_i)^2\n\t\t// so minimize across columns to find the min value of D(x,medoids_i)\n\t\tarma::uvec assigned = medoids(arma::span(0,i-1));\n\t\tarma::vec Dsq = arma::square(arma::min(dists.cols(assigned),1));\n\n\t\tarma::vec cdf = arma::cumsum(Dsq/arma::accu(Dsq));\n\t\tarma::vec r = arma::randu(1);\n\t\tarma::uvec loc = arma::find(cdf > r[0],1,\"first\");\n\t\tif(loc.is_empty())\n\t\t{\n\t\t\tmedoids[i] = dists.n_rows-1;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmedoids[i] = loc[0];\n\t\t}\n\t}\n\n\treturn medoids;\n}\n// uses Voronoi iteration\nKMedNode\nselect_kmedoids(const arma::mat& dists, size_t k, const arma::uvec& seeds = arma::uvec() )\n{\n\tint N = dists.n_rows;\n\tKMedNode kmn(N, k);\n\t\n\tkmn.medoids = arma::sort(kmpp_init(dists,k,seeds));\n\tarma::uvec old_medoids = kmn.medoids;\n\tarma::uvec diff, sindex;\n\n\tbool converged = false;\n\tfor(size_t i = 0; i < MAX_ITERS && !converged; ++i)\n\t{\n\t\tprintf(\"Iteration %lu\\n\",i);\n\t\tassign_to_medoids(dists,kmn);\n\t\tupdate_medoids(dists,kmn);\n\t\tkmn.medoids = arma::sort(kmn.medoids);\n\n\t\tdiff = arma::find(old_medoids != kmn.medoids);\n\t\tif(diff.is_empty())\n\t\t\tconverged = true;\n\t\telse\n\t\t\told_medoids = kmn.medoids;\n\t}\n\n\tassign_to_medoids(dists,kmn);\n\treturn kmn;\n}\n\nstd::tuple\nkmedoids(pyarr_d dists, size_t k, pyarr_u seeds = pyarr_u(0,nullptr))\n{\n\tarma::arma_rng::set_seed_random();\n\tarma::mat d = py_to_mat(dists);\n\tarma::uvec seed_medoid = py_to_uvec(seeds);\n\tseed_medoid.print(\"Seed Medoids\");\n\tKMedNode kmn = select_kmedoids(d,k, seed_medoid);\n\treturn std::make_tuple(uvec_to_py(kmn.medoids),uvec_to_py(kmn.multiplicity));\n}\n", "meta": {"hexsha": "cdeac377ef68784f3d8bf1967a8b935a761be55d", "size": 3463, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/KMedoids.hpp", "max_stars_repo_name": "awlong/DiffusionMap", "max_stars_repo_head_hexsha": "64eac6871197723ddd1a2e536cf699c6fb905217", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2015-08-12T16:54:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T10:32:04.000Z", "max_issues_repo_path": "src/KMedoids.hpp", "max_issues_repo_name": "awlong/DiffusionMap", "max_issues_repo_head_hexsha": "64eac6871197723ddd1a2e536cf699c6fb905217", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/KMedoids.hpp", "max_forks_repo_name": "awlong/DiffusionMap", "max_forks_repo_head_hexsha": "64eac6871197723ddd1a2e536cf699c6fb905217", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2017-08-11T17:05:06.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-07T04:20:00.000Z", "avg_line_length": 24.3873239437, "max_line_length": 90, "alphanum_fraction": 0.6621426509, "num_tokens": 1218, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681195338728, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6667430446589162}} {"text": "#include \n#include \n#include \n#include \n\n#include \n\nnamespace ub = boost::numeric::ublas;\ntypedef kv::interval itv;\n\nint main()\n{\n\tub::matrix a(2, 2);\n\tub::matrix b(2, 1);\n\tub::matrix x(2, 1);\n\n\ta(0, 0) = 1.; a(0, 1) = 2.;\n\ta(1, 0) = 3.; a(1, 1) = 4.;\n\n\tb(0, 0) = 5.; b(1, 0) = 6.;\n\n\tkv::vleq(a, b, x);\n\n\tstd::cout.precision(20);\n\tstd::cout << x << \"\\n\";\n\tstd::cout << prod(a, x) << \"\\n\";\n}\n", "meta": {"hexsha": "49e5bcf198b493bb46da1a0a63e74ef5b4718918", "size": 529, "ext": "cc", "lang": "C++", "max_stars_repo_path": "test/test-vleq.cc", "max_stars_repo_name": "soonho-tri/kv", "max_stars_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 67.0, "max_stars_repo_stars_event_min_datetime": "2017-01-04T15:30:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T05:45:02.000Z", "max_issues_repo_path": "test/test-vleq.cc", "max_issues_repo_name": "soonho-tri/kv", "max_issues_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2017-02-10T02:59:45.000Z", "max_issues_repo_issues_event_max_datetime": "2019-10-10T14:17:08.000Z", "max_forks_repo_path": "test/test-vleq.cc", "max_forks_repo_name": "soonho-tri/kv", "max_forks_repo_head_hexsha": "4963be6560d8600cdc9ff22d004b2b965ae7b1df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T02:27:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T05:45:04.000Z", "avg_line_length": 18.8928571429, "max_line_length": 41, "alphanum_fraction": 0.572778828, "num_tokens": 224, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9196425355825848, "lm_q2_score": 0.7248702761768249, "lm_q1q2_score": 0.6666215387517037}} {"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2013-2014 Kyle Lutz \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 \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace compute = boost::compute;\n\n// return a random float between lo and hi\nfloat rand_float(float lo, float hi)\n{\n float x = (float) std::rand() / (float) RAND_MAX;\n\n return (1.0f - x) * lo + x * hi;\n}\n\n// this example demostrates a black-scholes option pricing kernel.\nint main()\n{\n // number of options\n const int N = 4000000;\n\n // black-scholes parameters\n const float risk_free_rate = 0.02f;\n const float volatility = 0.30f;\n\n // get default device and setup context\n compute::device gpu = compute::system::default_device();\n compute::context context(gpu);\n compute::command_queue queue(context, gpu);\n std::cout << \"device: \" << gpu.name() << std::endl;\n\n // initialize option data on host\n std::vector stock_price_data(N);\n std::vector option_strike_data(N);\n std::vector option_years_data(N);\n\n std::srand(5347);\n for(int i = 0; i < N; i++){\n stock_price_data[i] = rand_float(5.0f, 30.0f);\n option_strike_data[i] = rand_float(1.0f, 100.0f);\n option_years_data[i] = rand_float(0.25f, 10.0f);\n }\n\n // create memory buffers on the device\n compute::vector call_result(N, context);\n compute::vector put_result(N, context);\n compute::vector stock_price(N, context);\n compute::vector option_strike(N, context);\n compute::vector option_years(N, context);\n\n // copy initial values to the device\n compute::copy_n(stock_price_data.begin(), N, stock_price.begin(), queue);\n compute::copy_n(option_strike_data.begin(), N, option_strike.begin(), queue);\n compute::copy_n(option_years_data.begin(), N, option_years.begin(), queue);\n\n // source code for black-scholes program\n const char source[] = BOOST_COMPUTE_STRINGIZE_SOURCE(\n // approximation of the cumulative normal distribution function\n static float cnd(float d)\n {\n const float A1 = 0.319381530f;\n const float A2 = -0.356563782f;\n const float A3 = 1.781477937f;\n const float A4 = -1.821255978f;\n const float A5 = 1.330274429f;\n const float RSQRT2PI = 0.39894228040143267793994605993438f;\n\n float K = 1.0f / (1.0f + 0.2316419f * fabs(d));\n float cnd =\n RSQRT2PI * exp(-0.5f * d * d) *\n (K * (A1 + K * (A2 + K * (A3 + K * (A4 + K * A5)))));\n\n if(d > 0){\n cnd = 1.0f - cnd;\n }\n\n return cnd;\n }\n\n // black-scholes option pricing kernel\n __kernel void black_scholes(__global float *call_result,\n __global float *put_result,\n __global const float *stock_price,\n __global const float *option_strike,\n __global const float *option_years,\n float risk_free_rate,\n float volatility)\n {\n const uint opt = get_global_id(0);\n\n float S = stock_price[opt];\n float X = option_strike[opt];\n float T = option_years[opt];\n float R = risk_free_rate;\n float V = volatility;\n\n float sqrtT = sqrt(T);\n float d1 = (log(S / X) + (R + 0.5f * V * V) * T) / (V * sqrtT);\n float d2 = d1 - V * sqrtT;\n float CNDD1 = cnd(d1);\n float CNDD2 = cnd(d2);\n\n float expRT = exp(-R * T);\n call_result[opt] = S * CNDD1 - X * expRT * CNDD2;\n put_result[opt] = X * expRT * (1.0f - CNDD2) - S * (1.0f - CNDD1);\n }\n );\n\n // build black-scholes program\n compute::program program = compute::program::create_with_source(source, context);\n program.build();\n\n // setup black-scholes kernel\n compute::kernel kernel(program, \"black_scholes\");\n kernel.set_arg(0, call_result);\n kernel.set_arg(1, put_result);\n kernel.set_arg(2, stock_price);\n kernel.set_arg(3, option_strike);\n kernel.set_arg(4, option_years);\n kernel.set_arg(5, risk_free_rate);\n kernel.set_arg(6, volatility);\n\n // execute black-scholes kernel\n queue.enqueue_1d_range_kernel(kernel, 0, N, 0);\n\n // print out the first option's put and call prices\n float call0, put0;\n compute::copy_n(put_result.begin(), 1, &put0, queue);\n compute::copy_n(call_result.begin(), 1, &call0, queue);\n\n std::cout << \"option 0 call price: \" << call0 << std::endl;\n std::cout << \"option 0 put price: \" << put0 << std::endl;\n\n // due to the differences in the random-number generators between linux and\n // mac os x, we will get different \"expected\" results for this example\n#ifdef __APPLE__\n double expected_call0 = 0.000249461;\n double expected_put0 = 26.2798;\n#else\n double expected_call0 = 0.0999f;\n double expected_put0 = 43.0524f;\n#endif\n\n // check option prices\n if(std::abs(call0 - expected_call0) > 1e-4 || std::abs(put0 - expected_put0) > 1e-4){\n std::cerr << \"error: option prices are wrong\" << std::endl;\n return -1;\n }\n\n return 0;\n}\n", "meta": {"hexsha": "b4b046956b2e9cc96a0d2932e27d544f657fa192", "size": 5860, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/black_scholes.cpp", "max_stars_repo_name": "skozilla/compute", "max_stars_repo_head_hexsha": "861a75ae9f05f5bbd25d13120788133a1c9dc886", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/black_scholes.cpp", "max_issues_repo_name": "skozilla/compute", "max_issues_repo_head_hexsha": "861a75ae9f05f5bbd25d13120788133a1c9dc886", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/black_scholes.cpp", "max_forks_repo_name": "skozilla/compute", "max_forks_repo_head_hexsha": "861a75ae9f05f5bbd25d13120788133a1c9dc886", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.3012048193, "max_line_length": 89, "alphanum_fraction": 0.5872013652, "num_tokens": 1530, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297834483234, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6665490631223572}} {"text": "#include \n#include \n\n#include \n#include \n#include \"ceres/ceres.h\"\n#include \"glog/logging.h\"\n#include \n\nusing ceres::AutoDiffCostFunction;\nusing ceres::NumericDiffCostFunction;\nusing ceres::CENTRAL;\nusing ceres::CostFunction;\nusing ceres::Problem;\nusing ceres::Solve;\nusing ceres::Solver;\nusing Eigen::Isometry3d;\nusing Eigen::Vector3d;\nusing Eigen::Quaterniond;\nusing Eigen::Matrix3d;\nusing Eigen::cos;\nusing Eigen::sin;\nusing std::vector;\n\nconst double DT = 1.0 / 18;\n// const Eigen::Vector3d GRAVITY{0, 0, 0};\nconst Eigen::Vector3d GRAVITY{0, 0, -9.8};\n\nvoid DrawTrajectory(vector>);\nvoid DrawTrajectoryComparison(vector>,\n vector>);\n\nstruct State {\n Eigen::Vector3d pos = Eigen::Vector3d::Random(); // position \n Eigen::Vector3d vel = Eigen::Vector3d::Random(); // velocity\n Eigen::Vector3d aaxis = Eigen::Vector3d::Random(); // Lie Algebra (Angle axis)\n // Eigen::Quaterniond q = Eigen::Quaterniond::UnitRandom(); // pose Qwr\n\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\nstruct Measurement{\n Eigen::Matrix3d Rwr;\n Eigen::Quaterniond qwr;\n Eigen::Vector3d twr;\n Eigen::Vector3d acc;\n Eigen::Vector3d omega;\n\n Measurement(Eigen::Matrix3d Rwr, \n Eigen::Quaterniond qwr,\n Eigen::Vector3d twr,\n Eigen::Vector3d acc,\n Eigen::Vector3d omega)\n : Rwr(Rwr), qwr(qwr), twr(twr), acc(acc), omega(omega) {}\n\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\nstruct PoseError {\n PoseError(const Eigen::Vector3d& pos_measured,\n const Eigen::Matrix3d& R_measured)\n : pos_measured_(pos_measured), R_measured_(R_measured) {}\n\n template \n bool operator()(const T* const pos_hat_ptr,\n const T* const aaxis_hat_ptr,\n T* residuals_ptr) const { \n Eigen::Matrix residuals;\n \n Eigen::Matrix pos_hat(pos_hat_ptr);\n Eigen::Matrix pos_delta;\n residuals.template block<3, 1>(0, 0) = pos_hat - pos_measured_.template cast();\n\n Eigen::Matrix axis_hat(aaxis_hat_ptr);\n Eigen::AngleAxisd aaxis_m(R_measured_);\n\n T angle_hat = -axis_hat.norm();\n axis_hat.normalize();\n T sin_half_hat = sin(angle_hat / T(2.0));\n T cos_half_hat = cos(angle_hat / T(2.0));\n\n T angle_m = T(aaxis_m.angle());\n Eigen::Matrix axis_m = aaxis_m.axis().template cast();\n T sin_half_m = sin(angle_m / T(2.0));\n T cos_half_m = cos(angle_m / T(2.0));\n\n T cos_half_delta = cos_half_hat * cos_half_m - sin_half_hat * sin_half_m * axis_hat.dot(axis_m);\n Eigen::Matrix axis_delta = sin_half_hat * cos_half_m * axis_hat + \n cos_half_hat * sin_half_m * axis_m + \n sin_half_hat * sin_half_m * axis_hat.cross(axis_m);\n\n residuals.template block<3, 1>(3, 0) = axis_delta;\n for (int i = 0; i < 6; i++) {\n residuals_ptr[i] = residuals[i];\n }\n return true;\n } \n \n static CostFunction* Create(const Eigen::Vector3d& pos_measured,\n const Eigen::Matrix3d& R_measured) {\n return new AutoDiffCostFunction(\n new PoseError(pos_measured, R_measured));\n }\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n const Eigen::Vector3d pos_measured_;\n const Eigen::Matrix3d R_measured_;\n};\n\nstruct PredictionError{\n PredictionError(const Eigen::Vector3d& acc_measured,\n const Eigen::Vector3d& omega_measured)\n : acc_measured_(acc_measured), omega_measured_(omega_measured) {}\n\n template \n bool operator()(const T* const pos_b_ptr,\n const T* const vel_b_ptr,\n const T* const aaxis_b_ptr,\n const T* const pos_e_ptr,\n const T* const vel_e_ptr,\n const T* const aaxis_e_ptr,\n const T* const bias_ptr,\n T* residuals_ptr) const {\n Eigen::Matrix residuals;\n\n // rot error\n Eigen::Matrix axis_b(aaxis_b_ptr);\n Eigen::Matrix axis_e(aaxis_e_ptr);\n Eigen::Matrix axis_d = omega_measured_.template cast() * DT;\n\n int choice = 1;\n if (choice == 0) {\n // Eigen::AngleAxis aaxis_b(axis_b.norm(), axis_b.normalized());\n // Eigen::AngleAxis aaxis_e(axis_e.norm(), axis_e.normalized());\n // Eigen::AngleAxis aaxis_d(axis_d.norm(), axis_d.normalized());\n\n // Eigen::AngleAxis aaxis_delta(aaxis_d.inverse() * aaxis_b.inverse() * aaxis_e);\n // residuals.template block<3, 1>(6, 0) = aaxis_delta.angle() * aaxis_delta.axis();\n } else if (choice == 1) {\n }\n // Reference: https://math.stackexchange.com/questions/382760/composition-of-two-axis-angle-rotations\n T angle_b = -axis_b.norm();\n axis_b.normalize();\n T sin_half_b = sin(angle_b / T(2));\n T cos_half_b = cos(angle_b / T(2));\n\n T angle_e = axis_e.norm();\n axis_e.normalize();\n T sin_half_e = sin(angle_e / T(2));\n T cos_half_e = cos(angle_e / T(2));\n\n T cos_half_be = cos_half_b * cos_half_e - sin_half_b * sin_half_e * axis_b.dot(axis_e);\n Eigen::Matrix axis_be = sin_half_b * cos_half_e * axis_b + cos_half_b * sin_half_e * axis_e + sin_half_b * sin_half_e * axis_b.cross(axis_e);\n T sin_half_be = axis_be.norm();\n axis_be.normalize();\n\n T angle_d = -axis_d.norm();\n axis_d.normalize();\n T sin_half_d = sin(angle_d / T(2));\n T cos_half_d = cos(angle_d / T(2));\n\n T cos_half_delta = cos_half_d * cos_half_be - sin_half_d * sin_half_be * axis_d.dot(axis_be);\n Eigen::Matrix axis_delta = sin_half_d * cos_half_be * axis_d + cos_half_d * sin_half_be * axis_be + sin_half_d * sin_half_be * axis_d.cross(axis_be);\n\n residuals.template block<3, 1>(6, 0) = axis_delta;\n \n angle_b = -angle_b;\n T sin_b = sin(angle_b);\n T cos_b = cos(angle_b);\n Eigen::Matrix axis_b_cross = Eigen::Matrix::Zero();\n axis_b_cross(0, 1) = -axis_b[2]; \n axis_b_cross(1, 0) = axis_b[2]; \n axis_b_cross(0, 2) = axis_b[1]; \n axis_b_cross(2, 0) = -axis_b[1]; \n axis_b_cross(1, 2) = -axis_b[0]; \n axis_b_cross(2, 1) = axis_b[0]; \n \n Eigen::Matrix rot_b = cos_b * Eigen::Matrix::Identity() +\n (T(1.0) - cos_b) * axis_b * axis_b.transpose() + \n sin_b * axis_b_cross;\n // vel error\n const Eigen::Matrix bias(bias_ptr);\n const Eigen::Matrix vel_b(vel_b_ptr);\n const Eigen::Matrix vel_e(vel_e_ptr);\n residuals.template block<3, 1>(3, 0) = vel_b + (rot_b * (acc_measured_.template cast() - bias) - GRAVITY) * DT - vel_e;\n\n // pos error\n const Eigen::Matrix pos_b(pos_b_ptr);\n const Eigen::Matrix pos_e(pos_e_ptr);\n residuals.template block<3, 1>(0, 0) = pos_b + vel_b * DT - pos_e;\n\n for (int i = 0; i < 9; i++) {\n residuals_ptr[i] = residuals[i];\n }\n return true;\n } \n \n static CostFunction* Create(const Eigen::Vector3d& acc_measured,\n const Eigen::Vector3d& omega_measured) {\n return new AutoDiffCostFunction(\n new PredictionError(acc_measured, omega_measured));\n }\n\nEIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\nprivate:\n const Eigen::Vector3d acc_measured_;\n const Eigen::Vector3d omega_measured_;\n};\n\nstd::vector> readSensorData(std::string path) {\n std::vector> ret;\n\n std::ifstream csvFile;\n csvFile.open(path);\n\n std::string line;\n while(std::getline(csvFile, line)) {\n std::vector 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>& states,\n const std::vector>& 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> data = readSensorData(path); \n \n int cnt = data.size();\n // int cnt = 3;\n\n // Eigen::Vector3d bias = Eigen::Vector3d::Random();\n Eigen::Vector3d bias;\n bias << 0, 0, 0;\n std::vector> states(cnt);\n std::vector> gt_states(cnt);\n std::cout << \"states size: \" << states.size() << std::endl;\n\n for (int i = 0; i < gt_states.size(); i++) {\n gt_states[i].pos = data[i].twr;\n gt_states[i].vel = Eigen::Vector3d::Zero();\n Eigen::AngleAxisd temp(data[i].Rwr);\n gt_states[i].aaxis = temp.angle() * temp.axis();\n }\n\n Problem problem;\n \n ceres::LossFunction* loss_function = nullptr;\n\n for (int i = 0; i < cnt; i++) {\n ceres::CostFunction* pos_cost_function = PoseError::Create(data[i].twr, data[i].Rwr);\n problem.AddResidualBlock(pos_cost_function,\n loss_function,\n states[i].pos.data(),\n states[i].aaxis.data());\n if (i > 0) {\n ceres::CostFunction* pred_cost_function = PredictionError::Create(data[i].acc, data[i].omega);\n problem.AddResidualBlock(pred_cost_function,\n loss_function,\n states[i - 1].pos.data(),\n states[i - 1].vel.data(),\n states[i - 1].aaxis.data(),\n states[i].pos.data(),\n states[i].vel.data(),\n states[i].aaxis.data(),\n bias.data());\n }\n } \n\n ceres::Solver::Options options;\n\toptions.max_num_iterations = 200;\n options.linear_solver_type = ceres::DENSE_SCHUR;\n // options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY;\n options.minimizer_progress_to_stdout = true;\n\n ceres::Solver::Summary summary;\n ceres::Solve(options, &problem, &summary);\n std::cout << summary.FullReport() << \"\\n\";\n \n vector> poses;\n vector> gt_poses;\n for (int i = 0; i < cnt; i++) {\n Eigen::AngleAxisd temp(states[i].aaxis.norm(), states[i].aaxis.normalized());\n Isometry3d Twr(temp.matrix());\n Twr.pretranslate(states[i].pos / 20); // manually divided by 20 to zoom out\n poses.push_back(Twr);\n }\n for (int i = 0; i < cnt; i++) {\n Eigen::AngleAxisd temp(gt_states[i].aaxis.norm(), gt_states[i].aaxis.normalized());\n Isometry3d Twr(temp.matrix());\n Twr.pretranslate(gt_states[i].pos / 20); // manually divided by 20 to zoom out\n gt_poses.push_back(Twr);\n }\n\n double err = abs_pos_error(states, gt_states); \n std::cout << \"absolute position error: \" << err << std::endl;\n DrawTrajectoryComparison(poses, gt_poses);\n return 0;\n}\n\nvoid DrawTrajectoryComparison(vector> poses,\n vector> gt_poses) {\n // create pangolin window and plot the trajectory\n pangolin::CreateWindowAndBind(\"Trajectory Viewer\", 1024, 768);\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n pangolin::OpenGlRenderState s_cam(\n pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n );\n\n pangolin::View &d_cam = pangolin::CreateDisplay()\n .SetBounds(0.0, 1.0, 0.0, 1.0, -1024.0f / 768.0f)\n .SetHandler(new pangolin::Handler3D(s_cam));\n\n while (pangolin::ShouldQuit() == false) {\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n d_cam.Activate(s_cam);\n glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n glLineWidth(2);\n for (size_t i = 0; i < poses.size(); i++) {\n // 画每个位姿的三个坐标轴\n Vector3d Ow = poses[i].translation();\n Vector3d Xw = poses[i] * (0.1 * Vector3d(1, 0, 0));\n Vector3d Yw = poses[i] * (0.1 * Vector3d(0, 1, 0));\n Vector3d Zw = poses[i] * (0.1 * Vector3d(0, 0, 1));\n glBegin(GL_LINES);\n glColor3f(1.0, 0.0, 0.0);\n glVertex3d(Ow[0], Ow[1], Ow[2]);\n glVertex3d(Xw[0], Xw[1], Xw[2]);\n glColor3f(0.0, 1.0, 0.0);\n glVertex3d(Ow[0], Ow[1], Ow[2]);\n glVertex3d(Yw[0], Yw[1], Yw[2]);\n glColor3f(0.0, 0.0, 1.0);\n glVertex3d(Ow[0], Ow[1], Ow[2]);\n glVertex3d(Zw[0], Zw[1], Zw[2]);\n glEnd();\n }\n // 画出连线\n for (size_t i = 0; i < poses.size(); i++) {\n glColor3f(1.0, 0.0, 0.0);\n glBegin(GL_LINES);\n auto p1 = poses[i], p2 = poses[i + 1];\n glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n glEnd();\n }\n\n for (size_t i = 0; i < gt_poses.size(); i++) {\n // 画每个位姿的三个坐标轴\n Vector3d Ow = gt_poses[i].translation();\n Vector3d Xw = gt_poses[i] * (0.1 * Vector3d(1, 0, 0));\n Vector3d Yw = gt_poses[i] * (0.1 * Vector3d(0, 1, 0));\n Vector3d Zw = gt_poses[i] * (0.1 * Vector3d(0, 0, 1));\n glBegin(GL_LINES);\n glColor3f(1.0, 0.0, 0.0);\n glVertex3d(Ow[0], Ow[1], Ow[2]);\n glVertex3d(Xw[0], Xw[1], Xw[2]);\n glColor3f(0.0, 1.0, 0.0);\n glVertex3d(Ow[0], Ow[1], Ow[2]);\n glVertex3d(Yw[0], Yw[1], Yw[2]);\n glColor3f(0.0, 0.0, 1.0);\n glVertex3d(Ow[0], Ow[1], Ow[2]);\n glVertex3d(Zw[0], Zw[1], Zw[2]);\n glEnd();\n }\n // 画出连线\n for (size_t i = 0; i < gt_poses.size(); i++) {\n glColor3f(0.0, 1.0, 0.0);\n glBegin(GL_LINES);\n auto p1 = gt_poses[i], p2 = gt_poses[i + 1];\n glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n glEnd();\n }\n pangolin::FinishFrame();\n usleep(5000); // sleep 5 ms\n }\n}\n\n/*******************************************************************************************/\nvoid DrawTrajectory(vector> poses) {\n // create pangolin window and plot the trajectory\n pangolin::CreateWindowAndBind(\"Trajectory Viewer\", 1024, 768);\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n pangolin::OpenGlRenderState s_cam(\n pangolin::ProjectionMatrix(1024, 768, 500, 500, 512, 389, 0.1, 1000),\n pangolin::ModelViewLookAt(0, -0.1, -1.8, 0, 0, 0, 0.0, -1.0, 0.0)\n );\n\n pangolin::View &d_cam = pangolin::CreateDisplay()\n .SetBounds(0.0, 1.0, 0.0, 1.0, -1024.0f / 768.0f)\n .SetHandler(new pangolin::Handler3D(s_cam));\n\n while (pangolin::ShouldQuit() == false) {\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n d_cam.Activate(s_cam);\n glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n glLineWidth(2);\n for (size_t i = 0; i < poses.size(); i++) {\n // 画每个位姿的三个坐标轴\n Vector3d Ow = poses[i].translation();\n Vector3d Xw = poses[i] * (0.1 * Vector3d(1, 0, 0));\n Vector3d Yw = poses[i] * (0.1 * Vector3d(0, 1, 0));\n Vector3d Zw = poses[i] * (0.1 * Vector3d(0, 0, 1));\n glBegin(GL_LINES);\n glColor3f(1.0, 0.0, 0.0);\n glVertex3d(Ow[0], Ow[1], Ow[2]);\n glVertex3d(Xw[0], Xw[1], Xw[2]);\n glColor3f(0.0, 1.0, 0.0);\n glVertex3d(Ow[0], Ow[1], Ow[2]);\n glVertex3d(Yw[0], Yw[1], Yw[2]);\n glColor3f(0.0, 0.0, 1.0);\n glVertex3d(Ow[0], Ow[1], Ow[2]);\n glVertex3d(Zw[0], Zw[1], Zw[2]);\n glEnd();\n }\n // 画出连线\n for (size_t i = 0; i < poses.size(); i++) {\n glColor3f(0.0, 0.0, 0.0);\n glBegin(GL_LINES);\n auto p1 = poses[i], p2 = poses[i + 1];\n glVertex3d(p1.translation()[0], p1.translation()[1], p1.translation()[2]);\n glVertex3d(p2.translation()[0], p2.translation()[1], p2.translation()[2]);\n glEnd();\n }\n pangolin::FinishFrame();\n usleep(5000); // sleep 5 ms\n }\n}", "meta": {"hexsha": "10346858bcb6ca78cd73b49f6f253eaf6a982ba6", "size": 17392, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "experimental/solverLieNum.cpp", "max_stars_repo_name": "yimuw/expriment", "max_stars_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "experimental/solverLieNum.cpp", "max_issues_repo_name": "yimuw/expriment", "max_issues_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "experimental/solverLieNum.cpp", "max_forks_repo_name": "yimuw/expriment", "max_forks_repo_head_hexsha": "5c4185d969556e7ec007aceaf0eb82f7e79f8abb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.2333333333, "max_line_length": 162, "alphanum_fraction": 0.6001034959, "num_tokens": 5555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787537, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6665490508236882}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\nauto fit(const arma::fvec& x, const arma::fvec& y) -> arma::fvec\n{\n auto xx = x - arma::mean(x);\n auto yy = y - arma::mean(y);\n float b = arma::sum(xx % yy) / arma::sum(xx % xx);\n float a = arma::mean(y) - b * arma::mean(x);\n return a + b * x;\n}\n\n\nauto random(arma::fvec x, float mean, float std)\n{\n std::random_device rd;\n std::mt19937 gen(rd());\n std::normal_distribution<> dis(mean, std);\n\n for(auto& e: x)\n {\n e += dis(gen);\n }\n\n return x;\n}\n\n\nauto get_dots()\n{\n arma::fvec x = mona::linspace(-4, 4, 30);\n arma::fvec y = random(x, 0, 0.9);\n return mona::dots(x, y, mona::colors::tomato);\n}\n\nauto get_line()\n{\n auto f = [](double x)\n {\n return std::sin(x);\n };\n\n arma::fvec x = mona::linspace(-4, 4, 50);\n arma::fvec y = x;\n y.transform(f);\n\n return mona::line(x, y, mona::colors::midnight_blue);\n}\n\n\nauto f1(double x, double y)\n{\n return (7 * x * y) / std::exp(x*x + y*y);\n};\n\nauto f2(double x, double y)\n{\n return std::pow(x, 4) + std::pow(y, 4) - std::pow(x + y, 2);\n};\n\ntemplate \nauto get_surface(F f)\n{\n arma::fvec line = mona::linspace(-2, 2, 50);\n auto [x, y] = mona::meshgrid(line, line);\n auto z = mona::apply(f, x, y);\n\n auto mesh = mona::surface_mesh(x, y, z);\n\n return mesh;\n}\n\nint main()\n{\n auto win = mona::targets::window();\n auto view = mona::grid(2, 2);\n auto cam = mona::camera();\n auto axes_dots = mona::axes();\n auto axes_line = mona::axes();\n auto axes_surf1 = mona::axes3({-4, 4}, {-4, 4}, {-4, 4}, 5);\n axes_surf1.set_camera_control(win.get_camera_control());\n\n auto axes_surf2 = mona::axes3({-4, 4}, {-4, 4}, {-4, 4}, 5);\n axes_surf2.set_camera_control(mona::camera_steady_control(0.2f, 0.f));\n\n auto dots = get_dots();\n auto line = get_line();\n auto surf1 = get_surface(f1);\n auto surf2 = get_surface(f2);\n\n while (win.active())\n {\n axes_dots.submit(dots);\n axes_line.submit(line);\n axes_surf1.submit(surf1);\n axes_surf2.submit(surf2);\n\n view(0, 0).submit(axes_dots);\n view(0, 1).submit(axes_surf1);\n view(1, 0).submit(axes_surf2);\n view(1, 1).submit(axes_line);\n\n win.submit(view);\n win.draw();\n }\n}", "meta": {"hexsha": "c6398d902fdb59704ecb6aa3fd1fc2451daf70bc", "size": 2551, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/grid_view/main.cpp", "max_stars_repo_name": "Eleobert/mona", "max_stars_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/grid_view/main.cpp", "max_issues_repo_name": "Eleobert/mona", "max_issues_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/grid_view/main.cpp", "max_forks_repo_name": "Eleobert/mona", "max_forks_repo_head_hexsha": "079e70b190b0850cf2579c1b0872da87f2706d80", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9913793103, "max_line_length": 74, "alphanum_fraction": 0.5770286162, "num_tokens": 844, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543487, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6665329806982901}} {"text": "///////////////////////////////////////////////////////////////////////////////\r\n// Copyright Christopher Kormanyos 2015 - 2016.\r\n// Distributed under the Boost Software License,\r\n// Version 1.0. (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n//\r\n\r\n// fixed_point_detail_constants.hpp implements templates\r\n// for computing fixed-point representations of the\r\n// mathematical constants sqrt(2), pi, log(2) and e.\r\n\r\n#ifndef FIXED_POINT_DETAIL_CONSTANTS_2015_08_16_HPP_\r\n #define FIXED_POINT_DETAIL_CONSTANTS_2015_08_16_HPP_\r\n\r\n #include \r\n #include \r\n\r\n #include \r\n\r\n namespace boost { namespace fixed_point { namespace detail {\r\n\r\n template\r\n NumericType calculate_root_two()\r\n {\r\n // Provide a very rough initial guess of 4/3, which is about\r\n // 5 percent off of the actual value. Use small integers here\r\n // because the underlying NumericType might have limited range.\r\n NumericType a(NumericType(4U) / 3U);\r\n\r\n // Estimate the zero'th term of the iteration with [1 / (2 * result)],\r\n // giving [1 / (2 * (4/3))] = 3/8.\r\n using std::ldexp;\r\n NumericType vi(ldexp(NumericType(3U), -3));\r\n\r\n // Compute the square root of x using coupled Newton iteration.\r\n // We begin with an estimate of 1 binary digit of precision and\r\n // double the number of binary digits of precision with each iteration.\r\n\r\n for(std::uint_fast16_t i = UINT16_C(1); i <= std::uint_fast16_t(std::numeric_limits::digits); i *= UINT16_C(2))\r\n {\r\n // Perform the next iteration of vi.\r\n vi += vi * (-((a * vi) * 2U) + NumericType(1U));\r\n\r\n // Perform the next iteration of the result.\r\n a += (vi * (-((a) * (a)) + NumericType(2U)));\r\n }\r\n\r\n return a;\r\n }\r\n\r\n template\r\n NumericType calculate_pi()\r\n {\r\n using std::fabs;\r\n using std::ldexp;\r\n using std::sqrt;\r\n\r\n // Use a quadratically converging Gauss-AGM method to compute pi.\r\n\r\n NumericType val_pi;\r\n\r\n NumericType a (1U);\r\n NumericType bB(ldexp(NumericType(1U), -1));\r\n NumericType s (bB);\r\n NumericType t (ldexp(NumericType(3U), -3));\r\n\r\n // This loop is designed for computing a maximum of a few million\r\n // decimal digits of pi. The number of digits roughly doubles\r\n // with each iteration of the loop. After 20 iterations,\r\n // the precision is about 2.8 million decimal digits.\r\n // We are, however, not using that many digits in this\r\n // application --- rarely more than a few thousand at most.\r\n\r\n const NumericType tolerance = ldexp(NumericType(1U), -int((long(std::numeric_limits::digits) * 3L) / 4L));\r\n\r\n for(std::uint_least8_t k = UINT8_C(1); k < UINT8_C(32); ++k)\r\n {\r\n // Perform the iteration steps of the Gauss AGM.\r\n\r\n a += sqrt(bB);\r\n a /= 2U;\r\n val_pi = (a * a);\r\n bB = (val_pi - t) * 2U;\r\n\r\n const NumericType iterate_term((bB - val_pi) * (UINT32_C(1) << k));\r\n\r\n s += iterate_term;\r\n\r\n const bool minimum_number_of_iterations_is_complete = (k > UINT8_C(4));\r\n\r\n if((minimum_number_of_iterations_is_complete) && (fabs(iterate_term) <= tolerance))\r\n {\r\n break;\r\n }\r\n\r\n t = (val_pi + bB) / 4U;\r\n }\r\n\r\n val_pi += bB;\r\n val_pi /= s;\r\n\r\n return val_pi;\r\n }\r\n\r\n template\r\n NumericType calculate_ln_two()\r\n {\r\n using std::fabs;\r\n using std::ldexp;\r\n using std::sqrt;\r\n\r\n // Use a quadratically converging Gauss-AGM method for computing log(2).\r\n\r\n // Choose m > (N * 1.661), where N is the number of decimal digits requested.\r\n BOOST_CONSTEXPR_OR_CONST int m((long(std::numeric_limits::digits10) * 17L) / 10L);\r\n\r\n // Set a0 = 1.\r\n // Set b0 = 4 / (2^m) = 1 / 2^(m - 2).\r\n NumericType ak(1);\r\n\r\n NumericType bk(ldexp(NumericType(1), -(m - 2)));\r\n\r\n const NumericType tolerance = ldexp(NumericType(1U), -int((long(std::numeric_limits::digits) * 3L) / 4L));\r\n\r\n for(std::uint_least8_t k = UINT8_C(0); k < UINT8_C(32); ++k)\r\n {\r\n const NumericType a(ak);\r\n\r\n ak += bk;\r\n ak /= 2U;\r\n\r\n bk = sqrt(bk * a);\r\n\r\n const bool minimum_number_of_iterations_is_complete = (k > UINT8_C(4));\r\n\r\n if((minimum_number_of_iterations_is_complete) && (fabs(ak - bk) <= tolerance))\r\n {\r\n break;\r\n }\r\n }\r\n\r\n // The iteration is now finished. Compute ln2 = pi / [AGM(1, 4 / 2^m) * 2m].\r\n // Note that the result of the AGM iteration is [ak = bk = AGM(...)].\r\n const NumericType val_ln_two = calculate_pi() / (ak * (2U * m));\r\n\r\n return val_ln_two;\r\n }\r\n\r\n template\r\n NumericType calculate_e()\r\n {\r\n using std::fabs;\r\n\r\n NumericType term(1U);\r\n NumericType sum (2U);\r\n\r\n BOOST_CONSTEXPR_OR_CONST std::uint32_t maximum_number_of_iterations = UINT32_C(10000);\r\n\r\n // Perform the Taylor series expansion of Euler's constant, e = exp(1).\r\n for(std::uint32_t n = UINT32_C(2); n < maximum_number_of_iterations; ++n)\r\n {\r\n term /= n;\r\n\r\n const bool minimum_number_of_iterations_is_complete = (n > UINT32_C(4));\r\n\r\n if( (minimum_number_of_iterations_is_complete)\r\n && (fabs(term) <= std::numeric_limits::epsilon()))\r\n {\r\n break;\r\n }\r\n\r\n sum += term;\r\n }\r\n\r\n return sum;\r\n }\r\n } } } // namespace boost::fixed_point::detail\r\n\r\n#endif // FIXED_POINT_DETAIL_CONSTANTS_2015_08_16_HPP_\r\n", "meta": {"hexsha": "673359d2e296e8a902a82051385cfb86a4bdebfb", "size": 5549, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/fixed_point/detail/fixed_point_detail_constants.hpp", "max_stars_repo_name": "BoostGSoC15/fixed-point", "max_stars_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/fixed_point/detail/fixed_point_detail_constants.hpp", "max_issues_repo_name": "BoostGSoC15/fixed-point", "max_issues_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/fixed_point/detail/fixed_point_detail_constants.hpp", "max_forks_repo_name": "BoostGSoC15/fixed-point", "max_forks_repo_head_hexsha": "d71b4a622ded821a2429d8d857097441c2a10246", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8277777778, "max_line_length": 129, "alphanum_fraction": 0.6136240764, "num_tokens": 1492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.666532977263737}} {"text": "/*=============================================================================\n\nMPHYG0022CW1: CW1, 2019: Linear Regression.\n\nCopyright (c) University College London (UCL). All rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE.\n\nSee LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include \"mphyNormalEquationSolverStrategy.h\"\n#include \"vectorPairTypes.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace mphy {\n\npairdd normSolver::FitData(vecPairdd data){\n\t/* \n\tFinds optimal theta using the Normal Equation. \n\ttheta_best = inv(X^T . X) . X^T . y, where:\n\n\tdata:\t\ta vector of pairs (x, y)\n\tX:\t\t\ta 2xnumData matrix of (1, x0; 1, x1; 1, x2...)\n\t */\n\t\n\tEigen::Matrix xdata; \n\tEigen::VectorXd ydata, theta_best; \n\n\txdata = copyXtoEigen(data);\n\tydata = copyYtoEigen(data);\n\t\n\ttheta_best = ((xdata.transpose()*xdata).inverse())*xdata.transpose()*ydata;\n\t\n\n\treturn pairdd(theta_best(0), theta_best(1));\n}\n\n} // end namespace mphy", "meta": {"hexsha": "c8bfaada1f11a7a8c7779a30c63e4d31c551b2bd", "size": 1228, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/Lib/mphyNormalEquationSolverStrategy.cpp", "max_stars_repo_name": "DylanScotney/MPHY0022CW1", "max_stars_repo_head_hexsha": "003ee2b4b8fc45d4b967a36fd7332d80f2abbef9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/Lib/mphyNormalEquationSolverStrategy.cpp", "max_issues_repo_name": "DylanScotney/MPHY0022CW1", "max_issues_repo_head_hexsha": "003ee2b4b8fc45d4b967a36fd7332d80f2abbef9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Code/Lib/mphyNormalEquationSolverStrategy.cpp", "max_forks_repo_name": "DylanScotney/MPHY0022CW1", "max_forks_repo_head_hexsha": "003ee2b4b8fc45d4b967a36fd7332d80f2abbef9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5833333333, "max_line_length": 79, "alphanum_fraction": 0.6294788274, "num_tokens": 306, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9399133447766224, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.6664165339883676}} {"text": "// Eigen lib tutorial -- Array class and coefficient-wise operations\n// Source:\n// http://eigen.tuxfamily.org/dox/group__TutorialArrayClass.html\n#include \n#include \n\nusing namespace Eigen;\n\nint main(void)\n{\n // Accessing values inside an Array\n ArrayXXf m(2,2);\n\n // assign some value coefficient by coefficient\n m(0,0) = 1.0; m(0,1) = 2.0;\n m(1,0) = 3.0; m(1,1) = m(0,1) + m(1,0);\n\n // print values to standard output\n std::cout << m << '\\n' << std::endl;\n\n // using the comma-initializer is also allowed\n m << 1.0, 3.0,\n 5.0, 7.0;\n std::cout << m << std::endl;\n\n // Array addition and subtraction\n ArrayXXf a(3,3);\n ArrayXXf b(3,3);\n a << 1,2,3,\n 4,5,6,\n 7,8,9;\n b << 1,2,3,\n 1,2,3,\n 1,2,3;\n\n // Adding two arrays\n std::cout << \"a + b = \" << '\\n' << a + b << std::endl;\n\n // Subtracting a scalar from an array\n std::cout << \"a - 2 = \" << '\\n' << a -2 << std::endl;\n\n\n // Array multiplication\n ArrayXXf c(2,2);\n ArrayXXf d(2,2);\n c << 1,2,\n 3,4;\n d << 5,6,\n 7,8;\n std::cout << \"c * d = \" << '\\n' << c * d << std::endl;\n\n // Converting b/w array and matrix expressions\n MatrixXf u(2,2);\n MatrixXf v(2,2);\n MatrixXf result(2,2);\n\n u << 1,2,\n 3,4;\n v << 5,6,\n 7,8;\n\n result = u * v;\n std::cout << \"-- Matrix u * v: --\\n\" << result << '\\n' << std::endl;\n\n result = u.array() * v.array();\n std::cout << \"-- Array u * v: --\\n\" << result << '\\n' << std::endl;\n\n result = u.cwiseProduct(v);\n std::cout << \"-- With cwiseProduct: --\\n\" << result << '\\n' << std::endl;\n\n result = u.array() + 4;\n std::cout << \"-- Array u + 4: --\\n\" << result << '\\n' << std::endl;\n\n result = (u.array() + 4).matrix() * u;\n std::cout << \"-- Combination 1: --\" << std::endl << result << std::endl << std::endl;\n result = (u.array() * v.array()).matrix() * u;\n std::cout << \"-- Combination 2: --\" << std::endl << result << std::endl << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "3047aa69acd8b2a4fe50edb57ed716f435a28f17", "size": 2059, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Eigen_practice/eigen_ex5.cpp", "max_stars_repo_name": "RobinCPC/ros_tutorials", "max_stars_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Eigen_practice/eigen_ex5.cpp", "max_issues_repo_name": "RobinCPC/ros_tutorials", "max_issues_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Eigen_practice/eigen_ex5.cpp", "max_forks_repo_name": "RobinCPC/ros_tutorials", "max_forks_repo_head_hexsha": "9f7ce9a4a08dd8ca26416a04b9bc7941a248a645", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-29T06:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-29T06:32:54.000Z", "avg_line_length": 25.4197530864, "max_line_length": 89, "alphanum_fraction": 0.4934434191, "num_tokens": 731, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391617003942, "lm_q2_score": 0.7718435083355187, "lm_q1q2_score": 0.6664032147357991}} {"text": "#include \n#include \n#include \n\ntemplate \nvoid kron(const Matrix & A, const Matrix & B, Matrix & C)\n{\t\n\t/*int n=A.cols();\n\tint m=A.rows();*/\n\tC= Matrix(A.rows()*B.rows(),A.cols()*B.cols());\n\tfor (int i=0;i\n\n#include \"opentsb/math.h\"\n#include \n#include \n\nusing namespace NTL;\nusing namespace std;\n\n void lcm(ZZ& k, const ZZ& x, const ZZ& y) {\n ZZ gcd;\n mul(k, x, y);\n GCD(gcd, x, y);\n k /= gcd;\n}\n\n//一次性运算求 向量的 lcm/gcd\nvec_ZZ lcm_gcd_vec(const vec_ZZ& v,int typemode){\n \n vec_ZZ vec_out;\n long m,n,j,i;\n ZZ temp;\n i=0;\n j=0;\n\n n= v.length();\n m= ceil(n/2.0);//向上取整,必须是非整数,即 2---》2.0\n vec_out.SetLength(m);\n switch (typemode) {\n case 1:\n for (i=0; i < n-1; i+=2) {\n \n lcm(temp,v[i],v[i+1]);\n // cout << temp<< endl;\n vec_out[j] = temp;\n //cout << vec_out << endl;\n j++;\n // cout << j << endl;\n }\n // cout << i << endl;\n if (n % 2 == 1 ) {\n lcm( vec_out[j],v[i],ZZ(1));\n }\n break;\n case 2:\n for (i=0; i < n-1; i+=2) {\n GCD(temp,v[i],v[i+1]);\n // cout << temp<< endl;\n vec_out[j] = temp;\n //cout << vec_out << endl;\n j++;\n // cout << j << endl;\n }\n // cout << i << endl;\n if (n % 2 == 1 ) {\n GCD( vec_out[j],v[i],v[i-1]);\n }\n break;\n }\n return vec_out;\n}\n\n//求 n 个数的最大公约数/最小公倍数\nvec_ZZ lcm_gcd_vec(const vec_ZZ& v,int typemode,long endleng){\n \n vec_ZZ vec_out;\n \n vec_out= lcm_gcd_vec(v, typemode);\n endleng=vec_out.length();\n \n while (endleng != 1) {\n vec_out= lcm_gcd_vec(vec_out, typemode);\n endleng=vec_out.length();\n }\n \n return vec_out;\n}\n\n\n\n//array can use \"for\" to assignment,but vector can't。if must,can use vector.push_back\nvoid array_to_vec(const ZZ arr[],vec_ZZ &v,long len) {\n // long n= v.length();\n \n v.SetLength(len);\n for (int i=0; i<=len-1; i++) {\n v[i]=arr[i];\n }\n //cout< > arr,mat_ZZ &v){\n long m= v.NumRows();\n long n= v.NumCols();\n \n for (int i=0;i<=m-1;i++){\n for (int j=0; j<=n-1; j++) {\n v[i][j]=arr[i][j];\n }\n }\n \n}\n\nvoid array2_to_mat(const vector< vector > arr,mat_ZZ &v){\n long m= v.NumRows();\n long n= v.NumCols();\n \n for (int i=0;i<=m-1;i++){\n for (int j=0; j<=n-1; j++) {\n v[i][j]=to_ZZ(arr[i][j]);\n }\n }\n \n}\n\nvoid array2_to_mat(const vector< vector > arr,mat_GF2 &v){\n long m= v.NumRows();\n long n= v.NumCols();\n \n for (int i=0;i<=m-1;i++){\n for (int j=0; j<=n-1; j++) {\n v[i][j]=to_GF2(arr[i][j]);\n }\n }\n \n}\n\nvoid array2_to_mat(const vector< vector > arr,mat_GF2 &v){\n long m= v.NumRows();\n long n= v.NumCols();\n \n for (int i=0;i<=m-1;i++){\n for (int j=0; j<=n-1; j++) {\n v[i][j]=to_GF2(arr[i][j]);\n }\n }\n \n}\n\nvoid array2_to_mat(const vector< vector > arr,mat_GF2 &v){\n long m= v.NumRows();\n long n= v.NumCols();\n \n for (int i=0;i<=m-1;i++){\n for (int j=0; j<=n-1; j++) {\n v[i][j]=arr[i][j];\n }\n }\n \n}\n\nvoid array2_to_mat(const vector< vector > arr,mat_GF2E &v){\n \n \n long m= v.NumRows();\n long n= v.NumCols();\n \n// const GF2X P(INIT_MONO,8);\n// GF2E::init(P);\n GF2X P;\n SetCoeff(P, 8, 1);\n SetCoeff(P, 4, 1);\n SetCoeff(P, 3, 1);\n SetCoeff(P, 1, 1);\n SetCoeff(P, 0, 1);\n GF2E::init(P);\n \n for (int i=0;i<=m-1;i++){\n for (int j=0; j<=n-1; j++) {\n v[i][j]=to_GF2E(arr[i][j]);\n }\n }\n \n}\n\nvoid array2_to_mat(const vector< vector > arr,mat_ZZ_p &v){\n \n v.SetDims(arr.size(),arr[0].size());\n \n long m= v.NumRows();\n long n= v.NumCols();\n \n ZZ_p::init(ZZ(256));\n \n for (int i=0;i<=m-1;i++){\n for (int j=0; j<=n-1; j++) {\n v[i][j]=to_ZZ_p(long(arr[i][j]));\n }\n }\n \n}\n\n\n//void inv_array2_to_mat(const mat_GF2E &v, vector< vector > &arr) //gf2e --> int ?????\n\n\n//to_ZZX(vec);可以把一个一维数组/向量 转为多项式(系数更换)\nvoid kc_lagrange(vec_vec_ZZ_p &pointMat,vec_zz_p &coeffVec) {\n \n}\n", "meta": {"hexsha": "6a28a08fd3a03d7d8af77d99b4736dc0ec2e2861", "size": 4569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kcalg/math/common.cpp", "max_stars_repo_name": "kn1ghtc/kctsb", "max_stars_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-03-16T00:10:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-16T00:10:51.000Z", "max_issues_repo_path": "kcalg/math/common.cpp", "max_issues_repo_name": "kn1ghtc/kctsb", "max_issues_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kcalg/math/common.cpp", "max_forks_repo_name": "kn1ghtc/kctsb", "max_forks_repo_head_hexsha": "ee0e5b31dbe293dad0fb6ea5acf5da1652e4e733", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8630136986, "max_line_length": 93, "alphanum_fraction": 0.4602757715, "num_tokens": 1570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6661838915755645}} {"text": "#pragma once\n#include \n#include \n#include \n\n#include \"stiffness_matrix.hpp\"\n\n//----------------AssembleMatrixBegin----------------\n//! Assemble the stiffness matrix\n//! for the linear system.\n//!\n//!\n//! @param[in] vertices a list of triangle vertices\n//! @param[in] triangles a list of triangles\nSparseMatrix assembleStiffnessMatrix(\n const Eigen::MatrixXd &vertices,\n const Eigen::MatrixXi &triangles) {\n\tSparseMatrix A(vertices.rows(), vertices.rows());\n\tstd::vector triplets;\n\tconst int numberOfElements = triangles.rows();\n\n\tfor (int i = 0; i < numberOfElements; ++i) {\n\t\tauto &indexSet = triangles.row(i);\n\n\t\tconst auto &a = vertices.row(indexSet(0));\n\t\tconst auto &b = vertices.row(indexSet(1));\n\t\tconst auto &c = vertices.row(indexSet(2));\n\n\t\tEigen::Matrix3d stiffnessMatrix;\n\t\tcomputeStiffnessMatrix(stiffnessMatrix, a, b, c);\n\n\t\tfor (int n = 0; n < 3; ++n) {\n\t\t\tfor (int m = 0; m < 3; ++m) {\n\t\t\t\tauto triplet = Triplet(indexSet(n), indexSet(m), stiffnessMatrix(n, m));\n\t\t\t\ttriplets.push_back(triplet);\n\t\t\t}\n\t\t}\n\t}\n\n\tA.setFromTriplets(triplets.begin(), triplets.end());\n\n\treturn A;\n}\n//----------------AssembleMatrixEnd----------------\n", "meta": {"hexsha": "b669e9083ef1db80162d517e2e5ace008c88d8bd", "size": 1213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series4/2d-rad-cooling/stiffness_matrix_assembly.hpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series4/2d-rad-cooling/stiffness_matrix_assembly.hpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series4/2d-rad-cooling/stiffness_matrix_assembly.hpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9555555556, "max_line_length": 76, "alphanum_fraction": 0.6380873866, "num_tokens": 321, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.760650658103136, "lm_q1q2_score": 0.6661679515551763}} {"text": "/**\n * @file gweyl.hpp\n * @author ALIKAWA Hidehisa \n * @date 2018/04/30\n * \n * @brief public header file of gweyl\n * \n * Released under the MIT license\n */\n#pragma once\n\n#include \n#include \n#include \n#include \n\n//\n// our namespace \"gweyl\"\n//\nnamespace gweyl{\n\n//\n// rational numbers\n//\nusing rational=boost::rational;\n\n//\n// matrix of rational numbers\n//\nusing matrix=boost::numeric::ublas::matrix;\n\n//\n// number vector\n// this is vector of mathematics (primitive linear algera)\n//\nusing NumberVector=boost::numeric::ublas::vector;\n\n//\n// we define equality of matirx and number vector\n// because boost does not define the equality\n//\nbool equal(const matrix &X, const matrix &Y);\nbool equal(const NumberVector &v, const NumberVector &w);\n\n//\n// gweyl treats simple Lie algebra types\n// in Cartan's classification\n//\nenum class Type{\n invalid,A,B,C,D,E,F,G,\n};\n\n//\n// Coordinate system\n// There are at least two coordinates on root spaces.\n// One is simple roots, and the other is fundamental weights.\n//\nenum class Coordinate {\n simple, fundamental,\n};\n\n//\n// trace the message\n// @param[in] msg message\n// \n//\nvoid trace(std::string& msg);\n\n///\n/// The definition of Cartan Matrix is equivalent to\n/// the definition of the root space, according to structure theory of Lie algebra,\n/// that is, Cartan matrix is the source of \"gweyl\"\n///\nmatrix CartanMatrix(Type X, unsigned n);\nmatrix InverseCartanMatrix(Type X, unsigned n);\n\nclass VectorRootSpace;\n\n//\n// class Cartan\n// other names are RootSpace, DynkinDiagram, ..\n// fundamental class of gweyl\n//\nclass Cartan\n{\npublic:\n explicit Cartan(Type X, unsigned n);\n Cartan();\n Cartan(const Cartan &rhs);\n virtual ~Cartan();\n Cartan& operator=(const Cartan& rhs);\n\n //\n // @return Cartan matrix\n //\n matrix CartanMatrix();\n \n //\n // @return invers of Cartan matrix\n //\n matrix InverseCartanMatrix();\n\n //\n // @return the 'i'-th simple root\n //\n VectorRootSpace SimpleRoot(unsigned i);\n\n //\n // @return the 'i'-th fundamental weight\n //\n VectorRootSpace FundamentalWeight(unsigned i);\n\n //\n // @return highest root \n //\n VectorRootSpace HighestRoot();\n\n //\n // @return zero vector\n //\n VectorRootSpace Zero();\n \n //\n // @return half sum of positive roots\n //\n VectorRootSpace Rho();\n\n //\n // @return positive roots\n //\n std::vector PositiveRoots();\n\n //\n // @return roots \n //\n std::vector Roots();\n\n // getters\n Type type();\n Type type() const;\n unsigned rank();\n unsigned rank() const;\n\n // operators\n bool operator==(const Cartan& rhs);\n bool operator!=(const Cartan& rhs);\n\n \nprivate:\n struct Impl;\n std::unique_ptr pImpl;\n};\n\n//\n// In gweyl, the class RootSpace, DynkinDiagram and the class Cartan are same\n//\nusing RootSpace = Cartan;\nusing DynkinDiagram = Cartan;\n\n//\n// Vector in root space\n//\nclass VectorRootSpace \n{\npublic:\n // constructors\n explicit VectorRootSpace(Type X, NumberVector& v, Coordinate c);\n VectorRootSpace();\n virtual ~VectorRootSpace();\n VectorRootSpace(const VectorRootSpace& rhs);\n VectorRootSpace& operator=(const VectorRootSpace& rhs);\n\n // for debug\n void printf();\n\n // getters\n NumberVector simpleCoefficients();\n NumberVector simpleCoefficients() const;\n NumberVector fundamentalCoefficients();\n NumberVector fundamentalCoefficients() const;\n Type type();\n Type type() const;\n unsigned rank();\n unsigned rank() const;\n\n // eqaulity\n bool isInSameSpace(const VectorRootSpace& rhs);\n bool operator==(const VectorRootSpace& rhs);\n bool operator!=(const VectorRootSpace& rhs);\n\n // operators\n VectorRootSpace& operator+=(const VectorRootSpace& rhs);\n VectorRootSpace& operator-=(const VectorRootSpace& rhs);\n VectorRootSpace& operator*=(rational r);\n\n // dominant integral\n bool dominant();\n bool integral();\n bool isDominantIntegral();\nprivate:\n struct Impl;\n std::unique_ptr pImpl;\n};\n\n//\n// operators of the class VectorRootSpace\n//\nrational InnerProduct(VectorRootSpace& v, VectorRootSpace& w);\nVectorRootSpace operator+(const VectorRootSpace& v1, const VectorRootSpace& v2);\nVectorRootSpace operator-(const VectorRootSpace& v1, const VectorRootSpace& v2);\nVectorRootSpace operator*(const VectorRootSpace& v1, const rational r);\nVectorRootSpace operator*(const rational r, const VectorRootSpace& v1);\n\n//\n// class IrreducibleRepresentation\n// \nclass IrreducibleRepresentation{\npublic:\n //constructors\n IrreducibleRepresentation();\n explicit IrreducibleRepresentation(VectorRootSpace& highestweight);\n virtual ~IrreducibleRepresentation();\n IrreducibleRepresentation(const IrreducibleRepresentation& rhs);\n IrreducibleRepresentation& operator=(const IrreducibleRepresentation& rhs);\n\n //getters\n Type type();\n Type type() const;\n unsigned rank();\n unsigned rank() const;\n VectorRootSpace highestweight();\n VectorRootSpace highestweight() const;\n\n //operators\n bool operator==(const IrreducibleRepresentation& rhs);\n bool operator!=(const IrreducibleRepresentation& rhs);\n\n int dimension();\n \nprivate:\n struct Impl;\n std::unique_ptr pImpl;\n};\n\n\n}\n", "meta": {"hexsha": "669cb7824966fe1b33cc7d2ddd119b64251f6e7f", "size": 5502, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gweyl.hpp", "max_stars_repo_name": "alleyhide/gweyl", "max_stars_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gweyl.hpp", "max_issues_repo_name": "alleyhide/gweyl", "max_issues_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gweyl.hpp", "max_forks_repo_name": "alleyhide/gweyl", "max_forks_repo_head_hexsha": "a632d0e42ad7141950f387a783774950dbf41a64", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2753036437, "max_line_length": 83, "alphanum_fraction": 0.6862958924, "num_tokens": 1327, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869948899666, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6661679445174472}} {"text": "#include \n#include \n#include \n#include \n\nnamespace common_robotics_utilities\n{\nnamespace math\n{\nbool Equal3d(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)\n{\n if ((v1.x() == v2.x()) && (v1.y() == v2.y()) && (v1.z() == v2.z()))\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\n\nbool Equal4d(const Eigen::Vector4d& v1, const Eigen::Vector4d& v2)\n{\n if ((v1(0) == v2(0)) && (v1(1) == v2(1))\n && (v1(2) == v2(2)) && (v1(3) == v2(3)))\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\nbool CloseEnough(const double p1, const double p2, const double threshold)\n{\n const double real_threshold = std::abs(threshold);\n const double abs_delta = std::abs(p2 - p1);\n if (abs_delta <= real_threshold)\n {\n return true;\n }\n else\n {\n return false;\n }\n}\n\nbool CloseEnough(const Eigen::Vector3d& v1,\n const Eigen::Vector3d& v2,\n const double threshold)\n{\n const double real_threshold = std::abs(threshold);\n if (std::abs(v1.x() - v2.x()) > real_threshold)\n {\n return false;\n }\n if (std::abs(v1.y() - v2.y()) > real_threshold)\n {\n return false;\n }\n if (std::abs(v1.z() - v2.z()) > real_threshold)\n {\n return false;\n }\n return true;\n}\n\nEigen::Vector3d RotateVector(const Eigen::Quaterniond& quat,\n const Eigen::Vector3d& vec)\n{\n const Eigen::Quaterniond temp(0.0, vec.x(), vec.y(), vec.z());\n const Eigen::Quaterniond res = quat * (temp * quat.inverse());\n return Eigen::Vector3d(res.x(), res.y(), res.z());\n}\n\nEigen::Vector3d RotateVectorReverse(const Eigen::Quaterniond& quat,\n const Eigen::Vector3d& vec)\n{\n const Eigen::Quaterniond temp(0.0, vec.x(), vec.y(), vec.z());\n const Eigen::Quaterniond res = quat.inverse() * (temp * quat);\n return Eigen::Vector3d(res.x(), res.y(), res.z());\n}\n\ndouble EnforceContinuousRevoluteBounds(const double value)\n{\n if ((value <= -M_PI) || (value > M_PI))\n {\n const double remainder = std::fmod(value, 2.0 * M_PI);\n if (remainder <= -M_PI)\n {\n return (remainder + (2.0 * M_PI));\n }\n else if (remainder > M_PI)\n {\n return (remainder - (2.0 * M_PI));\n }\n else\n {\n return remainder;\n }\n }\n else\n {\n return value;\n }\n}\n\nEigen::VectorXd SafeNormal(const Eigen::VectorXd& vec)\n{\n if (vec.size() > 0)\n {\n const double norm = vec.norm();\n if (norm > std::numeric_limits::epsilon())\n {\n return vec / norm;\n }\n else\n {\n return Eigen::VectorXd::Zero(vec.size());\n }\n }\n else\n {\n return Eigen::VectorXd::Zero(vec.size());\n }\n}\n\ndouble SquaredNorm(const std::vector& vec)\n{\n double squared_norm = 0.0;\n for (size_t idx = 0; idx < vec.size(); idx++)\n {\n const double element = vec[idx];\n squared_norm += (element * element);\n }\n return squared_norm;\n}\n\ndouble Norm(const std::vector& vec)\n{\n return std::sqrt(SquaredNorm(vec));\n}\n\nstd::vector Abs(const std::vector& vec)\n{\n std::vector absed(vec.size(), 0.0);\n for (size_t idx = 0; idx < absed.size(); idx++)\n {\n absed[idx] = std::abs(vec[idx]);\n }\n return absed;\n}\n\nstd::vector Multiply(const std::vector& vec,\n const double scalar)\n{\n std::vector multiplied(vec.size(), 0.0);\n for (size_t idx = 0; idx < multiplied.size(); idx++)\n {\n const double element = vec[idx];\n multiplied[idx] = element * scalar;\n }\n return multiplied;\n}\n\nstd::vector Multiply(const std::vector& vec1,\n const std::vector& vec2)\n{\n if (vec1.size() == vec2.size())\n {\n std::vector multiplied(vec1.size(), 0.0);\n for (size_t idx = 0; idx < multiplied.size(); idx++)\n {\n const double element1 = vec1[idx];\n const double element2 = vec2[idx];\n multiplied[idx] = element1 * element2;\n }\n return multiplied;\n }\n else\n {\n throw std::invalid_argument(\"vec1.size() != vec2.size()\");\n }\n}\n\nstd::vector Divide(const std::vector& vec, const double scalar)\n{\n const double inv_scalar = 1.0 / scalar;\n return Multiply(vec, inv_scalar);\n}\n\nstd::vector Divide(const std::vector& vec1,\n const std::vector& vec2)\n{\n if (vec1.size() == vec2.size())\n {\n std::vector divided(vec1.size(), 0.0);\n for (size_t idx = 0; idx < divided.size(); idx++)\n {\n const double element1 = vec1[idx];\n const double element2 = vec2[idx];\n divided[idx] = element1 / element2;\n }\n return divided;\n }\n else\n {\n throw std::invalid_argument(\"vec1.size() != vec2.size()\");\n }\n}\n\nstd::vector Add(const std::vector& vec, const double scalar)\n{\n std::vector added(vec.size(), 0.0);\n for (size_t idx = 0; idx < added.size(); idx++)\n {\n added[idx] = vec[idx] + scalar;\n }\n return added;\n}\n\nstd::vector Add(const std::vector& vec1,\n const std::vector& vec2)\n{\n if (vec1.size() == vec2.size())\n {\n std::vector added(vec1.size(), 0.0);\n for (size_t idx = 0; idx < added.size(); idx++)\n {\n const double element1 = vec1[idx];\n const double element2 = vec2[idx];\n added[idx] = element1 + element2;\n }\n return added;\n }\n else\n {\n throw std::invalid_argument(\"vec1.size() != vec2.size()\");\n }\n}\n\nstd::vector Sub(const std::vector& vec, const double scalar)\n{\n std::vector subed(vec.size(), 0.0);\n for (size_t idx = 0; idx < subed.size(); idx++)\n {\n subed[idx] = vec[idx] - scalar;\n }\n return subed;\n}\n\nstd::vector Sub(const std::vector& vec1,\n const std::vector& vec2)\n{\n if (vec1.size() == vec2.size())\n {\n std::vector subed(vec1.size(), 0.0);\n for (size_t idx = 0; idx < subed.size(); idx++)\n {\n const double element1 = vec1[idx];\n const double element2 = vec2[idx];\n subed[idx] = element1 - element2;\n }\n return subed;\n }\n else\n {\n throw std::invalid_argument(\"vec1.size() != vec2.size()\");\n }\n}\n\ndouble Sum(const std::vector& vec)\n{\n double sum = 0.0;\n for (size_t idx = 0; idx < vec.size(); idx++)\n {\n const double element = vec[idx];\n sum += element;\n }\n return sum;\n}\n\nEigen::Matrix3d Skew(const Eigen::Vector3d& vector)\n{\n Eigen::Matrix3d skewed;\n skewed << 0.0, -vector.z(), vector.y(),\n vector.z(), 0.0, -vector.x(),\n -vector.y(), vector.x(), 0.0;\n return skewed;\n}\n\nEigen::Vector3d Unskew(const Eigen::Matrix3d& matrix)\n{\n const Eigen::Matrix3d matrix_symetric = (matrix - matrix.transpose()) / 2.0;\n const Eigen::Vector3d unskewed(matrix_symetric(2, 1),\n matrix_symetric(0, 2),\n matrix_symetric(1, 0));\n return unskewed;\n}\n\nEigen::Matrix4d TwistHat(const Eigen::Matrix& twist)\n{\n const Eigen::Vector3d trans_velocity = twist.segment<3>(0);\n const Eigen::Matrix3d hatted_rot_velocity = Skew(twist.segment<3>(3));\n Eigen::Matrix4d hatted_twist = Eigen::Matrix4d::Zero();\n hatted_twist.block<3, 3>(0, 0) = hatted_rot_velocity;\n hatted_twist.block<3, 1>(0, 3) = trans_velocity;\n return hatted_twist;\n}\n\nEigen::Matrix TwistUnhat(const Eigen::Matrix4d& hatted_twist)\n{\n const Eigen::Vector3d trans_velocity = hatted_twist.block<3, 1>(0, 3);\n const Eigen::Vector3d rot_velocity = Unskew(hatted_twist.block<3, 3>(0, 0));\n Eigen::Matrix twist;\n twist.segment<3>(0) = trans_velocity;\n twist.segment<3>(3) = rot_velocity;\n return twist;\n}\n\nEigen::Matrix AdjointFromTransform(\n const Eigen::Isometry3d& transform)\n{\n const Eigen::Matrix3d rotation = transform.matrix().block<3, 3>(0, 0);\n const Eigen::Vector3d translation = transform.matrix().block<3, 1>(0, 3);\n const Eigen::Matrix3d translation_hat = Skew(translation);\n // Assemble the adjoint matrix\n Eigen::Matrix adjoint;\n adjoint.block<3, 3>(0, 0) = rotation;\n adjoint.block<3, 3>(0, 3) = translation_hat * rotation;\n adjoint.block<3, 3>(3, 0) = Eigen::Matrix3d::Zero();\n adjoint.block<3, 3>(3, 3) = rotation;\n return adjoint;\n}\n\nEigen::Matrix TransformTwist(\n const Eigen::Isometry3d& transform,\n const Eigen::Matrix& initial_twist)\n{\n return (Eigen::Matrix)(AdjointFromTransform(transform)\n * initial_twist);\n}\n\nEigen::Matrix TwistBetweenTransforms(\n const Eigen::Isometry3d& start,\n const Eigen::Isometry3d& end)\n{\n const Eigen::Isometry3d t_diff = start.inverse() * end;\n return TwistUnhat(t_diff.matrix().log());\n}\n\nEigen::Matrix3d ExpMatrixExact(const Eigen::Matrix3d& hatted_rot_velocity,\n const double delta_t)\n{\n if (std::abs(Unskew(hatted_rot_velocity).norm() - 1.0) < 1e-10)\n {\n const Eigen::Matrix3d exp_matrix = Eigen::Matrix3d::Identity()\n + (hatted_rot_velocity * sin(delta_t))\n + (hatted_rot_velocity * hatted_rot_velocity * (1.0 - cos(delta_t)));\n return exp_matrix;\n }\n else\n {\n throw std::invalid_argument(\"Invalid hatted_rot_velocity: \"\n \"std::abs(Unskew(hatted_rot_velocity).norm()\"\n \" - 1.0) >= 1e-10\");\n }\n}\n\nEigen::Isometry3d ExpTwist(const Eigen::Matrix& twist,\n const double delta_t)\n{\n const Eigen::Vector3d trans_velocity = twist.segment<3>(0);\n const Eigen::Vector3d rot_velocity = twist.segment<3>(3);\n const double trans_velocity_norm = trans_velocity.norm();\n const double rot_velocity_norm = rot_velocity.norm();\n Eigen::Matrix4d raw_transform = Eigen::Matrix4d::Identity();\n if (rot_velocity_norm >= 1e-100)\n {\n const double scaled_delta_t = delta_t * rot_velocity_norm;\n const Eigen::Vector3d scaled_trans_velocity\n = trans_velocity / rot_velocity_norm;\n const Eigen::Vector3d scaled_rot_velocity\n = rot_velocity / rot_velocity_norm;\n const Eigen::Matrix3d rotation_displacement\n = ExpMatrixExact(Skew(scaled_rot_velocity), scaled_delta_t);\n const Eigen::Vector3d translation_displacement\n = ((Eigen::Matrix3d::Identity() - rotation_displacement)\n * scaled_rot_velocity.cross(scaled_trans_velocity))\n + (scaled_rot_velocity * scaled_rot_velocity.transpose()\n * scaled_trans_velocity * scaled_delta_t);\n raw_transform.block<3, 3>(0, 0) = rotation_displacement;\n raw_transform.block<3, 1>(0, 3) = translation_displacement;\n }\n else\n {\n if ((trans_velocity_norm >= 1e-100) || (rot_velocity_norm == 0.0))\n {\n raw_transform.block<3, 1>(0, 3) = trans_velocity * delta_t;\n }\n else\n {\n std::cerr << \"YOU MAY ENCOUNTER NUMERICAL INSTABILITY IN EXPTWIST(...)\"\n \" WITH TRANS & ROT VELOCITY NORM < 1e-100 ***\" << std::endl;\n const double scaled_delta_t = delta_t * rot_velocity_norm;\n const Eigen::Vector3d scaled_trans_velocity\n = trans_velocity / rot_velocity_norm;\n const Eigen::Vector3d scaled_rot_velocity\n = rot_velocity / rot_velocity_norm;\n const Eigen::Matrix3d rotation_displacement\n = ExpMatrixExact(Skew(scaled_rot_velocity), scaled_delta_t);\n const Eigen::Vector3d translation_displacement\n = ((Eigen::Matrix3d::Identity() - rotation_displacement)\n * scaled_rot_velocity.cross(scaled_trans_velocity))\n + (scaled_rot_velocity * scaled_rot_velocity.transpose()\n * scaled_trans_velocity * scaled_delta_t);\n raw_transform.block<3, 3>(0, 0) = rotation_displacement;\n raw_transform.block<3, 1>(0, 3) = translation_displacement;\n }\n }\n Eigen::Isometry3d transform;\n transform = raw_transform;\n return transform;\n}\n\ndouble Interpolate(const double p1, const double p2, const double ratio)\n{\n // Safety check ratio\n const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n // Interpolate\n // This is the numerically stable version,\n // rather than (p1 + (p2 - p1) * real_ratio)\n return ((p1 * (1.0 - real_ratio)) + (p2 * real_ratio));\n}\n\ndouble InterpolateContinuousRevolute(const double p1,\n const double p2,\n const double ratio)\n{\n // Safety check ratio\n const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n // Safety check args\n const double real_p1 = EnforceContinuousRevoluteBounds(p1);\n const double real_p2 = EnforceContinuousRevoluteBounds(p2);\n // Interpolate\n double interpolated = 0.0;\n double diff = real_p2 - real_p1;\n if (std::abs(diff) <= M_PI)\n {\n interpolated = real_p1 + diff * real_ratio;\n }\n else\n {\n if (diff > 0.0)\n {\n diff = 2.0 * M_PI - diff;\n }\n else\n {\n diff = -2.0 * M_PI - diff;\n }\n interpolated = real_p1 - diff * real_ratio;\n // Input states are within bounds, so the following check is sufficient\n if (interpolated > M_PI)\n {\n interpolated -= 2.0 * M_PI;\n }\n else\n {\n if (interpolated < -M_PI)\n {\n interpolated += 2.0 * M_PI;\n }\n }\n }\n return interpolated;\n}\n\nstd::vector Interpolate(const std::vector& v1,\n const std::vector& v2,\n const double ratio)\n{\n // Safety check ratio\n const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n // Safety check inputs\n const size_t len = v1.size();\n if (len != v2.size())\n {\n throw std::invalid_argument(\"Vectors v1 and v2 must be the same size\");\n }\n // Interpolate\n // This is the numerically stable version,\n // rather than (p1 + (p2 - p1) * real_ratio)\n std::vector interped(len, 0);\n for (size_t idx = 0; idx < len; idx++)\n {\n interped[idx] = ((v1[idx] * (1.0 - real_ratio)) + (v2[idx] * real_ratio));\n }\n return interped;\n}\n\nEigen::Quaterniond Interpolate(const Eigen::Quaterniond& q1,\n const Eigen::Quaterniond& q2,\n const double ratio)\n{\n // Safety check ratio\n const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n // Interpolate\n return q1.slerp(real_ratio, q2);\n}\n\nEigen::VectorXd InterpolateXd(const Eigen::VectorXd& v1,\n const Eigen::VectorXd& v2,\n const double ratio)\n{\n // Safety check sizes\n if (v1.size() != v2.size())\n {\n throw std::invalid_argument(\"Vectors v1 and v2 must be the same size\");\n }\n // Safety check ratio\n const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n // Interpolate\n // This is the numerically stable version,\n // rather than (p1 + (p2 - p1) * real_ratio)\n return ((v1 * (1.0 - real_ratio)) + (v2 * real_ratio));\n}\n\nEigen::Vector3d Interpolate3d(const Eigen::Vector3d& v1,\n const Eigen::Vector3d& v2,\n const double ratio)\n{\n // Safety check ratio\n const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n // Interpolate\n // This is the numerically stable version,\n // rather than (p1 + (p2 - p1) * real_ratio)\n return ((v1 * (1.0 - real_ratio)) + (v2 * real_ratio));\n}\n\nEigen::Vector4d Interpolate4d(const Eigen::Vector4d& v1,\n const Eigen::Vector4d& v2,\n const double ratio)\n{\n // Safety check ratio\n const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n // Interpolate\n // This is the numerically stable version,\n // rather than (p1 + (p2 - p1) * real_ratio)\n return ((v1 * (1.0 - real_ratio)) + (v2 * real_ratio));\n}\n\nEigen::Isometry3d Interpolate(const Eigen::Isometry3d& t1,\n const Eigen::Isometry3d& t2,\n const double ratio)\n{\n // Safety check ratio\n const double real_ratio = utility::ClampValue(ratio, 0.0, 1.0);\n // Interpolate\n const Eigen::Vector3d v1 = t1.translation();\n const Eigen::Quaterniond q1(t1.rotation());\n const Eigen::Vector3d v2 = t2.translation();\n const Eigen::Quaterniond q2(t2.rotation());\n const Eigen::Vector3d vint = Interpolate3d(v1, v2, real_ratio);\n const Eigen::Quaterniond qint = Interpolate(q1, q2, real_ratio);\n const Eigen::Isometry3d tint = ((Eigen::Translation3d)vint) * qint;\n return tint;\n}\n\ndouble SquaredDistance(const Eigen::Vector2d& v1, const Eigen::Vector2d& v2)\n{\n const double xd = v2.x() - v1.x();\n const double yd = v2.y() - v1.y();\n return ((xd * xd) + (yd * yd));\n}\n\ndouble Distance(const Eigen::Vector2d& v1, const Eigen::Vector2d& v2)\n{\n return std::sqrt(SquaredDistance(v1, v2));\n}\n\ndouble SquaredDistance(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)\n{\n const double xd = v2.x() - v1.x();\n const double yd = v2.y() - v1.y();\n const double zd = v2.z() - v1.z();\n return ((xd * xd) + (yd * yd) + (zd * zd));\n}\n\ndouble Distance(const Eigen::Vector3d& v1, const Eigen::Vector3d& v2)\n{\n return std::sqrt(SquaredDistance(v1, v2));\n}\n\ndouble SquaredDistance(const Eigen::VectorXd& v1, const Eigen::VectorXd& v2)\n{\n if (v1.size() == v2.size())\n {\n return (v2 - v1).squaredNorm();\n }\n else\n {\n throw std::invalid_argument(\"v1.size() != v2.size()\");\n }\n}\n\ndouble Distance(const Eigen::VectorXd& v1, const Eigen::VectorXd& v2)\n{\n return std::sqrt(SquaredDistance(v1, v2));\n}\n\ndouble Distance(const Eigen::Quaterniond& q1, const Eigen::Quaterniond& q2)\n{\n const double dq = std::abs((q1.w() * q2.w())\n + (q1.x() * q2.x())\n + (q1.y() * q2.y())\n + (q1.z() * q2.z()));\n if (dq < (1.0 - std::numeric_limits::epsilon()))\n {\n return std::acos(2.0 * (dq * dq) - 1.0);\n }\n else\n {\n return 0.0;\n }\n}\n\ndouble Distance(const Eigen::Isometry3d& t1,\n const Eigen::Isometry3d& t2,\n const double alpha)\n{\n const double real_alpha = utility::ClampValue(alpha, 0.0, 1.0);\n const Eigen::Vector3d v1 = t1.translation();\n const Eigen::Quaterniond q1(t1.rotation());\n const Eigen::Vector3d v2 = t2.translation();\n const Eigen::Quaterniond q2(t2.rotation());\n const double vdist = Distance(v1, v2) * (1.0 - real_alpha);\n const double qdist = Distance(q1, q2) * (real_alpha);\n return vdist + qdist;\n}\n\ndouble SquaredDistance(const std::vector& p1,\n const std::vector& p2)\n{\n if (p1.size() == p2.size())\n {\n double distance = 0.0;\n for (size_t idx = 0; idx < p1.size(); idx++)\n {\n distance += (p2[idx] - p1[idx]) * (p2[idx] - p1[idx]);\n }\n return distance;\n }\n else\n {\n throw std::invalid_argument(\"p1.size() != p2.size()\");\n }\n}\n\ndouble Distance(const std::vector& p1, const std::vector& p2)\n{\n if (p1.size() == p2.size())\n {\n return std::sqrt(SquaredDistance(p1, p2));\n }\n else\n {\n throw std::invalid_argument(\"p1.size() != p2.size()\");\n }\n}\n\ndouble ContinuousRevoluteSignedDistance(const double p1, const double p2)\n{\n // Safety check args\n const double real_p1 = EnforceContinuousRevoluteBounds(p1);\n const double real_p2 = EnforceContinuousRevoluteBounds(p2);\n const double raw_distance = real_p2 - real_p1;\n if ((raw_distance <= -M_PI) || (raw_distance > M_PI))\n {\n if (raw_distance <= -M_PI)\n {\n return (-(2.0 * M_PI) - raw_distance);\n }\n else if (raw_distance > M_PI)\n {\n return ((2.0 * M_PI) - raw_distance);\n }\n else\n {\n return raw_distance;\n }\n }\n else\n {\n return raw_distance;\n }\n}\n\ndouble ContinuousRevoluteDistance(const double p1, const double p2)\n{\n return std::abs(ContinuousRevoluteSignedDistance(p1, p2));\n}\n\ndouble AddContinuousRevoluteValues(const double start, const double change)\n{\n return EnforceContinuousRevoluteBounds(start + change);\n}\n\ndouble GetContinuousRevoluteRange(const double start, const double end)\n{\n const double raw_range = ContinuousRevoluteSignedDistance(start, end);\n if (raw_range >= 0.0)\n {\n return raw_range;\n }\n else\n {\n return (2.0 * M_PI) + raw_range;\n }\n}\n\nbool CheckInContinuousRevoluteRange(const double start,\n const double range,\n const double val)\n{\n const double real_val = EnforceContinuousRevoluteBounds(val);\n const double real_start = EnforceContinuousRevoluteBounds(start);\n const double delta = ContinuousRevoluteSignedDistance(real_start, real_val);\n if (delta >= 0.0)\n {\n if (delta <= range)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n const double real_delta = (2.0 * M_PI) + delta;\n if (real_delta <= range)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n}\n\nbool CheckInContinuousRevoluteBounds(const double start,\n const double end,\n const double val)\n{\n const double range = GetContinuousRevoluteRange(start, end);\n return CheckInContinuousRevoluteRange(start, range, val);\n}\n\ndouble AverageStdVectorDouble(const std::vector& values,\n const std::vector& weights)\n{\n // Get the weights\n if (values.empty())\n {\n throw std::invalid_argument(\"Provided vector is empty\");\n }\n if ((weights.size() != values.size()) && (weights.size() != 0))\n {\n throw std::invalid_argument(\"Provided weights must be empty\"\n \" or same size to provided vector\");\n }\n const bool use_weights = (weights.size() != 0);\n // Find the first element with non-zero weight\n size_t starting_idx = 0;\n while (starting_idx < weights.size()\n && std::abs(weights[starting_idx]) == 0.0)\n {\n starting_idx++;\n }\n // If all weights are zero, result is undefined\n if (starting_idx >= values.size())\n {\n throw std::invalid_argument(\"Provided weights are all zero\");\n }\n // Start the recursive definition with the base case\n double average = values[starting_idx];\n const double starting_weight = use_weights ? std::abs(weights[starting_idx])\n : 1.0;\n double weights_running_sum = starting_weight;\n // Do the weighted averaging on the rest of the vectors\n for (size_t idx = starting_idx + 1; idx < values.size(); idx++)\n {\n const double weight = use_weights ? std::abs(weights[idx]) : 1.0;\n weights_running_sum += weight;\n const double effective_weight = weight / weights_running_sum;\n const double prev_average = average;\n const double current = values[idx];\n average = prev_average + (effective_weight * (current - prev_average));\n }\n return average;\n}\n\ndouble ComputeStdDevStdVectorDouble(const std::vector& values,\n const double mean)\n{\n if (values.empty())\n {\n throw std::invalid_argument(\"Provided vector is empty\");\n }\n else if (values.size() == 1)\n {\n return 0.0;\n }\n else\n {\n const double inv_n_minus_1 = 1.0 / (double)(values.size() - 1);\n double stddev_sum = 0.0;\n for (size_t idx = 0; idx < values.size(); idx++)\n {\n const double delta = values[idx] - mean;\n stddev_sum += (delta * delta);\n }\n return std::sqrt(stddev_sum * inv_n_minus_1);\n }\n}\n\ndouble ComputeStdDevStdVectorDouble(const std::vector& values)\n{\n const double mean = AverageStdVectorDouble(values);\n return ComputeStdDevStdVectorDouble(values, mean);\n}\n\ndouble AverageContinuousRevolute(const std::vector& angles,\n const std::vector& weights)\n{\n return AverageStdVectorDouble(angles, weights);\n}\n\nEigen::Vector3d AverageEigenVector3d(const VectorVector3d& vectors,\n const std::vector& weights)\n{\n return AverageEigenVector(vectors, weights);\n}\n\nEigen::VectorXd AverageEigenVectorXd(\n const std::vector& vectors,\n const std::vector& weights)\n{\n return AverageEigenVector(vectors, weights);\n}\n\n// Implementation of method described in (http://stackoverflow.com/a/27410865)\n// See paper at (http://www.acsu.buffalo.edu/~johnc/ave_quat07.pdf) for more\nEigen::Quaterniond AverageEigenQuaterniond(const VectorQuaterniond& quaternions,\n const std::vector& weights)\n{\n // Get the weights\n const bool use_weights = weights.size() == quaternions.size() ? true : false;\n if (quaternions.empty())\n {\n throw std::invalid_argument(\"Provided vector is empty\");\n }\n if ((weights.size() != quaternions.size()) && (weights.size() != 0))\n {\n throw std::invalid_argument(\"Provided weights must be empty\"\n \" or same size to provided vector\");\n }\n // Shortcut the process if there is only 1 quaternion\n if (quaternions.size() == 1)\n {\n if (weights.size() > 0)\n {\n if (std::abs(weights[0]) == 0.0)\n {\n throw std::invalid_argument(\"Single quaternion with zero weight\");\n }\n }\n return quaternions[0];\n }\n // Build the averaging matrix\n Eigen::MatrixXd q_matrix(4, quaternions.size());\n for (size_t idx = 0; idx < quaternions.size(); idx++)\n {\n const double weight = use_weights ? std::abs(weights[idx]) : 1.0;\n const Eigen::Quaterniond& q = quaternions[idx];\n q_matrix.col((ssize_t)idx) << weight * q.w(),\n weight * q.x(),\n weight * q.y(),\n weight * q.z();\n }\n // Make the matrix square\n const Eigen::Matrix qqtranspose_matrix\n = q_matrix * q_matrix.transpose();\n // Compute the eigenvectors and eigenvalues of the qqtranspose matrix\n const Eigen::EigenSolver>\n solver(qqtranspose_matrix);\n const Eigen::EigenSolver>::EigenvalueType\n eigen_values = solver.eigenvalues();\n const Eigen::EigenSolver>::EigenvectorsType\n eigen_vectors = solver.eigenvectors();\n // Extract the eigenvector corresponding to the largest eigenvalue\n double max_eigenvalue = -std::numeric_limits::infinity();\n int64_t max_eigenvector_index = -1;\n for (size_t idx = 0; idx < 4; idx++)\n {\n const double current_eigenvalue = eigen_values((long)idx).real();\n if (current_eigenvalue > max_eigenvalue)\n {\n max_eigenvalue = current_eigenvalue;\n max_eigenvector_index = (int64_t)idx;\n }\n }\n if (max_eigenvector_index < 0)\n {\n throw std::runtime_error(\"Failed to find max eigenvector\");\n }\n // Note that these are already normalized!\n const Eigen::Vector4cd best_eigenvector\n = eigen_vectors.col((long)max_eigenvector_index);\n // Convert back into a quaternion\n const Eigen::Quaterniond average_q(best_eigenvector(0).real(),\n best_eigenvector(1).real(),\n best_eigenvector(2).real(),\n best_eigenvector(3).real());\n return average_q;\n}\n\nEigen::Isometry3d AverageEigenIsometry3d(const VectorIsometry3d& transforms,\n const std::vector& weights)\n{\n if (transforms.empty())\n {\n throw std::invalid_argument(\"Provided vector is empty\");\n }\n if ((weights.size() != transforms.size()) && (weights.size() != 0))\n {\n throw std::invalid_argument(\"Provided weights must be empty\"\n \" or same size to provided vector\");\n }\n // Shortcut the process if there is only 1 transform\n if (transforms.size() == 1)\n {\n if (weights.size() > 0)\n {\n if (std::abs(weights[0]) == 0.0)\n {\n throw std::invalid_argument(\"Single transform with zero weight\");\n }\n }\n return transforms[0];\n }\n // Extract components\n VectorVector3d translations(transforms.size());\n VectorQuaterniond rotations(transforms.size());\n for (size_t idx = 0; idx < transforms.size(); idx++)\n {\n translations[idx] = transforms[idx].translation();\n rotations[idx] = Eigen::Quaterniond(transforms[idx].rotation());\n }\n // Average\n const Eigen::Vector3d average_translation\n = AverageEigenVector(translations, weights);\n const Eigen::Quaterniond average_rotation\n = AverageEigenQuaterniond(rotations, weights);\n // Make the average transform\n const Eigen::Isometry3d average_transform\n = (Eigen::Translation3d)average_translation * average_rotation;\n return average_transform;\n}\n\ndouble WeightedDotProduct(const Eigen::VectorXd& vec1,\n const Eigen::VectorXd& vec2,\n const Eigen::VectorXd& weights)\n{\n return vec1.cwiseProduct(weights).dot(vec2);\n}\n\ndouble WeightedSquaredNorm(const Eigen::VectorXd& vec,\n const Eigen::VectorXd weights)\n{\n return WeightedDotProduct(vec, vec, weights);\n}\n\ndouble WeightedNorm(const Eigen::VectorXd& vec, const Eigen::VectorXd& weights)\n{\n return std::sqrt(WeightedSquaredNorm(vec, weights));\n}\n\ndouble WeightedCosineAngleBetweenVectors(const Eigen::VectorXd& vec1,\n const Eigen::VectorXd& vec2,\n const Eigen::VectorXd& weights)\n{\n const double vec1_norm = WeightedNorm(vec1, weights);\n const double vec2_norm = WeightedNorm(vec2, weights);\n if (vec1_norm > 0 && vec2_norm > 0)\n {\n const double result\n = WeightedDotProduct(vec1, vec2, weights) / (vec1_norm * vec2_norm);\n return std::max(-1.0, std::min(result, 1.0));;\n }\n else\n {\n throw std::invalid_argument(\"One or more input vectors has zero norm\");\n }\n}\n\ndouble WeightedAngleBetweenVectors(const Eigen::VectorXd& vec1,\n const Eigen::VectorXd& vec2,\n const Eigen::VectorXd& weights)\n{\n return std::acos(WeightedCosineAngleBetweenVectors(vec1, vec2, weights));\n}\n} // namespace math\n} // namespace common_robotics_utilities\n", "meta": {"hexsha": "ef709c034f7d5bad41fd27b43e2dec133fc65c46", "size": 30106, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/common_robotics_utilities/math.cpp", "max_stars_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_stars_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/common_robotics_utilities/math.cpp", "max_issues_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_issues_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/common_robotics_utilities/math.cpp", "max_forks_repo_name": "EricCousineau-TRI/common_robotics_utilities", "max_forks_repo_head_hexsha": "df2f0c68d92d93c919bb7401abe5e12bd5ca2345", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5156862745, "max_line_length": 80, "alphanum_fraction": 0.6195110609, "num_tokens": 8144, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6660756329316053}} {"text": "#include \"simulate.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace std;\n\n// constants\nconst double ALPHA = 0.05;\n\nint main(int argc, char *argv[]) {\n clock_t startTime = clock();\n ios::sync_with_stdio(false); cin.tie(NULL);\n // parse arguments\n int ITERATIONS = stoi(argv[1]); // simulation runs\n int N = stoi(argv[2]); // 1/2 sample size\n double POWER = stod(argv[3]); // power\n\n // calculate variance used for generators\n double variance = calculateVariance(N, ALPHA, POWER);\n double standardDeviation = sqrt(variance);\n \n // set up generators\n random_device randomDevice;\n mt19937_64 rng; \n rng.seed(randomDevice());\n normal_distribution normalMean0(0, standardDeviation); \n normal_distribution normalMean1(1, standardDeviation); \n\n // store and print results\n vector> results(ITERATIONS); // initial p-value, \"cheated\" beta, set size, subset size, balance p-value, \"cheated\" p-value\n cout << setprecision(12) << fixed;\n cout << \"2N\\tpower\\tp.value\\tbeta\\tset.size\\tsubset.size\\tbalance.p.value\\tfake.p.value\" << endl;\n // randomly assign treatment\n vector X(2*N); \n for (int i = 0; i < N; ++i) X[i] = 1; \n shuffle(X.begin() , X.end(), rng); \n arma::mat Z(2*N, 2*N, arma::fill::zeros); // pre allocate Z matrix\n for (int i = 0; i < ITERATIONS; ++i) {\n // generate response\n arma::Col Y(2*N);\n for (int j = 0; j < 2*N; ++j) {\n Y(j) = X[j] == 0 ? normalMean0(rng) : normalMean1(rng);\n } \n results[i] = simulate(Y, X, standardDeviation, true, Z, rng);\n cout << 2*N << '\\t' << POWER << '\\t' \n << get<0>(results[i]) << '\\t' \n << get<1>(results[i]) << '\\t' \n << get<2>(results[i]) << '\\t' \n << get<3>(results[i]) << '\\t'\n << get<4>(results[i]) << '\\t'\n << get<5>(results[i]) << endl;\n }\n\n double duration = (clock() - startTime) / (double) CLOCKS_PER_SEC;\n cerr << \"Time taken (seconds): \" << duration << endl;\n return 0;\n}\n", "meta": {"hexsha": "c67398c435da291cdbb88578dbac4b7814a5de4d", "size": 2233, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "powerSimulation.cpp", "max_stars_repo_name": "ppham27/cheating-linear-models-simulations", "max_stars_repo_head_hexsha": "ea71915c37ebd2b7c3e4e45e1cfacfba848277bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "powerSimulation.cpp", "max_issues_repo_name": "ppham27/cheating-linear-models-simulations", "max_issues_repo_head_hexsha": "ea71915c37ebd2b7c3e4e45e1cfacfba848277bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "powerSimulation.cpp", "max_forks_repo_name": "ppham27/cheating-linear-models-simulations", "max_forks_repo_head_hexsha": "ea71915c37ebd2b7c3e4e45e1cfacfba848277bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3623188406, "max_line_length": 172, "alphanum_fraction": 0.6157635468, "num_tokens": 658, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6660458745721101}} {"text": "\n// requires LAPACK v. 3.0\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"utils.h\"\n\nnamespace ublas = boost::numeric::ublas;\nnamespace lapack = boost::numeric::bindings::lapack;\n\nusing std::size_t; \nusing std::cout;\nusing std::endl; \n\ntypedef double real_t; \ntypedef ublas::matrix m_t;\ntypedef ublas::vector v_t;\n\nint main() {\n\n cout << endl; \n\n size_t m = 3, n = 4; \n size_t minmn = m < n ? m : n; \n m_t a (m, n); \n a(0,0) = 2.; a(0,1) = 2.; a(0,2) = 2.; a(0,3) = 2.;\n a(1,0) = 1.7; a(1,1) = 0.1; a(1,2) = -1.7; a(1,3) = -0.1;\n a(2,0) = 0.6; a(2,1) = 1.8; a(2,2) = -0.6; a(2,3) = -1.8;\n\n m_t a2 (a); // for parts 2 & 3\n\n print_m (a, \"A\"); \n cout << endl; \n\n v_t s (minmn); \n m_t u (m, minmn);\n m_t vt (minmn, n);\n\n// lapack::gesdd (a, s, u, vt);\n lapack::gesdd ('S', a, s, u, vt);\n\n print_v (s, \"s\"); \n cout << endl; \n print_m (u, \"U\"); \n cout << endl; \n print_m (vt, \"V^T\"); \n cout << endl << endl;\n\n // part 2\n \n // singular values and singular vectors satisfy A v_i == s_i u_i\n for (int i = 0; i < minmn; ++i) {\n cout << \"A v_\" << i << \" == s_\" << i << \" u_\" << i << endl; \n v_t avi = ublas::prod (a2, ublas::row (vt, i)); \n print_v (avi);\n v_t siui = s[i] * ublas::column (u, i);\n print_v (siui);\n cout << endl; \n }\n cout << endl; \n \n // singular values and singular vectors satisfy A^T u_i == s_i v_i\n for (int i = 0; i < minmn; ++i) {\n cout << \"A^T u_\" << i << \" == s_\" << i << \" v_\" << i << endl; \n v_t atui = ublas::prod (trans (a2), ublas::column (u, i)); \n print_v (atui);\n v_t sivi = s[i] * ublas::row (vt, i);\n print_v (sivi);\n cout << endl; \n }\n cout << endl; \n \n // part 3 \n \n// lapack::gesdd (a2, s);\n lapack::gesdd ('N', a2, s, u, vt);\n \n print_v (s, \"singular values only\"); \n cout << endl; \n}\n\n", "meta": {"hexsha": "3a02a1d8b1a11c45c2c2b0425dcf8281b44b3490", "size": 2119, "ext": "cc", "lang": "C++", "max_stars_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gesdd4.cc", "max_stars_repo_name": "ljktest/siconos", "max_stars_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 137.0, "max_stars_repo_stars_event_min_datetime": "2015-06-16T15:55:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T06:01:59.000Z", "max_issues_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gesdd4.cc", "max_issues_repo_name": "ljktest/siconos", "max_issues_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 381.0, "max_issues_repo_issues_event_min_datetime": "2015-09-22T15:31:08.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T09:05:23.000Z", "max_forks_repo_path": "externals/numeric_bindings/libs/numeric/bindings/lapack/test/ublas_gesdd4.cc", "max_forks_repo_name": "ljktest/siconos", "max_forks_repo_head_hexsha": "85b60e62beca46e6bf06bfbd65670089e86607c7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 30.0, "max_forks_repo_forks_event_min_datetime": "2015-08-06T22:57:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-02T20:30:20.000Z", "avg_line_length": 24.0795454545, "max_line_length": 69, "alphanum_fraction": 0.5474280321, "num_tokens": 847, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6660230567460257}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\n\n#define PI 3.1415926\n\nclass Point\n{\n public:\n double x;\n double y;\n double z;\n Point(double v[]):x(v[0]),y(v[1]),z(v[2]){}\n};\n\n//求法向量\ndouble* get_normal(Point p1, Point p2, Point p3)\n{ \n double* norm_vec;\n norm_vec = new double[3];\n double a = ( (p2.y-p1.y)*(p3.z-p1.z)-(p2.z-p1.z)*(p3.y-p1.y));\n \n double b = ( (p2.z-p1.z)*(p3.x-p1.x)-(p2.x-p1.x)*(p3.z-p1.z));\n \n double c = ( (p2.x-p1.x)*(p3.y-p1.y)-(p2.y-p1.y)*(p3.x-p1.x));\n\n \n\n double norm = std::sqrt(a*a+b*b+c*c);\n \n norm_vec[0] = a/norm;\n norm_vec[1] = b/norm;\n norm_vec[2] = c/norm;\n // double v[3] = {a/norm, b/norm, c/norm};\n\n return norm_vec;\n}\n\n//求旋转矩阵4*4\n\ndouble get_theta_from_2_vec(double*v1,double*v2)\n{\n double costheta = (v1[0]*v2[0]+v1[1]*v2[1]+v1[2]*v2[2]) / (0.000001+std::sqrt((v1[0]*v1[0]+v1[1]*v1[1]+v1[2]*v1[2])*(v2[0]*v2[0]+v2[1]*v2[1]+v2[2]*v2[2])));\n return std::acos(costheta);\n}\n\nEigen::Matrix4d get_mat(Eigen::VectorXd coed)\n{\n double z[3] = {0,0,1};\n // double a[3] = {-0.0554246, 0.0372348, 0.997768};\n // double a[3] = {-0.0842539, 0.882628, 0.462459};\n double a[3] = {coed[0], coed[1], coed[2]};\n\n std::cout<<\"normal vector: \"< boost shared pointer and initializes it.\n pcl::PointCloud::Ptr source_cloud (new pcl::PointCloud ());\n \n if (pcl::console::find_switch (argc, argv, \"-h\"))\n {\n showHelp ();\n exit (0);\n }\n std::string input_path;\n if (argc < 2)\n {\n showHelp ();\n exit (0);\n }\n else\n {\n input_path = argv[1];\n if (pcl::io::loadPCDFile (input_path, *source_cloud) == -1) //* load the file\n {\n std::cerr << \"Input path: \" << input_path << std::endl;\n PCL_ERROR (\"Couldn't read file model, please try again. \\n\");\n showHelp();\n return (-1);\n }\n }\n \n std::size_t sz = source_cloud->points.size();\n std::cout<<\"Points size: \"<::Ptr\n model_p (new pcl::SampleConsensusModelPlane (source_cloud));\n Eigen::VectorXf coef = Eigen::VectorXf::Zero(4 , 1);\n pcl::RandomSampleConsensus ransac (model_p);\n\n double threshold;\n if (pcl::console::parse_argument (argc, argv, \"-t\", threshold) != -1)\n {\n std::cout<<\"Distance threshold: \"<();\n \n std::clock_t t2 = std::clock();\n\n\n Eigen::Matrix4d transform_1_d = get_mat(coed);\n\n \n // std::cout << transform_1_d << std::endl;\n\n\n // Executing the transformation\n pcl::PointCloud::Ptr transformed_cloud (new pcl::PointCloud ());\n /*\n void pcl::transformPointCloud(const pcl::PointCloud< PointT > & cloud_in, \n pcl::PointCloud< PointT > & cloud_out, \n const Eigen::Matrix4f & transform ) \n */\n // Apply an affine transform defined by an Eigen Transform.\n\n Eigen::Matrix4f transform_1_f = transform_1_d.cast(); \n\n pcl::transformPointCloud (*source_cloud, *transformed_cloud, transform_1_f);\n \n\n std::clock_t t3 = std::clock();\n // pcl::io::savePCDFileASCII(\"model_1_transform.pcd\", *transformed_cloud);\n std::string output_path;\n if (pcl::console::parse_argument (argc, argv, \"-o\", output_path) != -1)\n {\n std::cout << \"Rotated model will saved at: \"< source_cloud_color_handler (source_cloud, 255, 255, 255);\n //We add the point cloud to the viewer and pass the color handler\n viewer.addPointCloud (source_cloud, source_cloud_color_handler, \"original_cloud\");\n\n pcl::visualization::PointCloudColorHandlerCustom transformed_cloud_color_handler (transformed_cloud, 230, 20, 20); // Red\n viewer.addPointCloud (transformed_cloud, transformed_cloud_color_handler, \"transformed_cloud\");\n\n double coord_scale;\n if (pcl::console::parse_argument (argc, argv, \"-cs\", coord_scale) != -1)\n {\n std::cout<<\"Display coordinate scale: \"<\r\n#include \r\n#include \r\n#include \r\n\r\n\r\n#include \"Basic/Statistic.h\"\r\n#include \"Basic/UtilMath.h\"\r\n#include \"WeatherBasedSimulationString.h\"\r\n\r\n\r\nusing namespace std;\r\n\r\nnamespace WBSF\r\n{\r\n\r\n\t \r\n\t//this static variable is share by CStatistic and CStatisticXY\r\n\tdouble STAT_VMISS = -9999999.0;\r\n\r\n\r\n\tconst char* CStatistic::NAME[NB_STATXY_TYPE_EX] =\r\n\t{ \r\n\t\t\"Lowest\", \"Mean\", \"Sum\", \"Sum²\", \"StandardDeviation (N-1)\", \"StandardDeviation (N)\", \"StandardError\", \"CoeficientOfVariation\", \"Variance\", \"Highest\", \"TotalSumOfSquares\", \"QuadraticMean\", \"Range\", \"NbValue\",\r\n\t\t\"MeanAbsoluteDeviation\", \"Skewness\", \"Kurtosis\", \"Median\", \"Mode\", \"Lo\", \"Q¹\", \"Q³\", \"Hi\", \"IQR\",\r\n\t\t\"MeanX\", \"MeanY\", \"Intercept\", \"Slope\", \"Covariance\", \"Correlation\", \"Bias\", \"MeanAbsolutError\", \"RootMeanSquareError\", \"ResidualSumOfSquare\", \"CoeficientOfDetermination\", \"CoeficientOfCorrelation\", \"R²\",\r\n\t\t\"TheilSenIntercept\", \"TheilSenSlope\", \"Likelihood\"\r\n\t\t//, \"LogLikelihood2\"\r\n\t};\r\n\r\n\t\r\n\r\n\tStringVector CStatistic::TITLE;\r\n\tconst char* CStatistic::GetTitle(size_t s)\r\n\t{\r\n\t\tassert(s < NB_STATXY_TYPE_EX);\r\n\t\tif (TITLE.empty())\r\n\t\t\tTITLE.LoadString(IDS_STR_STATISTIC, \"|;\");\r\n\r\n\t\tassert(TITLE.size() == NB_STATXY_TYPE_EX);\r\n\r\n\t\treturn TITLE[s].c_str();\r\n\t}\r\n\r\n\tvoid CStatistic::ReloadString()\r\n\t{\r\n\t\tTITLE.clear();\r\n\t}\r\n\r\n\tCStatistic::CStatistic()\r\n\t{\r\n\t\tReset();\r\n\t}\r\n\r\n\tvoid CStatistic::Reset()\r\n\t{\r\n\t\tm_nbValues = 0;\r\n\r\n\t\tm_lowest = DBL_MAX;\r\n\t\tm_sum = 0;\r\n\t\tm_sum² = 0;\r\n\t\tm_hightest = -DBL_MAX;\r\n\t}\r\n\r\n\tCStatistic& CStatistic::operator=(const CStatistic& in)\r\n\t{\r\n\t\tif (&in != this)\r\n\t\t{\r\n\t\t\tm_nbValues = in.m_nbValues;\r\n\r\n\t\t\tm_lowest = in.m_lowest;\r\n\t\t\tm_sum = in.m_sum;\r\n\t\t\tm_sum² = in.m_sum²;\r\n\t\t\tm_hightest = in.m_hightest;\r\n\t\t}\r\n\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatistic& CStatistic::operator+=(double value)\r\n\t{\r\n\t\t_ASSERTE(!_isnan(value));\r\n\r\n\t\tm_nbValues++;\r\n\r\n\t\tif (value < m_lowest)\r\n\t\t\tm_lowest = value;\r\n\r\n\t\tm_sum += value;\r\n\t\tm_sum² += Square(value);\r\n\t\tif (value > m_hightest)\r\n\t\t\tm_hightest = value;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatistic& CStatistic::operator+=(const CStatistic& statistic)\r\n\t{\r\n\t\tm_nbValues += statistic.m_nbValues;\r\n\r\n\t\tif (statistic.m_lowest < m_lowest)\r\n\t\t\tm_lowest = statistic.m_lowest;\r\n\r\n\t\tm_sum += statistic.m_sum;\r\n\t\tm_sum² += statistic.m_sum²;\r\n\t\tif (statistic.m_hightest > m_hightest)\r\n\t\t\tm_hightest = statistic.m_hightest;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tdouble CStatistic::operator[](size_t type)const\r\n\t{\r\n\t\t_ASSERTE(type >= 0 && type < NB_STAT_TYPE);\r\n\t\tconst CStatistic& me = *this;\r\n\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tif (m_nbValues > 0 || type == NB_VALUE)\r\n\t\t{\r\n\t\t\tsize_t nbVal = m_nbValues == 1 ? m_nbValues : m_nbValues - 1;\r\n\t\t\tswitch (type)\r\n\t\t\t{\r\n\t\t\tcase LOWEST: value = m_lowest; break;\r\n\t\t\tcase SUM:value = m_sum; break;\r\n\t\t\tcase SUM²:value = m_sum²; break;\r\n\t\t\tcase MEAN:value = m_sum / m_nbValues; break;\r\n\t\t\tcase STD_DEV:value = sqrt(std::max(0.0, (m_sum² - Square(m_sum) / m_nbValues)) / (nbVal)); break;\r\n\t\t\tcase STD_DEV_OVER_POP:value = sqrt(std::max(0.0, (m_sum² - Square(m_sum) / m_nbValues)) / (m_nbValues)); break;\r\n\t\t\tcase STD_ERR:value = (me[STD_DEV] / sqrt((double)m_nbValues)); break;\r\n\t\t\tcase TSS: value = std::max(0.0, m_sum² - Square(m_sum) / m_nbValues); break;\r\n\t\t\tcase COEF_VAR:\r\n\t\t\t\tif (!(m_sum² > 0 && m_sum == 0))\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue = m_sum != 0 ? me[STD_DEV] / me[MEAN] : 0;//est-ce que doit accepter les valeur négative???\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\tcase VARIANCE:value = std::max(0.0, (m_sum² - Square(m_sum) / m_nbValues) / (nbVal)); break;\r\n\t\t\tcase HIGHEST:value = m_hightest; break;\r\n\t\t\tcase QUADRATIC_MEAN: value = sqrt(m_sum² / m_nbValues); break;\r\n\t\t\tcase RANGE: value = m_hightest - m_lowest; break;\r\n\t\t\tcase NB_VALUE:value = (double)m_nbValues; break;\r\n\t\t\tdefault: _ASSERTE(false);//not supported by this statistic class\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_ASSERTE(!_isnan(value));\r\n\t\treturn value;\r\n\t}\r\n\r\n\r\n\tdouble CStatistic::GetVMiss(){ return STAT_VMISS; }\r\n\tvoid CStatistic::SetVMiss(double vmiss){ STAT_VMISS = vmiss; }\r\n\r\n\tbool CStatistic::operator==(const CStatistic& in)const\r\n\t{\r\n\t\tbool bEqual = true;\r\n\t\tif (m_nbValues != in.m_nbValues)bEqual = false;\r\n\t\tif (fabs(m_lowest - in.m_lowest) > EPSILON_DATA)bEqual = false;\r\n\t\tif (fabs(m_sum - in.m_sum) > EPSILON_DATA)bEqual = false;\r\n\t\tif (fabs(m_sum² - in.m_sum²) > EPSILON_DATA)bEqual = false;\r\n\t\tif (fabs(m_hightest - in.m_hightest) > EPSILON_DATA)bEqual = false;\r\n\r\n\t\treturn bEqual;\r\n\t}\r\n\t//*************************************************************\r\n\t//CStatisticEx : keep in memory all elements for MAD computation\r\n\r\n\tCStatisticEx::CStatisticEx()\r\n\t{\r\n\t\tReset();\r\n\t}\r\n\r\n\tvoid CStatisticEx::Reset()\r\n\t{\r\n\t\tCStatistic::Reset();\r\n\t\tm_values.clear();\r\n\t\tm_sorted.clear();\r\n\t}\r\n\r\n\tCStatisticEx& CStatisticEx::operator=(const CStatisticEx& in)\r\n\t{\r\n\t\tCStatistic::operator=(in);\r\n\t\tm_values = in.m_values;\r\n\t\tm_sorted.clear();\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticEx& CStatisticEx::operator+=(double value)\r\n\t{\r\n\t\tCStatistic::operator+=(value);\r\n\t\tm_values.push_back(value);\r\n\t\tm_sorted.clear();\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticEx& CStatisticEx::operator+=(const CStatisticEx& statistic)\r\n\t{\r\n\t\tCStatistic::operator+=(statistic);\r\n\t\tm_values.insert(m_values.end(), statistic.m_values.begin(), statistic.m_values.end());\r\n\t\tm_sorted.clear();\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tvoid CStatisticEx::sort()const\r\n\t{\r\n\t\tif (m_sorted.empty())\r\n\t\t{\r\n\t\t\tCStatisticEx& me = const_cast(*this);\r\n\t\t\tme.m_sorted = m_values;\r\n\t\t\tstd::sort(me.m_sorted.begin(), me.m_sorted.end());\r\n\t\t}\r\n\r\n\t\tASSERT(m_sorted.size() == m_values.size());\r\n\t}\r\n\r\n\tdouble CStatisticEx::operator[](size_t type)const\r\n\t{\r\n\t\t_ASSERTE(m_values.size() == m_nbValues);\r\n\t\t_ASSERTE(type >= 0 && type < NB_STAT_TYPE_EX);\r\n\t\tconst CStatisticEx& me = *this;\r\n\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tif (m_nbValues > 0 || type == NB_VALUE)\r\n\t\t{\r\n\t\t\tif (type == MAD)\r\n\t\t\t{\r\n\t\t\t\tvalue = 0;\r\n\t\t\t\tdouble mean = CStatistic::operator[](MEAN);\r\n\t\t\t\tfor (int i = 0; i < (int)m_values.size(); i++)\r\n\t\t\t\t\tvalue += fabs(m_values[i] - mean);\r\n\r\n\t\t\t\tvalue /= m_values.size();\r\n\t\t\t}\r\n\t\t\telse if (type == SKEWNESS)\r\n\t\t\t{\r\n\t\t\t\tvalue = 0;\r\n\t\t\t\tdouble mean = CStatistic::operator[](MEAN);\r\n\t\t\t\tfor (int i = 0; i < (int)m_values.size(); i++)\r\n\t\t\t\t\tvalue += pow(m_values[i] - mean, 3);\r\n\r\n\t\t\t\tdouble SD = CStatistic::operator[](STD_DEV);\r\n\t\t\t\tdouble tmp = ((m_values.size() - 1)*pow(SD, 3));\r\n\r\n\t\t\t\tif (tmp != 0)\r\n\t\t\t\t\tvalue /= tmp;\r\n\t\t\t}\r\n\t\t\telse if (type == KURTOSIS)\r\n\t\t\t{\r\n\t\t\t\tvalue = 0;\r\n\t\t\t\tdouble mean = CStatistic::operator[](MEAN);\r\n\t\t\t\tfor (int i = 0; i < (int)m_values.size(); i++)\r\n\t\t\t\t\tvalue += pow(m_values[i] - mean, 4);\r\n\r\n\t\t\t\tdouble SD = CStatistic::operator[](STD_DEV);\r\n\t\t\t\tdouble tmp = ((m_values.size() - 1)*pow(SD, 4));\r\n\r\n\t\t\t\tif (tmp != 0)\r\n\t\t\t\t\tvalue /= tmp;\r\n\t\t\t}\r\n\t\t\telse if (type == MEDIAN || type == Q²)\r\n\t\t\t{\r\n\t\t\t\tsort();\r\n\r\n\t\t\t\tsize_t N1 = (m_sorted.size() + 1) / 2 - 1;\r\n\t\t\t\tsize_t N2 = m_sorted.size() / 2 + 1 - 1;\r\n\t\t\t\tASSERT(N2 == N1 || N2 == N1 + 1);\r\n\t\t\t\t\r\n\t\t\t\tvalue = (m_sorted[N1] + m_sorted[N2]) / 2.0;\r\n\t\t\t}\r\n\t\t\telse if (type == MODE )\r\n\t\t\t{\r\n\t\t\t\tsort();\r\n\r\n\t\t\t\tint maxOcc = 0;\r\n\t\t\t\tint occ = 0;\r\n\t\t\t\tdouble lastVal = -DBL_MAX;\r\n\t\t\t\tfor (size_t i = 0; i < m_sorted.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (fabs(m_sorted[i] - lastVal) < 0.000001)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tocc++;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tocc = 1;\r\n\t\t\t\t\t\tlastVal = m_sorted[i];\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (occ > maxOcc)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmaxOcc = occ;\r\n\t\t\t\t\t\tvalue = lastVal;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse if (type == Qᴸ)\r\n\t\t\t{\r\n\t\t\t\tsort();\r\n\t\t\t\t\r\n\t\t\t\tdouble Q1 = me[Q¹];\r\n\t\t\t\tdouble IQR = me[INTER_Q];\r\n\t\t\t\tvalue = max(Q1 - 1.5*IQR, m_sorted.front());\r\n\t\t\t}\r\n\t\t\telse if (type == Q¹)\r\n\t\t\t{\r\n\t\t\t\tsize_t N1 = (m_sorted.size() + 1) / 4 - 1;\r\n\t\t\t\tsize_t N2 = m_sorted.size() / 4 + 1 - 1;\r\n\t\t\t\tASSERT(N2 == N1 || N2 == N1 + 1);\r\n\r\n\t\t\t\tsort();\r\n\t\t\t\tvalue = (m_sorted[N1] + m_sorted[N2]) / 2.0;\r\n\t\t\t}\r\n\t\t\telse if (type == Q³)\r\n\t\t\t{\r\n\t\t\t\tsize_t N1 = 3 * (m_sorted.size() + 1) / 4 - 1;\r\n\t\t\t\tsize_t N2 = 3 * m_sorted.size() / 4 + 1 - 1;\r\n\t\t\t\tASSERT(N2 == N1 || N2 == N1 + 1);\r\n\r\n\t\t\t\tsort();\r\n\t\t\t\tvalue = (m_sorted[N1] + m_sorted[N2]) / 2.0;\r\n\t\t\t}\r\n\t\t\telse if (type == Qᴴ)\r\n\t\t\t{\r\n\t\t\t\tsort();\r\n\r\n\t\t\t\tdouble Q3 = me[Q³];\r\n\t\t\t\tdouble IQR = me[INTER_Q];\r\n\t\t\t\tvalue = min(Q3 + 1.5*IQR, m_sorted.back());\r\n\t\t\t}\r\n\t\t\telse if (type == INTER_Q)\r\n\t\t\t{\r\n\t\t\t\tvalue = me[Q³] - me[Q¹];\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tvalue = CStatistic::operator[](type);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_ASSERTE(!_isnan(value));\r\n\t\treturn value;\r\n\t}\r\n\r\n\tdouble CStatisticEx::percentil(double p)const\r\n\t{\r\n\t\tASSERT(p >= 0 && p <= 100);\r\n\t\tsort();//create sorted array\r\n\t\t\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tif (!m_sorted.empty())\r\n\t\t{\r\n\t\t\tsize_t n = max(size_t(1), size_t(ceil(p / 100 * m_sorted.size()))) - size_t(1);\r\n\t\t\tvalue = m_sorted[n];\r\n\t\t}\r\n\r\n\t\treturn value;\r\n\t}\r\n\r\n\t//*************************************************************\r\n\t//Weighted CStatistic\r\n\tCStatisticXW::CStatisticXW()\r\n\t{\r\n\t\tm_wx = 0;\r\n\t\tm_wx² = 0;\r\n\t}\r\n\r\n\r\n\tvoid CStatisticXW::Reset()\r\n\t{\r\n\t\tm_x.clear();\r\n\t\tm_w.clear();\r\n\t\tm_wx = 0;\r\n\t\tm_wx² = 0;\r\n\t}\r\n\r\n\tCStatisticXW& CStatisticXW::operator=(const CStatisticXW& in)\r\n\t{\r\n\t\tm_x = in.m_x;\r\n\t\tm_w = in.m_w;\r\n\t\tm_wx = in.m_wx;\r\n\t\tm_wx² = in.m_wx²;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticXW& CStatisticXW::Add(double x, double w)\r\n\t{\r\n\t\tm_x.insert(x);\r\n\t\tm_w.insert(w);\r\n\t\tm_wx += w*x;\r\n\t\tm_wx² += w*x*x;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticXW& CStatisticXW::operator+=(const CStatisticXW& statistic)\r\n\t{\r\n\t\tm_x += statistic.m_x;\r\n\t\tm_w += statistic.m_w;\r\n\t\tm_wx += statistic.m_wx;\r\n\t\tm_wx² += statistic.m_wx²;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tdouble CStatisticXW::operator[](size_t type)const\r\n\t{\r\n\t\tASSERT(m_x[NB_VALUE] == m_w[NB_VALUE]);\r\n\t\tASSERT(type >= 0 && type < NB_STAT_TYPE);\r\n\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tconst CStatisticXW& me = *this;\r\n\t\tdouble nbValues = m_x[NB_VALUE];\r\n\r\n\t\tif (nbValues > 0 || type == NB_VALUE)\r\n\t\t{\r\n\t\t\tswitch (type)\r\n\t\t\t{\r\n\t\t\tcase LOWEST:\tvalue = m_x[LOWEST]; break;\r\n\t\t\tcase SUM:\t\tvalue = m_wx; break;\r\n\t\t\tcase SUM²:\t\tvalue = m_wx²; break;\r\n\t\t\tcase MEAN:\t\tvalue = m_wx / m_w[SUM]; break;\r\n\t\t\t\t//from https://stat.ethz.ch/pipermail/r-help/2008-July/168762.html\r\n\t\t\tcase STD_DEV:\r\n\t\t\tcase STD_DEV_OVER_POP:\r\n\t\t\t{\r\n\t\t\t\tif ((Square(m_w[SUM]) - m_w[SUM²]) != 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble mean = me[MEAN];\r\n\t\t\t\t\tdouble sum = 0;\r\n\t\t\t\t\tfor (size_t i = 0; i < m_x().size(); i++)\r\n\t\t\t\t\t\tsum += m_w(i) * Square(m_x(i) - mean);\r\n\r\n\t\t\t\t\tvalue = m_w[SUM] / (Square(m_w[SUM]) - m_w[SUM²]) *sum;\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase STD_ERR:value = (me[STD_DEV] / sqrt(m_w[SUM])); break;\r\n\t\t\tcase TSS: value = std::max(0.0, m_wx² * m_w[SUM] - Square(m_wx)); break;\r\n\t\t\tcase COEF_VAR:\r\n\t\t\t\tif (!(m_wx²>0 && m_wx == 0))\r\n\t\t\t\t{\r\n\t\t\t\t\tvalue = m_wx > 0 ? me[STD_DEV] / me[MEAN] : 0;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\r\n\t\t\tcase VARIANCE: value = ((Square(m_w[SUM]) - m_w[SUM²]) != 0) ? (m_wx² * m_w[SUM] - Square(m_wx)) / (Square(m_w[SUM]) - m_w[SUM²]) : VMISS; break;\r\n\t\t\tcase HIGHEST: value = m_x[HIGHEST]; break;\r\n\t\t\tcase QUADRATIC_MEAN: value = sqrt(m_wx² / m_w[SUM]); break;\r\n\t\t\tcase RANGE: value = m_x[RANGE]; break;\r\n\t\t\tcase NB_VALUE: value = nbValues; break;\r\n\t\t\tdefault: ASSERT(false);//not supported by this class\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_ASSERTE(!_isnan(value));\r\n\r\n\t\treturn value;\r\n\t}\r\n\r\n\r\n\t//*************************************************************\r\n\t//CStatisticXY: statistic of 2 variables\r\n\r\n\tCStatisticXY::CStatisticXY()\r\n\t{\r\n\t\tReset();\r\n\t}\r\n\r\n\tCStatisticXY& CStatisticXY::operator=(const CStatisticXY& in)\r\n\t{\r\n\t\tif (&in != this)\r\n\t\t{\r\n\t\t\tm_x = in.m_x;\r\n\t\t\tm_y = in.m_y;\r\n\t\t\tm_lowest = in.m_lowest;\r\n\t\t\tm_xy = in.m_xy;\r\n\t\t\tm_e = in.m_e;\r\n\t\t\tm_rs = in.m_rs;\r\n\t\t\tm_ae = in.m_ae;\r\n\t\t\tm_hightest = in.m_hightest;\r\n\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tvoid CStatisticXY::Reset()\r\n\t{\r\n\t\tm_x.clear();\r\n\t\tm_y.clear();\r\n\r\n\t\tm_lowest = DBL_MAX;\r\n\t\tm_xy = 0;\r\n\t\tm_e = 0;\r\n\t\tm_rs = 0;\r\n\t\tm_ae = 0;\r\n\t\tm_hightest = -DBL_MAX;\r\n\t}\r\n\r\n\t//x = pred, y = obs\r\n\tCStatisticXY& CStatisticXY::Add(double x, double y)\r\n\t{\r\n\t\tm_x += x;\r\n\t\tm_y += y;\r\n\r\n\t\tdouble e = (x - y);\r\n\t\tif (e < m_lowest)\r\n\t\t\tm_lowest = e;\r\n\r\n\t\tm_xy += x*y;\r\n\t\tm_e += (x - y);\r\n\t\tm_rs += Square(x - y);\r\n\t\tm_ae += abs(x - y);\r\n\r\n\t\tif (e > m_hightest)\r\n\t\t\tm_hightest = e;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticXY& CStatisticXY::operator+=(const CStatisticXY& in)\r\n\t{\r\n\t\tm_x += in.m_x;\r\n\t\tm_y += in.m_y;\r\n\r\n\t\tif (in.m_lowest < m_lowest)\r\n\t\t\tm_lowest = in.m_lowest;\r\n\r\n\t\tm_xy += in.m_xy;\r\n\t\tm_e += in.m_e;\r\n\t\tm_rs += in.m_rs;\r\n\t\tm_ae += in.m_ae;\r\n\r\n\t\tif (in.m_hightest > m_hightest)\r\n\t\t\tm_hightest = in.m_hightest;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tdouble CStatisticXY::operator[](size_t type)const\r\n\t{\r\n\t\t_ASSERTE(m_x[NB_VALUE] == m_y[NB_VALUE]);\r\n\t\t_ASSERTE(type >= 0 && type < NB_STATXY_TYPE);\r\n\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tconst CStatisticXY& me = *this;\r\n\t\tdouble nbValues = m_x[NB_VALUE];\r\n\r\n\t\tif (nbValues > 0 || type == NB_VALUE)\r\n\t\t{\r\n\t\t\tdouble nbVal = (nbValues == 1) ? nbValues : nbValues - 1;\r\n\t\t\tswitch (type)\r\n\t\t\t{\r\n\t\t\tcase LOWEST:\tvalue = m_lowest; break;\r\n\t\t\tcase MEAN:\t\tvalue = m_e / nbValues; break;//mean of error (bias) (m_y[MEAN] + m_x[MEAN]) / 2; break;\r\n\t\t\tcase MEAN_X:\tvalue = m_x[MEAN]; break;\r\n\t\t\tcase MEAN_Y:\tvalue = m_y[MEAN]; break;\r\n\t\t\tcase TSS:\t\tvalue = m_y[TSS]; break;\r\n\t\t\tcase INTERCEPT: value = m_y[MEAN] - m_x[MEAN] * me[SLOPE]; break;\r\n\t\t\tcase SLOPE:\r\n\t\t\t\tif (m_x[TSS] != 0)\r\n\t\t\t\t\tvalue = (m_xy - (m_x[SUM] * m_y[SUM] / nbValues)) / m_x[TSS];\r\n\t\t\t\tbreak;\r\n\t\t\tcase COVARIANCE: value = ((m_xy - m_x[SUM] * m_y[MEAN] - m_y[SUM] * m_x[MEAN] + nbValues*m_x[MEAN] * m_y[MEAN])) / nbVal; break;\r\n\t\t\tcase CORRELATION:\r\n\t\t\t{\r\n\t\t\t\tdouble stdDev = (m_x[STD_DEV] * m_y[STD_DEV]);\r\n\t\t\t\tif (stdDev != 0)\r\n\t\t\t\t\tvalue = me[COVARIANCE] / stdDev;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase BIAS:\t\tvalue = m_e / nbValues; break;\r\n\t\t\tcase MAE:\t\tvalue = m_ae / nbValues; break;\r\n\t\t\tcase RMSE:\t\tvalue = sqrt(m_rs / nbValues); break;\r\n\t\t\tcase RSS:\t\tvalue = m_rs; break;\r\n\t\t\tcase COEF_D:\tvalue = me[TSS] > 0 ? (1 - me[RSS] / me[TSS]) : STAT_VMISS; break;\r\n\t\t\tcase COEF_C:\r\n\t\t\t{\r\n\t\t\t\tdouble d = sqrt(nbValues*m_x[SUM²] - Square(m_x[SUM]))*sqrt(nbValues*m_y[SUM²] - Square(m_y[SUM]));\r\n\t\t\t\tif (d != 0)\r\n\t\t\t\t\tvalue = (nbValues*m_xy - m_x[SUM] * m_y[SUM]) / d;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase STAT_R²:\r\n\t\t\t{\r\n\t\t\t\tdouble c = me[COEF_C];\r\n\t\t\t\tif (c > STAT_VMISS)\r\n\t\t\t\t\tvalue = Square(c);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase HIGHEST:\tvalue = m_hightest; break;\r\n\t\t\tcase RANGE:\t\tvalue = m_hightest - m_lowest; break;\r\n\t\t\tcase NB_VALUE:\tvalue = nbValues; break;\r\n\t\t\tdefault: _ASSERTE(false);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_ASSERTE(!_isnan(value));\r\n\r\n\t\treturn value;\r\n\t}\r\n\r\n\tdouble CStatisticXY::GetVMiss(){ return STAT_VMISS; }\r\n\tvoid CStatisticXY::SetVMiss(double vmiss){ STAT_VMISS = vmiss; }\r\n\r\n\t//*****************************************************************\r\n\t//CStatisticXYEx: statistic of 2 variables, keeps all values in memory\r\n\tCStatisticXYEx::CStatisticXYEx()\r\n\t{\r\n\t\tReset();\r\n\t}\r\n\r\n\tvoid CStatisticXYEx::Reset()\r\n\t{\r\n\t\tCStatisticXY::Reset();\r\n\t\tm_xValues.clear();\r\n\t\tm_yValues.clear();\r\n\t}\r\n\r\n\tCStatisticXYEx& CStatisticXYEx::operator=(const CStatisticXYEx& in)\r\n\t{\r\n\t\tif (&in != this)\r\n\t\t{\r\n\t\t\tCStatisticXY::operator=(in);\r\n\t\t\tm_xValues = m_xValues;\r\n\t\t\tm_yValues = m_yValues;\r\n\t\t}\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tdouble CStatisticXYEx::operator[](size_t type)const\r\n\t{\r\n\t\t_ASSERTE(m_xValues.size() == m_yValues.size());\r\n\t\t_ASSERTE(m_xValues.size() == GetX()[NB_VALUE]);\r\n\t\t_ASSERTE(m_yValues.size() == GetY()[NB_VALUE]);\r\n\t\t_ASSERTE(type >= 0 && type < NB_STATXY_TYPE_EX);\r\n\r\n\t\tconst CStatisticXYEx& me = *this;\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tif (m_xValues.size() > 0)\r\n\t\t{\r\n\t\t\tif (type == INTERCEPT_THEIL_SEN)\r\n\t\t\t{\r\n\t\t\t\tvalue = m_yValues[MEDIAN] - m_xValues[MEDIAN] * me[SLOPE_THEIL_SEN];\r\n\t\t\t}\r\n\t\t\telse if (type == SLOPE_THEIL_SEN)\r\n\t\t\t{\r\n\t\t\t\tCStatisticEx stat;\r\n\t\t\t\tASSERT(m_xValues.size() == m_yValues.size());\r\n\t\t\t\tfor (size_t i = 0; i < m_xValues.size(); i++)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t j = i + 1; j < m_xValues.size(); j++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble deltaX = (m_xValues[i] - m_xValues[j]);\r\n\t\t\t\t\t\tdouble deltaY = (m_yValues[i] - m_yValues[j]);\r\n\t\t\t\t\t\tif (deltaX != 0)\r\n\t\t\t\t\t\t\tstat += deltaY / deltaX;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tvalue = stat[MEDIAN];\r\n\t\t\t}\r\n\t\t\t//else if (type == LOG_LIKELIHOOD1)\r\n\t\t\t//{\r\n\t\t\t//\t//double xSum = m_x[SUM];\r\n\t\t\t//\tdouble ySum = m_y[SUM];\r\n\t\t\t//\tif (ySum > 0)\r\n\t\t\t//\t{\r\n\t\t\t//\t\tdouble LL = 0;\r\n\t\t\t//\t\t//likelihood with classical sigma hat\r\n\t\t\t//\t\tdouble sigma = sqrt(me[RSS] / (m_xValues.size() - 1))*(m_xValues.size()) / (m_xValues.size() - 1);\r\n\t\t\t//\t\tfor (size_t i = 0; i < m_xValues.size(); i++)\r\n\t\t\t//\t\t{\r\n\t\t\t//\t\t\tdouble m = m_xValues[i];\r\n\t\t\t//\t\t\tboost::math::normal_distribution<> N(m, sigma);\r\n\r\n\t\t\t//\t\t\tdouble x = m_yValues[i];\r\n\t\t\t//\t\t\tdouble p = boost::math::pdf(N, x);\r\n\t\t\t//\t\t\tASSERT(p > 0);\r\n\t\t\t//\t\t\tLL += log(p);\r\n\t\t\t//\t\t}\r\n\r\n\t\t\t//\t\tvalue = LL;\r\n\t\t\t//\t}\r\n\t\t\t//}\r\n\t\t\telse if (type == LIKELIHOOD)\r\n\t\t\t{\r\n\t\t\t\tdouble xSum = m_x[SUM];\r\n\t\t\t\tdouble ySum = m_y[SUM];\r\n\t\t\t\tif (ySum > 0)\r\n\t\t\t\t{\r\n\t\t\t\t\tdouble LL = LogFactorial(xSum);\r\n\t\t\t\t\tfor (size_t i = 0; i < m_xValues.size(); i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdouble p = pow(m_yValues[i] / ySum, m_xValues[i]);\r\n\t\t\t\t\t\tLL += log(p);\r\n\t\t\t\t\t\tLL -= LogFactorial(m_xValues[i]);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tvalue = LL;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tvalue = CStatisticXY::operator[](type);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_ASSERTE(!_isnan(value) && _finite(value));\r\n\t\treturn value;\r\n\t}\r\n\r\n\r\n\t//x = pred, y = obs\r\n\tCStatisticXYEx& CStatisticXYEx::Add(double x, double y)\r\n\t{\r\n\t\tm_CS.Enter();\r\n\t\tCStatisticXY::Add(x, y);\r\n\r\n\t\tm_xValues.push_back(x);\r\n\t\tm_yValues.push_back(y);\r\n\t\tm_CS.Leave();\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticXYEx& CStatisticXYEx::operator+=(const CStatisticXYEx& statistic)\r\n\t{\r\n\t\tCStatisticXY::operator+=(statistic);\r\n\t\tm_xValues.insert(m_xValues.end(), statistic.m_xValues.begin(), statistic.m_xValues.end());\r\n\t\tm_yValues.insert(m_yValues.end(), statistic.m_yValues.begin(), statistic.m_yValues.end());\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\t//cook distance\r\n\tstd::vector CStatisticXYEx::GetCookDistance()const\r\n\t{\r\n\t\tASSERT(m_xValues.size() == m_yValues.size());\r\n\r\n\t\tstd::vector cookD(x().size());\r\n\r\n\t\tvector> X(x().size());\r\n\t\tfor (size_t i = 0; i < x().size(); i++)\r\n\t\t{\r\n\t\t\tX[i][0] = 1;\r\n\t\t\tX[i][1] = x(i);\r\n\t\t}\r\n\t\t\r\n\t\t\t\r\n\t\t\r\n\t\tdouble d = (m_x[NB_VALUE] * m_x[SUM²]) - Square(m_x[SUM]);\r\n\t\tarray, 2> s =\r\n\t\t{ \r\n\t\t\t{{m_x[SUM²] / d,-m_x[SUM] / d},\r\n\t\t\t{-m_x[SUM] / d, m_x[NB_VALUE] / d}}\r\n\t\t};\r\n\r\n\t\tvector> P(X.size());\r\n\t\tfor (size_t i = 0; i < X.size(); i++)\r\n\t\t{\r\n\t\t\tP[i].resize(X.size());\r\n\t\t\tfor (size_t j = 0; j < X.size(); j++)\r\n\t\t\t{\r\n\t\t\t\tP[i][j] = (s[0][0] * X[i][0] + s[1][0] * X[i][1])*X[j][0] + (s[0][1] * X[i][0] + s[1][1] * X[i][1])*X[j][1];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\tarray b = { 0 };\r\n\t\tfor (size_t i = 0; i < X.size(); i++)\r\n\t\t{\r\n\t\t\tb[0] += (s[0][0] * X[i][0] + s[1][0] * X[i][1])*y(i);\r\n\t\t\tb[1] += (s[0][1] * X[i][0] + s[1][1] * X[i][1])*y(i);\r\n\t\t}\r\n\r\n\t\tdouble RSS=0;\r\n\t\tfor (size_t i = 0; i < X.size(); i++)\r\n\t\t\tRSS += Square(y(i) - (b[0] * X[i][0] + b[1] * X[i][1]));\r\n\t\t\r\n\t\tsize_t k = 2;\r\n\t\tdouble s2 = RSS / (X.size() - k); //three predictors(including intercept(100 - k = 98))\r\n\r\n\t\tfor (size_t i = 0; i < X.size(); i++)\r\n\t\t{\r\n\t\t\tdouble res² = Square(y(i) - (b[0] * X[i][0] + b[1] * X[i][1]));\r\n\t\t\tcookD[i] = (res² / (k*s2))*(P[i][i] / Square(1.0 - P[i][i]));\r\n\t\t}\r\n\r\n\t\treturn cookD;\r\n\r\n\t}\r\n\r\n\t//*************************************************************\r\n\t//Weighted CStatisticXY\r\n\tCStatisticXYW::CStatisticXYW()\r\n\t{\r\n\t\tm_wxy = 0;\r\n\t\tm_we = 0;\r\n\t\tm_wrs = 0;\r\n\t\tm_wae = 0;\r\n\t}\r\n\r\n\r\n\tvoid CStatisticXYW::Reset()\r\n\t{\r\n\t\tm_xw.clear();\r\n\t\tm_yw.clear();\r\n\t\tm_wxy = 0;\r\n\t\tm_we = 0;\r\n\t\tm_wrs = 0;\r\n\t\tm_wae = 0;\r\n\t}\r\n\r\n\tCStatisticXYW& CStatisticXYW::operator=(const CStatisticXYW& in)\r\n\t{\r\n\t\tm_xw = in.m_xw;\r\n\t\tm_yw = in.m_yw;\r\n\t\tm_wxy = in.m_wxy;\r\n\t\tm_we = in.m_we;\r\n\t\tm_wrs = in.m_wrs;\r\n\t\tm_wae = in.m_wae;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticXYW& CStatisticXYW::Add(double x, double y, double w)\r\n\t{\r\n\t\tm_xw.insert(x, w);\r\n\t\tm_yw.insert(y, w);\r\n\t\tdouble e = x - y;\r\n\t\tm_wxy += w*x*y;\r\n\t\tm_we += w*e;\r\n\t\tm_wrs += w*e*e;\r\n\t\tm_wae += w*fabs(e);\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tCStatisticXYW& CStatisticXYW::operator+=(const CStatisticXYW& in)\r\n\t{\r\n\t\tm_xw += in.m_xw;\r\n\t\tm_yw += in.m_yw;\r\n\t\tm_wxy += in.m_wxy;\r\n\t\tm_we += in.m_we;\r\n\t\tm_wrs += in.m_wrs;\r\n\t\tm_wae += in.m_wae;\r\n\r\n\t\treturn *this;\r\n\t}\r\n\r\n\tdouble CStatisticXYW::operator[](size_t type)const\r\n\t{\r\n\t\tASSERT(m_xw[NB_VALUE] == m_yw[NB_VALUE]);\r\n\t\tASSERT(type >= 0 && type < NB_STATXY_TYPE);\r\n\r\n\t\tdouble value = STAT_VMISS;\r\n\r\n\t\tconst CStatisticXYW& me = *this;\r\n\t\tdouble nbValues = m_xw[NB_VALUE];\r\n\r\n\t\tif (nbValues > 0 || type == NB_VALUE)\r\n\t\t{\r\n\t\t\tswitch (type)\r\n\t\t\t{\r\n\t\t\tcase LOWEST: /*value = m_e[LOWEST];*/ break;\r\n\t\t\tcase MEAN: value = m_we / m_xw.W(SUM); break;\r\n\t\t\tcase MEAN_X: value = m_xw[MEAN]; break;\r\n\t\t\tcase MEAN_Y:value = m_yw[MEAN]; break;\r\n\t\t\tcase TSS: value = m_yw[TSS]; break;\r\n\t\t\tcase INTERCEPT: value = m_yw[MEAN] - m_xw[MEAN] * me[SLOPE]; break;\r\n\t\t\tcase SLOPE:\r\n\t\t\t\tif (m_xw[TSS] != 0)\r\n\t\t\t\t\tvalue = (m_wxy - (m_xw[SUM] * m_yw[SUM] / m_xw.W(SUM))) / m_xw[TSS];\r\n\t\t\t\tbreak;\r\n\t\t\tcase COVARIANCE: value = ((m_wxy - m_xw[SUM] * m_yw[MEAN] - m_yw[SUM] * m_xw[MEAN] + m_xw.W(SUM)*m_xw[MEAN] * m_yw[MEAN])) / m_xw.W(SUM); break;\r\n\t\t\tcase CORRELATION:\r\n\t\t\t{\r\n\t\t\t\tdouble stdDev = (m_xw[STD_DEV] * m_yw[STD_DEV]);\r\n\t\t\t\tif (stdDev != 0)\r\n\t\t\t\t\tvalue = me[COVARIANCE] / stdDev;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tcase BIAS: value = m_we / m_xw.W(SUM); break;\r\n\t\t\tcase MAE: value = m_wae / m_xw.W(SUM); break;\r\n\t\t\tcase RMSE: value = sqrt(m_wrs / m_xw.W(SUM)); break;//ici il ya une erreur dans le calcul... a faire\r\n\t\t\tcase RSS: value = m_wrs / m_xw.W(SUM); break;\r\n\t\t\tcase COEF_D: value = me[TSS] > 0 ? (1 - me[RSS] / me[TSS]) : STAT_VMISS; break;\r\n\t\t\tcase COEF_C:\r\n\t\t\t{\r\n\t\t\t\tdouble d = sqrt(max(0.0, m_xw.W(SUM)*m_xw[SUM²] - Square(m_xw[SUM])))*sqrt(max(0.0, m_xw.W(SUM) * m_yw[SUM²] - Square(m_yw[SUM])));\r\n\t\t\t\tif (d != 0)\r\n\t\t\t\t\tvalue = (m_xw.W(SUM)*m_wxy - m_xw[SUM] * m_yw[SUM]) / d;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase STAT_R²:\r\n\t\t\t{\r\n\t\t\t\tdouble c = me[COEF_C];\r\n\t\t\t\tif (c > STAT_VMISS)\r\n\t\t\t\t\tvalue = Square(c);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\tcase HIGHEST: value = STAT_VMISS; break;\r\n\t\t\tcase RANGE: value = STAT_VMISS; break;\r\n\t\t\tcase NB_VALUE: value = nbValues; break;\r\n\t\t\tdefault: _ASSERTE(false);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_ASSERTE(!_isnan(value));\r\n\r\n\t\treturn value;\r\n\t}\r\n\r\n\r\n\r\n\r\n\t//************************************************************\r\n\r\n\tCClassify::CClassify()\r\n\t{\r\n\t\tReset();\r\n\t}\r\n\r\n\tvoid CClassify::Reset()\r\n\t{\r\n\t\tm_stat.clear();\r\n\t\tm_values.clear();\r\n\t}\r\n\r\n\r\n\tvoid CClassify::Add(double x, double y)\r\n\t{\r\n\t\tm_values.push_back(CXY(x, y));\r\n\t}\r\n\r\n\tvoid CClassify::ClassifyManual(vector classLimit)\r\n\t{\r\n\t\t_ASSERTE(classLimit.size() >= 2);\r\n\t\tm_stat.clear();\r\n\t\tm_stat.resize(classLimit.size() - 1);\r\n\r\n\t\tif (m_values.size() > 0)\r\n\t\t{\r\n\t\t\tstd::sort(m_values.begin(), m_values.end());\r\n\r\n\t\t\tdouble first = m_values.begin()->m_x;\r\n\t\t\tdouble last = m_values.rbegin()->m_x;\r\n\t\t\tif (classLimit[0] == -1)\r\n\t\t\t\tclassLimit[0] = first;\r\n\r\n\t\t\tif (classLimit[classLimit.size() - 1] == -1)\r\n\t\t\t\tclassLimit[classLimit.size() - 1] = last;\r\n\r\n\t\t\tint j = 0;\r\n\t\t\tfor (int i = 0; i= classLimit[i] &&\r\n\t\t\t\t\tm_values[j].m_x < classLimit[i + 1])\r\n\t\t\t\t{\r\n\t\t\t\t\tm_stat[i].m_x += m_values[j].m_x;\r\n\t\t\t\t\tm_stat[i].m_y += m_values[j].m_y;\r\n\t\t\t\t\tj++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tvoid CClassify::ClassifyEqualInterval(short nbClass)\r\n\t{\r\n\t\tm_stat.clear();\r\n\t\tm_stat.resize(nbClass);\r\n\r\n\t\tif (m_values.size() > 0)\r\n\t\t{\r\n\t\t\tstd::sort(m_values.begin(), m_values.end());\r\n\r\n\t\t\tdouble first = m_values.begin()->m_x;\r\n\t\t\tdouble last = m_values.rbegin()->m_x;\r\n\t\t\tdouble classSize = (double)(last - first) / nbClass;\r\n\t\t\tint j = 0;\r\n\t\t\tfor (int i = 0; i < nbClass; i++)\r\n\t\t\t{\r\n\t\t\t\tdouble limit = first + (i + 1)*classSize;\r\n\r\n\t\t\t\twhile (j < (int)m_values.size() &&\r\n\t\t\t\t\tm_values[j].m_x <= limit)\r\n\t\t\t\t{\r\n\t\t\t\t\tm_stat[i].m_x += m_values[j].m_x;\r\n\t\t\t\t\tm_stat[i].m_y += m_values[j].m_y;\r\n\t\t\t\t\tj++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tvoid CClassify::ClassifyNaturalBreak(short nbClass)\r\n\t{\r\n\t\tm_stat.clear();\r\n\t\tm_stat.resize(nbClass);\r\n\r\n\r\n\t\tstd::sort(m_values.begin(), m_values.end());\r\n\r\n\t\tdouble classSize = (double)m_values.size() / nbClass;\r\n\t\tfor (int i = 0; i < nbClass; i++)\r\n\t\t{\r\n\t\t\tint f = int(i*classSize);\r\n\t\t\tint l = int((i + 1)*classSize);\r\n\t\t\t_ASSERTE(f >= 0 && f <= (int)m_values.size());\r\n\t\t\t_ASSERTE(l >= 0 && l <= (int)m_values.size());\r\n\r\n\t\t\tfor (int j = f; j < l; j++)\r\n\t\t\t{\r\n\t\t\t\tm_stat[i].m_x += m_values[j].m_x;\r\n\t\t\t\tm_stat[i].m_y += m_values[j].m_y;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n}//namespace WBSF", "meta": {"hexsha": "643f4a208e572f9cba45dd413e2674055a85066a", "size": 25709, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "wbs/src/Basic/Statistic.cpp", "max_stars_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_stars_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2017-05-26T21:19:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T14:17:29.000Z", "max_issues_repo_path": "wbs/src/Basic/Statistic.cpp", "max_issues_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_issues_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-02-18T12:39:58.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-13T12:57:45.000Z", "max_forks_repo_path": "wbs/src/Basic/Statistic.cpp", "max_forks_repo_name": "RNCan/WeatherBasedSimulationFramework", "max_forks_repo_head_hexsha": "19df207d11b1dddf414d78e52bece77f31d45df8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-16T02:49:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-16T02:49:20.000Z", "avg_line_length": 24.3687203791, "max_line_length": 210, "alphanum_fraction": 0.5572756622, "num_tokens": 8620, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637577007394, "lm_q2_score": 0.7745833893685269, "lm_q1q2_score": 0.6658812671571228}} {"text": "// Implementing the class that is defined in the header file: ChooserOption.hpp\r\n//\r\n// (c) Sudhansh Dua\r\n\r\n\r\n\r\n#include \"ChooserOption.hpp\"\r\n#include \r\n#include \r\n#include \r\n\r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n\r\n//\tGaussian functions using boost libraries\r\ndouble ChooserOption::N(double x) const\r\n{\r\n\tnormal_distribution<> Standard_normal(0.0, 1.0);\r\n\treturn cdf(Standard_normal, x);\r\n}\r\n\r\ndouble ChooserOption::n(double x) const\r\n{\r\n\tnormal_distribution<> Standard_normal(0.0, 1.0);\r\n\treturn pdf(Standard_normal, x);\r\n}\r\n\r\n\r\ndouble ChooserOption::ChooserPrice() const\r\n{\r\n\treturn ::ChooserPrice(S, K, T, t, r, sig, b);\r\n}\r\n\r\n\r\n// Initialising all the default values\r\nvoid ChooserOption::init()\t\t\t\t\t\r\n{\r\n\t//\tDefault values\r\n\tr = 0.03;\r\n\tsig = 0.2;\r\n\tK = 105;\r\n\tS = 100;\t\t\t//\tDefault stock price \r\n\tb = r;\t\t\t\t//\tBlack - Scholes(1973) stock option model : b = r\r\n\tT = 1;\t\t\t\t\r\n\tt = 0.5;\t\t\t//\ttime that has passed since t = 0\r\n\r\n}\r\n\r\n\r\nvoid ChooserOption::copy(const ChooserOption& option)\r\n{\r\n\tr = option.r;\r\n\tt = option.t;\r\n\tT = option.T;\r\n\tsig = option.sig;\r\n\tK = option.K;\r\n\tb = option.b;\r\n\tS = option.S;\r\n}\r\n\r\n\r\n//\tConstructors and destructor\r\n//\tDefault Constructor\r\nChooserOption::ChooserOption() : Option()\r\n{\r\n\tinit();\r\n}\r\n\r\n//\tCopy constructor\r\nChooserOption::ChooserOption(const ChooserOption& option) : Option(option)\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nChooserOption::ChooserOption(const double& S1, const double& K1, const double& T1, const double& t1, const double& r1,\r\n\tconst double& sig1, const double& b1) : Option(), S(S1), K(K1), T(T1), t(t1), r(r1), sig(sig1), b(b1) {}\r\n\r\n//\tDestructor\r\nChooserOption::~ChooserOption() {}\r\n\r\n\r\n//\tAssignment Operator\r\nChooserOption& ChooserOption::operator = (const ChooserOption& option)\r\n{\r\n\tif (this == &option)\r\n\t{\r\n\t\treturn *this;\t\t//\tSelf-assignment check!\r\n\t}\r\n\tOption::operator = (option);\r\n\tcopy(option);\r\n\treturn *this;\r\n}\r\n\r\n\r\n// Member function that calculate the option price\r\ndouble ChooserOption::Price() const\r\n{\r\n\treturn ChooserPrice();\r\n}\r\n\r\n\r\n// Global functions\r\ndouble ChooserPrice(const double S, const double K, const double T, const double t, const double r, const double sig, const double b)\r\n{\r\n\r\n\tdouble y1 = (log(S / K) + (b * T) + (sig * sig * 0.5 * t)) / (sig * sqrt(t));\r\n\tdouble y2 = y1 - (sig * sqrt(t));\r\n\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\tdouble d2 = d1 - (sig * sqrt(T));\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\r\n\tdouble w = (S * exp((b - r) * T) * cdf(standard_normal, d1)) - (K * exp(-r * T) * cdf(standard_normal, d2)) - (S * exp((b - r) * T) * cdf(standard_normal, -y1)) + (K * exp(-r * T) * cdf(standard_normal, -y2));\r\n\treturn w;\r\n\r\n}\r\n\r\n", "meta": {"hexsha": "cc49aa2cb7bd5843464cd7405cc29082eed08963", "size": 2785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ChooserOption.cpp", "max_stars_repo_name": "sudhanshdua/Option_Classes", "max_stars_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ChooserOption.cpp", "max_issues_repo_name": "sudhanshdua/Option_Classes", "max_issues_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ChooserOption.cpp", "max_forks_repo_name": "sudhanshdua/Option_Classes", "max_forks_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8278688525, "max_line_length": 211, "alphanum_fraction": 0.6301615799, "num_tokens": 810, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105696, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6658707067810831}} {"text": "/*\n * Copyright 2021 MusicScience37 (Kenta Kabashima)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*!\n * \\file\n * \\brief Example of 1-dimensional RBF interpolation.\n */\n#include \n#include \n#include \n#include \n#include \n\n#include \"num_collect/interp/kernel/euclidean_distance.h\"\n#include \"num_collect/interp/kernel/gaussian_rbf.h\"\n#include \"num_collect/interp/kernel/kernel_interpolator.h\"\n#include \"num_collect/interp/kernel/rbf_kernel.h\"\n\nauto main() -> int {\n using num_collect::interp::kernel::euclidean_distance;\n using num_collect::interp::kernel::gaussian_rbf;\n using num_collect::interp::kernel::kernel_interpolator;\n using num_collect::interp::kernel::rbf_kernel;\n\n using kernel_type =\n rbf_kernel, gaussian_rbf>;\n\n const auto vars = std::vector{0.0, 0.1, 0.5, 0.4, 1.2, 1.0};\n const auto data = Eigen::VectorXd{{0.0, 0.2, 0.5, 0.7, 1.0, 2.0}};\n\n auto interpolator = kernel_interpolator();\n interpolator.compute(vars, data);\n\n constexpr num_collect::index_type num_samples = 201;\n const Eigen::VectorXd sample_vars =\n Eigen::VectorXd::LinSpaced(num_samples, -0.1, 1.3);\n Eigen::VectorXd sample_data = Eigen::VectorXd::Zero(num_samples);\n Eigen::VectorXd sample_upper = Eigen::VectorXd::Zero(num_samples);\n Eigen::VectorXd sample_lower = Eigen::VectorXd::Zero(num_samples);\n for (num_collect::index_type i = 0; i < num_samples; ++i) {\n const auto [mean, var] =\n interpolator.evaluate_mean_and_variance_on(sample_vars(i));\n const auto err = 3.0 * std::sqrt(var);\n sample_data(i) = mean;\n sample_upper(i) = mean + err;\n sample_lower(i) = mean - err;\n }\n\n pybind11::scoped_interpreter interpreter;\n auto go = pybind11::module::import(\"plotly.graph_objects\");\n auto fig = go.attr(\"Figure\")();\n\n // upper and lower limits\n fig.attr(\"add_trace\")(go.attr(\"Scatter\")(pybind11::arg(\"x\") = sample_vars,\n pybind11::arg(\"y\") = sample_lower, pybind11::arg(\"mode\") = \"lines\",\n pybind11::arg(\"name\") = \"Lower bound (3 sigma)\"));\n fig.attr(\"add_trace\")(go.attr(\"Scatter\")(pybind11::arg(\"x\") = sample_vars,\n pybind11::arg(\"y\") = sample_upper, pybind11::arg(\"mode\") = \"lines\",\n pybind11::arg(\"name\") = \"Uppper bound (3 sigma)\",\n pybind11::arg(\"fill\") = \"tonexty\"));\n\n // interpolated line\n fig.attr(\"add_trace\")(go.attr(\"Scatter\")(pybind11::arg(\"x\") = sample_vars,\n pybind11::arg(\"y\") = sample_data, pybind11::arg(\"mode\") = \"lines\",\n pybind11::arg(\"name\") = \"Interpolation\"));\n\n // inputs\n fig.attr(\"add_trace\")(go.attr(\"Scatter\")(pybind11::arg(\"x\") = vars,\n pybind11::arg(\"y\") = data, pybind11::arg(\"mode\") = \"markers\",\n pybind11::arg(\"name\") = \"Input data\"));\n\n fig.attr(\"update_layout\")(pybind11::arg(\"title\") = \"RBF Interpolation\",\n pybind11::arg(\"xaxis_title\") = \"x\", pybind11::arg(\"yaxis_title\") = \"y\");\n\n fig.attr(\"write_html\")(\"interp_rbf_1dim.html\");\n fig.attr(\"write_image\")(\"interp_rbf_1dim.png\");\n}\n", "meta": {"hexsha": "1b6019784a04d3959c012e28078ed0f53cd5edcc", "size": 3676, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/interp/kernel/rbf_1dim.cpp", "max_stars_repo_name": "MusicScience37/numerical-collection-cpp", "max_stars_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/interp/kernel/rbf_1dim.cpp", "max_issues_repo_name": "MusicScience37/numerical-collection-cpp", "max_issues_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/interp/kernel/rbf_1dim.cpp", "max_forks_repo_name": "MusicScience37/numerical-collection-cpp", "max_forks_repo_head_hexsha": "490c24aae735ba25f1060b2941cff39050a41f8f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8444444444, "max_line_length": 80, "alphanum_fraction": 0.6700217628, "num_tokens": 1014, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802507195636, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6657790275429911}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \"GRANSAC.hpp\"\n#include \"least_squares_model.hpp\"\n\n#include \n#include \n\nusing namespace std;\n\n\nint main(int argc, char *argv[])\n{\n if (argc != 1 && argc != 3)\n {\n std::cout << \"[ USAGE ]: \" << argv[0] << \" [ = 1000] [ = 500]\" << std::endl;\n return -1;\n }\n\n int side = 400;\n int n_points = 50;\n if (argc == 3)\n {\n side = std::atoi(argv[1]);\n n_points = std::atoi(argv[2]);\n }\n\n cv::Mat img_canvas(side, side, CV_8UC3);\n img_canvas.setTo(255);\n\n // Randomly generate points in a 2D plane roughly aligned in a line for testing\n std::random_device seed_device;\n std::mt19937 RNG = std::mt19937(seed_device());\n\n std::uniform_int_distribution uni_dist(0, side - 1); // [Incl, Incl]\n int perturb = 40;\n std::normal_distribution perturb_dist(0, perturb);\n\n std::vector> cand_points;\n while (n_points > 0){\n int diag = uni_dist(RNG);\n float x = diag + perturb_dist(RNG);\n // y = 2100-20x+0.05*x*x\n float y;\n if (n_points > 5 )\n y = 2100 - 20 * x + 0.05 * x * x + perturb_dist(RNG);\n else\n y = uni_dist(RNG);\n\n if (x<=side && x > 0 && y<=side && y > 0){\n cv::Point pt(floor(x), floor(y));\n cv::circle(img_canvas, pt, floor(side / 100) + 2, cv::Scalar(0, 0, 0), 2, cv::LINE_AA);\n\n std::shared_ptr cand_pt = std::make_shared(pt.x, pt.y);\n cand_points.push_back(cand_pt);\n\n n_points -= 1;\n }\n }\n\n //set grid\n std::map additional_params = {{\"img_width\", float(side)}, {\"img_height\", float(side)}, {\"grid_num_x\", float(side/10)}, {\"grid_num_y\", float(side/10)}};\n\n //draw grid\n cv::Mat img_overlay;\n float alpha = 0.3;\n img_canvas.copyTo(img_overlay);\n for (int i=0; i < side/10; i++){\n cv::Point pt_1(i*10, 0);\n cv::Point pt_2(i*10, side);\n cv::line(img_overlay, pt_1, pt_2, cv::Scalar(0, 100, 0), 1, cv::LINE_AA, 0);\n cv::Point pt_3(0, i*10);\n cv::Point pt_4(side, i*10);\n cv::line(img_overlay, pt_3, pt_4, cv::Scalar(0, 100, 0), 1, cv::LINE_AA, 0);\n }\n cv::addWeighted(img_overlay, alpha, img_canvas, 1 - alpha, 0, img_canvas);\n \n // estimate parameters with RANSAC\n int param_num = 4; // 3rd order\n additional_params[\"sample_number\"]=10; // sample number for over-deterministic least squares\n GRANSAC::RANSAC, 4> estimator;\n estimator.initialize(1, 100, additional_params); // Threshold, iterations, the threshold is p-1 distance on grid, 1 means 1 grid cell distance\n\n float time_average = 0;\n for (int i=0; i<100; i++){\n int start = cv::getTickCount();\n estimator.estimate(cand_points);\n int end = cv::getTickCount();\n float time_of_trial = float(end - start) / float(cv::getTickFrequency()) * 1000.0; // [ms]\n time_average += time_of_trial;\n }\n std::cout << \"RANSAC took, average time in 100 trials: \" << time_average/100 << \" ms.\" << std::endl;\n\n // draw definition points from best model\n auto best_inliers = estimator.getBestInliers();\n if (best_inliers.size() > 0)\n {\n for (auto &inlier : best_inliers)\n {\n auto RPt = std::dynamic_pointer_cast(inlier);\n cv::Point pt(floor(RPt->m_point2D[0]), floor(RPt->m_point2D[1]));\n cv::circle(img_canvas, pt, floor(side / 100), cv::Scalar(0, 255, 0), -1, cv::LINE_AA);\n }\n }\n\n // draw curve from best model\n auto best_line = estimator.getBestModel();\n if (best_line)\n {\n cout << \"coefficients are : \" << endl;\n for (auto each : best_line->getModelCoefficients()){\n cout << each << \", \";\n }\n cout << endl;\n\n std::vector x_values, y_values, coeff;\n for (int i=0; igetModelDefParams().size(); i++){\n auto best_line_pt = std::dynamic_pointer_cast(best_line->getModelDefParams()[i]);\n x_values.push_back(best_line_pt->m_point2D[0]); //x\n y_values.push_back(best_line_pt->m_point2D[1]); //x\n cv::Point pt(floor(best_line_pt->m_point2D[0]), floor(best_line_pt->m_point2D[1]));\n cv::circle(img_canvas, pt, floor(side / 100), cv::Scalar(0, 0, 255), -1, cv::LINE_AA);\n }\n\n // draw polynomial line\n float start_point_x = 0;\n float end_point_x = side;\n vector curve_points;\n //Define the curve through equation. In this example, a simple parabola\n for (float x = start_point_x; x <= end_point_x; x+=1){\n float y = 0;\n for (int j = 0; j < best_line->getModelCoefficients().size(); j++){\n y += best_line->getModelCoefficients()[j]*std::pow(x, float(j));\n } \n\n cv::Point2f new_point = cv::Point2f(x, y); //resized to better visualize\n curve_points.push_back(new_point); //add point to vector/list\n }\n for (int i = 0; i < curve_points.size() - 1; i++){\n cv::line(img_canvas, curve_points[i], curve_points[i + 1], cv::Scalar(0,255,0), 2, CV_AA);\n }\n }\n\n while (true)\n {\n cv::imshow(\"RANSAC Example\", img_canvas);\n char Key = cv::waitKey(1);\n if (Key == 27)\n return 0;\n }\n\n return 0;\n}", "meta": {"hexsha": "00705a28a36e2b123359052603cdd044c440a827", "size": 5653, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/lls_fitting_example.cpp", "max_stars_repo_name": "masszhou/GRANSAC", "max_stars_repo_head_hexsha": "10afa96d7c0bf50959186403d3830a0d197cf823", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/lls_fitting_example.cpp", "max_issues_repo_name": "masszhou/GRANSAC", "max_issues_repo_head_hexsha": "10afa96d7c0bf50959186403d3830a0d197cf823", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/lls_fitting_example.cpp", "max_forks_repo_name": "masszhou/GRANSAC", "max_forks_repo_head_hexsha": "10afa96d7c0bf50959186403d3830a0d197cf823", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0063694268, "max_line_length": 170, "alphanum_fraction": 0.5770387405, "num_tokens": 1662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7662936377487305, "lm_q1q2_score": 0.6657764309370606}} {"text": "#include \n#include \n#include \n\n\nusing namespace boost::numeric::odeint;\n\nconst double b = 0.1;\nconst double g = 0.05;\n\ntypedef boost::array< double , 3 > state_type;\n\nvoid sir( const state_type &x , state_type &dxdt , double t )\n{\n dxdt[0] = -b * x[0] * x[1];\n dxdt[1] = b * x[0] * x[1] - g * x[1];\n dxdt[2] = g * x[1];\n}\n\nvoid write_sir(const state_type &x , const double t )\n{\n std::cout << t << ' ' << x[0] << ' ' << x[1] << ' ' << x[2] << std::endl;\n}\n\nint main(int argc, char **argv)\n{\n state_type x = { 0.99 , 0.01 , 0.0 }; // initial conditions\n integrate( sir , x , 0.0 , 200.0 , 0.1 , write_sir );\n}\n", "meta": {"hexsha": "7cea7d9d50a790cdc6968ca9bd6ce21a5f29c04d", "size": 680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "models/simple_deterministic_models/sir/sir.cpp", "max_stars_repo_name": "epimodels/epicookbook", "max_stars_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "models/simple_deterministic_models/sir/sir.cpp", "max_issues_repo_name": "epimodels/epicookbook", "max_issues_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "models/simple_deterministic_models/sir/sir.cpp", "max_forks_repo_name": "epimodels/epicookbook", "max_forks_repo_head_hexsha": "496088ddc8fc913505d92877e0a687c81976c8f2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T12:46:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-10T12:46:31.000Z", "avg_line_length": 22.6666666667, "max_line_length": 77, "alphanum_fraction": 0.5632352941, "num_tokens": 250, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587993853654, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6657578471843814}} {"text": "\n\n// Spline fit with unknown parameter positions.\n\n\n#include \n\n#include \"main.h\"\n#include \n#include \n\n#include \n#include \"unsupported/Eigen/src/SparseExtra/BlockSparseQR.h\"\n#include \"unsupported/Eigen/src/SparseExtra/BlockDiagonalSparseQR.h\"\n\n// This disables some useless Warnings on MSVC.\n// It is intended to be done for this test only.\n#include \n\n#define NUM_SAMPLE_POINTS 100\n\nstruct SplineParameter {\n int segment;\n double t;\n};\n\ntemplate \nstruct SplineFitting : LevenbergMarquardtFunctor<_Scalar>\n{\n typedef LevenbergMarquardtFunctor Base;\n\n typedef int Index;\n typedef Matrix InputType;\n typedef Matrix ValueType;\n typedef Matrix StepType;\n\n typedef SparseMatrix JacobianType;\n\n typedef SparseQR, COLAMDOrdering > BlockSolver;\n typedef ColPivHouseholderQR > DenseSolver;\n typedef BlockDiagonalSparseQR LeftSuperBlockSolver;\n typedef BlockSparseQR QRSolver;\n\n const Eigen::Matrix SplinePoints;\n\n static const int nParamsModel = 5;\n\n SplineFitting(Eigen::Matrix& points) :\n Base(nParamsModel + points.cols(), points.cols() * 2),\n SplinePoints(points)\n {\n }\n\n // Functor functions\n int operator()(const InputType& uv, ValueType& fvec) {\n int npoints = SplinePoints.cols();\n auto params = uv.tail(nParamsModel);\n double a = params[0];\n double b = params[1];\n double x0 = params[2];\n double y0 = params[3];\n double r = params[4];\n for (int i = 0; i < npoints; i++) {\n double t = uv[i];\n double x = a*cos(t)*cos(r) - b*sin(t)*sin(r) + x0;\n double y = a*cos(t)*sin(r) + b*sin(t)*cos(r) + y0;\n fvec(2 * i + 0) = SplinePoints(0, i) - x;\n fvec(2 * i + 1) = SplinePoints(1, i) - y;\n }\n\n return 0;\n }\n\n int df(const InputType& uv, JacobianType& fjac) {\n // X_i - (a*cos(t_i) + x0)\n // Y_i - (b*sin(t_i) + y0)\n int npoints = SplinePoints.cols();\n auto params = uv.tail(nParamsModel);\n double a = params[0];\n double b = params[1];\n double r = params[4];\n for (int i = 0; i SplinePoints;\n SplinePoints.resize(3, nDataPoints);\n double incr = 1.3*EIGEN_PI / double(nDataPoints);\n for (int i = 0; i::InputType lm_params;\n auto& params = lm_params;\n params.resize(SplineFitting::nParamsModel + nDataPoints);\n double minX, minY, maxX, maxY;\n minX = maxX = SplinePoints(0, 0);\n minY = maxY = SplinePoints(1, 0);\n for (int i = 0; i functor(SplinePoints);\n Eigen::LevenbergMarquardt< SplineFitting > lm(functor);\n Eigen::LevenbergMarquardtSpace::Status info;\n\n info = lm.minimizeInit(lm_params);\n if (info == Eigen::LevenbergMarquardtSpace::ImproperInputParameters) {\n std::cerr << \"Improper Input Parameters\" << std::endl;\n return;\n }\n\n do {\n info = lm.minimizeOneStep(lm_params);\n } while (info == Eigen::LevenbergMarquardtSpace::Running);\n\n std::cout << \"END\" << \" \";\n std::cout << \"a=\" << params(SplinePoints.cols()) << \"\\t\";\n std::cout << \"b=\" << params(SplinePoints.cols() + 1) << \"\\t\";\n std::cout << \"x0=\" << params(SplinePoints.cols() + 2) << \"\\t\";\n std::cout << \"y0=\" << params(SplinePoints.cols() + 3) << \"\\t\";\n std::cout << \"r=\" << params(SplinePoints.cols() + 4)*180. / EIGEN_PI << \"\\t\";\n std::cout << std::endl << std::endl;\n\n // check parameters ambiguity before test result\n // a should be bigger than b\n if (fabs(params(SplinePoints.cols() + 1)) > fabs(params(SplinePoints.cols()))) {\n std::swap(params(SplinePoints.cols()), params(SplinePoints.cols() + 1));\n params(SplinePoints.cols() + 4) -= 0.5*EIGEN_PI;\n }\n // a and b should be positive\n if (params(SplinePoints.cols())<0) {\n params(SplinePoints.cols()) *= -1.;\n params(SplinePoints.cols() + 1) *= -1.;\n params(SplinePoints.cols() + 4) += EIGEN_PI;\n }\n // fix rotation angle range\n while (params(SplinePoints.cols() + 4) < 0) params(SplinePoints.cols() + 4) += 2.*EIGEN_PI;\n while (params(SplinePoints.cols() + 4) > EIGEN_PI) params(SplinePoints.cols() + 4) -= EIGEN_PI;\n\n\n eigen_assert(fabs(a - params(SplinePoints.cols())) < 0.00001);\n eigen_assert(fabs(b - params(SplinePoints.cols() + 1)) < 0.00001);\n eigen_assert(fabs(x0 - params(SplinePoints.cols() + 2)) < 0.00001);\n eigen_assert(fabs(y0 - params(SplinePoints.cols() + 3)) < 0.00001);\n eigen_assert(fabs(r - params(SplinePoints.cols() + 4)) < 0.00001);\n\n\n\n}\n\n\nvoid test_spline_fitting()\n{\n CALL_SUBTEST(testSplineFitting());\n}\n", "meta": {"hexsha": "ce3c8931feb1bd2e1c5986d8291e65ae7ea6a27e", "size": 7621, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eigen_pr/unsupported/test/spline_fitting.cpp", "max_stars_repo_name": "pmkalshetti/parametric_sphere_fitting", "max_stars_repo_head_hexsha": "1d86a18a997ecbc6ab4234c9550db1cc6c707b42", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-10-26T07:50:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-13T00:41:14.000Z", "max_issues_repo_path": "eigen_pr/unsupported/test/spline_fitting.cpp", "max_issues_repo_name": "pmkalshetti/parametric_sphere_fitting", "max_issues_repo_head_hexsha": "1d86a18a997ecbc6ab4234c9550db1cc6c707b42", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eigen_pr/unsupported/test/spline_fitting.cpp", "max_forks_repo_name": "pmkalshetti/parametric_sphere_fitting", "max_forks_repo_head_hexsha": "1d86a18a997ecbc6ab4234c9550db1cc6c707b42", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.429787234, "max_line_length": 97, "alphanum_fraction": 0.6206534576, "num_tokens": 2534, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6655066021229994}} {"text": "/**\n * @file cd_tools.cc\n * @brief Utility Functions for the Convection-Diffusion Problem\n * @author Philippe Peter\n * @date July 2021\n * @copyright Developed at SAM, ETH Zurich\n */\n\n#include \"cd_tools.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace ConvectionDiffusion {\n\ndouble Diameter(const lf::mesh::Entity& entity) {\n const lf::geometry::Geometry* geo_p = entity.Geometry();\n Eigen::MatrixXd corners = lf::geometry::Corners(*geo_p);\n\n switch (entity.RefEl()) {\n case lf::base::RefEl::kTria(): {\n // Diameter of a triangle corresponds to the longest edge\n Eigen::Vector2d e0 = corners.col(1) - corners.col(0);\n Eigen::Vector2d e1 = corners.col(2) - corners.col(1);\n Eigen::Vector2d e2 = corners.col(0) - corners.col(1);\n return std::max(e0.norm(), std::max(e1.norm(), e2.norm()));\n }\n case lf::base::RefEl::kQuad(): {\n // Diameter of a (convex) quadrilateral corresponds to the longer diagonal\n Eigen::Vector2d d0 = corners.col(2) - corners.col(0);\n Eigen::Vector2d d1 = corners.col(3) - corners.col(1);\n return std::max(d0.norm(), d1.norm());\n }\n default: {\n LF_ASSERT_MSG(false,\n \"Diameter not available for \" << entity.RefEl().ToString());\n }\n }\n} // namespace ConvectionDiffusion\n\ndouble MeshWidth(std::shared_ptr mesh_p) {\n double h = 0.0;\n for (const lf::mesh::Entity* entity_p : mesh_p->Entities(0)) {\n h = std::max(h, Diameter(*entity_p));\n }\n return h;\n}\n\n} // namespace ConvectionDiffusion\n", "meta": {"hexsha": "e05aaabab64e26998ee85ebf44a65be36a79ea56", "size": 1642, "ext": "cc", "lang": "C++", "max_stars_repo_path": "lecturecodes/ConvectionDiffusion/cd_tools.cc", "max_stars_repo_name": "yiluchen1066/NPDECODES", "max_stars_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "lecturecodes/ConvectionDiffusion/cd_tools.cc", "max_issues_repo_name": "yiluchen1066/NPDECODES", "max_issues_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "lecturecodes/ConvectionDiffusion/cd_tools.cc", "max_forks_repo_name": "yiluchen1066/NPDECODES", "max_forks_repo_head_hexsha": "f7b1d96555bace59aba2b65f3ef1e95fa7a9017c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 29.8545454545, "max_line_length": 80, "alphanum_fraction": 0.6485992692, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.800692021119887, "lm_q2_score": 0.831143054132195, "lm_q1q2_score": 0.6654896118528629}} {"text": "#ifndef CANNON_ML_RLS_H\n#define CANNON_ML_RLS_H \n\n/*!\n * \\file cannon/ml/rls.hpp\n * \\brief File containing RLSFilter class definition.\n */\n\n#include \n\n#include \n\nusing namespace Eigen;\n\nnamespace cannon {\n namespace ml {\n\n /*!\n * \\brief Class representing a Recursive Least Squares Filter supporting\n * intercept estimation and forgetting. See\n * http://cannontwo.com/assets/rls_notes.pdf.\n */\n class RLSFilter {\n public:\n\n RLSFilter() = delete;\n\n /*!\n * \\brief Constructor taking input dimension, output dimension, inverse\n * covariance matrix initialization alpha, and forgetting factor.\n */\n RLSFilter(unsigned int in_dim, unsigned int out_dim,\n double alpha = 1.0e6, double forgetting = 1.0)\n : in_dim_(in_dim), out_dim_(out_dim), param_dim_(in_dim),\n alpha_(alpha), forgetting_(forgetting),\n intercept_(VectorXd::Zero(out_dim_)),\n theta_(MatrixXd::Zero(param_dim_, out_dim_)),\n corrected_theta_(MatrixXd::Zero(param_dim_, out_dim_)),\n feat_mean_(RowVectorXd::Zero(param_dim_)),\n output_mean_(RowVectorXd::Zero(out_dim_)),\n covar_(MatrixXd::Identity(param_dim_, param_dim_) * alpha_),\n pred_error_covar_(MatrixXd::Zero(out_dim_, out_dim_)) {}\n\n /*!\n * \\brief Get number of data points contributing to this filter.\n *\n * \\returns Number of data points used to fit this filter.\n */\n unsigned int get_num_data() const;\n\n /*!\n * \\brief Process a single datum and update this filter.\n *\n * \\param in_vec Input features of the datum to process.\n * \\param output Output features of the datum to process.\n */\n void process_datum(const VectorXd& in_vec, const VectorXd& output);\n\n /*!\n * \\brief Get the identified linear parameters and offset vector fit by\n * this filter.\n *\n * \\returns A pair containing the linear parameters and offset vector.\n */ \n std::pair get_identified_mats() const;\n \n /*!\n * \\brief Get prediction error covariance matrix for this filter.\n *\n * \\returns Prediction error covariance matrix.\n */\n MatrixXd get_pred_error_covar() const;\n\n /*!\n * \\brief Predict the value of the linear approximation fit by this\n * filter for the input point.\n *\n * \\param in_vec Input features of point to predict for.\n *\n * \\returns Prediction fit by this filter.\n */\n VectorXd predict(const VectorXd& in_vec) const;\n\n /*!\n * \\brief Set the parameters of this RLS filter. Input and output mean\n * are recovered from the intercept.\n *\n * \\param theta Parameter matrix to set.\n * \\param intercept Intercept to set.\n * \\param in_mean Input mean. \n */\n void set_params(const Ref &theta,\n const Ref &intercept,\n const Ref &in_mean);\n\n /*!\n * \\brief Reset this filter.\n */\n void reset();\n\n private:\n\n /*!\n * \\brief Make internal feature vector for the input features.\n *\n * \\param in_vec Input features to transform into internal feature space.\n *\n * \\returns Internal features.\n */\n RowVectorXd make_feature_vec_(const VectorXd& in_vec) const;\n \n /*!\n * \\brief Make U matrix for inverse covariance matrix update.\n *\n * \\param feat Internal feature vector for update.\n *\n * \\returns U matrix.\n */\n MatrixX2d make_u_(const RowVectorXd& feat) const;\n\n /*!\n * \\brief Make V matrix for inverse covariance matrix update.\n *\n * \\param feat Internal feature vector for update.\n *\n * \\returns V matrix.\n */\n Matrix2Xd make_v_(const RowVectorXd& feat) const;\n\n /*!\n * \\brief Make C matrix for inverse covariance matrix update.\n *\n * \\returns C matrix.\n */\n Matrix2d make_c_() const;\n\n /*!\n * \\brief Update inverse covariance matrix for this filter.\n *\n * \\param u U matrix\n * \\param c C matrix\n * \\param v V matrix\n */\n void update_covar_(const MatrixX2d& u, const Matrix2d& c, \n const Matrix2Xd& v);\n\n /*!\n * \\brief Update linear approximation stored by this filter.\n *\n * \\param c_t C matrix transpose.\n * \\param feat Internal feature vector for new datum.\n * \\param output Output for new datum.\n */\n void update_theta_(const MatrixXd& c_t, const RowVectorXd& feat, \n const VectorXd& output);\n \n /*!\n * \\brief Update output mean for this filter.\n *\n * \\param output Observed output.\n */\n void update_output_mean_(const VectorXd& output);\n\n /*!\n * \\brief Update internal feature mean for this filter.\n *\n * \\param feat Observed internal features.\n */\n void update_feat_mean_(const RowVectorXd& feat);\n\n /*!\n * \\brief Update prediction error covariance matrix in light of an\n * observed datum.\n *\n * \\param in_vec Input feature vector.\n * \\param output Observed output.\n */\n void update_pred_error_covar_(const VectorXd& in_vec, const VectorXd& output);\n\n // Parameters\n unsigned int in_dim_; //!< Dimension of input to this filter.\n unsigned int out_dim_; //!< Dimension of output for this filter.\n unsigned int param_dim_; //!< Number of linear parameters of this filter.\n double alpha_; //!< Inverse covariance matrix initialization parameter.\n double forgetting_; //!< Forgetting factor.\n double t_ = 0.0; //!< Number of observed data points.\n\n // Matrices\n VectorXd intercept_; //!< Intercept vector of filter\n MatrixXd theta_; //!< Linear parameters of filter\n MatrixXd corrected_theta_; //!< Linear parameters corrected for intercept\n RowVectorXd feat_mean_; //!< Mean of internal features for this filter\n RowVectorXd output_mean_; //!< Mean of observed outputs for this filter\n MatrixXd covar_; //!< Internal inverse covariance matrix.\n MatrixXd pred_error_covar_; //!< Prediction error covariance matrix for this filter.\n\n };\n\n } // namespace ml\n} // namespace cannon\n\n#endif /* ifndef CANNON_ML_RLS_H */\n", "meta": {"hexsha": "83fd3766e22b144fc6950a5732f0982f69ba6d08", "size": 6780, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cannon/ml/rls.hpp", "max_stars_repo_name": "cannontwo/cannon", "max_stars_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cannon/ml/rls.hpp", "max_issues_repo_name": "cannontwo/cannon", "max_issues_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 46.0, "max_issues_repo_issues_event_min_datetime": "2021-01-12T23:03:52.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-01T17:29:01.000Z", "max_forks_repo_path": "cannon/ml/rls.hpp", "max_forks_repo_name": "cannontwo/cannon", "max_forks_repo_head_hexsha": "4be79f3a6200d1a3cd26c28c8f2250dbdf08f267", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3990147783, "max_line_length": 92, "alphanum_fraction": 0.589380531, "num_tokens": 1406, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7461389986757758, "lm_q1q2_score": 0.6654150025965393}} {"text": "/* Basic example showing the usage of QuantLibAdjoint\n*/\n\n#include \n#include \n#include \n\n#include \n\n#include \n\nusing namespace QuantLib;\nusing std::vector;\nusing std::cout;\nusing std::endl;\nusing std::ios;\n\nint main(int, char* []) {\n\t\n\tDate referenceDate(3, Aug, 2016);\n\tSettings::instance().evaluationDate() = referenceDate;\n\tActual365Fixed dayCounter;\n\t\n\t// Example 1\n\t\n\t// These will be the X (independent) and Y (dependent) vectors\n\tvector zeroRate(1, 0.02);\n\tvector swapNpv(1, 0.0);\n\n\t// Start taping with zeroRate as independent variable and set up flat zero curve\n\tcl::Independent(zeroRate);\n\tRelinkableHandle flatCurve(boost::make_shared(referenceDate, zeroRate[0], dayCounter));\n\tflatCurve->enableExtrapolation();\n\n\t// Create and price swap\n\tPeriod swapTenor(5, Years);\n\tboost::shared_ptr iborIndex = boost::make_shared(flatCurve);\n\tRate fixedRate = 0.03;\n\tPeriod forwardStart(0, Days);\n\tboost::shared_ptr swap = MakeVanillaSwap(swapTenor, iborIndex, fixedRate, forwardStart) .withNominal(100);\n\tswapNpv[0] = swap->NPV();\n\n\t// Stop taping and transfer operation sequence to function f (ultimately an AD function object)\n\tcl::tape_function f(zeroRate, swapNpv);\n\n\t// Calculate d(swapNpv) / d(zero) with forward and reverse mode\n\tvector dZ(1, 1.0);\n\tdouble forwardDeriv = f.Forward(1, dZ)[0];\n\tdouble reverseDeriv = f.Reverse(1, dZ)[0];\n\n\t// Calculate analytically the derivative\n\tReal derivative = 0.0;\n\tconst Leg& fixedLeg = swap->fixedLeg();\n\tfor (const auto& cf : fixedLeg) {\n\t\tReal amount = cf->amount();\n\t\tTime time = dayCounter.yearFraction(referenceDate, cf->date());\n\t\tDiscountFactor discount = flatCurve->discount(time);\n\t\tderivative += amount * time * discount;\n\t}\n\tTime timeToStart = dayCounter.yearFraction(referenceDate, swap->startDate());\n\tTime timeToEnd = dayCounter.yearFraction(referenceDate, swap->maturityDate());\n\tderivative += 100*(timeToEnd * flatCurve->discount(timeToEnd) - timeToStart * flatCurve->discount(timeToStart));\n\n\t//Compare bumped value to Taylor approximation\n\tReal basis_point = 0.01; \n\tReal approx_sensitivity = derivative * basis_point;\n\t//new bumped yield curve\n\t//when yield curve changes, swap recalculates \n\tflatCurve.linkTo(boost::make_shared(referenceDate, zeroRate[0] + basis_point, dayCounter));\n\tReal bumped_npv = swap->NPV();\n\n\n\t// Output the results\n\tcout.precision(9);\n\tcout.setf(ios::fixed, ios::floatfield);\n\tcout << \"Forward derivative: \" << forwardDeriv << endl;\n\tcout << \"Reverse derivative: \" << reverseDeriv << endl;\n\tcout << \"Analytic derivative: \" << derivative << endl;\n\t//approx should be close to bumped\n\tcout << \"Approx_Sensitivity: \" << approx_sensitivity << endl;\n\tcout << \"Bumped Sensitivity: \" << bumped_npv - swapNpv[0] << endl;\n\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "137dab6140dad9a985d295afbc49790f876e5d78", "size": 2973, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/BasicExample/basicexample.cpp", "max_stars_repo_name": "kedonaghey/QuantLibAdjoint", "max_stars_repo_head_hexsha": "62f725b2ba02304171bf6694ee5281c3d936affe", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-08-24T13:31:35.000Z", "max_stars_repo_stars_event_max_datetime": "2016-08-24T13:31:35.000Z", "max_issues_repo_path": "Examples/BasicExample/basicexample.cpp", "max_issues_repo_name": "kedonaghey/QuantLibAdjoint", "max_issues_repo_head_hexsha": "62f725b2ba02304171bf6694ee5281c3d936affe", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/BasicExample/basicexample.cpp", "max_forks_repo_name": "kedonaghey/QuantLibAdjoint", "max_forks_repo_head_hexsha": "62f725b2ba02304171bf6694ee5281c3d936affe", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1724137931, "max_line_length": 121, "alphanum_fraction": 0.7346115035, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7772998611746911, "lm_q1q2_score": 0.6652529777238508}} {"text": "/**\n * @ file pointEvaluation.cc\n * @ brief NPDE homework PointEvaluationRhs code\n * @ author Christian Mitsch, Liaowang Huang (refactoring)\n * @ date 22/03/2019, 06/01/2020 (refactoring)\n * @ copyright Developed at ETH Zurich\n */\n\n#include \"pointevaluationrhs.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"pointevaluationrhs_norms.h\"\n\nnamespace PointEvaluationRhs {\n\n/* SAM_LISTING_BEGIN_5 */\nEigen::Vector2d GlobalInverseTria(Eigen::Matrix mycorners,\n Eigen::Vector2d x) {\n Eigen::Vector2d x_hat;\n\n#if SOLUTION\n // The unique affine mapping of the unit triangle to a general triangle\n // is given by the formula $\\cob{\\Bx = \\VA_K*\\wh{\\Bx} + \\Bs}$,\n // Use the vertex coordinates to calculate matrix A and translation vector s\n Eigen::Matrix2d A(2, 2);\n A.col(0) = mycorners.col(1) - mycorners.col(0);\n A.col(1) = mycorners.col(2) - mycorners.col(0);\n // The inverse mapping: $\\cob{\\wh{\\Bx} = \\VA_K^{-1} * (\\Bx - \\Ba_0)}$\n x_hat = A.partialPivLu().solve(x - mycorners.col(0));\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return x_hat;\n}\n/* SAM_LISTING_END_5 */\n\n/** @brief Numerically stable solution of a quadratic equation in R\n * @param a,b,c coefficients of quadratic polynomias ax^2+bx+c\n * @return both zeros, NaN if complex\n */\n/* SAM_LISTING_BEGIN_4 */\nstd::pair solveQuadraticEquation(double a, double b, double c) {\n // Implement the cases which are solvable and return their solutions\n#if SOLUTION\n if (a != 0.) {\n b /= a;\n c /= a;\n const double D = b * b - 4 * c; // discriminant\n if (D >= 0) { // real solutions\n const double rtD = std::sqrt(D);\n // Real solutions, cancellation-free formulas !\n if (b < 0) {\n const double root = 0.5 * (-b + rtD);\n return {root, c / root};\n } else { // b >= 0\n const double root = 0.5 * (-b - rtD);\n return {root, c / root};\n }\n }\n } else {\n if (b != 0.0) {\n return {-c / b, -c / b};\n }\n }\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n // Return NAN if there are no (real) roots\n return {NAN, NAN};\n}\n\n/* SAM_LISTING_END_4 */\n\n/** @brief Computes the area of a triangle\n * @param a,b,c vertex coordinate vectors\n */\ninline double triaArea(const Eigen::Vector2d a, const Eigen::Vector2d b,\n const Eigen::Vector2d c) {\n double result = 0;\n#if SOLUTION\n result = 0.5 * std::abs((b[0] - a[0]) * (c[1] - a[1]) -\n (b[1] - a[1]) * (c[0] - a[0]));\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return result;\n}\n\nEigen::Vector2d GlobalInverseQuad(Eigen::Matrix vert,\n Eigen::Vector2d x) {\n constexpr double kEPS = 1.0E-8;\n Eigen::Vector2d x_hat;\n\n // Implement and use the functions triaArea and solveQuadraticEquation\n#if SOLUTION\n /* SAM_LISTING_BEGIN_1 */\n // I: Find sub-triangle with largest area and use its\n // middle vertex as new \"vertex 0\".\n unsigned int vt_zero_idx{0};\n double max_area{0.0};\n for (int l = 0; l < 4; ++l) {\n const double sub_tria_area =\n triaArea(vert.col(l), vert.col((l + 1) % 4), vert.col((l + 2) % 4));\n if (sub_tria_area > max_area) {\n vt_zero_idx = (l + 1) % 4;\n max_area = sub_tria_area;\n }\n }\n // vt_zero_idx stores the index of the vertex that will now\n // be regarded as \"pivotal vertex 0\"\n\n /* SAM_LISTING_END_1 */\n\n const Eigen::Vector2d corner0 = vert.col(vt_zero_idx);\n const Eigen::Vector2d corner1 = vert.col((vt_zero_idx + 1) % 4);\n const Eigen::Vector2d corner2 = vert.col((vt_zero_idx + 2) % 4);\n const Eigen::Vector2d corner3 = vert.col((vt_zero_idx + 3) % 4);\n\n /* SAM_LISTING_BEGIN_2 */\n // Use corners to calculate matrix A, the translation t\n // and the coefficient vector d\n Eigen::Matrix2d A(2, 2);\n A.col(0) = corner1 - corner0;\n A.col(1) = corner3 - corner0;\n Eigen::Vector2d t = corner0;\n Eigen::Vector2d d = corner2 + corner0 - corner1 - corner3;\n\n // Calculate the coefficients in the non-linear system of equations\n Eigen::Vector2d y = A.partialPivLu().solve(x - t);\n Eigen::Vector2d q = A.partialPivLu().solve(d);\n Eigen::Vector2d q_orth(q(1), -q(0));\n\n // Treat exceptional cases\n // If q vanishes\n const double ref_size = y.norm();\n if (q.norm() < kEPS * ref_size) {\n x_hat = y;\n } else if (std::abs(q(0)) < kEPS * ref_size) {\n x_hat(0) = y(0);\n x_hat(1) = y(1) / (1 + q(1) * x_hat(0));\n } else if (std::abs(q(1)) < kEPS * ref_size) {\n x_hat(1) = y(1);\n x_hat(0) = y(0) / (1 + q(0) * x_hat(1));\n } else {\n // Generic case; solve quadratic equation\n double a = q(0);\n double b = 1 + y.dot(q_orth);\n double c = -y(1);\n\n auto [x_op1, x_op2] = solveQuadraticEquation(a, b, c);\n // No solution\n if (std::isnan(x_op1) || std::isnan(x_op2)) {\n x_hat(0) = NAN;\n x_hat(1) = NAN;\n } else {\n // There is a solution\n // Find root in the unit interval -> x_op1\n if ((x_op1 < 0.) || (x_op1 > 1.)) {\n if ((x_op2 >= 0.) && (x_op2 <= 1.)) {\n x_op1 = x_op2;\n }\n }\n x_hat(1) = x_op1;\n x_hat(0) = (y.dot(q_orth) + q(0) * x_hat(1)) / q(1);\n }\n }\n /* SAM_LISTING_END_2 */\n /* SAM_LISTING_BEGIN_3 */\n // Reverse initial permutation\n switch (vt_zero_idx) {\n case 1: {\n x_hat = ((Eigen::Matrix2d() << 0., -1., 1., 0.)).finished() * x_hat +\n Eigen::Vector2d(1.0, 0.0);\n break;\n }\n case 2: {\n x_hat = -x_hat + Eigen::Vector2d(1.0, 1.0);\n break;\n }\n case 3: {\n x_hat = ((Eigen::Matrix2d() << 0., 1., -1., 0.)).finished() * x_hat +\n Eigen::Vector2d(0.0, 1.0);\n break;\n }\n }\n /* SAM_LISTING_END_3 */\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return x_hat;\n}\n\nstd::pair normsSolutionPointLoadDirichletBVP(\n const lf::assemble::DofHandler &dofh, Eigen::Vector2d source_point,\n Eigen::VectorXd &sol_vec) {\n std::pair result(0, 0);\n const unsigned int N_dofs = dofh.NumDofs();\n sol_vec.resize(N_dofs);\n sol_vec.setZero();\n#if SOLUTION\n /* SAM_LISTING_BEGIN_7 */\n // Assemble matrix A\n lf::assemble::COOMatrix A(N_dofs, N_dofs);\n lf::uscalfe::LinearFELaplaceElementMatrix loc_mat_laplace{};\n lf::assemble::AssembleMatrixLocally(0, dofh, dofh, loc_mat_laplace, A);\n // Build rhs vector using dedicated ENTITY_VECTOR_PROVIDER\n Eigen::VectorXd rhs(N_dofs);\n rhs.setZero();\n PointEvaluationRhs::DeltaLocalVectorAssembler myvec_pro(source_point);\n lf::assemble::AssembleVectorLocally(0, dofh, myvec_pro, rhs);\n\n // Enforce Dirichlet boundary conditions\n const double boundary_val = 0; // zero Dirichlet boundary conditions\n auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(dofh.Mesh(), 2)};\n auto my_selector = [&dofh, &bd_flags, &boundary_val](unsigned int dof_idx) {\n if (bd_flags(dofh.Entity(dof_idx))) {\n return (std::pair(true, boundary_val));\n } else {\n // interior node: the value we return here does not matter\n return (std::pair(false, 42.0));\n }\n };\n lf::assemble::FixFlaggedSolutionComponents(my_selector, A, rhs);\n\n // Solve linear system of equations A*x = rhs\n const Eigen::SparseMatrix A_crs(A.makeSparse());\n Eigen::SparseLU> solver;\n solver.compute(A_crs);\n if (solver.info() == Eigen::Success) {\n sol_vec = solver.solve(rhs);\n } else {\n LF_ASSERT_MSG(false, \"Eigen Factorization failed\");\n }\n /* SAM_LISTING_END_7 */\n // return the norms of the solution vector\n result = std::pair(\n PointEvaluationRhs::computeL2normLinearFE(dofh, sol_vec),\n PointEvaluationRhs::computeH1seminormLinearFE(dofh, sol_vec));\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return result;\n}\n\n/* SAM_LISTING_BEGIN_6 */\nEigen::VectorXd DeltaLocalVectorAssembler::Eval(const lf::mesh::Entity &cell) {\n Eigen::VectorXd result;\n // get the coordinates of the corners of this cell\n const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n auto vertices = lf::geometry::Corners(*geo_ptr);\n#if SOLUTION\n Eigen::Vector2d x_hat;\n // the margin we allow when we determine wether a point is inside an\n // element\n const double margin = 1e-10;\n if (lf::base::RefEl::kTria() == cell.RefEl()) {\n x_hat = PointEvaluationRhs::GlobalInverseTria(vertices, x_0);\n result.resize(3);\n result.setZero();\n if (x_hat(0) <= 1 + margin && x_hat(0) >= 0 - margin &&\n x_hat(1) <= 1 + margin && x_hat(1) >= 0 - margin &&\n x_hat(1) + x_hat(0) <= 1 + margin) {\n already_found = true;\n // Barycentric coordinates on reference triangle\n result[0] = 1.0 - x_hat(0) - x_hat(1);\n result[1] = x_hat(0);\n result[2] = x_hat(1);\n }\n } else if (lf::base::RefEl::kQuad() == cell.RefEl()) {\n x_hat = PointEvaluationRhs::GlobalInverseQuad(vertices, x_0);\n result.resize(4);\n result.setZero();\n if (x_hat(0) <= 1 + margin && x_hat(0) >= 0 - margin &&\n x_hat(1) <= 1 + margin && x_hat(1) >= 0 - margin) {\n already_found = true;\n // Local shape functions on unit square\n result[0] = (1.0 - x_hat(0)) * (1.0 - x_hat(1));\n result[1] = x_hat(0) * (1.0 - x_hat(1));\n result[2] = x_hat(0) * x_hat(1);\n result[3] = (1.0 - x_hat(0)) * x_hat(1);\n }\n } else {\n LF_ASSERT_MSG(\n false, \"Function only defined for triangular or quadrilateral cells\");\n }\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return result;\n}\n/* SAM_LISTING_END_6 */\n\n} // namespace PointEvaluationRhs\n", "meta": {"hexsha": "827acf8bc7fab3855882ef870424a6acb0ed3d7b", "size": 10065, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/PointEvaluationRhs/mastersolution/pointevaluationrhs.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/PointEvaluationRhs/mastersolution/pointevaluationrhs.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/PointEvaluationRhs/mastersolution/pointevaluationrhs.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 31.6509433962, "max_line_length": 80, "alphanum_fraction": 0.6021857923, "num_tokens": 3149, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711642563824, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6652405470731572}} {"text": "// HardCoded.cpp\n//\n// C++ code to price an option, essential algorithms.\n//\n// We take CEV model with a choice of the elaticity parameter\n// and the Euler method. We give option price and number of times\n// S hits the origin.\n//\n// (C) Datasim Education BC 2008-2011\n//\n\n#ifndef _SCL_SECURE_NO_WARNINGS\n#define _SCL_SECURE_NO_WARNINGS\n#endif\n\n#ifndef _CRT_SECURE_NO_WARNINGS\n#define _CRT_SECURE_NO_WARNINGS\n#endif\n\n#include \"OptionData.hpp\" \n#include \"StandardDeviation_StandardError.hpp\"\n#include \"UtilitiesDJD/RNG/NormalGenerator.hpp\"\n#include \"UtilitiesDJD/Geometry/Range.cpp\"\n#include // include tuple class\n#include // include I/O for tuple\n#include \n#include \n#include \n\ntemplate void print(const std::vector& myList)\n{ // A generic print function for vectors\n\t\n\tstd::cout << std::endl << \"Size of vector is \" << l.size() << \"\\n[\";\n\n\t// We must use a const iterator here, otherwise we get a compiler error.\n\tstd::vector::const_iterator i;\n\tfor (i = myList.begin(); i != myList.end(); ++i)\n\t{\n\t\t\tstd::cout << *i << \",\";\n\n\t}\n\n\tstd::cout << \"]\\n\";\n}\n\nnamespace SDEDefinition\n{ // Defines drift + diffusion + data\n\n\tOptionData* data;\t\t\t\t// The data for the option MC\n\n\tdouble drift(double t, double X)\n\t{ // Drift term\n\t\n\t\treturn (data->r)*X; // r - D\n\t}\n\n\t\n\tdouble diffusion(double t, double X)\n\t{ // Diffusion term\n\t\n\t\tdouble betaCEV = 1.0;\n\t\treturn data->sig * pow(X, betaCEV);\n\t\t\n\t}\n\n\tdouble diffusionDerivative(double t, double X)\n\t{ // Diffusion term, needed for the Milstein method\n\t\n\t\tdouble betaCEV = 1.0;\n\t\treturn 0.5 * (data->sig) * (betaCEV) * pow(X, 2.0 * betaCEV - 1.0);\n\t}\n} // End of namespace\n\n\nint main()\n{\n\tstd::cout << \"1 factor MC with explicit Euler\\n\";\n\n\t/*==========================MODIFIED================================*/\n\tvector price_vec; // create a vector to store prices for each simulation\n\t/*================================================================*/\n\n\t// Batch 1 data\n\tOptionData myOption;\n\tmyOption.K = 65.0;\n\tmyOption.T = 0.25;\n\tmyOption.r = 0.08;\n\tmyOption.sig = 0.3;\n\tmyOption.type = -1;\t// Put -1, Call +1\n\tdouble S_0 = 60.0;\n\n\t//// Batch 2 data\n\t//OptionData myOption;\n\t//myOption.K = 100.0;\n\t//myOption.T = 1.0;\n\t//myOption.r = 0.0;\n\t//myOption.sig = 0.2;\n\t//myOption.type = -1;\t// Put -1, Call +1\n\t//double S_0 = 100.0;\n\n\t//// Batch 4 data\n\t//OptionData myOption;\n\t//myOption.K = 100.0;\n\t//myOption.T = 30.0;\n\t//myOption.r = 0.08;\n\t//myOption.sig = 0.30;\n\t//myOption.type = 1;\t// Put -1, Call +1\n\t//double S_0 = 100.0;\n\n\tlong N = 100;\n\tstd::cout << \"Number of subintervals in time: \";\n\tstd::cin >> N;\n\n\t// Create the basic SDE (Context class)\n\tRange range (0.0, myOption.T);\n\tdouble VOld = S_0;\n\tdouble VNew;\n\n\tstd::vector x = range.mesh(N);\n\t\n\n\t// V2 mediator stuff\n\tlong NSim = 50000;\n\tstd::cout << \"Number of simulations: \";\n\tstd::cin >> NSim;\n\n\tdouble k = myOption.T / double (N);\n\tdouble sqrk = sqrt(k);\n\n\t// Normal random number\n\tdouble dW;\n\tdouble price = 0.0;\t// Option price\n\n\t// NormalGenerator is a base class\n\tNormalGenerator* myNormal = new BoostNormal();\n\n\tusing namespace SDEDefinition;\n\tSDEDefinition::data = &myOption;\n\n\tstd::vector res;\n\tint coun = 0; // Number of times S hits origin\n\n\t// A.\n\tfor (long i = 1; i <= NSim; ++i)\n\t{ // Calculate a path at each iteration\n\t\t\t\n\t\tif ((i/10000) * 10000 == i)\n\t\t{// Give status after each 10000th iteration\n\n\t\t\t\tstd::cout << i << std::endl;\n\t\t}\n\n\t\tVOld = S_0;\n\t\tfor (unsigned long index = 1; index < x.size(); ++index)\n\t\t{\n\n\t\t\t// Create a random number\n\t\t\tdW = myNormal->getNormal();\n\t\t\t\t\n\t\t\t// The FDM (in this case explicit Euler)\n\t\t\tVNew = VOld + (k * drift(x[index-1], VOld))\n\t\t\t\t\t\t+ (sqrk * diffusion(x[index-1], VOld) * dW);\n\n\t\t\tVOld = VNew;\n\n\t\t\t// Spurious values\n\t\t\tif (VNew <= 0.0) coun++;\n\t\t}\n\t\t\t\n\t\tdouble tmp = myOption.myPayOffFunction(VNew);\n\t\t/*==========================MODIFIED================================*/\n\t\tprice_vec.push_back(tmp); // add each simulation price to the price vector\n\t /*================================================================*/\n\t\tprice += (tmp)/double(NSim);\n\t}\n\t\n\t// D. Finally, discounting the average price\n\tprice *= exp(-myOption.r * myOption.T);\n\n\t// Cleanup; V2 use scoped pointer\n\tdelete myNormal;\n\n\tstd::cout << \"Price, after discounting: \" << price << \", \" << std::endl;\n\tstd::cout << \"Number of times origin is hit: \" << coun << endl;\n\n\t/*==========================MODIFIED================================*/\n\t// show the standard deviation and standard error \n\tboost::tuple SD_SE = get_SD_SE(price_vec, myOption.r, myOption.T);\n\n\tcout << \"SD = \" << get<0>(SD_SE) << \", SE = \" << get<1>(SD_SE) << endl;\n\t/*================================================================*/\n\tsystem(\"Pause\");\n\n\treturn 0;\n}", "meta": {"hexsha": "12435a4c5a6c9d8c120c32ca22ccb86211133e41", "size": 4821, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/TestMC.cpp", "max_stars_repo_name": "bondxue/Option-Pricing-Model", "max_stars_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/TestMC.cpp", "max_issues_repo_name": "bondxue/Option-Pricing-Model", "max_issues_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Part D Monte Carlo Pricing Methods/Exericse D Monte Carlo Pricing Methods/TestMC.cpp", "max_forks_repo_name": "bondxue/Option-Pricing-Model", "max_forks_repo_head_hexsha": "5f22df0ff31e90fd536eb216c5af19c697fb87b2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7230769231, "max_line_length": 83, "alphanum_fraction": 0.5907488073, "num_tokens": 1417, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7826624738835052, "lm_q1q2_score": 0.665240537120972}} {"text": "#include \n\n#include \"geometrycentral/numerical/linear_solvers.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\n\nnamespace geometrycentral {\nnamespace surface {\n\nnamespace {\n\nSparseMatrix> computeVertexConnectionLaplacian(IntrinsicGeometryInterface& geometry, int nSym) {\n\n SurfaceMesh& mesh = geometry.mesh;\n\n geometry.requireVertexIndices();\n geometry.requireEdgeCotanWeights();\n geometry.requireTransportVectorsAlongHalfedge();\n\n int numInvalid = 0;\n\n std::vector>> triplets;\n for (Halfedge he : mesh.halfedges()) {\n\n size_t iTail = geometry.vertexIndices[he.vertex()];\n size_t iTip = geometry.vertexIndices[he.next().vertex()];\n\n // Levi-Civita connection between vertices\n Vector2 rot = geometry.transportVectorsAlongHalfedge[he.twin()].pow(nSym);\n double weight = geometry.edgeCotanWeights[he.edge()];\n if (!rot.isFinite() || !isfinite(weight)) {\n#ifndef GC_NLINALG_DEBUG\n //std::cout << \"computeVertexConnectionLaplacian: Oopsie at \" << iTip << \" x \" << iTail << std::endl;\n#endif\n weight = 0;\n rot = Vector2::zero();\n numInvalid++;\n }\n\n triplets.emplace_back(iTail, iTail, weight);\n triplets.emplace_back(iTail, iTip, -weight * rot);\n }\n if (numInvalid > 0) {\n std::cout << \"computeVertexConnectionLaplacian: \" << numInvalid << \" invalid entried.\" << std::endl;\n }\n\n // assemble matrix from triplets\n Eigen::SparseMatrix> vertexConnectionLaplacian(mesh.nVertices(), mesh.nVertices());\n vertexConnectionLaplacian.setFromTriplets(triplets.begin(), triplets.end());\n\n // Shift to avoid singularity\n Eigen::SparseMatrix> eye(mesh.nVertices(), mesh.nVertices());\n eye.setIdentity();\n vertexConnectionLaplacian += 1e-9 * eye;\n\n return vertexConnectionLaplacian;\n}\n\nSparseMatrix> computeFaceConnectionLaplacian(IntrinsicGeometryInterface& geometry, int nSym) {\n\n SurfaceMesh& mesh = geometry.mesh;\n\n geometry.requireFaceIndices();\n geometry.requireTransportVectorsAcrossHalfedge();\n\n std::vector>> triplets;\n for (Face f : mesh.faces()) {\n size_t i = geometry.faceIndices[f];\n\n std::complex weightDiagSum = 0;\n for (Halfedge he : f.adjacentHalfedges()) {\n if (he.twin().isInterior()) {\n\n Face neighFace = he.twin().face();\n size_t j = geometry.faceIndices[neighFace];\n\n // Levi-Civita connection between the faces\n Vector2 rot = geometry.transportVectorsAcrossHalfedge[he.twin()].pow(nSym);\n\n double weight = 1;\n triplets.emplace_back(i, j, -weight * rot);\n\n weightDiagSum += weight;\n }\n }\n\n triplets.emplace_back(i, i, weightDiagSum + 1e-9); // Shift to avoid singularity\n }\n // assemble matrix from triplets\n Eigen::SparseMatrix> faceConnectionLaplacian(mesh.nFaces(), mesh.nFaces());\n faceConnectionLaplacian.setFromTriplets(triplets.begin(), triplets.end());\n\n return faceConnectionLaplacian;\n}\n\n} // namespace\n\nVertexData computeSmoothestVertexDirectionField(IntrinsicGeometryInterface& geometry, int nSym) {\n\n\n SurfaceMesh& mesh = geometry.mesh;\n\n geometry.requireVertexIndices();\n geometry.requireVertexGalerkinMassMatrix();\n\n // Mass matrix\n SparseMatrix> massMatrix = geometry.vertexGalerkinMassMatrix.cast>();\n\n // Energy matrix\n SparseMatrix> energyMatrix = computeVertexConnectionLaplacian(geometry, nSym);\n\n // Find the smallest eigenvector\n Vector> solution = smallestEigenvectorSquare(energyMatrix, massMatrix);\n\n // Copy the result to a VertexData vector\n VertexData toReturn(mesh);\n for (Vertex v : mesh.vertices()) {\n toReturn[v] = Vector2::fromComplex(solution(geometry.vertexIndices[v]));\n toReturn[v] = unit(toReturn[v]);\n }\n\n return toReturn;\n}\n\nFaceData computeSmoothestFaceDirectionField(IntrinsicGeometryInterface& geometry, int nSym) {\n\n SurfaceMesh& mesh = geometry.mesh;\n\n geometry.requireFaceIndices();\n geometry.requireFaceGalerkinMassMatrix();\n\n // Mass matrix\n SparseMatrix> massMatrix = geometry.faceGalerkinMassMatrix.cast>();\n\n // Energy matrix\n SparseMatrix> energyMatrix = computeFaceConnectionLaplacian(geometry, nSym);\n\n // Find the smallest eigenvector\n Vector> solution = smallestEigenvectorSquare(energyMatrix, massMatrix);\n\n // Copy the result to a FaceData vector\n FaceData toReturn(mesh);\n for (Face f : mesh.faces()) {\n toReturn[f] = Vector2::fromComplex(solution(geometry.faceIndices[f]));\n toReturn[f] = unit(toReturn[f]);\n }\n\n return toReturn;\n}\n\nVertexData computeSmoothestBoundaryAlignedVertexDirectionField(IntrinsicGeometryInterface& geometry,\n int nSym) {\n SurfaceMesh& mesh = geometry.mesh;\n\n if (!mesh.hasBoundary()) {\n throw std::logic_error(\"tried to compute smoothest boundary aligned direction field on a mesh without boundary\");\n }\n\n geometry.requireVertexGalerkinMassMatrix();\n geometry.requireHalfedgeVectorsInVertex();\n\n // Mass matrix\n SparseMatrix> massMatrix = geometry.vertexGalerkinMassMatrix.cast>();\n\n // Energy matrix\n SparseMatrix> energyMatrix = computeVertexConnectionLaplacian(geometry, nSym);\n\n // Compute the boundary values\n VertexData> boundaryValues(mesh);\n for (Vertex v : mesh.vertices()) {\n if (v.isBoundary()) {\n\n // Find incoming and outgoing boundary vectors as tangent\n Halfedge heBoundaryA = v.halfedge();\n Halfedge heBoundaryB = heBoundaryA.twin().next();\n\n Vector2 vecA = geometry.halfedgeVectorsInVertex[heBoundaryA];\n Vector2 vecB = geometry.halfedgeVectorsInVertex[heBoundaryB];\n\n Vector2 tangentV = unit(-vecA + vecB);\n Vector2 normalV = tangentV.rotate90();\n\n boundaryValues[v] = normalV.pow(nSym);\n } else {\n boundaryValues[v] = 0;\n }\n }\n\n // Assemble right-hand side from these boundary values\n Vector> b(mesh.nVertices());\n b.setZero();\n\n for (Vertex v : mesh.vertices()) {\n if (!v.isBoundary()) {\n\n for (Halfedge he : v.incomingHalfedges()) {\n Face neighFace = he.twin().face();\n if (he.vertex().isBoundary()) {\n\n size_t i = geometry.vertexIndices[v];\n size_t j = geometry.vertexIndices[he.vertex()];\n\n // move boundary terms to the right-hand side and remove the corresponding matrix entries\n std::complex Aij = energyMatrix.coeff(i, j);\n energyMatrix.coeffRef(i, j) = 0;\n std::complex bVal = boundaryValues[he.vertex()];\n b(i) += -Aij * bVal;\n }\n }\n }\n }\n\n Eigen::SparseMatrix, Eigen::ColMajor> LHS = energyMatrix;\n Eigen::VectorXcd RHS = massMatrix * b;\n Eigen::VectorXcd solution = solveSquare(LHS, RHS);\n\n // Copy the result to a VertexData vector for both the boundary and interior\n VertexData toReturn(mesh);\n for (Vertex v : mesh.vertices()) {\n if (v.isBoundary()) {\n toReturn[v] = Vector2::fromComplex(boundaryValues[v]);\n } else {\n toReturn[v] = Vector2::fromComplex(solution(geometry.vertexIndices[v]));\n toReturn[v] = unit(toReturn[v]);\n }\n }\n\n return toReturn;\n}\n\nFaceData computeSmoothestBoundaryAlignedFaceDirectionField(IntrinsicGeometryInterface& geometry, int nSym) {\n\n SurfaceMesh& mesh = geometry.mesh;\n\n if (!mesh.hasBoundary()) {\n throw std::logic_error(\"tried to compute smoothest boundary aligned direction field on a mesh without boundary\");\n }\n\n geometry.requireFaceGalerkinMassMatrix();\n geometry.requireHalfedgeVectorsInFace();\n\n // Mass matrix\n SparseMatrix> massMatrix = geometry.faceGalerkinMassMatrix.cast>();\n\n // Energy matrix\n SparseMatrix> energyMatrix = computeFaceConnectionLaplacian(geometry, nSym);\n\n // Compute boundary values\n FaceData isInterior(mesh);\n FaceData> boundaryValues(mesh);\n for (Face f : mesh.faces()) {\n bool isBoundary = false;\n for (Edge e : f.adjacentEdges()) {\n isBoundary |= e.isBoundary();\n }\n isInterior[f] = !isBoundary;\n\n if (isInterior[f]) {\n boundaryValues[f] = 0;\n } else {\n Vector2 bC = Vector2::zero();\n for (Halfedge he : f.adjacentHalfedges()) {\n if (he.edge().isBoundary()) {\n bC -= geometry.halfedgeVectorsInFace[he].rotate90(); // negate the vector to point outwards\n }\n }\n bC = unit(bC);\n boundaryValues[f] = bC.pow(nSym);\n }\n }\n\n // Assemble right-hand side from these boundary values\n Vector> b(mesh.nFaces());\n b.setZero();\n\n for (Face f : mesh.faces()) {\n if (isInterior[f]) {\n\n for (Halfedge he : f.adjacentHalfedges()) {\n Face neighFace = he.twin().face();\n if (!isInterior[neighFace]) {\n\n size_t i = geometry.faceIndices[f];\n size_t j = geometry.faceIndices[neighFace];\n\n // move boundary terms to the right-hand side and remove the corresponding matrix entries\n std::complex Aij = energyMatrix.coeff(i, j);\n energyMatrix.coeffRef(i, j) = 0;\n std::complex bVal = boundaryValues[neighFace];\n b(i) += -Aij * bVal;\n }\n }\n }\n }\n\n Eigen::SparseMatrix, Eigen::ColMajor> LHS = energyMatrix;\n Eigen::VectorXcd RHS = massMatrix * b;\n Eigen::VectorXcd solution = solveSquare(LHS, RHS);\n\n // Copy the result to a FaceData object\n FaceData field(mesh);\n for (Face f : mesh.faces()) {\n if (isInterior[f]) {\n field[f] = Vector2::fromComplex(solution(geometry.faceIndices[f]));\n field[f] = unit(field[f]);\n } else {\n field[f] = Vector2::fromComplex(boundaryValues[f]);\n }\n }\n\n return field;\n}\n\nVertexData computeCurvatureAlignedVertexDirectionField(ExtrinsicGeometryInterface& geometry, int nSym) {\n\n\n SurfaceMesh& mesh = geometry.mesh;\n size_t N = mesh.nVertices();\n\n geometry.requireVertexIndices();\n geometry.requireVertexGalerkinMassMatrix();\n geometry.requireVertexPrincipalCurvatureDirections();\n\n // Mass matrix\n SparseMatrix> massMatrix = geometry.vertexGalerkinMassMatrix.cast>();\n\n // Energy matrix\n SparseMatrix> energyMatrix = computeVertexConnectionLaplacian(geometry, nSym);\n\n Vector> dirVec(N);\n if (nSym == 2) {\n for (Vertex v : mesh.vertices()) {\n dirVec[geometry.vertexIndices[v]] = geometry.vertexPrincipalCurvatureDirections[v];\n }\n } else if (nSym == 4) {\n for (Vertex v : mesh.vertices()) {\n dirVec[geometry.vertexIndices[v]] =\n std::pow(std::complex(geometry.vertexPrincipalCurvatureDirections[v]), 2);\n }\n } else {\n throw std::logic_error(\"ERROR: It only makes sense to align with curvature when nSym = 2 or 4\");\n }\n\n // Normalize the alignment field\n double scale = std::sqrt(std::abs((dirVec.adjoint() * massMatrix * dirVec)[0]));\n dirVec /= scale;\n\n // this is something of a magical constant, see \"Globally Optimal Direction Fields\", eqn 16\n double lambdaT = 0;\n\n Eigen::VectorXcd RHS = massMatrix * dirVec;\n Eigen::SparseMatrix, Eigen::ColMajor> LHS = energyMatrix - lambdaT * massMatrix;\n Eigen::VectorXcd solution = solveSquare(LHS, RHS);\n\n // Copy the result to a VertexData vector\n VertexData toReturn(mesh);\n for (Vertex v : mesh.vertices()) {\n toReturn[v] = Vector2::fromComplex(solution(geometry.vertexIndices[v]));\n toReturn[v] = unit(toReturn[v]);\n }\n\n return toReturn;\n}\n\nFaceData computeCurvatureAlignedFaceDirectionField(EmbeddedGeometryInterface& geometry, int nSym) {\n\n SurfaceMesh& mesh = geometry.mesh;\n const unsigned int N = mesh.nFaces();\n\n geometry.requireFaceIndices();\n geometry.requireFaceGalerkinMassMatrix();\n geometry.requireFacePrincipalCurvatureDirections();\n\n // Mass matrix\n SparseMatrix> massMatrix = geometry.faceGalerkinMassMatrix.cast>();\n\n // Energy matrix\n SparseMatrix> energyMatrix = computeFaceConnectionLaplacian(geometry, nSym);\n\n Eigen::VectorXcd dirVec(N);\n if (nSym == 2) {\n for (Face f : mesh.faces()) {\n dirVec[geometry.faceIndices[f]] = geometry.facePrincipalCurvatureDirections[f];\n }\n } else if (nSym == 4) {\n for (Face f : mesh.faces()) {\n dirVec[geometry.faceIndices[f]] = std::pow(std::complex(geometry.facePrincipalCurvatureDirections[f]), 2);\n }\n } else {\n throw std::logic_error(\"ERROR: It only makes sense to align with curvature when nSym = 2 or 4\");\n }\n\n // Normalize the alignment field\n double scale = std::sqrt(std::abs((dirVec.adjoint() * massMatrix * dirVec)[0]));\n dirVec /= scale;\n\n double lambdaT = 0.0; // this is something of a magical constant, see \"Globally Optimal Direction Fields\", eqn 16\n\n Eigen::VectorXcd RHS = massMatrix * dirVec;\n Eigen::SparseMatrix, Eigen::ColMajor> LHS = energyMatrix - lambdaT * massMatrix;\n Eigen::VectorXcd solution = solveSquare(LHS, RHS);\n\n // Copy the result to a FaceData object\n FaceData field(mesh);\n for (Face f : mesh.faces()) {\n field[f] = Vector2::fromComplex(solution[geometry.faceIndices[f]]);\n field[f] = unit(field[f]);\n }\n\n return field;\n}\n\n\nFaceData computeFaceIndex(IntrinsicGeometryInterface& geometry, const VertexData& directionField,\n int nSym) {\n\n SurfaceMesh& mesh = geometry.mesh;\n\n geometry.requireTransportVectorsAlongHalfedge();\n geometry.requireFaceGaussianCurvatures();\n\n // Store the result here\n FaceData indices(mesh);\n\n // TODO haven't tested that this correctly reports the index when it is larger\n // than +-1\n\n for (Face f : mesh.faces()) {\n // Trace the direction field around the face and see how many times it\n // spins!\n double totalRot = geometry.faceGaussianCurvatures[f] * nSym;\n\n for (Halfedge he : f.adjacentHalfedges()) {\n if (he.twin().isInterior()) {\n // Compute the rotation along the halfedge implied by the field\n Vector2 x0 = directionField[he.vertex()];\n Vector2 x1 = directionField[he.twin().vertex()];\n Vector2 rot = geometry.transportVectorsAlongHalfedge[he].pow(nSym);\n\n // Find the difference in angle\n double theta0 = (rot * x0).arg();\n double theta1 = x1.arg();\n double deltaTheta = regularizeAngle(theta1 - theta0 + PI) - PI; // regularize to [-PI,PI]\n\n totalRot += deltaTheta; // accumulate\n }\n }\n\n // Compute the net rotation and corresponding index\n int index = static_cast(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 computeVertexIndex(IntrinsicGeometryInterface& geometry, const FaceData& directionField,\n int nSym) {\n\n SurfaceMesh& mesh = geometry.mesh;\n\n geometry.requireTransportVectorsAcrossHalfedge();\n geometry.requireVertexGaussianCurvatures();\n\n // Store the result here\n VertexData indices(mesh);\n\n // TODO haven't tested that this correctly reports the index when it is larger\n // than +-1\n\n for (Vertex v : mesh.vertices()) {\n\n // Trace the direction field around the face and see how many times it\n // spins!\n double totalRot = geometry.vertexGaussianCurvatures[v] * nSym;\n\n if (!v.isBoundary()) {\n for (Halfedge he : v.incomingHalfedges()) {\n // Compute the rotation along the halfedge implied by the field\n Vector2 x0 = directionField[he.face()];\n Vector2 x1 = directionField[he.twin().face()];\n Vector2 rot = geometry.transportVectorsAcrossHalfedge[he].pow(nSym);\n\n double deltaTheta = regularizeAngle(x1.arg() - (rot * x0).arg() + PI) - PI; // regularize to [-PI,PI]\n\n totalRot += deltaTheta;\n }\n }\n\n // Compute the net rotation and corresponding index\n int index = static_cast(std::round(totalRot / (2 * PI))); // should be very close to a multiple of 2PI\n indices[v] = index;\n }\n\n return indices;\n}\n/*\nVertexData computeSmoothestBoundaryAlignedVertexDirectionField(IntrinsicGeometryInterface& geometry,\n int nSym) {\n SurfaceMesh& mesh = geometry.mesh;\n\n\n if (!mesh.hasBoundary()) {\n throw std::logic_error(\"tried to compute smoothest boundary aligned direction field on a mesh without boundary\");\n }\n\n geometry.requireVertexGalerkinMassMatrix();\n geometry.requireVertexConnectionLaplacian();\n geometry.requireHalfedgeVectorsInVertex();\n\n // Mass matrix\n SparseMatrix> massMatrix = geometry.vertexGalerkinMassMatrix.cast>();\n\n // Energy matrix\n SparseMatrix> energyMatrix = geometry.vertexConnectionLaplacian;\n\n // Compute the boundary values\n VertexData> boundaryValues(mesh);\n VertexData isBoundary(mesh, false);\n for (Vertex v : mesh.vertices()) {\n if (v.isBoundary()) {\n isBoundary[v] = true;\n\n // Find incoming and outgoing boundary vectors as tangent\n Halfedge heBoundaryA = v.halfedge();\n Halfedge heBoundaryB = heBoundaryA.twin().next();\n\n Vector2 vecA = geometry.halfedgeVectorsInVertex[heBoundaryA];\n Vector2 vecB = geometry.halfedgeVectorsInVertex[heBoundaryB];\n\n Vector2 tangentV = unit(-vecA + vecB);\n Vector2 normalV = tangentV.rotate90();\n\n boundaryValues[v] = normalV.pow(nSym);\n } else {\n boundaryValues[v] = 0;\n }\n }\n Vector> b = boundaryValues.toVector();\n Vector isBoundaryVec = isBoundary.toVector();\n\n // Block decompose problem\n\n\n // Compute the actual solution\n std::cout << \"Solving linear problem...\" << std::endl;\n\n // Store the solution here\n Eigen::VectorXcd solution;\n\n // If requested, align to principal curvatures\n if (alignCurvature) {\n\n geometry.requirePrincipalDirections();\n\n Eigen::VectorXcd dirVec(nInterior);\n for (Vertex v : mesh.vertices()) {\n if (v.isBoundary()) {\n continue;\n }\n\n Vector2 directionVal = geometry.principalDirections[v];\n if (nSym == 4) {\n directionVal = std::pow(directionVal, 2);\n }\n\n // Normalize the curvature vectors. By doing so, we lose the property of adjusting the strength of the alignment\n // based on the strength of the curvature, but resolve any scaling issues between the magnitude of the normals and\n // the magnitude of the desired field. Be careful when interpreting this as opposed to the usual direction field\n // optimization.\n dirVec[geometry.interiorVertexIndices[v]] = directionVal / std::abs(directionVal);\n }\n\n double t = 0.01; // this is something of a magical constant, see \"Globally\n // Optimal Direction Fields\", eqn 9\n\n Eigen::VectorXcd RHS = massMatrix * (t * dirVec + b);\n Eigen::SparseMatrix, 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, 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 toReturn(*mesh);\n for (Vertex v : mesh.vertices()) {\n if (v.isBoundary()) {\n toReturn[v] = boundaryValues[v];\n } else {\n toReturn[v] = unit(solution[geometry.interiorVertexIndices[v]]);\n }\n }\n\n return toReturn;\n}\n\n// Helpers for computing face-based direction fields\nnamespace {\n\nFaceData computeSmoothestFaceDirectionField_noBoundary(IntrinsicGeometryInterface& geometry, int nSym = 1,\n bool alignCurvature = false) {\n\n\n SurfaceMesh* mesh = geometry->getMesh();\n unsigned int N = mesh.nFaces();\n\n GeometryCache& geometry = geometry->cache;\n geometry.requireFaceTransportCoefs();\n geometry.requireFaceNormals();\n geometry.requireFaceAreas();\n geometry.requireDihedralAngles();\n geometry.requireFaceIndices();\n\n // === Allocate matrices\n // Energy matrix\n Eigen::SparseMatrix, Eigen::ColMajor> energyMatrix(N, N);\n energyMatrix.reserve(Eigen::VectorXi::Constant(N, 4));\n\n // Mass matrix\n Eigen::SparseMatrix, Eigen::ColMajor> massMatrix(N, N);\n massMatrix.reserve(Eigen::VectorXi::Constant(N, 1));\n\n\n // === Build matrices\n\n // Build the mass matrix\n for (Face f : mesh.faces()) {\n size_t i = geometry.faceIndices[f];\n massMatrix.insert(i, i) = geometry.faceAreas[f];\n }\n\n // Build the energy matrix\n for (Face f : mesh.faces()) {\n size_t i = geometry.faceIndices[f];\n\n std::complex weightISum = 0;\n for (Halfedge he : f.adjacentHalfedges()) {\n\n if (!he.twin().isInterior()) {\n continue;\n }\n\n Face neighFace = he.twin().face();\n unsigned int j = geometry.faceIndices[neighFace];\n\n // LC connection between the faces\n Vector2 rBar = std::pow(geometry.faceTransportCoefs[he.twin()], nSym);\n\n double weight = 1; // FIXME TODO figure out weights\n energyMatrix.insert(i, j) = -weight * rBar;\n weightISum += weight;\n }\n\n energyMatrix.insert(i, i) = weightISum;\n }\n\n // Shift to avoid singularity\n Eigen::SparseMatrix eye(N, N);\n eye.setIdentity();\n energyMatrix += 1e-4 * eye;\n\n // Store the solution here\n Eigen::VectorXcd solution;\n\n // If requested, align to principal curvatures\n if (alignCurvature) {\n\n Eigen::VectorXcd dirVec(N);\n for (Face f : mesh.faces()) {\n\n // Compute something like the principal directions\n double weightSum = 0;\n Vector2 sum = 0;\n\n for (Halfedge he : f.adjacentHalfedges()) {\n\n double dihedralAngle = std::abs(geometry.dihedralAngles[he.edge()]);\n double weight = norm(geometry->vector(he));\n weightSum += weight;\n double angleCoord = angleInPlane(geometry->vector(f.halfedge()), geometry->vector(he), geometry.faceNormals[f]);\n Vector2 coord = std::exp(angleCoord * IM_I *\n (double)nSym); // nsym should be 2 or 4, checked in the funciton which calls this\n\n sum += coord * weight * dihedralAngle;\n }\n\n sum /= weightSum;\n\n dirVec[geometry.faceIndices[f]] = sum;\n }\n\n // Normalize the alignment field\n double scale = std::sqrt(std::abs((dirVec.adjoint() * massMatrix * dirVec)[0]));\n dirVec /= scale;\n\n double lambdaT = 0.0; // this is something of a magical constant, see \"Globally Optimal Direction Fields\", eqn 16\n\n // Eigen::VectorXcd RHS = massMatrix * dirVec;\n Eigen::VectorXcd RHS = dirVec;\n Eigen::SparseMatrix, 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 field(*mesh);\n for (Face f : mesh.faces()) {\n field[f] = solution[geometry.faceIndices[f]] / std::abs(solution[geometry.faceIndices[f]]);\n }\n\n return field;\n}\n\nFaceData computeSmoothestFaceDirectionField_boundary(IntrinsicGeometryInterface& geometry, int nSym = 1,\n bool alignCurvature = false) {\n\n SurfaceMesh* mesh = geometry->getMesh();\n\n GeometryCache& geometry = geometry->cache;\n geometry.requireFaceTransportCoefs();\n geometry.requireFaceNormals();\n geometry.requireFaceAreas();\n geometry.requireDihedralAngles();\n\n\n // Index interior faces\n size_t nInteriorFace = 0;\n FaceData interiorFaceInd(*mesh, -77);\n FaceData isInterior(*mesh);\n for (Face f : mesh.faces()) {\n bool isBoundary = false;\n for (Edge e : f.adjacentEdges()) {\n isBoundary |= e.isBoundary();\n }\n isInterior[f] = !isBoundary;\n if (!isBoundary) {\n interiorFaceInd[f] = nInteriorFace++;\n }\n }\n\n // Compute boundary values\n FaceData boundaryValues(*mesh);\n for (Face f : mesh.faces()) {\n if (isInterior[f]) {\n boundaryValues[f] = 0;\n } else {\n Vector3 bVec = Vector3::zero();\n for (Halfedge he : f.adjacentHalfedges()) {\n if (he.edge().isBoundary()) {\n bVec += geometry->vector(he).rotate_around(geometry.faceNormals[f], -PI / 2.0);\n }\n }\n Vector2 bC(dot(geometry.faceBases[f][0], bVec), dot(geometry.faceBases[f][1], bVec));\n bC = unit(bC);\n boundaryValues[f] = std::pow(bC, nSym);\n }\n }\n\n\n // === Allocate matrices\n // Energy matrix\n Eigen::SparseMatrix, Eigen::ColMajor> energyMatrix(nInteriorFace, nInteriorFace);\n energyMatrix.reserve(Eigen::VectorXi::Constant(nInteriorFace, 4));\n\n // Mass matrix\n Eigen::SparseMatrix, Eigen::ColMajor> massMatrix(nInteriorFace, nInteriorFace);\n massMatrix.reserve(Eigen::VectorXi::Constant(nInteriorFace, 1));\n\n // RHS\n Eigen::VectorXcd b(nInteriorFace);\n\n // === Build matrices\n\n // Build the mass matrix\n for (Face f : mesh.faces()) {\n if (isInterior[f]) {\n size_t i = interiorFaceInd[f];\n massMatrix.insert(i, i) = geometry.faceAreas[f];\n }\n }\n\n // Build the energy matrix\n for (Face f : mesh.faces()) {\n if (isInterior[f]) {\n size_t i = interiorFaceInd[f];\n\n std::complex weightISum = 0;\n for (Halfedge he : f.adjacentHalfedges()) {\n\n Face neighFace = he.twin().face();\n double weight = 1; // FIXME TODO figure out weights\n Vector2 rBar = std::pow(geometry.faceTransportCoefs[he.twin()], nSym);\n\n if (isInterior[neighFace]) {\n size_t j = interiorFaceInd[neighFace];\n energyMatrix.insert(i, j) = -weight * rBar;\n } else {\n std::complex 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 eye(nInteriorFace, nInteriorFace);\n eye.setIdentity();\n energyMatrix += 1e-4 * eye;\n\n // Store the solution here\n Eigen::VectorXcd solution;\n\n // If requested, align to principal curvatures\n if (alignCurvature) {\n\n Eigen::VectorXcd dirVec(nInteriorFace);\n for (Face f : mesh.faces()) {\n if (isInterior[f]) {\n\n // Compute something like the principal directions\n double weightSum = 0;\n Vector2 sum = 0;\n\n for (Halfedge he : f.adjacentHalfedges()) {\n\n double dihedralAngle = std::abs(geometry.dihedralAngles[he.edge()]);\n double weight = norm(geometry->vector(he));\n weightSum += weight;\n double angleCoord =\n angleInPlane(geometry->vector(f.halfedge()), geometry->vector(he), geometry.faceNormals[f]);\n Vector2 coord = std::exp(angleCoord * IM_I *\n (double)nSym); // nsym should be 2 or 4, checked in the funciton which calls this\n\n sum += coord * weight * dihedralAngle;\n }\n\n sum /= weightSum;\n\n // Normalize the curvature vectors. By doing so, we lose the property of adjusting the strength of the alignment\n // based on the strength of the curvature, but resolve any scaling issues between the magnitude of the normals\n // and the magnitude of the desired field. Be careful when interpreting this as opposed to the usual direction\n // field optimization.\n dirVec[interiorFaceInd[f]] = unit(sum);\n }\n }\n\n\n double t = 0.1; // this is something of a magical constant, see \"Globally\n // Optimal Direction Fields\", eqn 9\n // NOTE: This value is different from the one used for vertex fields; seems to work better?\n\n std::cout << \"Solving smoothest field dirichlet problem with curvature term...\" << std::endl;\n Eigen::VectorXcd RHS = massMatrix * (t * dirVec + b);\n Eigen::SparseMatrix, 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, 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 field(*mesh);\n for (Face f : mesh.faces()) {\n if (isInterior[f]) {\n field[f] = unit(solution[interiorFaceInd[f]]);\n } else {\n field[f] = unit(boundaryValues[f]);\n }\n }\n\n return field;\n}\n\n} // namespace\n\nFaceData computeSmoothestFaceDirectionField(Geometry* geometry, int nSym, bool alignCurvature) {\n\n std::cout << \"Computing globally optimal direction field in faces\" << std::endl;\n\n if (alignCurvature && !(nSym == 2 || nSym == 4)) {\n throw std::logic_error(\"ERROR: It only makes sense to align with curvature when nSym = 2 or \"\n \"4\");\n }\n\n // Dispatch to either the boundary of no boundary variant depending on the mesh type\n bool hasBoundary = false;\n for (Vertex v : geometry->getMesh()->vertices()) {\n hasBoundary |= v.isBoundary();\n }\n\n\n if (hasBoundary) {\n std::cout << \"Mesh has boundary, computing dirichlet boundary condition solution\" << std::endl;\n return computeSmoothestFaceDirectionField_boundary(geometry, nSym, alignCurvature);\n } else {\n std::cout << \"Mesh has no boundary, computing unit-norm solution\" << std::endl;\n return computeSmoothestFaceDirectionField_noBoundary(geometry, nSym, alignCurvature);\n }\n}\n\nFaceData computeFaceIndex(IntrinsicGeometryInterface& geometry, const VertexData& directionField,\n int nSym) {\n\n SurfaceMesh* mesh = geometry->getMesh();\n\n GeometryCache& geometry = geometry->cache;\n geometry.requireFaceTransportCoefs();\n\n // Store the result here\n FaceData indices(*mesh);\n\n // TODO haven't tested that this correctly reports the index when it is larger\n // than +-1\n\n for (Face f : mesh.faces()) {\n // Trace the direction field around the face and see how many times it\n // spins!\n double totalRot = 0;\n\n for (Halfedge he : f.adjacentHalfedges()) {\n // Compute the rotation along the halfedge implied by the field\n Vector2 x0 = directionField[he.vertex()];\n Vector2 x1 = directionField[he.twin().vertex()];\n Vector2 transport = std::pow(geometry.vertexTransportCoefs[he], nSym);\n\n // Find the difference in angle\n double theta0 = std::arg(transport * x0);\n double theta1 = std::arg(x1);\n double deltaTheta = regularizeAngle(theta1 - theta0 + PI) - PI; // regularize to [-PI,PI]\n\n totalRot += deltaTheta; // accumulate\n }\n\n // Compute the net rotation and corresponding index\n int index = static_cast(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 computeVertexIndex(IntrinsicGeometryInterface& geometry, const FaceData& directionField,\n int nSym) {\n\n SurfaceMesh* mesh = geometry->getMesh();\n GeometryCache& geometry = geometry->cache;\n geometry.requireFaceTransportCoefs();\n\n // Store the result here\n VertexData indices(*mesh);\n\n // TODO haven't tested that this correctly reports the index when it is larger\n // than +-1\n\n for (Vertex v : mesh.vertices()) {\n\n // Trace the direction field around the face and see how many times it\n // spins!\n double totalRot = 0;\n\n for (Halfedge he : v.incomingHalfedges()) {\n // Compute the rotation along the halfedge implied by the field\n Vector2 x0 = directionField[he.face()];\n Vector2 x1 = directionField[he.twin().face()];\n Vector2 transport = std::pow(geometry.faceTransportCoefs[he], nSym);\n\n // Find the difference in angle\n double theta0 = std::arg(transport * x0);\n double theta1 = std::arg(x1);\n double deltaTheta = std::arg(x1 / (transport * x0));\n\n totalRot += deltaTheta;\n }\n\n double angleDefect = geometry->angleDefect(v);\n totalRot += angleDefect * nSym;\n\n // Compute the net rotation and corresponding index\n int index = static_cast(std::round(totalRot / (2 * PI))); // should be very close to a multiple of 2PI\n indices[v] = index;\n }\n\n return indices;\n}\n*/\n\n} // namespace surface\n} // namespace geometrycentral\n", "meta": {"hexsha": "4fb25f1faacb2d37ffdace8c016ea5b52462a0b3", "size": 33442, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/surface/direction_fields.cpp", "max_stars_repo_name": "erkil1452/geometry-central", "max_stars_repo_head_hexsha": "719a9da37897ad3028add4372133b7f73013bb60", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/surface/direction_fields.cpp", "max_issues_repo_name": "erkil1452/geometry-central", "max_issues_repo_head_hexsha": "719a9da37897ad3028add4372133b7f73013bb60", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/surface/direction_fields.cpp", "max_forks_repo_name": "erkil1452/geometry-central", "max_forks_repo_head_hexsha": "719a9da37897ad3028add4372133b7f73013bb60", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.8184494603, "max_line_length": 120, "alphanum_fraction": 0.6707134741, "num_tokens": 8255, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099070011518829, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6651953296107715}} {"text": "#pragma once\n#include \n#include \"DenseMatrix.hpp\"\n#include \"Mapping.hpp\"\n\nnamespace NonlinearSolvers {\n\n\tstruct FixedPointData {\n\t\tOperator f; // residual operator\n\t\tOperator g; // iteration operator\n\t};\n\n\tinline void logFixedPoint(double r, Index i, Index max = 1) {\n\t\tauto& logger = SingletonLogger::instance();\n\t\tauto& w = std::setw(std::to_string(max).length());\n\t\tlogger.buf << \"|| f(x_\" << std::setfill('0') << w << i << \") || = \" << std::scientific << r;\n\t\tlogger.log();\n\t}\n\n\tinline std::vector FixedPointMethod(\n\t\tFixedPointData const & fp,\n\t\tstd::vector const & x_0,\n\t\tIndex n = 100, // max numb of iters\n\t\tdouble eps = 1e-7\n\t) {\n\t\tauto& logger = SingletonLogger::instance();\n\t\tlogger.log(\"start Fixed Point method\");\n\t\tauto x = x_0;\n\t\tauto r_norm = norm(fp.f(x));\n\t\tlogFixedPoint(r_norm, 0, n);\n\t\tif (r_norm < eps) {\n\t\t\tlogger.log(\"stop Fixed Point method\");\n\t\t\treturn x;\n\t\t}\n\t\tIndex i;\n\t\tfor (i = 1; i <= n; ++i) {\n\t\t\tx = fp.g(x);\n\t\t\tr_norm = norm(fp.f(x));\n\t\t\tlogFixedPoint(r_norm, i, n);\n\t\t\tif (r_norm < eps) break;\n\t\t}\n\t\tlogger.log(\"stop Fixed Point method\");\n\t\tif (i > n) logger.wrn(\"Fixed Point Method exceeded max numb of iterations\");\n\t\treturn x;\n\t}\n\t\n\tinline std::vector AndersonMixingMethod(\n\t\t\tFixedPointData const & fp,\n\t\t\tstd::vector const & x_0,\n\t\t\tIndex m = 0,\n\t\t\tIndex n = 100, // max numb of iters\n\t\t\tdouble eps = 1e-7\n\t\t) {\n\t\tauto& logger = SingletonLogger::instance();\n\t\tif (m == 0) {\n\t\t\tlogger.log(\"m = 0 -> Fixed Point Method\");\n\t\t\treturn FixedPointMethod(fp, x_0, n, eps);\n\t\t}\n\t\tboost::circular_buffer> F(m), G(m + 1);\n\t\tlogger.log(\"start Fixed Point method\");\n\t\t// i = 0\n\t\tauto x = x_0;\n\t\tauto r = fp.f(x);\n\t\tauto r_norm = norm(r);\n\t\tlogFixedPoint(r_norm, 0, n);\n\t\tif (r_norm < eps) {\n\t\t\tlogger.log(\"stop Fixed Point method\");\n\t\t\treturn x;\n\t\t}\n\t\tG.push_front(fp.g(x));\n\t\t// i = 1\n\t\tx = G[0];\n\t\tauto r_new = fp.f(x);\n\t\tr_norm = norm(r_new);\n\t\tlogFixedPoint(r_norm, 1, n);\n\t\tif (r_norm < eps) {\n\t\t\tlogger.log(\"stop Fixed Point method\");\n\t\t\treturn x;\n\t\t}\n\t\tG.push_front(fp.g(x));\n\t\tF.push_front(r_new - r);\n\t\tr = r_new;\n\t\tlogger.log(\"stop Fixed Point method\");\n\t\t// i = 2, 3, . . .\n\t\tlogger.log(\"start Anderson Mixing method\");\n\t\tIndex i;\n\t\tfor (i = 2; i <= n; ++i) {\n\t\t\tm = F.size();\n\t\t\tDenseMatrix A(m);\n\t\t\tstd::vector b(m);\n\t\t\tfor (Index k = 0; k < m; ++k) {\n\t\t\t\tb[k] = F[k] * r;\n\t\t\t\tfor (Index j = 0; j < m; ++j)\n\t\t\t\t\tA(k, j) = F[k] * F[j];\n\t\t\t}\n\t\t\tauto beta = A.GaussElimination(b);\n\t\t\tdecltype(beta) alpha(m + 1);\n\t\t\talpha[0] = 1. - beta[0];\n\t\t\tfor (Index k = 1; k < m; ++k) alpha[k] = beta[k - 1] - beta[k];\n\t\t\talpha[m] = beta[m - 1];\n\t\t\tstd::fill(x.begin(), x.end(), 0.);\n\t\t\tfor (Index k = 0; k < m + 1; ++k) x += alpha[k] * G[k];\n\t\t\tr_new = fp.f(x);\n\t\t\tr_norm = norm(r_new);\n\t\t\tlogFixedPoint(r_norm, i, n);\n\t\t\tif (r_norm < eps) break;\n\t\t\tG.push_front(fp.g(x));\n\t\t\tF.push_front(r_new - r);\n\t\t\tr = r_new;\n\t\t}\n\t\tlogger.log(\"stop Anderson Mixing method\");\n\t\tif (i > n) logger.wrn(\"Anderson Mixing Method exceeded max numb of iterations\");\n\t\treturn x;\n\t}\n\n}", "meta": {"hexsha": "b52c2cb7673cf2a7b06b731168d3f0988f27fa51", "size": 3086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sln/Tools/NonlinearSolvers.hpp", "max_stars_repo_name": "frfly/CATSPDEs", "max_stars_repo_head_hexsha": "41bcc7cf4fe5636572603199e807fa6c7c25dd93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-09-09T13:30:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-24T19:37:44.000Z", "max_issues_repo_path": "sln/Tools/NonlinearSolvers.hpp", "max_issues_repo_name": "frfly/Solving-elliptic-equation-using-FEM", "max_issues_repo_head_hexsha": "41bcc7cf4fe5636572603199e807fa6c7c25dd93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-06T17:37:04.000Z", "max_issues_repo_issues_event_max_datetime": "2016-03-06T17:37:04.000Z", "max_forks_repo_path": "sln/Tools/NonlinearSolvers.hpp", "max_forks_repo_name": "frfly/Solving-elliptic-equation-using-FEM", "max_forks_repo_head_hexsha": "41bcc7cf4fe5636572603199e807fa6c7c25dd93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2016-12-08T15:45:37.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T21:44:50.000Z", "avg_line_length": 26.6034482759, "max_line_length": 94, "alphanum_fraction": 0.588139987, "num_tokens": 1039, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333245870332531, "lm_q2_score": 0.7981867705385762, "lm_q1q2_score": 0.665148660934465}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"common.h\"\n#include \"result_verify.h\"\n\nusing namespace std;\n\ntypedef pcl::PointXYZRGB PointType;\nEigen::Matrix3d inner;\nstring lidar_path, photo_path, intrinsic_path, extrinsic_path;\nint error_threshold;\nvector init;\n\nvoid getParameters();\n\nclass external_cali {\npublic:\n external_cali(PnPData p) {\n pd = p;\n }\n\n template \n bool operator()(const T *_q, const T *_t, T *residuals) const {\n Eigen::Matrix innerT = inner.cast();\n Eigen::Quaternion q_incre{_q[ 3 ], _q[ 0 ], _q[ 1 ], _q[ 2 ]};\n Eigen::Matrix t_incre{_t[ 0 ], _t[ 1 ], _t[ 2 ]};\n\n Eigen::Matrix p_l(T(pd.x), T(pd.y), T(pd.z));\n Eigen::Matrix p_c = q_incre.toRotationMatrix() * p_l + t_incre;\n Eigen::Matrix p_2 = innerT * p_c;\n\n residuals[0] = p_2[0]/p_2[2] - T(pd.u);\n residuals[1] = p_2[1]/p_2[2] - T(pd.v);\n\n return true;\n }\n\n static ceres::CostFunction *Create(PnPData p) {\n return (new ceres::AutoDiffCostFunction(new external_cali(p)));\n }\n\n\nprivate:\n PnPData pd;\n\n};\n\nvoid getParameters() {\n cout << \"Get the parameters from the launch file\" << endl;\n\n if (!ros::param::get(\"input_lidar_path\", lidar_path)) {\n cout << \"Can not get the value of input_lidar_path\" << endl;\n exit(1);\n }\n if (!ros::param::get(\"input_photo_path\", photo_path)) {\n cout << \"Can not get the value of input_photo_path\" << endl;\n exit(1);\n }\n if (!ros::param::get(\"intrinsic_path\", intrinsic_path)) {\n cout << \"Can not get the value of intrinsic_path\" << endl;\n exit(1);\n }\n if (!ros::param::get(\"extrinsic_path\", extrinsic_path)) {\n cout << \"Can not get the value of extrinsic_path\" << endl;\n exit(1);\n }\n if (!ros::param::get(\"error_threshold\", error_threshold)) {\n cout << \"Can not get the value of error_threshold\" << endl;\n exit(1);\n }\n init.resize(12);\n if (!ros::param::get(\"init_value\", init)) {\n cout << \"Can not get the value of init_value\" << endl;\n exit(1);\n }\n}\n\nint main(int argc, char **argv) {\n ros::init(argc, argv, \"getExt1\");\n getParameters();\n\n vector pData;\n getData(lidar_path, photo_path, pData);\n\n Eigen::Matrix4d extrin;\n // set the intrinsic parameters\n vector intrinsic;\n getIntrinsic(intrinsic_path, intrinsic);\n inner << intrinsic[0], intrinsic[1], intrinsic[2],\n intrinsic[3], intrinsic[4], intrinsic[5],\n intrinsic[6], intrinsic[7], intrinsic[8];\n\n // init the matrix of extrinsic, matrix of rotation and translation\n // keep this init value, or it is possible to get a local optimal result\n Eigen::Matrix3d R; \n R << init[0], init[1], init[2],\n init[4], init[5], init[6],\n init[8], init[9], init[10];\n Eigen::Quaterniond q(R); \n double ext[7];\n\n ext[0] = q.x();\n ext[1] = q.y();\n ext[2] = q.z();\n ext[3] = q.w();\n ext[4] = init[3]; \n ext[5] = init[7]; \n ext[6] = init[11]; \n\n Eigen::Map m_q = Eigen::Map(ext);\n Eigen::Map m_t = Eigen::Map(ext + 4);\n\n ceres::LocalParameterization * q_parameterization = new ceres::EigenQuaternionParameterization();\n ceres::Problem problem;\n\n problem.AddParameterBlock(ext, 4, q_parameterization);\n problem.AddParameterBlock(ext + 4, 3);\n \n for(auto val : pData) {\n ceres::CostFunction *cost_function;\n cost_function = external_cali::Create(val);\n problem.AddResidualBlock(cost_function, NULL, ext, ext + 4);\n }\n\n ceres::Solver::Options options;\n options.linear_solver_type = ceres::DENSE_SCHUR;\n options.minimizer_progress_to_stdout = true;\n options.trust_region_strategy_type = ceres::LEVENBERG_MARQUARDT;\n\n ceres::Solver::Summary summary;\n ceres::Solve(options, &problem, &summary);\n cout << summary.BriefReport() << endl;\n\n Eigen::Matrix3d rot = m_q.toRotationMatrix();\n writeExt(extrinsic_path, rot, m_t);\n cout << rot << endl;\n cout << m_t << endl;\n\n cout << \"Use the extrinsic result to reproject the data\" << endl;\n float error[2] = {0, 0};\n getUVError(intrinsic_path, extrinsic_path, lidar_path, photo_path, error, error_threshold, 1, cv::Size(2464, 2056)); \n \n cout << \"u average error is: \" << error[0] << endl;\n cout << \"v average error is: \" << error[1] << endl;\n if (error[0] + error[1] < error_threshold) {\n cout << endl << \"The reprojection error smaller than the threshold, extrinsic result seems ok\" << endl;\n }\n else {\n cout << endl << \"The reprojection error bigger than the threshold, extrinsic result seems not ok\" << endl;\n }\n\n return 0; \n}\n\n\n", "meta": {"hexsha": "7b258275bfeaa122ce088878594c6c64b0245dd0", "size": 5093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cam_lid_external1.cpp", "max_stars_repo_name": "Te12944265-AMAHA/livox_camera_lidar_calibration", "max_stars_repo_head_hexsha": "ee6e9589fb7480f4eef64d27b6c869d92053b9f1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cam_lid_external1.cpp", "max_issues_repo_name": "Te12944265-AMAHA/livox_camera_lidar_calibration", "max_issues_repo_head_hexsha": "ee6e9589fb7480f4eef64d27b6c869d92053b9f1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cam_lid_external1.cpp", "max_forks_repo_name": "Te12944265-AMAHA/livox_camera_lidar_calibration", "max_forks_repo_head_hexsha": "ee6e9589fb7480f4eef64d27b6c869d92053b9f1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6807228916, "max_line_length": 124, "alphanum_fraction": 0.6214411938, "num_tokens": 1483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966732132748, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6650126210581654}} {"text": "#include \"writer.hpp\"\n#include \n#include \n#include \n#include \n#include \n\n//! Sparse Matrix type. Makes using this type easier.\ntypedef Eigen::SparseMatrix SparseMatrix;\n\n//! Used for filling the sparse matrix.\ntypedef Eigen::Triplet Triplet;\n\n//! Vector type\ntypedef Eigen::VectorXd Vector;\n\n//! Our function pointer, typedef'd to make it easier to use\ntypedef double (*FunctionPointer)(double, double);\n\n//----------------poissonBegin----------------\n//! Create the Poisson matrix for 2D finite difference.\n//! @param[out] A will be the Poisson matrix (as in the exercise)\n//! @param[in] N number of elements in the x-direction\nvoid createPoissonMatrix2D(SparseMatrix &A, int N) {\n\t// Fill the matrix A using setFromTriplets - method (see other exercise\n\t// for how to use it).\n\t// (write your solution here)\n}\n//----------------poissonEnd----------------\n\n//----------------RHSBegin----------------\n//! Create the Right hand side for the 2D finite difference\n//! @param[out] rhs will at the end contain the right hand side\n//! @param[in] f the right hand side function f\n//! @param[in] N the number of points in the x direction\n//! @param[in] dx the cell width\nvoid createRHS(Vector &rhs, FunctionPointer f, int N, double dx) {\n\trhs.resize(N * N);\n\t// fill up RHS\n\t// remember that the index (i,j) corresponds to i*N+j\n\t// (write your solution here)\n}\n//----------------RHSEnd----------------\n\n//----------------solveBegin----------------\n//! Solve the Poisson equation in 2D\n//! @param[out] u will contain the solution u\n//! @param[in] f the function pointer to f\n//! @param[in] N the number of points to use (in x direction)\nvoid poissonSolve(Vector &u, FunctionPointer f, int N) {\n\t// Solve Poisson 2D here\n\t// (write your solution here)\n}\n//----------------solveEnd----------------\n\ndouble F(double x, double y) {\n\treturn 8 * M_PI * M_PI * sin(2 * M_PI * x) * sin(2 * M_PI * y);\n}\n\nint main(int, char **) {\n\tVector u;\n\tpoissonSolve(u, F, 100);\n\twriteToFile(\"u_fd.txt\", u);\n}\n", "meta": {"hexsha": "ddfebdd517d1f0a6ca01dbe423244c4d3402d759", "size": 2061, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "series1_warmup/2d-FD/finite_difference.cpp", "max_stars_repo_name": "westernmagic/NumPDE", "max_stars_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "series1_warmup/2d-FD/finite_difference.cpp", "max_issues_repo_name": "westernmagic/NumPDE", "max_issues_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2017-04-01T22:52:16.000Z", "max_issues_repo_issues_event_max_datetime": "2017-04-30T16:21:55.000Z", "max_forks_repo_path": "series1_warmup/2d-FD/finite_difference.cpp", "max_forks_repo_name": "westernmagic/NumPDE", "max_forks_repo_head_hexsha": "98786723b0944d48202f32bc8b9a0185835e03e8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7076923077, "max_line_length": 72, "alphanum_fraction": 0.6399805919, "num_tokens": 521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615381952105441, "lm_q2_score": 0.7718434978390746, "lm_q1q2_score": 0.6649726541132698}} {"text": "// Implements functions that fit planes to data.\n// File: planefit.h\n// Author: Philipp Allgeuer \n\n// Includes\n#include \n#include \n#include \n#include \n\n// Namespaces\nusing namespace rc_utils;\n\n//\n// Plane fitting\n//\n\n// Fit a plane to 3D data\nvoid PlaneFit::fitPlane(const Points3D& P, Eigen::Vector4d& coeff)\n{\n\t// Calculate a point on the plane and the normal vector to it\n\tEigen::Vector3d normal, mean;\n\tfitPlane(P, normal, mean);\n\n\t// Construct the coefficient vector (a,b,c,d) where the equation of the plane is ax + by + cz + d = 0\n\tcoeff << normal, -normal.dot(mean);\n}\n\n// Fit a plane to 3D data\nvoid PlaneFit::fitPlane(const Points3D& P, Eigen::Vector4d& coeff, Eigen::Vector3d& mean)\n{\n\t// Calculate a point on the plane and the normal vector to it\n\tEigen::Vector3d normal;\n\tfitPlane(P, normal, mean);\n\n\t// Construct the coefficient vector (a,b,c,d) where the equation of the plane is ax + by + cz + d = 0\n\tcoeff << normal, -normal.dot(mean);\n}\n\n// Fit a plane to 3D data\nvoid PlaneFit::fitPlane(const Points3D& P, Eigen::Vector3d& normal)\n{\n\t// Calculate a point on the plane and the normal vector to it\n\tEigen::Vector3d mean;\n\tfitPlane(P, normal, mean);\n}\n\n// Fit a plane to 3D data\nvoid PlaneFit::fitPlane(const Points3D& P, Eigen::Vector3d& normal, Eigen::Vector3d& mean)\n{\n\t// Retrieve how many data points there are\n\tsize_t N = P.size();\n\n\t// Handle trivial cases\n\tif(N <= 0)\n\t{\n\t\tnormal << 0.0, 0.0, 1.0;\n\t\tmean.setZero();\n\t\treturn;\n\t}\n\telse if(N == 1)\n\t{\n\t\tnormal << 0.0, 0.0, 1.0;\n\t\tmean = P[0];\n\t\treturn;\n\t}\n\n\t// Calculate the mean of the data points (the plane of best fit always passes through the mean)\n\tmean = Eigen::Vector3d::Zero();\n\tif(N >= 1)\n\t\tmean = std::accumulate(P.begin(), P.end(), mean) / N;\n\n\t// Construct the matrix of zero mean data points\n\tEigen::MatrixXd A(3, N);\n\tfor(size_t i = 0; i < N; i++)\n\t\tA.col(i) = P[i] - mean;\n\n\t// Perform an SVD decomposition to determine the direction with the minimum variance\n\tunsigned int options = (N >= 3 ? Eigen::ComputeThinU : Eigen::ComputeFullU) | Eigen::ComputeThinV;\n\tnormal = A.jacobiSvd(options).matrixU().col(2).normalized();\n}\n\n// Calculate the fitting error of a plane to certain 3D data\ndouble PlaneFit::fitPlaneError(const Points3D& P, const Eigen::Vector4d& coeff)\n{\n\t// Calculate the normalised equation coefficients (to put the resulting error in units of normal distance to plane)\n\tEigen::Vector3d normal = coeff.head<3>();\n\tdouble norm = normal.norm();\n\tdouble scale = (norm > 0.0 ? norm : coeff.w());\n\tEigen::Vector3d abc = normal / scale;\n\tdouble d = coeff.w() / scale;\n\n\t// Calculate the average distance to the plane of the data points\n\tdouble err = 0.0;\n\tsize_t N = P.size();\n\tfor(size_t i = 0; i < N; i++)\n\t\terr += fabs(abc.dot(P[i]) + d)/N;\n\n\t// Return the calculated error\n\treturn err;\n}\n\n// Calculate the fitting error of a plane to certain 3D data\ndouble PlaneFit::fitPlaneError(const Points3D& P, const Eigen::Vector3d& normal, Eigen::Vector3d& point)\n{\n\t// Normalise the normal vector (to put the resulting error in units of normal distance to plane)\n\tEigen::Vector3d n = normal.normalized();\n\n\t// Calculate the average distance to the plane of the data points\n\tdouble err = 0.0;\n\tsize_t N = P.size();\n\tfor(size_t i = 0; i < N; i++)\n\t\terr += fabs(n.dot(P[i] - point))/N;\n\n\t// Return the calculated error\n\treturn err;\n}\n// EOF", "meta": {"hexsha": "d3367434e94832e0e574d86278a9b5afa056f8ba", "size": 3405, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/planefit.cpp", "max_stars_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_stars_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-11-04T01:29:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T05:37:42.000Z", "max_issues_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/planefit.cpp", "max_issues_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_issues_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-08-10T04:00:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-08-10T12:59:36.000Z", "max_forks_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/planefit.cpp", "max_forks_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_forks_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-03-05T14:28:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:50:47.000Z", "avg_line_length": 28.8559322034, "max_line_length": 116, "alphanum_fraction": 0.6851688693, "num_tokens": 1009, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6649469752776731}} {"text": "#pragma once\n\n#include \"cppitertools/enumerate.hpp\"\n#include \"cppitertools/range.hpp\"\n\n#include \n\n#include \n#include \n\n\ntemplate\nstruct KalmanSmoother\n{\n using DataTable = std::vector>;\n\n Eigen::VectorX x;\n Eigen::MatrixX P;\n Eigen::MatrixX F;\n Eigen::MatrixX H;\n Eigen::MatrixX R;\n Eigen::MatrixX Q;\n\n std::vector> x_;\n std::vector> _x;\n std::vector> P_;\n std::vector> _P;\n\n std::function)> function_beforeKFcorrect;\n std::function)> function_afterKFcorrect;\n\n KalmanSmoother(int dynamParams, int measureParams, int controlParams = 0);\n\n DataTable forwardPass(DataTable & dataSeries);\n DataTable backwardPass();\n\nprivate:\n\n int m_dynamParams;\n int m_measureParams;\n int m_controlParams;\n\n std::vector> zk;\n};\n\ntemplate\ninline KalmanSmoother::KalmanSmoother(int dynamParams, int measureParams, int controlParams)\n{\n m_dynamParams = dynamParams;\n m_measureParams = measureParams;\n m_controlParams = controlParams;\n\n x = Eigen::VectorX(dynamParams);\n P = Eigen::MatrixX(dynamParams, dynamParams);\n F = Eigen::MatrixX(dynamParams, dynamParams);\n H = Eigen::MatrixX(measureParams, dynamParams);\n R = Eigen::MatrixX(measureParams, measureParams);\n Q = Eigen::MatrixX(dynamParams, dynamParams);\n}\n\ntemplate\ninline std::vector>\n KalmanSmoother::forwardPass(DataTable & dataSeries)\n{\n for (auto & data : dataSeries) {\n if (data.size() != m_measureParams)\n throw std::length_error(\"One of the data point's dimension is inadequate.\");\n }\n\n x_.clear();\n x_.resize(dataSeries.size() + 1, x);\n _x.clear();\n _x.resize(dataSeries.size() + 1, x);\n P_.clear();\n P_.resize(dataSeries.size() + 1, P);\n _P.clear();\n _P.resize(dataSeries.size() + 1, P);\n\n for (auto && [idx, data] : iter::enumerate(dataSeries)) {\n const int i = idx + 1;\n\n Eigen::Map> z(data.data(), m_measureParams);\n\n // Kalman predict\n _x[i] = F * x_[i - 1];\n _P[i] = F * P_[i - 1] * F.transpose() + Q;\n\n // Kalman correct\n auto K = _P[i] * H.transpose() * (R + H * _P[i] * H.transpose()).inverse();\n auto I = Eigen::MatrixX::Identity(m_dynamParams, m_dynamParams);\n x_[i] = _x[i] + K * (z - H * _x[i]);\n P_[i] = (I - K * H) * _P[i];\n }\n\n DataTable result;\n result.reserve(x_.size());\n for (auto & x : x_) {\n std::vector temp;\n for (auto value : x) {\n temp.push_back(value);\n }\n result.push_back(temp);\n }\n\n return result;\n}\n\ntemplate\ninline std::vector>\n KalmanSmoother::backwardPass()\n{\n const int n = x_.size();\n\n std::vector> xs;\n xs.resize(n, x_[n - 1]);\n std::vector> Ps;\n Ps.resize(n, P_[n - 1]);\n\n for (auto i : iter::range(n - 2, -1, -1)) {\n // Ps[i] = F * P_[i] * F.transpose() + Q;\n\n // auto K = P_[i] * F.transpose() * Ps[i].inverse();\n // xs[i] += K * (x_[i + 1] - F * _x[i]);\n // Ps[i] += K * (P_[i + 1] - P_[i]) * K.transpose();\n\n auto C = P_[i] * F.transpose() * _P[i + 1].inverse();\n\n xs[i] += x_[i] + C * (xs[i + 1] - _x[i + 1]);\n Ps[i] += P_[i] + C * (Ps[i + 1] - _P[i + 1]) * C.transpose();\n }\n\n DataTable result;\n result.reserve(xs.size());\n for (auto & x : xs) {\n std::vector temp;\n for (auto value : x) {\n temp.push_back(value);\n }\n result.push_back(temp);\n }\n\n return result;\n}\n", "meta": {"hexsha": "f055d1408238229fec48cb41841e42a4c33e05af", "size": 3804, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/tools/KalmanSmoother.hpp", "max_stars_repo_name": "attila-fenyvesi/TrafficMapper", "max_stars_repo_head_hexsha": "b11c027b401d519d5082617939a6bc347c6a1b8c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/tools/KalmanSmoother.hpp", "max_issues_repo_name": "attila-fenyvesi/TrafficMapper", "max_issues_repo_head_hexsha": "b11c027b401d519d5082617939a6bc347c6a1b8c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/tools/KalmanSmoother.hpp", "max_forks_repo_name": "attila-fenyvesi/TrafficMapper", "max_forks_repo_head_hexsha": "b11c027b401d519d5082617939a6bc347c6a1b8c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.4166666667, "max_line_length": 95, "alphanum_fraction": 0.575446898, "num_tokens": 1147, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.754914975839675, "lm_q1q2_score": 0.6649269048413294}} {"text": "/*=================================================================\n*\n* todo!!!!!!!!\n* compute \"voronoi\" area of each vertex\n* reference: Discrete Differential Geometry Operators for triangulated 2-manifolds_02\n* usage: \n\t\tva = vertex_area(verts, faces);\n* inputs:\n\t\tverts: 3*nverts\n\t\tfaces: 3*faces\n\t\tbVoronoi: use fast approximation or voronoi area\n*\n* output:\n*\t\tva: nverts*1\n* \n*\n* JJCAO, 2013\n*\n*=================================================================*/\n\n#include \n#include \n\nusing namespace std;\n\nvoid compute_vertex_area_fast(Eigen::MatrixXd& V, Eigen::MatrixXd& F, double* va)\n{\n\tint n1,n2,n3;\n\tEigen::Vector3d v1,v2,v3;\n\tEigen::Vector3d e1,e2;\n\tEigen::Vector3d tmpV;\n\tdouble tmp;\n\tdouble farea;\n\tfor( int i = 0; i < F.rows(); ++i)\n\t{\n\t\tn1 = F.coeff(i,0)-1; n2 = F.coeff(i,1)-1; n3 = F.coeff(i,2)-1;\n\t\tv1 = V.row(n1); v2 = V.row(n2); v3 = V.row(n3);\n\t\te1 = v2 - v1; e2 = v3 - v1;\n\n\t\ttmpV = e1.cross(e2);\n\t\tfarea = tmpV.norm()*0.5;\n\t\ttmp = farea / 3.0;\n\t\t\n\t\tva[n1] += tmp;\n\t\tva[n2] += tmp;\n\t\tva[n3] += tmp;\n\t}\n}\nvoid compute_vertex_voronoi_area(Eigen::MatrixXd& V, Eigen::MatrixXd& F, double* va)\n{\n\tmexErrMsgTxt(\"not implemented still !\");\n}\nvoid mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[])\n{\n\t///////////// Error Check\n\tif ( nrhs < 2) \n\t\tmexErrMsgTxt(\"Number of input should > 1!\");\n\n\t///////////// input & output arguments\t\n\t// input 0: verts: 3*nverts\n\tint nverts = mxGetM(prhs[0]);\n\tint col = mxGetN(prhs[0]);\n\tif(col != 3)\n\t\tmexErrMsgTxt(\"The mesh must be triangle mesh! it is excepted to be n*3\");\n\n\tdouble *verts = mxGetPr(prhs[0]);\n\n\t// input 1: faces: 3*nfaces\n\tint nfaces = mxGetM(prhs[1]);\n\tcol = mxGetN(prhs[1]);\n\tif(col != 3)\n\t\tmexErrMsgTxt(\"The mesh must be triangle mesh! it is excepted to be n*3\");\n\n\tdouble* faces = mxGetPr(prhs[1]);\n\n\t\n\tbool bVoronoi(false);\n\tif ( nrhs > 2) \n\t{\n\t\tdouble* tmp = mxGetPr(prhs[2]);\n\t\tif ( *tmp != 0)\n\t\t\tbVoronoi = true;\n\t}\n\n\t///////////////////////////////////////////////\n\t// output 0\n\tplhs[0] = mxCreateDoubleMatrix( nverts, 1, mxREAL); \n\tdouble *va = mxGetPr(plhs[0]);\n\tfor ( int i = 0; i < nverts; ++i)\n\t{\n\t\tva[i] = 0;\n\t}\n\n\t///////////////////////////////////////////////\t\n\t// process\n\tEigen::MatrixXd V = Eigen::Map(verts, nverts, 3);\n\tEigen::MatrixXd F = Eigen::Map(faces, nfaces, 3);\n\n\tif ( bVoronoi)\n\t\tcompute_vertex_voronoi_area(V,F,va);\n\telse\n\t\tcompute_vertex_area_fast(V,F,va);\n}", "meta": {"hexsha": "0e1e16fcefe7f714d9a1588e97fb7b69541bf259", "size": 2450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "matlab_code/jjcao_code-head/toolbox/jjcao_mesh/vertex_area.cpp", "max_stars_repo_name": "joycewangsy/normals_pointnet", "max_stars_repo_head_hexsha": "fc74a8ed1a009b18785990b1b4c20eda0549721c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "matlab_code/jjcao_code-head/toolbox/jjcao_mesh/vertex_area.cpp", "max_issues_repo_name": "joycewangsy/normals_pointnet", "max_issues_repo_head_hexsha": "fc74a8ed1a009b18785990b1b4c20eda0549721c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "matlab_code/jjcao_code-head/toolbox/jjcao_mesh/vertex_area.cpp", "max_forks_repo_name": "joycewangsy/normals_pointnet", "max_forks_repo_head_hexsha": "fc74a8ed1a009b18785990b1b4c20eda0549721c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.786407767, "max_line_length": 85, "alphanum_fraction": 0.5648979592, "num_tokens": 820, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026573249612, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6649254305528799}} {"text": "/* Boost example/newton-raphson.cpp\n * Newton iteration for intervals\n *\n * Copyright 2003 Guillaume Melquiond\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate I f(const I& x)\n{ return x * (x - 1.) * (x - 2.) * (x - 3.) * (x - 4.); }\ntemplate I f_diff(const I& x)\n{ return (((5. * x - 40.) * x + 105.) * x - 100.) * x + 24.; }\n\nstatic const double max_width = 1e-10;\nstatic const double alpha = 0.75;\n\nusing namespace boost;\nusing namespace numeric;\nusing namespace interval_lib;\n\n// First method: no empty intervals\n\ntypedef interval I1_aux;\ntypedef unprotect::type I1;\n\nstd::vector newton_raphson(const I1& xs) {\n std::vector l, res;\n I1 vf, vd, x, x1, x2;\n l.push_back(xs);\n while (!l.empty()) {\n x = l.back();\n l.pop_back();\n bool x2_used;\n double xx = median(x);\n vf = f(xx);\n vd = f_diff(x);\n if (zero_in(vf) && zero_in(vd)) {\n x1 = I1::whole();\n x2_used = false;\n } else {\n x1 = xx - division_part1(vf, vd, x2_used);\n if (x2_used) x2 = xx - division_part2(vf, vd);\n }\n if (overlap(x1, x)) x1 = intersect(x, x1);\n else if (x2_used) { x1 = x2; x2_used = false; }\n else continue;\n if (x2_used)\n if (overlap(x2, x)) x2 = intersect(x, x2);\n else x2_used = false;\n if (x2_used && width(x2) > width(x1)) std::swap(x1, x2);\n if (!zero_in(f(x1)))\n if (x2_used) { x1 = x2; x2_used = false; }\n else continue;\n if (width(x1) < max_width) res.push_back(x1);\n else if (width(x1) > alpha * width(x)) {\n std::pair p = bisect(x);\n if (zero_in(f(p.first))) l.push_back(p.first);\n x2 = p.second;\n x2_used = true;\n } else l.push_back(x1);\n if (x2_used && zero_in(f(x2)))\n if (width(x2) < max_width) res.push_back(x2);\n else l.push_back(x2);\n }\n return res;\n}\n\n// Second method: with empty intervals\n\ntypedef change_checking >::type I2_aux;\ntypedef unprotect::type I2;\n\nstd::vector newton_raphson(const I2& xs) {\n std::vector l, res;\n I2 vf, vd, x, x1, x2;\n l.push_back(xs);\n while (!l.empty()) {\n x = l.back();\n l.pop_back();\n double xx = median(x);\n vf = f(xx);\n vd = f_diff(x);\n if (zero_in(vf) && zero_in(vd)) {\n x1 = x;\n x2 = I2::empty();\n } else {\n bool x2_used;\n x1 = intersect(x, xx - division_part1(vf, vd, x2_used));\n x2 = intersect(x, xx - division_part2(vf, vd, x2_used));\n }\n if (width(x2) > width(x1)) std::swap(x1, x2);\n if (empty(x1) || !zero_in(f(x1)))\n if (!empty(x2)) { x1 = x2; x2 = I2::empty(); }\n else continue;\n if (width(x1) < max_width) res.push_back(x1);\n else if (width(x1) > alpha * width(x)) {\n std::pair p = bisect(x);\n if (zero_in(f(p.first))) l.push_back(p.first);\n x2 = p.second;\n } else l.push_back(x1);\n if (!empty(x2) && zero_in(f(x2)))\n if (width(x2) < max_width) res.push_back(x2);\n else l.push_back(x2);\n }\n return res;\n}\n\ntemplate\nstd::ostream &operator<<(std::ostream &os,\n const boost::numeric::interval &x) {\n os << \"[\" << x.lower() << \", \" << x.upper() << \"]\";\n return os;\n}\n\nint main() {\n {\n I1_aux::traits_type::rounding rnd;\n std::vector res = newton_raphson(I1(-1, 5.1));\n std::cout << \"Results: \" << std::endl << std::setprecision(12);\n for(std::vector::const_iterator i = res.begin(); i != res.end(); ++i)\n std::cout << \" \" << *i << std::endl;\n std::cout << std::endl;\n }\n {\n I2_aux::traits_type::rounding rnd;\n std::vector res = newton_raphson(I2(-1, 5.1));\n std::cout << \"Results: \" << std::endl << std::setprecision(12);\n for(std::vector::const_iterator i = res.begin(); i != res.end(); ++i)\n std::cout << \" \" << *i << std::endl;\n std::cout << std::endl;\n }\n}\n", "meta": {"hexsha": "c1f9759370d3a7ad44dcfe3ae1e1faaaf7b5307e", "size": 4150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/interval/examples/newton-raphson.cpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/numeric/interval/examples/newton-raphson.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/numeric/interval/examples/newton-raphson.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 29.2253521127, "max_line_length": 77, "alphanum_fraction": 0.5761445783, "num_tokens": 1377, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6648674144282994}} {"text": "#include \"xpbd/tetrahedron_volume_constraint.h\"\n\n#include \n\nnamespace xpbd {\n\ntetrahedron_volume_constraint_t::tetrahedron_volume_constraint_t(\n std::initializer_list indices,\n positions_type const& p,\n scalar_type const alpha)\n : base_type(indices, alpha), V0_{0.}\n{\n assert(indices.size() == 4u);\n V0_ = volume(p);\n}\n\ntetrahedron_volume_constraint_t::scalar_type\ntetrahedron_volume_constraint_t::volume(positions_type const& V) const\n{\n Eigen::RowVector3d const p0 = V.row(indices()[0]);\n Eigen::RowVector3d const p1 = V.row(indices()[1]);\n Eigen::RowVector3d const p2 = V.row(indices()[2]);\n Eigen::RowVector3d const p3 = V.row(indices()[3]);\n\n auto const vol = (1. / 6.) * (p1 - p0).cross(p2 - p0).dot(p3 - p0);\n return std::abs(vol);\n}\n\ntetrahedron_volume_constraint_t::scalar_type\ntetrahedron_volume_constraint_t::evaluate(positions_type const& p, masses_type const& m) const\n{\n return volume(p) - V0_;\n}\n\nvoid tetrahedron_volume_constraint_t::project(\n positions_type& p,\n masses_type const& m,\n scalar_type& lagrange,\n scalar_type const dt) const\n{\n auto const v0 = indices()[0];\n auto const v1 = indices()[1];\n auto const v2 = indices()[2];\n auto const v3 = indices()[3];\n\n auto const w0 = 1. / m(v0);\n auto const w1 = 1. / m(v1);\n auto const w2 = 1. / m(v2);\n auto const w3 = 1. / m(v3);\n\n Eigen::RowVector3d const p0 = p.row(v0);\n Eigen::RowVector3d const p1 = p.row(v1);\n Eigen::RowVector3d const p2 = p.row(v2);\n Eigen::RowVector3d const p3 = p.row(v3);\n\n auto const C = evaluate(p, m);\n\n Eigen::RowVector3d const grad0 = (1. / 6.) * (p1 - p2).cross(p3 - p2);\n Eigen::RowVector3d const grad1 = (1. / 6.) * (p2 - p0).cross(p3 - p0);\n Eigen::RowVector3d const grad2 = (1. / 6.) * (p0 - p1).cross(p3 - p1);\n Eigen::RowVector3d const grad3 = (1. / 6.) * (p1 - p0).cross(p2 - p0);\n\n auto const weighted_sum_of_gradients = w0 * grad0.squaredNorm() + w1 * grad1.squaredNorm() +\n w2 * grad2.squaredNorm() + w3 * grad3.squaredNorm();\n\n if (weighted_sum_of_gradients < 1e-5)\n return;\n\n scalar_type const alpha_tilde = alpha_ / (dt * dt);\n scalar_type const delta_lagrange =\n -(C + alpha_tilde * lagrange) / (weighted_sum_of_gradients + alpha_tilde);\n\n lagrange += delta_lagrange;\n p.row(v0) += w0 * grad0 * delta_lagrange;\n p.row(v1) += w1 * grad1 * delta_lagrange;\n p.row(v2) += w2 * grad2 * delta_lagrange;\n p.row(v3) += w3 * grad3 * delta_lagrange;\n}\n\n} // namespace xpbd", "meta": {"hexsha": "8a68eeb0b42b164a8c7ed992b321377ddfd20458", "size": 2587, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/xpbd/tetrahedron_volume_constraint.cpp", "max_stars_repo_name": "Q-Minh/position-based-dynamics", "max_stars_repo_head_hexsha": "23fcf93bddd5daf425cdc3443da05760cc1343ec", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 20.0, "max_stars_repo_stars_event_min_datetime": "2021-02-28T23:41:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T06:30:58.000Z", "max_issues_repo_path": "src/xpbd/tetrahedron_volume_constraint.cpp", "max_issues_repo_name": "Q-Minh/position-based-dynamics", "max_issues_repo_head_hexsha": "23fcf93bddd5daf425cdc3443da05760cc1343ec", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/xpbd/tetrahedron_volume_constraint.cpp", "max_forks_repo_name": "Q-Minh/position-based-dynamics", "max_forks_repo_head_hexsha": "23fcf93bddd5daf425cdc3443da05760cc1343ec", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3375, "max_line_length": 96, "alphanum_fraction": 0.6401236954, "num_tokens": 824, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299612154571, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.664865067543896}} {"text": "#ifndef EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_FULLYCONNECTED_HPP\n#define EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_FULLYCONNECTED_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace exactsolution{\n\nclass PartitionFunctionClassicalXYFullyConnected{\npublic :\n static std::string name() { return \"Exact partition function, classical XY, Fully Connected\"; }\n PartitionFunctionClassicalXYFullyConnected(double J,unsigned int num) : J_(J), num_(num) {}\n \n double operator()(double T){\n double value = 0.0;\n value = logZ(T);\n value = std::exp(value);\n return value;\n }\n\n double logZ(double T) {\n double value = 0.0;\n double M_temp = M(T);\n value -= 0.5 * std::log(2.0 * M_PI * T) - 0.5 * J_ / T - 0.5 * M_temp * M_temp / T * J_ + F(M_temp / T * J_);\n value *= num_;\n return value;\n }\n\n double T(double U){\n double T0 = 0.0;\n double T1 = 0.75;\n if(U >= 0.25 + 0.5 * J_){\n return 2.0 * U - J_;\n } else{\n //False Position Method\n optimization::FalsePositionMethod optimizer;\n double J = J_;\n auto diff_U = [&J,&U,this](double x) { return U - ( 0.5 * x + 0.5 * J * ( 1 - this->M(x) * this->M(x)));};\n optimizer.find_zero(diff_U, T0, T1);\n return optimizer.zero();\n }\n }\n\n double M(double T) {\n double M_tmp = 0.0;\n if(T >= J_ * 0.5) return 0.0;\n else if( T == 0.0) return 1.0;\n else{\n M_tmp = std::sqrt(1 - 2.0 * T / J_);\n optimization::NewtonMethod optimizer;\n double J = J_;\n auto diff_M = [&J,&T,this](double x) { return x - this->dF(x * J / T);};\n auto d_diff_M = [&J,&T,this](double x) { return 1 - J / T * this->ddF(x * J / T);};\n optimizer.find_zero(diff_M, d_diff_M, M_tmp);\n return optimizer.zero();\n }\n }\n\n double F(double value){\n return std::log(2.0 * M_PI * boost::math::cyl_bessel_i(0,value));\n }\n\n double dF(double value){\n double value_output = 0.0;\n value_output = boost::math::cyl_bessel_i(1.0,value) / boost::math::cyl_bessel_i(0.0,value);\n return value_output;\n }\n\n double ddF(double value){\n double value_output = 0.0;\n value_output = 0.5 * ( boost::math::cyl_bessel_i(0.0,value) + boost::math::cyl_bessel_i(2.0,value) ) * boost::math::cyl_bessel_i(0.0,value); \n value_output -= boost::math::cyl_bessel_i(1.0,value) * boost::math::cyl_bessel_i(1.0,value);\n value_output /= boost::math::cyl_bessel_i(0.0,value) * boost::math::cyl_bessel_i(0.0,value);\n return value_output;\n }\n\nprivate :\n double J_;\n unsigned int num_;\n mutable double U_;\n mutable double T_;\n}; //end harmonic_chain \n\n}\n#endif //EXACTSOLUTION_PARTITION_FUNCTION_CLASSICAL_XY_FULLYCONNECTED_HPP\n", "meta": {"hexsha": "cf815da719b705e9ae141f55ffc13df59e9c6926", "size": 2840, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "clstatphys/clstatphys/physics/partition_function_classical_xy_fullyconnected.hpp", "max_stars_repo_name": "FIshikawa/ClassicalStatPhys", "max_stars_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "clstatphys/clstatphys/physics/partition_function_classical_xy_fullyconnected.hpp", "max_issues_repo_name": "FIshikawa/ClassicalStatPhys", "max_issues_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-01-21T08:54:05.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-21T09:29:10.000Z", "max_forks_repo_path": "clstatphys/clstatphys/physics/partition_function_classical_xy_fullyconnected.hpp", "max_forks_repo_name": "FIshikawa/ClassicalStatPhys", "max_forks_repo_head_hexsha": "e4010480d3c7977829c1b3fdeaf51401a2409373", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-07-18T03:36:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-21T22:58:27.000Z", "avg_line_length": 31.2087912088, "max_line_length": 145, "alphanum_fraction": 0.6454225352, "num_tokens": 888, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299488452012, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6648650586546994}} {"text": "#include \n#include \"util.hpp\"\n\nusing Eigen::MatrixXf;\n\nvector > inverse(vector > m) {\n int dim = m.size();\n MatrixXf m_(dim, dim);\n for (int i=0; i > inv(dim, vector(dim));\n for (int i=0; i > pseudo_inv(vector > m) {\n int dim = m.size();\n MatrixXf m_(dim, dim);\n for (int i=0; i > inv(dim, vector(dim));\n for (int i=0; i\n#include \n\n// STL includes\n#include \n#include \n#ifdef USE_THREADS\n#include \n#endif\n\n// Local include\n#include \"DirectionsSampling.hpp\"\n\n/* This header provide multiple ways to project spherical function to Spherical\n * Harmonics vectors.\n *\n * + 'ProjectToSH' return the SH coefficient vector when the Functor to be\n * projected is bandlimited to the max order of SH. Warning: do not use with\n * highly varying functions! This projection will probably behave very\n * badly. In such case, it is advised to use the 'ProjectToShMC' method.\n *\n * + 'ProjectToShMC' return the SH coefficient vector by integrating \n * using Monte Carlo integration. It is possible to choose the type of\n * random or quasi- random sequence for the integration.\n *\n * + 'TripleTensorProduct' return the premultiplied triple tensor product:\n * the integral of multiplied by the SH coefficients 'clm'\n * of 'f'. The integral is computed using Monte Carlo, as 'ProjectToShMC'\n * does.\n *\n * TODO: Template the direction sequence.\n */\n\n#define USE_FIBONACCI_SEQ\n//#define USE_BLUENOISE_SEQ\n\n/* From a set of `basis` vector directions, and a spherical function `Functor`,\n * generate the Spherical Harmonics projection of the `Functor`. This algorithm\n * works as follows:\n *\n * 1. Evaluate the matrix Ylm(w_i) for each SH index and each direction\n * 2. Evaluate the vector of the functor [f(w_0), ..., f(w_n)]\n * 3. Return the product Ylm(w_i)^{-1} [f(w_0), ..., f(w_n)]\n *\n * Requierement: `basis` must have the dimension of the output SH vector.\n * `f` must be real valued. Higher dimension functor are not\n * handled yet.\n */\ntemplate\ninline Eigen::VectorXf ProjectToSH(const Functor& f,\n const std::vector& basis) {\n\n // Get the number of elements to compute\n const int dsize = basis.size();\n const int order = sqrt(dsize)-1;\n\n Eigen::MatrixXf Ylm(dsize, dsize);\n Eigen::VectorXf flm(dsize);\n\n for(unsigned int i=0; i\ninline Eigen::VectorXf ProjectToShMC(const Functor& f, int order, int M=100000) {\n\n std::mt19937 gen(0);\n std::uniform_real_distribution dist(0.0,1.0);\n\n Eigen::VectorXf shCoeffs((order+1)*(order+1));\n#if defined(USE_FIBONACCI_SEQ)\n const std::vector directions = SamplingFibonacci(M);\n#elif defined(USE_BLUENOISE_SEQ)\n const std::vector directions = SamplingBlueNoise(M);\n#else\n const std::vector directions = SamplingRandom(M);\n#endif\n for(auto& w : directions) {\n // Evaluate the function and the basis vector\n shCoeffs += f(w) * SH::FastBasis(w, order);\n }\n shCoeffs *= 4.0*M_PI / float(M);\n\n return shCoeffs;\n}\n\n/* Compute the triple tensor product \\int Ylm * Ylm * Ylm\n *\n * ## Arguments:\n *\n * + 'ylm' is the input spherical function SH coeffcients. They will be\n * prefactored to the triple product tensor to build the matrix.\n *\n * + 'truncated' allows to export either the truncated matrix (up to order\n * 'n', where 'n' is the order the input SH coeffs 'ylm') or the full matrix\n * that is order '2n-1'.\n */\ntemplate\ninline Eigen::MatrixXf TripleTensorProduct(const Eigen::VectorXf& ylm,\n bool truncated=true,\n int nDirections=100000) {\n\n // Compute the max order\n const int vsize = ylm.size();\n const int order = (truncated) ? sqrt(vsize)-1 : 2*sqrt(vsize)-2;\n const int msize = (truncated) ? vsize : SH::Terms(order);\n\n Eigen::MatrixXf res = Eigen::MatrixXf::Zero(msize, msize);\n Eigen::VectorXf clm(msize);\n\n // Take a uniformly distributed point sequence and integrate the triple tensor\n // for each SH band\n#if defined(USE_FIBONACCI_SEQ)\n const std::vector directions = SamplingFibonacci(nDirections);\n#elif defined(USE_BLUENOISE_SEQ)\n const std::vector directions = SamplingBlueNoise(nDirections);\n#else\n const std::vector directions = SamplingRandom(nDirections);\n#endif\n for(auto& w : directions) {\n SH::FastBasis(w, order, clm);\n res += clm.segment(0, vsize).dot(ylm) * clm * clm.transpose();\n }\n\n res *= 4.0f * M_PI / float(nDirections);\n return res;\n}\n\n/* Compute the triple tensor product \\int Ylm * Ylm * Ylm for a bunch of\n * function projected on Spherical Harmonics. This method is specially\n * interesting to construct product of (R,G,B) component where each component\n * is stored in a separate vector.\n *\n * ## Arguments:\n *\n * + 'ylm' is the input spherical function SH coeffcients. They will be\n * prefactored to the triple product tensor to build the matrix.\n *\n * + 'truncated' allows to export either the truncated matrix (up to order\n * 'n', where 'n' is the order the input SH coeffs 'ylm') or the full matrix\n * that is order '2n-1'.\n */\ntemplate\ninline std::vector TripleTensorProduct(\n const std::vector& ylms,\n bool truncated=true,\n int nDirections=100000) {\n\n#ifdef USE_THREADS\n struct TTPThread : public std::thread {\n\n std::vector res;\n\n TTPThread(const std::vector& dirs, unsigned int start, unsigned int end,\n const std::vector& ylms, int order) :\n std::thread(&TTPThread::run, this, dirs, start, end, ylms, order) {}\n\n void run(const std::vector& dirs, unsigned int start, unsigned int end,\n const std::vector& ylms, int order) {\n const int vsize = ylms[0].size();\n const float fact = 4.0f * M_PI / float(dirs.size());\n\n const int msize = SH::Terms(order);\n Eigen::MatrixXf mat(msize, msize);\n Eigen::VectorXf clm(msize);\n\n res.reserve(3);\n res.push_back(Eigen::MatrixXf::Zero(msize, msize));\n res.push_back(Eigen::MatrixXf::Zero(msize, msize));\n res.push_back(Eigen::MatrixXf::Zero(msize, msize));\n\n for(unsigned int k=start; k res(ylms.size(), Eigen::MatrixXf::Zero(msize, msize));\n\n // Take a uniformly distributed point sequence and integrate the triple tensor\n // for each SH band\n#if defined(USE_FIBONACCI_SEQ)\n const std::vector directions = SamplingFibonacci(nDirections);\n#elif defined(USE_BLUENOISE_SEQ)\n const std::vector directions = SamplingBlueNoise(nDirections);\n#else\n const std::vector directions = SamplingRandom(nDirections);\n#endif\n\n#ifdef USE_THREADS\n std::vector threads;\n const unsigned int nthreads = std::thread::hardware_concurrency();\n for(unsigned int i=0; ijoin();\n\n for(unsigned int i=0; i<3; ++i) {\n res[i] += thread->res[i];\n }\n }\n#else\n Eigen::VectorXf clm(msize);\n const float fact = 4.0f * M_PI / float(nDirections);\n for(auto& w : directions) {\n // Construct the matrix\n SH::FastBasis(w, order, clm);\n const auto matrix = clm * clm.transpose();\n\n // For each SH vector apply the weight to the matrix and sum it\n for(unsigned int i=0; i\nEigen::MatrixXf TripleTensorProductCos(int order,\n int nDirections=100000) {\n\n // Compute the max order\n const int msize = SH::Terms(order);\n\n Eigen::MatrixXf res = Eigen::MatrixXf::Zero(msize, msize);\n\n // Take a uniformly distributed point sequence and integrate the triple tensor\n // for each SH band\n#if defined(USE_FIBONACCI_SEQ)\n const std::vector directions = SamplingFibonacci(nDirections);\n#elif defined(USE_BLUENOISE_SEQ)\n const std::vector directions = SamplingBlueNoise(nDirections);\n#else\n const std::vector directions = SamplingRandom(nDirections);\n#endif\n const float fact = 4.0f * M_PI / float(nDirections);\n for(auto& w : directions) {\n // Construct the matrix\n const Eigen::VectorXf clm = SH::FastBasis(w, order);\n const auto matrix = clm * clm.transpose();\n\n // For each SH vector apply the weight to the matrix and sum it\n if(w[2] > 0.0) {\n res += fact * w[2] * matrix;\n }\n }\n return res;\n}\n", "meta": {"hexsha": "782455f2c6216ebb83713978ff3b6e2caa6298d7", "size": 10037, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/SphericalHarmonics.hpp", "max_stars_repo_name": "belcour/IntegralSH", "max_stars_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2018-02-27T07:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:40:06.000Z", "max_issues_repo_path": "include/SphericalHarmonics.hpp", "max_issues_repo_name": "belcour/IntegralSH", "max_issues_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/SphericalHarmonics.hpp", "max_forks_repo_name": "belcour/IntegralSH", "max_forks_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-08T09:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T03:40:39.000Z", "avg_line_length": 35.0944055944, "max_line_length": 86, "alphanum_fraction": 0.6449138189, "num_tokens": 2646, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392817460333, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6648086604839326}} {"text": "#include \nusing namespace std;\n\n#include \n// Eigen 核心部分\n#include \n// 稠密矩阵的代数运算(逆,特征值等)\n#include \n// Eigenatrix Exponential\n#include \nusing namespace Eigen;\n\n// Declaration\nQuaterniond quat_mul(Quaterniond q1,Quaterniond q2);\n\nint main() {\n // Initializae an euler_angle vector\n // euler_angle: Roll-Pitch-Yaw\n // 0 -> -pi/2 -> -pi/4\n Eigen::Vector3d euler_angle(-M_PI/ 4.0, -M_PI/ 2.0, 0.0);\n cout << \"euler = \" << euler_angle.transpose() << endl;\n\n Eigen::Matrix3d R;\n R = Eigen::AngleAxisd(euler_angle[0], Eigen::Vector3d::UnitZ()) *\n Eigen::AngleAxisd(euler_angle[1], Eigen::Vector3d::UnitY()) *\n Eigen::AngleAxisd(euler_angle[2], Eigen::Vector3d::UnitX());\n cout << \"rotation matrix =\\n\" << R << endl;\n\n Eigen::Quaterniond q;\n q = Eigen::AngleAxisd(euler_angle[0], Eigen::Vector3d::UnitZ()) *\n Eigen::AngleAxisd(euler_angle[1], Eigen::Vector3d::UnitY()) *\n Eigen::AngleAxisd(euler_angle[2], Eigen::Vector3d::UnitX());\n cout << \"quaternion = \" << q.coeffs().transpose() << endl;\n\n // w\n Eigen::Vector3d w(0.01,0.02,0.03);\n cout << \"w = \" << w.transpose() << endl;\n // w^\n Eigen::Matrix3d w_hat;\n w_hat << 0, -w(2), w(1),\n w(2), 0, -w(0),\n -w(1), w(0), 0;\n cout << \"w^= \\n\" << w_hat << endl;\n\n // R <- Rexp(w^)\n R = R*w_hat.exp();\n cout << \"new R = \\n\" << R << endl;\n\n // q <- q x [1,w].T\n Eigen::Quaterniond w_mul(1,w(0)/2, w(1)/2, w(2)/2);\n q = quat_mul(q, w_mul);\n cout << \"new q = \" << q.coeffs().transpose() << endl;\n cout << \"new R from q = \\n\" << q.normalized().toRotationMatrix() << endl;\n\n return 0;\n}\n\n\nQuaterniond quat_mul(Quaterniond q1,Quaterniond q2) {\n double x = q1.x() * q2.w() + q1.y() * q2.z() - q1.z() * q2.y() + q1.w() * q2.x();\n double y = -q1.x() * q2.z() + q1.y() * q2.w() + q1.z() * q2.x() + q1.w() * q2.y();\n double z = q1.x() * q2.y() - q1.y() * q2.x() + q1.z() * q2.w() + q1.w() * q2.z();\n double w = -q1.x() * q2.x() - q1.y() * q2.y() - q1.z() * q2.z() + q1.w() * q2.w();\n\n return Quaterniond(w,x,y,z);\n}", "meta": {"hexsha": "b51a18ead139db89eecc252e9e738065ddc7d0b0", "size": 2173, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Week1-cpp-eigen/main.cpp", "max_stars_repo_name": "WeihengXia0123/VIO-Tutorial-from-scratch", "max_stars_repo_head_hexsha": "d9007de2f7874e58a5142430c1f6f5a5638c9e3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Week1-cpp-eigen/main.cpp", "max_issues_repo_name": "WeihengXia0123/VIO-Tutorial-from-scratch", "max_issues_repo_head_hexsha": "d9007de2f7874e58a5142430c1f6f5a5638c9e3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Week1-cpp-eigen/main.cpp", "max_forks_repo_name": "WeihengXia0123/VIO-Tutorial-from-scratch", "max_forks_repo_head_hexsha": "d9007de2f7874e58a5142430c1f6f5a5638c9e3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9242424242, "max_line_length": 86, "alphanum_fraction": 0.5439484584, "num_tokens": 803, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392786908831, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6648086581864212}} {"text": "// error.cpp: numerical error analysis benchmark environment\n//\n// Copyright (C) 2017-2020 Stillwater Supercomputing, Inc.\n//\n// This file is part of the HPRBLAS project, which is released under an MIT Open Source license.\n\n// include and configure number systems\n// configure the posit number system behavior\n#define POSIT_ROUNDING_ERROR_FREE_IO_FORMAT 0\n// configure the HPR-BLAS behavior\n#define HPRBLAS_TRACE_ROUNDING_EVENTS 0\n#include \n// Boost arbitrary precision floats\n#include \n\n// matrix generators\n#include \n\ntemplate\nvoid GenerateNumericalAnalysisTestCase(const std::string& header, unsigned N, bool verbose = false) {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing namespace sw::unum;\n\tusing namespace sw::hprblas;\n\n\tstd::cout << \">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\\n\" << header << std::endl;\n\n\t// calculate the numerical error caused by the linear algebra computation\n\tVector e(N), eprime(N), eabsolute(N), erelative(N), I(N);\n\te = Scalar(1);\n\tI = Scalar(1);\n\t// TODO: it is not clear that for posits this would be a fused matrix-vector operation\n\tmatvec(eprime, I, e);\n\tcout << \"reference vector : \" << e << '\\n';\n\tcout << \"error vector : \" << eprime << '\\n';\n\t// absolute error\n\teabsolute = e - eprime;\n\tcout << \"absolute error vector : \" << eabsolute << '\\n';\n\tcout << \"L1 norm \" << hex_format(l1_norm(eabsolute)) << \" \" << l1_norm(eabsolute) << '\\n';\n\tcout << \"L2 norm \" << hex_format(l2_norm(eabsolute)) << \" \" << l2_norm(eabsolute) << '\\n';\n\tcout << \"Linf norm \" << hex_format(linf_norm(eabsolute)) << \" \" << linf_norm(eabsolute) << '\\n';\n\n\t// relative error\n\tcout << \"relative error\\n\";\n\tScalar relative_error;\n\trelative_error = l1_norm(eabsolute) / l1_norm(e);\n\tcout << \"L1 norm \" << hex_format(relative_error) << \" \" << relative_error << '\\n';\n\trelative_error = l2_norm(eabsolute) / l2_norm(e);\n\tcout << \"L2 norm \" << hex_format(relative_error) << \" \" << relative_error << '\\n';\n\trelative_error = linf_norm(eabsolute) / linf_norm(e);\n\tcout << \"Linf norm \" << hex_format(relative_error) << \" \" << relative_error << '\\n';\n\n\t// error volume\n\tcout << \"error bounding box volume\\n\";\n\tcout << \"Measured in Euclidean distance : \" << error_volume(linf_norm(eabsolute), N, false) << '\\n';\n\tcout << \"Measured in ULPs : \" << error_volume(linf_norm(eabsolute), N, true) << \" ulps^\" << N << '\\n';\n\tScalar ulp = numeric_limits::epsilon();\n\tcout << \"L-infinitiy norm measured in ULPs : \" << linf_norm(eabsolute) / ulp << \" ulps\" << '\\n';\n\n\tcout << endl;\n}\n\n// Benchmark Suite runner for numerical error analysis measurements\nint main(int argc, char** argv)\ntry {\n\tusing namespace std;\n\tusing namespace mtl;\n\tusing namespace sw::unum;\n\tusing namespace sw::hprblas;\n\n\tint nrOfFailedTestCases = 0;\n\n\t// we need to enumerate along the following dimensions\n\t// 1- number systems: the key here is that when we have posits, we use FDP\n\t// 2- algorithms: different computational approaches to solve a system of linear equations\n\t// 3- matrices. easy, difficult, empirical\n\n\t// The measurement will always be the error to this equation:\n\t// Ax = b, with a b that delivers the solution x = ones()\n\n\t// There is another measure and that is driven by the characteristic polynomial of the matrix:\n\t// If we have very wildy differing eigenvalues, then there are b vectors that can lift up small\n\t// eigenvalues compared to large eigenvalues. Those are situations in which we want to make\n\t// certain we don't have cancellation: a big eigenvalue multiplied by a small scaling factor\n\t// and a small eigenvalue multiplied by a big scaling factor.\n\n\t// the benchmark runner is structured as follows:\n\t// foreach test system\n\t// pick a test size N\n\t// foreach number system\n\t// generate the test matrix A(N,N)\n\t// generate the test right hand side: b(N) = A * ones()\n\t// foreach algorithm\n\t// generate the inverse or decomposition\n\t// solve the system of equations: Ax = b\n\t// measure the difference between result x and ones()\n\tusing Scalar = sw::unum::posit<32, 2>;\n\tusing Vector = mtl::vec::dense_vector;\n\tusing Matrix = mtl::mat::dense2D;\n\n\tint N = 5;\n\tMatrix H(N, N);\n\tsw::hprblas::GenerateHilbertMatrix(H, false);\n\tMatrix Hinv = GaussJordanInversion(H);\n\tMatrix Href(N, N);\n\tGenerateHilbertMatrixInverse(Href);\n\tMatrix I(N, N); // H * Hinv should yield the identity matrix\n\t// TODO: this is not clear that for posits this would be a fused matrix multiply\n\tmatmul(I, H, Hinv);\n\n\tGenerateNumericalAnalysisTestCase(\"testing\", 10, true);\n\n\treturn (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS);\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const posit_internal_exception& err) {\n\tstd::cerr << \"Uncaught posit internal exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (std::runtime_error& err) {\n\tstd::cerr << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (...) {\n\tstd::cerr << \"Caught unknown exception\" << std::endl;\n\treturn EXIT_FAILURE;\n}\n", "meta": {"hexsha": "feef637f234f5799b6b5e2bc0e2909f2cb19e30b", "size": 5498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/benchmark/error.cpp", "max_stars_repo_name": "fossabot/hpr-blas", "max_stars_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "tools/benchmark/error.cpp", "max_issues_repo_name": "fossabot/hpr-blas", "max_issues_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tools/benchmark/error.cpp", "max_forks_repo_name": "fossabot/hpr-blas", "max_forks_repo_head_hexsha": "dad4656f556ea62abddbf3ddbb712d6b77fe7e91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5539568345, "max_line_length": 120, "alphanum_fraction": 0.6818843216, "num_tokens": 1413, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.835483553488848, "lm_q2_score": 0.795658090372256, "lm_q1q2_score": 0.6647592487063634}} {"text": "#pragma once\n\n#include \n#include \n\n/**\n* A Simple Kalman filter.\n* A - System dynamics matrix\n* C - Output matrix\n* Q - Process noise covariance\n* R - Measurement noise covariance\n* P - Estimate error covariance\n* The input is a 3d position vector.\n* Outputs are a 3d position, 3d velocity, and 3d acceleration vectors.\n*/\n\nclass KalmanFilter_Position3D {\n\npublic:\n\t/**\n\t* Initialize the kalman filter.\n\t* dt - a filter time step.\n\t*/\n\tKalmanFilter_Position3D(const double dt);\n\n\t/** Update the estimated state based on measured values. */\n\tvoid Update(const Eigen::VectorXd& y);\n\n\t/** Returns the filter estimation. */\n\tinline Eigen::VectorXd GetEstimate() { return x_predicted; }\nprivate:\n\tstatic const int n, m;\t\t\t\t// The size of the filter output and input vectors.\n\tconst double dt;\t\t\t\t\t// The filter time step size.\n\n\tEigen::VectorXd x_predicted;\t\t// Last predicted value.\n\tEigen::MatrixXd P, A, H, R, Q, I;\t// Kalman filter matrices.\n};\n", "meta": {"hexsha": "b9257d9bfb2c4f795213da3bf67838a085aac82f", "size": 973, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/kalman/kalman-pos-3d.hpp", "max_stars_repo_name": "bitbloop/KalmanFilter", "max_stars_repo_head_hexsha": "f1616134d6eeeab05afc56bb6b0a921fad106d7f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-29T15:55:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T15:55:01.000Z", "max_issues_repo_path": "src/kalman/kalman-pos-3d.hpp", "max_issues_repo_name": "bitbloop/KalmanFilter", "max_issues_repo_head_hexsha": "f1616134d6eeeab05afc56bb6b0a921fad106d7f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/kalman/kalman-pos-3d.hpp", "max_forks_repo_name": "bitbloop/KalmanFilter", "max_forks_repo_head_hexsha": "f1616134d6eeeab05afc56bb6b0a921fad106d7f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-18T07:29:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T07:29:55.000Z", "avg_line_length": 25.6052631579, "max_line_length": 78, "alphanum_fraction": 0.7009249743, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541544761566, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.664605409457244}} {"text": "#pragma once\n\n// Eigen includes\n#include \n\n// STL includes\n#include \n#include \n\n#define AXIAL_EPSILON 1.0E-6\n\n/* _Cosine Sum Integral_\n */\ninline Eigen::VectorXf CosSumIntegral(float x, float y, float c, int n) {\n\n\tconst float siny = sin(y);\n\tconst float sinx = sin(x);\n\tconst float cosy = cos(y);\n\tconst float cosx = cos(x);\n\tconst float cosy2 = cosy*cosy;\n\tconst float cosx2 = cosx*cosx;\n\n static const Eigen::Vector2i i1 = {1, 1};\n static const Eigen::Vector2i i2 = {2, 2};\n Eigen::Vector2i i = {0, 1};\n Eigen::Vector2f F = {y-x, siny-sinx};\n Eigen::Vector2f S = {0.0f, 0.0f};\n\n Eigen::VectorXf R = Eigen::VectorXf::Zero(n+2);\n\n Eigen::Vector2f pow_c = {1.0, c};\n Eigen::Vector2f pow_cosx = {cosx, cosx2};\n Eigen::Vector2f pow_cosy = {cosy, cosy2};\n\n while(i[1] <= n) {\n // S <= S + c^{i} F\n S += pow_c.cwiseProduct(F);\n\n // The resulting vector `R` is shifted of one to the right. This is due to\n // the fact that order `n` moment requires only up to order `n-1` power of\n // cosine integrals.\n R.segment(i[1], 2) = S;\n\n // T <= cos(y)^{i+1} sin(y) - cos(x)^{i+1} sin(x)\n // F <= (T + i+1) F / (i+2)\n auto T = pow_cosy*siny - pow_cosx*sinx;\n F = (T + (i+i1).cast().cwiseProduct(F)).cwiseQuotient((i+i2).cast());\n\n // Update temp variable\n i += i2;\n pow_c *= c*c;\n pow_cosx *= cosx2;\n pow_cosy *= cosy2;\n }\n\n return R;\n}\n\n/* _sign_\n *\n * Sign function template\n */\ntemplate \ninline int sign(T val) {\n return (T(0) <= val) - (val < T(0));\n}\n\n/* _clamp_\n *\n * Clamp function template to restrict a given function to be in between\n * boundaries.\n */\ntemplate \ninline T clamp(T val, T a, T b) {\n return std::max(a, std::min(b, val));\n}\n\n\n/* _Line Integral_\n */\ntemplate\ninline Eigen::VectorXf LineIntegral(const Vector& A, const Vector& B,\n const Vector& w, int n) {\n#ifdef ZERO_ORTHOGONAL\n auto wDotA = Vector::Dot(A, w);\n auto wDotB = Vector::Dot(B, w);\n // Zeroth moment and orthogonal directions 'w' to the while edge do not\n // require this part since it will always return '0';\n if(std::abs(wDotA) < AXIAL_EPSILON && std::abs(wDotB) < AXIAL_EPSILON) {\n return Eigen::VectorXf::Zero(n+2);\n }\n#endif\n\n // Note: expanding the (I-ssT)B expression from Arvo's LineIntegral pseudo\n // code to the projection of B on plane with A as normal.\n const auto s = Vector::Normalize(A);\n const auto t = Vector::Normalize(B - Vector::Dot(s, B)*s);\n\n const auto a = Vector::Dot(w, s);\n const auto b = Vector::Dot(w, t);\n const auto c = sqrt(a*a + b*b);\n\n // Compute the arc-length on which to compute the integral of the moment\n // function and the shift 'p' that change the integral to the integral of\n // a shifted cosine.\n const auto r = Vector::Dot(s, B) / Vector::Dot(B,B);\n const auto l = acos(clamp(r, -1.0f, 1.0f));\n const auto p = atan2(b, a);\n\n return CosSumIntegral(-p, l-p, c, n);\n}\n\n/* _Boundary Integral_\n *\n * Compute the integral along P egdes of the up to order 'n' axial moment\n * around w. By using 'n' = 'w' you can compute the single axis moment. Double\n * axis moment with second axis begin the normal must use 'v' == 'n' ('n' being\n * the normal).\n */\ntemplate\ninline Eigen::VectorXf BoundaryIntegral(const Polygon& P, const Vector& w,\n const Vector& v, int n) {\n // Init to zero\n Eigen::VectorXf b = Eigen::VectorXf::Zero(n+2);\n\n for(auto& edge : P) {\n // Compute the edge normal\n const auto normal = Vector::Normalize(Vector::Cross(edge.A, edge.B));\n\n // Add the egde integral to the total integral\n const auto dotNV = Vector::Dot(normal, v);\n const auto lineInt = LineIntegral(edge.A, edge.B, w, n);\n b += dotNV * lineInt;\n }\n\n return b;\n}\n\n/* _Solid Angle_\n *\n * Compute the solid angle sustained by a `Polygon P`.\n */\ntemplate\ninline float SolidAngle(const Polygon& P) {\n if(P.size() == 3) {\n // Using the method of Oosterom and Strackee [1983]\n const Vector& A = P[0].A;\n const Vector& B = P[1].A;\n const Vector& C = P[2].A;\n\n const Vector bc = Vector::Cross(B,C);\n const float num = std::abs(Vector::Dot(bc, A));\n const float al = Vector::Length(A);\n const float bl = Vector::Length(B);\n const float cl = Vector::Length(C);\n const float den = al*bl*cl\n + Vector::Dot(A, B)*cl\n + Vector::Dot(A, C)*bl\n + Vector::Dot(B, C)*al;\n\n float phi = atan2(num, den);\n if(phi < 0) {\n phi += M_PI;\n }\n return 2.0f * phi;\n\n } else {\n // Using the algorithm for computing solid angle of polyhedral cones by\n // Mazonka found in http://arxiv.org/pdf/1205.1396v2.pdf\n std::complex z(1, 0);\n for(unsigned int k=0; k 0) ? k-1 : P.size()-1].A;\n const Vector& B = P[k].A;\n const Vector& C = P[k].B;\n\n const float ak = Vector::Dot(A, C);\n const float bk = Vector::Dot(A, B);\n const float ck = Vector::Dot(B, C);\n const float dk = Vector::Dot(A, Vector::Cross(B, C));\n const std::complex zk(bk*ck-ak, dk);\n z *= zk;\n }\n const float arg = std::arg(z);\n return arg;\n }\n}\n\n/* _Check Polygon_\n *\n * Check if the Poylgon P is well oriented. For a triangle, the centroid of the\n * triangle `D` is computed as `A + B + C / 3` and compared to the normal of\n * the triangle using the orientation. The normal and the centroid must match\n * orientation for the normal of edges to be outwards.\n */\ntemplate\ninline bool CheckPolygon(const Polygon& P) {\n\n // A closed Polygon cannot be smaller than 3 Edges.\n if(P.size() < 3) {\n return false;\n\n // Special case for triangles.\n } else if(P.size() == 3) {\n // Check with respect to centroid\n const auto D = (P[0].A + P[1].A + P[2].A) / 3.0f;\n const auto N = Vector::Cross(P[1].A-P[0].A, P[2].A-P[0].A);\n return Vector::Dot(D, N) <= 0.0f;\n\n // General computation\n } else {\n // This is a heuristic to select a point on the bounding box of the\n // polygon. The orientation test is then computed on this particular\n // corner.\n unsigned int K = 0;\n const Vector* minX = &P[0].B;\n for(unsigned int k=1; kx < minX->x || (X->x <= minX->x && X->y < minX->y)) {\n minX = X;\n K = k;\n }\n }\n\n // Perform the test as defined on the Wikipedia page:\n // https://en.wikipedia.org/wiki/Curve_orientation\n const int K2 = (K < P.size()-1) ? K+1 : 0;\n const auto D = (P[K].A + P[K].B + P[K2].B) / 3.0f;\n const auto N = Vector::Cross(P[K].B-P[K].A, P[K2].B-P[K].A);\n const bool r = Vector::Dot(D, N) <= 0.0f;\n return r;\n }\n}\n\n/* _Axial Moments_\n *\n * input:\n * + Polygon P: A set of egdes that can be enumerated using iterators.\n Each edge must enable to access two Vector A and B.\n * + Vector w: A 3D vector with elements accessible as x,y,z this\n vector defines the axis on which to compute moments.\n * + int n: The maximum moment order to be computed.\n *\n * output:\n * + VectorX r: A vector containing all moments up to order 'n'\n */\ntemplate\ninline Eigen::VectorXf AxialMoment(const Polygon& P, const Vector& w, int n) {\n\n // Check if the polygon is well oriented\n const bool check = CheckPolygon(P);\n if(!check) {\n return Eigen::VectorXf::Zero(n+2);\n }\n\n // Arvo's boundary integral for single vector moment.\n Eigen::VectorXf a = - BoundaryIntegral(P, w, w, n);\n\n // Generate the 'b' vector which equals to the Polygon solid angle for\n // even moments and zero for odd moments.\n const int n2 = (n+2)/2;\n auto b = Eigen::Map>(a.data(), n2);\n b += Eigen::VectorXf::Constant(n2, SolidAngle(P));\n\n // 'c' is the vector of linear elements, storing 'i+1' for index 'i'\n auto c = Eigen::VectorXf::LinSpaced(n+2, 1, n+2);\n\n return a.cwiseQuotient(c);\n}\n\n/* _Axial Moments_\n *\n * Compute the axial moments for given set of directions used for lobe sharing\n * the maximum cosine order to compute the integral is a function of the size\n * of the directions list.\n */\ntemplate\ninline Eigen::VectorXf AxialMoments(const Polygon& P,\n const std::vector& directions) {\n\n const int dsize = directions.size();\n const int order = (dsize-1) / 2 + 1;\n\n Eigen::VectorXf result(dsize*order);\n\n for(int i=0; i(P, w, order-1);\n\n const int shift = i*order;\n result.segment(shift, order) = In.segment(0, order);\n }\n return result;\n}\n", "meta": {"hexsha": "714d6b42179bbddb5a5550804b569853fb429dbe", "size": 9328, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/AxialMoments.hpp", "max_stars_repo_name": "belcour/IntegralSH", "max_stars_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 48.0, "max_stars_repo_stars_event_min_datetime": "2018-02-27T07:07:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-08T04:40:06.000Z", "max_issues_repo_path": "include/AxialMoments.hpp", "max_issues_repo_name": "belcour/IntegralSH", "max_issues_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/AxialMoments.hpp", "max_forks_repo_name": "belcour/IntegralSH", "max_forks_repo_head_hexsha": "092bed8dc974f0f4c467f54a33d3e3e8968264ae", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-05-08T09:28:28.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-01T03:40:39.000Z", "avg_line_length": 31.3020134228, "max_line_length": 89, "alphanum_fraction": 0.5966981132, "num_tokens": 2739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045877523147, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6645936021626073}} {"text": "#include\n#include\n#include\n#include \n#include \n\nusing namespace dealii;\n\n// Computing matrix A times vector b, and using the A[0] to store the result and return it.\nstd::vector multiply(std::vector> A, std::vector b)\n{\n int m=A.size();\n int n=b.size();\n for (int i=0;i u, std::vector v)\n{\n if(u.size()!=v.size())\n {\n std::cout<<\"Multiply() ERROR: u'*v error! Please Check the size of u and v!\";\n }\n else\n {\n double sum=0;\n for(int i=0;i> transpose(std::vector> A)\n{\n int n=A.size();\n int m=A[0].size();\n if (n < m)\n {\n for (int i = 0; i < n; i++)\n\t {\n for (int j = 0; j < i; j++)\n\t {\n double temp = A[j][i];\n A[j][i] = A[i][j];\n A[i][j] = temp;\n\t }\n\t }\n for (int i = n; i < m; i++)\n\t {\n std::vector temp;\n for (int j = 0; j < n; j++)\n\t {\n temp.push_back(A[j][i]);\n\t }\n A.push_back(temp);\n\t }\n for (int i = 0; i < n; i++)\n\t {\n for (int j = n; j < m; j++)\n\t {\n A[i].pop_back();\n\t }\n\t }\n }\n else if(m> &A, std::vector> B)\n{\n int n = A.size();\n int m = B.size();\n int col = B[0].size();\n std::vector temp(m);\n std::vector> A0(n, temp);\n\n if (col < n)\n {\n for (int i = 0; i < n; i++)\n\t {\n for (int j = 0; j < col; j++)\n\t {\n double tempValue = 0;\n for (int t = 0; t < m; t++)\n\t\t {\n tempValue += A[i][t] * B[t][j];\n\t\t }\n A0[i][j] = tempValue;\n\t }\n for (int j = col; j < m; j++)\n\t {\n A0[i].pop_back();\n\t }\n\t }\n\n A = A0;\n }\n else\n {\n for (int i = 0; i > &Q, int n)\n{\n Q.clear();\n std::vector temp(n,0);\n for (int i=0;i x)\n{\n double norm=0;\n for (int i=0;i multiply(const SparseMatrix &A, std::vector x0)\n{\n std::vector x(x0.size(),0);\n // std::cout<<\"Flag 1!!\\n\";\n //std::cout<::const_iterator i=A.begin(k);\n\t \n\t while(i!=A.end(k))\n\t {\n\t x[k]+=i->value()*x0[i->column()];\n\t ++i;\n\t }\n\t}\n return x;\n }\n}\n\n\n//void Householder(std::vector> *A, std::vector> *P)\n//void Householder(std::vector> *A, std::vector> *P)\n\n// This function computes the householder process of the symmetric definite matrix, it return\n// two matrices. The tridiagonal matrix coordinating with A and the hermitian unitary matrix P.\nvoid Householder(std::vector> &A, std::vector> &P)\n{\n int n=A.size();\n std::vector> Pk;\n\n for(int k=0;k v(n-k,0), u(n-k,0), z(n-k,0);\n v[0]=0;\n v[1]=A[k+1][k]-alpha;\n\n //std::cout<<\"Check Point 3::: \"< temp(j-k,0);\n\t for(int i=k+1;i<=j;i++)\n\t {\n\t for(int t=k+1;t> &A, std::vector> &Q)\n{\n int n=A.size();\n\n // obtain the diagonal and subdiagonal entries of matrix A;\n /*\n std::vectoran(n),bn(n-1);\n for (int i=0;i> &A, std::vector> &Q, double tol=0.001)\n{\n int n=A.size();\n // using householder transform matrix A into the tridiagonal matrix\n // store it in A and store the Householder unitary matrix in Q; A=QA_Q; \n //Householder(A,Q);\n\n // Qk as the initial matrix for every QR factorization, multiplying it together to get the\n // final unitary matrix;\n std::vector> Qk;\n \n // Get the subdiagonal entries of the matrix A and verify if its norm smaller than the tolerance;\n // If it is small enough that means we diagonalize the matrix A and the diagonal entries are\n // eigenvalues of A.\n std::vector b(n-1,1);\n for(int i=0;itol&&num<1000)\n {\n num++;\n\n b.clear();\n\n Householder(A,Q);\n \n identitymatrix(Qk,n);\n\n QR(A,Qk);\n \n // Compute the num-th iteration, get the Qk in this step;\n multiply(Q,Qk);\n // compute R*Q beacuse I store the R(computed above) into A, So I directly use multiply\n // function to get A*Q into A=RQ.\n multiply(A,Qk);\n\n //update the entries of b, i.e. the subdiagonal entries of matrix A=RQ;\n for(int i=0;i A, SparseMatrix M, int p=1);\n\n // get the random initial matrix V which satisifies that: V'*M*V=I_p;\n std::vector>rand_V(); \n\n // compute the orthonormal vectors corresponding to M from the original vectors U={u_1,u_2,...,u_p};\n std::vector> M_GS(std::vector> U);\n \n // Compute the solution vector of the equation of X_k[i] and PAP*d_i=PA*X_k[i];\n std::vectorCG(std::vector X_ki);\n // get the p smallest eigenvalues of A correponding with M;\n std::vector min_trace(int max_iter, double eps);\n \n \n private:\n SparseMatrix A;\n SparseMatrix M;\n int p; // The number of the eigenvalues to be solved;\n};\n\nMinTrace::MinTrace()\n{\n int p=3;\n SparsityPattern sparsity_pattern(10,10,{2,3,3,3,3,3,3,3,3,2});\n SparsityPattern sp2(10,10,1);\n //sparsity_pattern.add(1,2);\n sparsity_pattern.add(0,1);\n sparsity_pattern.add(9,8);\n for (int i=1;i<9;i++)\n {\n sparsity_pattern.add(i,i+1);\n sparsity_pattern.add(i,i-1);\n }\n \n A.reinit(sparsity_pattern);\n M.reinit(sp2);\n\n for (int k=0;k::iterator i=A.begin(k);\n i->value()=2;\n while(i!=A.end(k))\n\t{\n\t i->value()+=1;\n\t ++i;\n\t}\n }\n\n SparseMatrix::iterator i=M.begin();\n double num=0;\n while(i!=M.end())\n {\n num=num+1;\n i->value()=num;\n ++i;\n }\n}\n\n// ATTENTION!!! There is a difficulty that SparseMatrix can not be copied directly!\nMinTrace::MinTrace(SparseMatrix A0, SparseMatrix M0, int p0)\n{\n \n};\n\nstd::vector> MinTrace::M_GS(std::vector> U)\n{\n std::vector> V;\n V=transpose(U);\n}\n\nstd::vector> MinTrace::rand_V()\n{\n std::cout<<\"CheckPoint1\\n\";\n std::vector x(M.n(),0);\n for (int i=0;i> V(p,x);\n std::cout<<\"CheckPoint12314113\\n\";\n \n V[0][0]=1;\n V[1][1]=sqrt(2.0)/2;\n V[2][2]=sqrt(3.0)/3;\n std::cout<<\"231wqrdasd24121321321321adsadq2q1312321sada\\n\";\n return V;\n}\n\nstd::vector MinTrace::min_trace(int max_iter=10, double eps=1e-03)\n{\n std::cout< x(p); // define the eigenvector;\n std::vector> V; // V is an n x p matrix and stored as V[p][n];\n\n V=rand_V();\n std::cout<<\"wewqewqewqewqeqw\\n\";\n // for(int k=0;k> VMV(p,x),tmpVMV(p); // VMV is a p x p matrix;\n std::cout<<\"AAAAAAAAAAAAAAAAAAAAAAAA\\n\";\n for(int i=0;i A, M;\n // std::ofstream sparsematrix1 (\"original_matrix.1\");\n //A.print(sparsematrix1);\n std::vector row_length(10,10);\n unsigned int t=3;\n SparsityPattern sparsity_pattern(10,10,{2,3,3,3,3,3,3,3,3,2});\n SparsityPattern sp2(10,10,1);\n //sparsity_pattern.add(1,2);\n sparsity_pattern.add(0,1);\n sparsity_pattern.add(9,8);\n for (int i=1;i<9;i++)\n {\n sparsity_pattern.add(i,i+1);\n sparsity_pattern.add(i,i-1);\n }\n \n A.reinit(sparsity_pattern);\n M.reinit(sp2);\n\n // In this way, I can construct a SparseMatrix to be the test data for the algorithm.\n for (int k=0;k::iterator i=A.begin(k);\n i->value()=2;\n while(i!=A.end(k))\n\t{\n\t i->value()+=1;\n\t ++i;\n\t}\n }\n\n SparseMatrix::iterator i=M.begin();\n double num=0;\n while(i!=M.end())\n {\n num=num+1;\n i->value()=num;\n ++i;\n }\n \n std::ofstream out (\"sparsity_pattern.1\");\n sparsity_pattern.print_gnuplot(out);\n\n std::ofstream sparsematrix (\"sparse_matrix.1\");\n A.print(sparsematrix);\n\n std::ofstream sparsematrix2 (\"sparse_matrix.2\");\n M.print(sparsematrix2); \n\n std::vector x(10,1);\n x=multiply(M,x);\n for(int i=0;i\n#include \n#include \n#include \n#include \n#include \n#include\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\n// 相机内参\nMat K = (Mat_(3,3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n\ntypedef vector> VecVector2d;\ntypedef vector> VecVector3d;\n\nvoid find_feature_matches(\n const Mat &img_1, const Mat &img_2,\n std::vector &keypoints_1,\n std::vector &keypoints_2,\n std::vector &matches);\n\nvoid bundleAdjustmentGaussNewton(const VecVector3d &points_3d, const VecVector2d &points_2d,\n const Mat &K, Sophus::SE3d &pose);\nvoid bundleAdjustmentG2O(const VecVector3d &points_3d, const VecVector2d &points_2d,\n const Mat &K, Sophus::SE3d &pose);\n\n\n// 像素坐标转相机归一化坐标\nPoint2d pixel2cam(const Point2d &p);\n\n\n\n\nint main(int argc, char **argv){\n\n // 读取图像\n Mat img_1 = imread(\"../1.png\", CV_LOAD_IMAGE_COLOR);\n Mat img_2 = imread(\"../2.png\", CV_LOAD_IMAGE_COLOR);\n assert(img_1.data && img_2.data);\n cout << \"读取图像 完成!\" << endl;\n\n\n // 特征点匹配\n cout << \"开始特征点匹配 ......\" << endl;\n vector keypoints_1, keypoints_2;\n vector matches;\n find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n cout << \"特征点匹配 完成! 一共找到了\" << matches.size() << \"组匹配点\" << endl << endl;\n // for (DMatch m:matches) {\n // cout << keypoints_1[m.queryIdx].pt.x << \" \" << keypoints_1[m.queryIdx].pt.y << endl;\n // }\n\n\n\n // 读取深度图,建立3D点\n Mat img_depth_1 = imread(\"../1_depth.png\", CV_LOAD_IMAGE_UNCHANGED);\n Mat img_depth_2 = imread(\"../2_depth.png\", CV_LOAD_IMAGE_UNCHANGED);\n\n vector points_3d;\n vector points_2d;\n\n for (DMatch m:matches){\n // ushort d = img_depth_1.ptr(int(keypoints_1[m.queryIdx].pt.y))[int(keypoints_1[m.queryIdx].pt.x)];\n ushort d = img_depth_1.at((int)keypoints_1[m.queryIdx].pt.y, (int)keypoints_1[m.queryIdx].pt.x);\n if (d==0) continue;\n float dd = d / 5000.0;\n Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt);\n points_3d.push_back(Point3f(p1.x * dd, p1.y * dd, dd));\n points_2d.push_back(keypoints_2[m.trainIdx].pt);\n }\n cout << \"Total number of valid 3d-2d pairs: \" << points_3d.size() << endl;\n\n\n cout << \"开始PnP求解 ......\" << endl;\n chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n Mat R, r, t;\n solvePnP(points_3d, points_2d, K, Mat(), r, t, false);\n cv::Rodrigues(r, R);\n cout << \"R = \" << endl << R << endl;\n cout << \"t = \" << t.t() << endl;\n chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n chrono::duration time_used = chrono::duration_cast>(t2 - t1);\n cout << \"solve pnp in opencv cost time: \" << time_used.count() << \" seconds.\" << endl;\n cout << endl;\n\n\n cout << \"开始手写G-N优化 ......\" << endl;\n VecVector3d points_3d_eig;\n VecVector2d points_2d_eig;\n for(size_t i=0; i>(t2 - t1);\n cout << \"pose by g-n: \" << endl << pose_gn.matrix() << endl;\n cout << \"solve pnp by gauss newton cost time: \" << time_used.count() << \" seconds.\" << endl << endl;\n\n\n cout << \"开始G2O优化 ......\" << endl;\n Sophus::SE3d pose_g2o(R_eig, t_eig);\n bundleAdjustmentG2O(points_3d_eig, points_2d_eig, K, pose_g2o);\n cout << \"pose by g2o: \" << endl << pose_gn.matrix() << endl;\n\n\n return 0;\n} \n\n\n\n\nvoid bundleAdjustmentGaussNewton(const VecVector3d &points_3d, const VecVector2d &points_2d,\n const Mat &K, Sophus::SE3d &pose){\n\n typedef Eigen::Matrix Vector6d;\n const int iterations = 10;\n double cost = 0, lastCost = 0;\n double fx = K.at(0, 0);\n double fy = K.at(1, 1);\n double cx = K.at(0, 2);\n double cy = K.at(1, 2);\n\n for (int iter=0; iter H = Matrix::Zero();\n Vector6d b = Vector6d::Zero();\n cost = 0;\n\n for (int i=0; i J;\n J << -fx * inv_z,\n 0,\n fx * pc[0] * inv_z2,\n fx * pc[0] * pc[1] * inv_z2,\n -fx - fx * pc[0] * pc[0] * inv_z2,\n fx * pc[1] * inv_z,\n 0,\n -fy * inv_z,\n fy * pc[1] * inv_z2,\n fy + fy * pc[1] * pc[1] * inv_z2,\n -fy * pc[0] * pc[1] * inv_z2,\n -fy * pc[0] * inv_z;\n\n H += J.transpose() * J;\n b += - J.transpose() * e;\n }\n\n Vector6d dx;\n dx = H.ldlt().solve(b);\n\n if (isnan(dx[0])){\n cout << \"result is nan!\" << endl;\n }\n\n if (iter > 0 && cost > lastCost){\n cout << \"the cost is larger than last cost!\";\n break;\n }\n\n pose *= Sophus::SE3d::exp(dx);\n lastCost = cost;\n\n cout << \"iteration \" << iter << \" cost=\" << cost << endl;\n\n if (dx.norm() < 1e-6){\n cout << \"have converge.\" << endl;\n break;\n }\n }\n}\n\n\n\n\n\n\nvoid find_feature_matches(\n const Mat &img_1, const Mat &img_2,\n std::vector &keypoints_1,\n std::vector &keypoints_2,\n std::vector &matches){\n\n Mat descriptors_1, descriptors_2;\n Ptr detector = ORB::create();\n Ptr descriptor = ORB::create();\n Ptr matcher = DescriptorMatcher::create(\"BruteForce-Hamming\");\n\n // --第一步:检测Oriented Fast角点位置\n detector->detect(img_1, keypoints_1);\n detector->detect(img_2, keypoints_2);\n cout << \"--第一步完成:检测Oriented Fast角点位置\" << endl;\n\n // --第二步:根据角点位置计算BRIEF描述子\n descriptor->compute(img_1, keypoints_1, descriptors_1);\n descriptor->compute(img_2, keypoints_2, descriptors_2);\n cout << \"--第二步完成:根据角点位置计算BRIEF描述子\" << endl;\n\n // -- 第三步:对两幅图像中的BRIEF描述子进行匹配,使用Hamming距离\n vector match;\n matcher->match(descriptors_1, descriptors_2, match);\n cout << \"--第三步完成:对两幅图像中的BRIEF描述子进行匹配,使用Hamming距离\" << endl;\n\n // --第四步:匹配点对 筛选\n auto min_max = minmax_element(match.begin(), match.end(),\n [] (const DMatch &m1, const DMatch &m2) {return m1.distance < m2.distance;});\n double min_dist = min_max.first->distance;\n double max_dist = min_max.second->distance;\n\n for (int i=0; i(0, 2)) / K.at(0, 0),\n (p.y - K.at(1, 2)) / K.at(1, 1)\n );\n}\n\n\n\n\n\n\n\n\n\n\n\n\nclass VertexPose: public g2o::BaseVertex<6, Sophus::SE3d>{\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n virtual void setToOriginImpl() override {\n _estimate = Sophus::SE3d();\n }\n\n virtual void oplusImpl(const double *update) override {\n Eigen::Matrix update_eigen;\n update_eigen << update[0], update[1], update[2], update[3], update[4], update[5];\n _estimate = Sophus::SE3d::exp(update_eigen) * _estimate;\n }\n\n virtual bool read(istream &in) override {}\n\n virtual bool write(ostream &out) const override {}\n};\n\n\nclass EdgeProjection: public g2o::BaseUnaryEdge<2, Vector2d, VertexPose>{\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n EdgeProjection(const Vector3d &pos, const Matrix3d &K): _pos3d(pos), _K(K){}\n\n virtual void computeError() override{\n const VertexPose *v = static_cast(_vertices[0]);\n Sophus::SE3d T = v->estimate();\n Vector3d pos_pixel = _K * (T * _pos3d);\n pos_pixel = pos_pixel / pos_pixel[2];\n _error = _measurement - pos_pixel.head<2>();\n }\n\n virtual void linearizeOplus() override {\n const VertexPose *v = static_cast(_vertices[0]);\n Sophus::SE3d T = v->estimate();\n Vector3d pos_cam = T * _pos3d;\n double fx = _K(0, 0);\n double fy = _K(1, 1);\n double cx = _K(0, 2);\n double cy = _K(1, 2);\n double X = pos_cam[0];\n double Y = pos_cam[1];\n double Z = pos_cam[2];\n double Z2 = Z * Z;\n _jacobianOplusXi\n << -fx / Z, 0, fx * X / Z2, fx * X * Y / Z2, -fx - fx * X * X / Z2, fx * Y / Z,\n 0, -fy / Z, fy * Y / (Z * Z), fy + fy * Y * Y / Z2, -fy * X * Y / Z2, -fy * X / Z;\n }\n\n virtual bool read(istream &in) override {}\n\n virtual bool write(ostream &out) const override {}\n\n private:\n Eigen::Vector3d _pos3d;\n Eigen::Matrix3d _K;\n};\n\n\nvoid bundleAdjustmentG2O(const VecVector3d &points_3d, const VecVector2d &points_2d,\n const Mat &K, Sophus::SE3d &pose){\n typedef g2o::BlockSolver> BlockSolverType;\n typedef g2o::LinearSolverDense LinearSolverType;\n\n auto solver = new g2o::OptimizationAlgorithmGaussNewton(\n g2o::make_unique(g2o::make_unique()));\n g2o::SparseOptimizer optimizer;\n optimizer.setAlgorithm(solver);\n optimizer.setVerbose(true);\n\n VertexPose *vertex_pose = new VertexPose();\n vertex_pose->setId(0);\n vertex_pose->setEstimate(Sophus::SE3d());\n optimizer.addVertex(vertex_pose);\n\n Matrix3d K_eigen;\n cv2eigen(K, K_eigen);\n\n for(size_t i=0; i < points_3d.size(); i++){\n auto p2d = points_2d[i];\n auto p3d = points_3d[i];\n EdgeProjection *edge = new EdgeProjection(p3d, K_eigen);\n edge->setId(i);\n edge->setVertex(0, vertex_pose);\n edge->setMeasurement(p2d);\n edge->setInformation(Matrix2d::Identity());\n optimizer.addEdge(edge);\n }\n\n chrono::steady_clock::time_point t1 = chrono::steady_clock::now();\n optimizer.initializeOptimization();\n optimizer.optimize(10);\n chrono::steady_clock::time_point t2 = chrono::steady_clock::now();\n chrono::duration time_used = chrono::duration_cast>(t2 - t1);\n cout << \"optimization costs time: \" << time_used.count() << \" seconds.\" << endl;\n pose = vertex_pose->estimate();\n}", "meta": {"hexsha": "8468cf3b35643303b40a0a0b2682da16aba31628", "size": 11108, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_implementation_1/ch7/pose_estimation_3d2d/pose_estimation_3d2d.cpp", "max_stars_repo_name": "Mingrui-Yu/slambook2", "max_stars_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-09T14:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-09T14:18:15.000Z", "max_issues_repo_path": "my_implementation_1/ch7/pose_estimation_3d2d/pose_estimation_3d2d.cpp", "max_issues_repo_name": "Mingrui-Yu/slambook2", "max_issues_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my_implementation_1/ch7/pose_estimation_3d2d/pose_estimation_3d2d.cpp", "max_forks_repo_name": "Mingrui-Yu/slambook2", "max_forks_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1029810298, "max_line_length": 120, "alphanum_fraction": 0.6380986676, "num_tokens": 3742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695283896349, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6644510443536438}} {"text": "/*\n EigenQP: Fast quadradic programming template library based on Eigen.\n \n From https://github.com/jarredbarber/eigen-QP\n \n MIT License\n\n Copyright (c) 2017 Jarred Barber\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n#ifndef _EIGEN_QP_H_\n#define _EIGEN_QP_H_\n\n#include \n\n/**\n * Solves quadradic programs with equality constraints\n * using direct matrix factorization of the KKT system.\n */\n\n\nnamespace EigenQP\n{\n\n// Default tolerance levels specialized on types\ntemplate t defTol();\ntemplate<>\n inline double defTol() { return 1E-9; }\ntemplate<>\n inline float defTol() { return 1E-4f; }\n\n/*\n * Solver for equality constrained problems.\n * The KKT conditions are linear here, so we just\n * invert with an LDLT decomposition.\n */\ntemplate\nclass QPEqSolver\n{\nprivate:\n const int n;\n const int m;\n\n static constexpr int NWork = \n ((NVars == -1) || (NEq == -1)) ? -1 : (NVars+NEq);\n Eigen::Matrix Z;\n Eigen::Matrix C;\n\npublic:\n QPEqSolver(int n_vars=NVars, int n_const=NEq) : n(n_vars),m(n_const),\n Z(n+m,n+m), C(n+m,1)\n {\n Z.block(n,n,m,m).setZero();\n }\n void solve(Eigen::Matrix &Q, Eigen::Matrix &c, \n Eigen::Matrix &A, Eigen::Matrix &b,\n Eigen::Matrix &x)\n {\n Z.block(0,0,n,n) = Q;\n Z.block(0,n,n,m) = A.adjoint();\n Z.block(n,0,m,n) = A;\n\n C.head(n) = -c;\n C.tail(m) = b;\n\n x = Z.ldlt().solve(C).head(n);\n }\n};\n\n/*\n * Solver for inequality constrained problems\n *\n * This uses a predictor-corrector interior point method from\n * \"Interior-Point Algorithms for Quadratic Programming\" by Thomas Kruth\n *\n * Some small notation changes from Kruth => this code:\n *\n * G => Q\n * g => c\n * A => A.adjoint() (i.e., the constraint matrix is transposed)\n * lambda => z\n */\ntemplate\nclass QPIneqSolver\n{\n typedef Eigen::Matrix PVec;\n typedef Eigen::Matrix DVec; // Dual (i.e., Lagrange multiplier) vector\n typedef Eigen::Matrix PMat;\nprivate:\n // Problem size\n const int n;\n const int m;\n \n // Work buffers\n DVec s;\n DVec z;\n\n PVec rd;\n DVec rp;\n DVec rs;\n\n PVec dx;\n DVec ds;\n DVec dz;\n\n PVec x;\n \npublic:\n // Parameters\n Scalar tolerance;\n int max_iters;\n\n QPIneqSolver(int n_vars=NVars, int n_const=NIneq) : n(n_vars),m(n_const), s(m), z(m), rd(n), rp(m), rs(m), dx(n), ds(m), dz(m)\n {\n tolerance = defTol();\n max_iters = 250;\n if (NVars == -1) {\n x.resize(n_vars);\n }\n if (NIneq == -1) {\n s.resize(n_const);\n z.resize(n_const);\n }\n }\n\n ~QPIneqSolver() {}\n\n void solve(Eigen::Matrix &Q, Eigen::Matrix &c, \n Eigen::Matrix &A, Eigen::Matrix &b,\n Eigen::Matrix &x_out)\n {\n const Scalar eta(0.95);\n const Scalar eps = tolerance;\n\n // Initialization\n s.setOnes();\n z.setOnes();\n x.setZero();\n\n // Initial residuals. Uses fact that x=0 here.\n rd = c - A.adjoint()*z;\n rp = s + b;\n rs = (s.array()*z.array());\n\n const Scalar ms = Scalar(1.0)/(Scalar)m;\n Scalar mu = (Scalar)n/((Scalar)m); // Initial mu based on knowing that s,z are ones.\n Scalar alpha;\n\n for (int iter=0; iter < max_iters; iter++)\n {\n // Precompute decompositions for this iteration\n Eigen::LLT Gbar = (Q + A.adjoint()*((z.array()/s.array()).matrix().asDiagonal())*A).llt();\n\n for (int ii=0; ii < 2; ii++)\n { \n // Prediction/correction step\n {\n auto tmp = (rs.array() - z.array()*rp.array())/s.array();\n dx = -Gbar.solve(rd + A.adjoint()*tmp.matrix());\n ds = A*dx - rp;\n dz.array() = -(rs.array() + z.array()*ds.array())/s.array();\n }\n\n // Compute alph,mu \n alpha = Scalar(1.0);\n for (int jj=0; jj < m; jj++)\n {\n Scalar a = -z(jj)/dz(jj);\n alpha = (a < alpha) && (a > 0) ? a : alpha;\n a = -s(jj)/ds(jj);\n alpha = (a < alpha) && (a > 0) ? a : alpha;\n }\n\n\n if (ii)\n break; // Don't need to compute any more\n\n // Centering \n Scalar mu_aff = (s + alpha*ds).dot(z + alpha*dz)*ms;\n Scalar sigma = mu_aff / mu;\n sigma *= sigma*sigma;\n\n // Corrector residual\n rs.array() += ds.array()*dz.array() - sigma*mu;\n }\n\n // Step\n alpha *= eta; // rescale step size\n x += alpha*dx;\n s += alpha*ds;\n z += alpha*dz;\n\n // Update residuals\n rd = Q*x + c - A*z;\n rp = s + A.adjoint()*x - b;\n rs = (s.array()*z.array());\n\n mu = s.dot(z)*ms;\n\n // Convergence test\n if ( (mu < eps) && \n (rd.norm() < eps) && \n (rs.norm() < eps) )\n {\n break;\n }\n }\n x_out = x;\n }\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n#if 0\n/**\n * General QPs with both equality and inequality constraints.\n * This doesn't currently work.\n */\ntemplate\nclass QPGenSolver\n{\n // Static size for work matrix.\n static constexpr int NWork = \n ((NVars == -1) || (NEq == -1) || (NIneq==-1)) ? -1 : (NVars+NEq+2*NIneq);\n typedef Eigen::Matrix PVec;\n typedef Eigen::Matrix DVec; // Dual (i.e., Lagrange multiplier) vector\n typedef Eigen::Matrix EVec; // Dual (i.e., Lagrange multiplier) vector for equality\n\n typedef Eigen::Matrix WorkBuf;\nprivate:\n\n // Problem size\n const int n;\n const int mi;\n const int me;\n\n // Work buffers\n DVec s;\n DVec z;\n EVec y; \n\n PVec rd;\n DVec rp;\n DVec rs;\n EVec ry;\n\n PVec dx;\n DVec ds;\n DVec dz;\n EVec dy;\n\n WorkBuf augSystem;\npublic:\n QPGenSolver(int n_vars=NVars, int n_const_eq=NEq, int n_const_ineq=NIneq) \n : n(n_vars),mi(n_const_ineq),me(n_const_eq), \n s(mi), z(mi), y(me), rd(n), rp(mi), rs(mi), \n ry(me), dx(n), ds(mi), dz(mi), dy(me),\n augSystem(2*mi+me+n,2*mi+me+n)\n {\n }\n\n ~QPGenSolver() {}\n\n void solve(Eigen::Matrix &Q, Eigen::Matrix &c, \n Eigen::Matrix &A, Eigen::Matrix &b,\n Eigen::Matrix &E, Eigen::Matrix &f,\n Eigen::Matrix &x)\n {\n \n }\n};\n#endif\n\ntemplate\nvoid quadprog(Eigen::Matrix &Q, Eigen::Matrix &c, \n Eigen::Matrix &A, Eigen::Matrix &b,\n Eigen::Matrix &x)\n{\n QPIneqSolver qp(c.size(),b.size());\n qp.solve(Q,c,A,b,x);\n}\n\n} // End namespace\n#endif\n", "meta": {"hexsha": "2356f3749e8c48fadc0cd3b37945c542b4288a51", "size": 8736, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "eigen-qp.hpp", "max_stars_repo_name": "jarredbarber/eigen-QP", "max_stars_repo_head_hexsha": "c319da488208b10be4f82f6887dea94e802766b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2015-09-23T20:00:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T16:40:24.000Z", "max_issues_repo_path": "eigen-qp.hpp", "max_issues_repo_name": "jarredbarber/eigen-QP", "max_issues_repo_head_hexsha": "c319da488208b10be4f82f6887dea94e802766b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-02-08T05:49:12.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-13T01:47:12.000Z", "max_forks_repo_path": "eigen-qp.hpp", "max_forks_repo_name": "jarredbarber/eigen-QP", "max_forks_repo_head_hexsha": "c319da488208b10be4f82f6887dea94e802766b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2018-02-07T15:55:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-01T06:43:00.000Z", "avg_line_length": 28.9271523179, "max_line_length": 130, "alphanum_fraction": 0.5549450549, "num_tokens": 2379, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952948443462, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6644510370217255}} {"text": "/* A namespace that extends Eigen to contain other necessary functions \n *\n * Author : Jonathan EDEN\n * Created : 2016\n * Description : A namepsace that extends the Eigen library\n*/\n\n#pragma once\n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\n// This is a namespace to add some necessary functions into.\nnamespace EigenExtension{\n /**\n * Skew symmetric matrix for cross product computation\n * @param v 3d Vector\n * @return skew symmetric matrix\n */\n Matrix3f SkewSymmetric(Vector3f v);\n /**\n * Skew symmetric matrix for cross product computation\n * @param v 3d Vector\n * @return skew symmetric matrix\n */\n Matrix3d SkewSymmetric2(Vector3d v);\n // Get the spline coefficients.\n Matrix GetLinearSplineCoefficients(float q_r_i, float q_r_ip1, double t);\n Matrix GetCubicSplineCoefficients(float q_r_i, float q_d_r_i,\n float q_r_ip1, float q_d_r_ip1, double t);\n Matrix GetQuinticSplineCoefficients(float q_r_i, float q_d_r_i, float q_dd_r_i,\n float q_r_ip1, float q_d_r_ip1, float q_dd_r_ip1, double t);\n // Interpolate the spline\n void LinearSplineInterpolate(float* q_r, float* q_d_r, float* q_dd_r, Matrix a, double t);\n void CubicSplineInterpolate(float* q_r, float* q_d_r, float* q_dd_r, Matrix a, double t); \n void QuinticSplineInterpolate(float* q_r, float* q_d_r, float* q_dd_r, Matrix a, double t);\n // Compute the rotation matrix\n Matrix3f ComputeRotationMatrix(AngleAxisf a);\n // Compute the derivative of a rotation matrix\n Matrix3f ComputeRotationMatrixDeriv(AngleAxisf a, AngleAxisf a_d);\n // Compute the double derivative of a rotation matrix\n Matrix3f ComputeRotationMatrixDoubleDeriv(AngleAxisf a, AngleAxisf a_d, AngleAxisf a_dd);\n /**\n * Pseudo inverse matrix\n * @param A\n * @return Pseudo inverse matrix\n */\n MatrixXf Pinv(MatrixXf A);\n /**\n * Pseudo inverse matrix\n * @param A\n * @return Pseudo inverse matrix\n */\n MatrixXd Pinv(MatrixXd A);\n\n //MatrixXf LeftPseudoInverse(MatrixXf A);\n //MatrixXf RightMatrixPseudoInverse(MatrixXf A);\n}", "meta": {"hexsha": "509191db6b39d389d4a1367098efe0019f06713b", "size": 2282, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/kindyn/include/kindyn/EigenExtension.hpp", "max_stars_repo_name": "NexusReflex/VRpuppet", "max_stars_repo_head_hexsha": "0b6a14e13951ceaf849b09da1f8dd797a4a1125d", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-11-12T09:58:35.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-31T02:52:54.000Z", "max_issues_repo_path": "src/kindyn/include/kindyn/EigenExtension.hpp", "max_issues_repo_name": "NexusReflex/VRpuppet", "max_issues_repo_head_hexsha": "0b6a14e13951ceaf849b09da1f8dd797a4a1125d", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-12-02T14:31:10.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-06T12:10:06.000Z", "max_forks_repo_path": "src/kindyn/include/kindyn/EigenExtension.hpp", "max_forks_repo_name": "NexusReflex/VRpuppet", "max_forks_repo_head_hexsha": "0b6a14e13951ceaf849b09da1f8dd797a4a1125d", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-12-02T09:55:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-08T11:54:30.000Z", "avg_line_length": 38.0333333333, "max_line_length": 142, "alphanum_fraction": 0.6958808063, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681158979307, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6644129255775039}} {"text": "/* @copyright The code is licensed under the MIT License\n * ,\n * Copyright (c) 2020 Christian Eskil Vaugelade Berg\n * @author Christian Eskil Vaugelade Berg\n*/\n#pragma once\n\n#include \n#include \n\nnamespace orient::detail {\n\ntemplate\nstd::pair asinWD(Scalar x)\n{\n return std::make_pair(std::asin(x), 1.0 / std::sqrt(1.0 - x*x));\n}\n\ntemplate\nstd::pair acosWD(Scalar x)\n{\n return std::make_pair(std::acos(x), -1.0 / std::sqrt(1.0 - x*x));\n}\n\n\ntemplate\nstd::tuple atan2WD(Scalar y, Scalar x)\n{\n const auto norm = x*x + y*y;\n const auto Jy = x / norm;\n const auto Jx = - y / norm;\n return std::make_tuple(std::atan2(y, x), Jy, Jx);\n}\n\ntemplate::Scalar>\nstd::pair, Eigen::Matrix> transposeWD(Eigen::MatrixBase const& M)\n{\n Eigen::Matrix J = Eigen::Matrix::Identity();\n J.col(1).swap(J.col(3));\n J.col(2).swap(J.col(6));\n J.col(5).swap(J.col(7));\n return std::make_pair(M.transpose(), J);\n}\n\ntemplate::Scalar>\nstd::pair> traceWD(Eigen::MatrixBase const& M)\n{\n Eigen::Matrix J;\n J << 1,0,0,0,1,0,0,0,1;\n return std::make_pair(M.trace(), J);\n}\n\n}\n", "meta": {"hexsha": "7d5242578c7eacb272a76ad3eb5c20751a70d7de", "size": 1509, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/orient/detail/derivative_helpers.hpp", "max_stars_repo_name": "Eskilade/orient", "max_stars_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T07:27:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-10T09:23:29.000Z", "max_issues_repo_path": "include/orient/detail/derivative_helpers.hpp", "max_issues_repo_name": "Eskilade/orient", "max_issues_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-09-20T02:22:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-21T01:42:47.000Z", "max_forks_repo_path": "include/orient/detail/derivative_helpers.hpp", "max_forks_repo_name": "Eskilade/orient", "max_forks_repo_head_hexsha": "d73e9459155e991539c20bfd92c04cb487b65538", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-09-14T11:11:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-10T04:26:22.000Z", "avg_line_length": 27.9444444444, "max_line_length": 114, "alphanum_fraction": 0.6706428098, "num_tokens": 469, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6644129070323158}} {"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University. \n// 2008 Dresden University of Technology and the Trustees of Indiana University.\n// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com. \n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#include \n#include \n\n#undef VERSION\n#define VERSION 3\n\nusing namespace std;\nusing namespace mtl;\n\ndense_vector inline last_unit_vector(size_t n)\n{\n dense_vector v(n, 0.0);\n v[n-1]= 1;\n return v;\n}\n\ndense_vector inline unit_vector(size_t k, size_t n)\n{\n dense_vector v(n, 0.0);\n v[k]= 1;\n return v;\n}\n\n#if VERSION == 1\n\ndense2D inline inverse_upper(dense2D const& A)\n{\n const size_t N= num_rows(A);\n assert(num_cols(A) == N); // Matrix must be square\n\n dense2D Inv(N, N);\n\n for (size_t k= 0; k < N; ++k) {\n\tdense_vector e_k(N);\n\tfor (size_t i= 0; i < N; ++i)\n\t if (i == k) \n\t\te_k[i]= 1.0;\n\t else\n\t\te_k[i]= 0.0; \n\n\tdense_vector res_k(N);\n\tres_k= upper_trisolve(A, e_k);\n\n\tfor (size_t i= 0; i < N; ++i)\n\t Inv[i][k]= res_k[i];\n }\n return Inv;\n}\n\n#elif VERSION == 2\n\ndense2D inverse_upper(dense2D const& A)\n{\n const size_t N= num_rows(A);\n assert(num_cols(A) == N); // Matrix must be square\n\n dense2D Inv(N, N);\n\n for (size_t k= 0; k < N; ++k) {\n\tdense_vector e_k(N);\n\tfor (size_t i= 0; i < N; ++i)\n\t e_k[i]= i == k ? 1.0 : 0.0;\n\n\tfor (size_t i= 0; i < N; ++i)\n\t Inv[i][k]= upper_trisolve(A, e_k)[i];\n }\n return Inv;\n}\n\n#elif VERSION == 3\n\ndense2D inverse_upper(dense2D const& A)\n{\n const size_t N= num_rows(A);\n assert(num_cols(A) == N); // Matrix must be square\n\n dense2D Inv(N, N);\n Inv= 0;\n\n for (size_t k= 0; k < N; ++k) {\n\tirange r(0, k+1);\n\tInv[r][k]= upper_trisolve(A[r][r], unit_vector(k, k+1));\n }\n return Inv;\n}\n\n#endif\n\ndense2D inline inverse_lower(dense2D const& A)\n{\n dense2D T(trans(A));\n return dense2D(trans(inverse_upper(T)));\n}\n\ndense2D inline inverse(dense2D const& A)\n{\n assert(num_cols(A) == num_rows(A)); // Matrix must be square\n\n dense2D PLU(A);\n dense_vector Pv(num_rows(A));\n\n lu(PLU, Pv);\n dense2D I(num_rows(A), num_cols(A));\n I= 1;\n dense2D PU(upper(PLU)), \n PL(strict_lower(PLU) + I);\n\n return dense2D(inverse_upper(PU) * inverse_lower(PL) * permutation(Pv));\n}\n\n\n\nint main(int, char**)\n{\n const unsigned size= 3;\n typedef dense2D Matrix;\n Matrix A(size, size);\n A= 4, 1, 2, \n\t1, 5, 3,\n\t2, 6, 9; \n\n cout << \"A is:\\n\" << A;\n\n Matrix LU(A);\n mtl::dense_vector Pv(size);\n lu(LU, Pv);\n\n Matrix P(permutation(Pv));\n cout << \"Permutation vector is \" << Pv << \"\\nPermutation matrix is\\n\" << P;\n\n cout << \"Permuted A is \\n\" << Matrix(P * A);\n Matrix I(size, size); I= 1;\n //Matrix I(mat::identity(size, size)), L(I + strict_lower(LU)), U(upper(LU));\n Matrix L(I + strict_lower(LU)), U(upper(LU));\n\n Matrix UI(inverse_upper(U));\n cout << \"inverse(U) [permuted] is:\\n\" << UI << \"UI * U is:\\n\" << Matrix(UI * U);\n assert(one_norm(Matrix(UI * U - I)) < 0.1);\n \n Matrix LI(inverse_lower(L));\n cout << \"inverse(L) [permuted] is:\\n\" << LI << \"LI * L is:\\n\" << Matrix(LI * L);\n assert(one_norm(Matrix(LI * L - I)) < 0.1);\n\n\n Matrix AI(UI * LI * P);\n cout << \"inverse(A) [UI * LI * P] is \\n\" << AI << \"A * AI is\\n\" << Matrix(AI * A);\n assert(one_norm(Matrix(AI * A - I)) < 0.1);\n \n Matrix A_inverse(inverse(A));\n cout << \"inverse(A) is \\n\" << A_inverse << \"A * AI is\\n\" << Matrix(A_inverse * A);\n assert(one_norm(Matrix(A_inverse * A - I)) < 0.1);\n\n Matrix A_e(inv(A));\n cout << \"inv(A) is \\n\" << A_e << \"\\n\";\n \n return 0;\n}\n", "meta": {"hexsha": "094ad4c9bd7062a2b586c595382a2eb5435c9727", "size": 4095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/inverse_matrix.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/inverse_matrix.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/inverse_matrix.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 24.0882352941, "max_line_length": 94, "alphanum_fraction": 0.5868131868, "num_tokens": 1356, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357460591568, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6644039712782871}} {"text": "#include \n#include \n\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char *argv[])\n{\n // Initialize matrix for initializer list\n auto A = mat{{1.0,2.0,3.0},{4.0, 5.0,6.0},{7.0, 8.0, 9.0}};\n cout << A << endl;\n\n // Zero filled matrix and direct element\n // initialization \n auto B = mat(3,3, fill::ones);\n B(1,1) = 10;\n cout << B << endl;\n\n // Elementwise multiplication\n auto C = A % B;\n\n\n auto b = vec{6.0, 60.0, 24.0};\n\n auto x = solve(C,b);\n\n cout << x << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "b81e6b217f7d457b377a6fce3edb389caff15c1b", "size": 543, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example_01/armasample01.cpp", "max_stars_repo_name": "putanowr/ArmadilloDrill", "max_stars_repo_head_hexsha": "33e3de2bc704c4ad627b7f7c0bb307cdd62849d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example_01/armasample01.cpp", "max_issues_repo_name": "putanowr/ArmadilloDrill", "max_issues_repo_head_hexsha": "33e3de2bc704c4ad627b7f7c0bb307cdd62849d7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example_01/armasample01.cpp", "max_forks_repo_name": "putanowr/ArmadilloDrill", "max_forks_repo_head_hexsha": "33e3de2bc704c4ad627b7f7c0bb307cdd62849d7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.5161290323, "max_line_length": 62, "alphanum_fraction": 0.5727440147, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6643213651763135}} {"text": "#ifndef OCC_RAYCASTING_HPP_7K2XI8HT\n#define OCC_RAYCASTING_HPP_7K2XI8HT\n\n#include \n\n#include \n\n#include \"scrollgrid/grid_types.hpp\"\n#include \"scrollgrid/scrollgrid3.hpp\"\n#include \"scrollgrid/dense_array3.hpp\"\n\n#include \n\nnamespace ca\n{\n\nstatic const int32_t CA_SG_COMPLETELY_FREE = 0;\nstatic const int32_t CA_SG_COMPLETELY_OCCUPIED = 255; //250\nstatic const int32_t CA_SG_BELIEF_UPDATE_POS = 20; // when hit\nstatic const int32_t CA_SG_BELIEF_UPDATE_NEG = 10; // when pass-through 2\n\ntemplate\nvoid occupancy_trace(const Vec3Ix& start_pos,\n const Vec3Ix& end_pos,\n const TraceFunctor& fun) {\n // beware: vec3ix are int64_t\n int x = start_pos[0],\n y = start_pos[1],\n z = start_pos[2];\n int dx = end_pos[0] - start_pos[0],\n dy = end_pos[1] - start_pos[1],\n dz = end_pos[2] - start_pos[2];\n int sx, sy, sz;\n //X\n if ( dx>0 ) {\n sx = 1;\n } else if ( dx<0 ) {\n sx = -1;\n dx = -dx;\n } else {\n sx = 0;\n }\n\n //Y\n if ( dy>0 ) {\n sy = 1;\n } else if ( dy<0 ) {\n sy = -1;\n dy = -dy;\n } else {\n sy = 0;\n }\n\n //Z\n if ( dz>0 ) {\n sz = 1;\n } else if ( dz<0 ) {\n sz = -1;\n dz = -dz;\n } else {\n sz = 0;\n }\n\n int ax = 2*dx,\n ay = 2*dy,\n az = 2*dz;\n\n if ( ( dy <= dx ) && ( dz <= dx ) ) {\n for (int decy=ay-dx, decz=az-dx;\n ;\n x+=sx, decy+=ay, decz+=az) {\n //SetP ( grid,x,y,z,end_pos, atMax, count);\n fun(x,y,z,false);\n //Bresenham step\n if ( x==end_pos[0] ) break;\n if ( decy>=0 ) {\n decy-=ax;\n y+=sy;\n }\n if ( decz>=0 ) {\n decz-=ax;\n z+=sz;\n }\n }\n } else if ( ( dx <= dy ) && ( dz <= dy ) ) {\n //dy>=dx,dy\n for (int decx=ax-dy,decz=az-dy;\n ;\n y+=sy,decx+=ax,decz+=az ) {\n // SetP ( grid,x,y,z,end_pos, atMax, count);\n fun(x,y,z,false);\n //Bresenham step\n if ( y==end_pos[1] ) break;\n if ( decx>=0 ) {\n decx-=ay;\n x+=sx;\n }\n if ( decz>=0 ) {\n decz-=ay;\n z+=sz;\n }\n }\n } else if ( ( dx <= dz ) && ( dy <= dz ) ) {\n //dy>=dx,dy\n for (int decx=ax-dz,decy=ay-dz;\n ;\n z+=sz,decx+=ax,decy+=ay ) {\n //SetP ( grid,x,y,z,end_pos, atMax, count);\n fun(x,y,z,false);\n //Bresenham step\n if ( z==end_pos[2] ) break;\n if ( decx>=0 ) {\n decx-=az;\n x+=sx;\n } if ( decy>=0 ) {\n decy-=az;\n y+=sy;\n }\n }\n }\n fun(x,y,z,true);\n}\n\ntemplate\nvoid occupancy_trace_dist(const Vec3Ix& start_pos,\n const Vec3Ix& end_pos,\n const TraceFunctor& fun,\n\t\t double distance) { //TODO add distance\n // beware: vec3ix are int64_t\n int x = start_pos[0],\n y = start_pos[1],\n z = start_pos[2];\n int dx = end_pos[0] - start_pos[0],\n dy = end_pos[1] - start_pos[1],\n dz = end_pos[2] - start_pos[2];\n int sx, sy, sz;\n //X\n if ( dx>0 ) {\n sx = 1;\n } else if ( dx<0 ) {\n sx = -1;\n dx = -dx;\n } else {\n sx = 0;\n }\n\n //Y\n if ( dy>0 ) {\n sy = 1;\n } else if ( dy<0 ) {\n sy = -1;\n dy = -dy;\n } else {\n sy = 0;\n }\n\n //Z\n if ( dz>0 ) {\n sz = 1;\n } else if ( dz<0 ) {\n sz = -1;\n dz = -dz;\n } else {\n sz = 0;\n }\n\n int ax = 2*dx,\n ay = 2*dy,\n az = 2*dz;\n\n if ( ( dy <= dx ) && ( dz <= dx ) ) {\n for (int decy=ay-dx, decz=az-dx;\n ;\n x+=sx, decy+=ay, decz+=az) {\n //SetP ( grid,x,y,z,end_pos, atMax, count);\n// fun(x,y,z,false,distance);\n distance=sqrt((x-start_pos[0])*(x-start_pos[0])+(y-start_pos[1])*(y-start_pos[1])+(z-start_pos[2])*(z-start_pos[2]));\n fun(x,y,z,false,distance);\n //Bresenham step\n if ( x==end_pos[0] ) break;\n if ( decy>=0 ) {\n decy-=ax;\n y+=sy;\n }\n if ( decz>=0 ) {\n decz-=ax;\n z+=sz;\n }\n }\n } else if ( ( dx <= dy ) && ( dz <= dy ) ) {\n //dy>=dx,dy\n for (int decx=ax-dy,decz=az-dy;\n ;\n y+=sy,decx+=ax,decz+=az ) {\n // SetP ( grid,x,y,z,end_pos, atMax, count);\n// fun(x,y,z,false,distance);\n distance=sqrt((x-start_pos[0])*(x-start_pos[0])+(y-start_pos[1])*(y-start_pos[1])+(z-start_pos[2])*(z-start_pos[2]));\n fun(x,y,z,false,distance);\n //Bresenham step\n if ( y==end_pos[1] ) break;\n if ( decx>=0 ) {\n decx-=ay;\n x+=sx;\n }\n if ( decz>=0 ) {\n decz-=ay;\n z+=sz;\n }\n }\n } else if ( ( dx <= dz ) && ( dy <= dz ) ) {\n //dy>=dx,dy\n for (int decx=ax-dz,decy=ay-dz;\n ;\n z+=sz,decx+=ax,decy+=ay ) {\n //SetP ( grid,x,y,z,end_pos, atMax, count);\n// fun(x,y,z,false,distance);\n distance=sqrt((x-start_pos[0])*(x-start_pos[0])+(y-start_pos[1])*(y-start_pos[1])+(z-start_pos[2])*(z-start_pos[2]));\n fun(x,y,z,false,distance);\n //Bresenham step\n if ( z==end_pos[2] ) break;\n if ( decx>=0 ) {\n decx-=az;\n x+=sx;\n } if ( decy>=0 ) {\n decy-=az;\n y+=sy;\n }\n }\n }\n// fun(x,y,z,true,distance);\n distance=sqrt((x-start_pos[0])*(x-start_pos[0])+(y-start_pos[1])*(y-start_pos[1])+(z-start_pos[2])*(z-start_pos[2]));\n fun(x,y,z,true,distance);\n}\n/**\n * Update occupancy information along ray.\n */\ntemplate\nvoid occupancy_trace_simple(const Vec3Ix& start_pos, // in ijk\n const Vec3Ix& end_pos, // in ijk\n const ca::ScrollGrid3& grid3,\n ca::DenseArray3& array3)\n {\n //int ray_ctr = 0;\n // beware: vec3ix are int64_t\n int x = start_pos[0],\n y = start_pos[1],\n z = start_pos[2];\n int dx = end_pos[0] - start_pos[0],\n dy = end_pos[1] - start_pos[1],\n dz = end_pos[2] - start_pos[2];\n int sx, sy, sz;\n //X\n if ( dx>0 ) {\n sx = 1;\n } else if ( dx<0 ) {\n sx = -1;\n dx = -dx;\n } else {\n sx = 0;\n }\n\n //Y\n if ( dy>0 ) {\n sy = 1;\n } else if ( dy<0 ) {\n sy = -1;\n dy = -dy;\n } else {\n sy = 0;\n }\n\n //Z\n if ( dz>0 ) {\n sz = 1;\n } else if ( dz<0 ) {\n sz = -1;\n dz = -dz;\n } else {\n sz = 0;\n }\n\n int ax = 2*dx,\n ay = 2*dy,\n az = 2*dz;\n\n if ( ( dy <= dx ) && ( dz <= dx ) ) {\n // this is tracing loop. we step through the ray in integer coordinates\n // until we reach the end\n for (int decy=ay-dx, decz=az-dx;\n ;\n x+=sx, decy+=ay, decz+=az) {\n\n // here we are in the middle of tracing the\n // ray. here we are passing through.\n mem_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n\n // by definition here we are passing through\n // TODO correct & efficent boundary check\n int32_t new_value = static_cast(array3[mem_ix])-CA_SG_BELIEF_UPDATE_NEG;\n array3[mem_ix] = static_cast(std::max(CA_SG_COMPLETELY_FREE, new_value));\n\n //Bresenham step\n if ( x==end_pos[0] ) break;\n if ( decy>=0 ) {\n decy-=ax;\n y+=sy;\n }\n if ( decz>=0 ) {\n decz-=ax;\n z+=sz;\n }\n }\n } else if ( ( dx <= dy ) && ( dz <= dy ) ) {\n //dy>=dx,dy\n for (int decx=ax-dy,decz=az-dy;\n ;\n y+=sy,decx+=ax,decz+=az ) {\n\n mem_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n int32_t new_value = static_cast(array3[mem_ix])-CA_SG_BELIEF_UPDATE_NEG;\n array3[mem_ix] = static_cast(std::max(CA_SG_COMPLETELY_FREE, new_value));\n\n //Bresenham step\n if ( y==end_pos[1] ) break;\n if ( decx>=0 ) {\n decx-=ay;\n x+=sx;\n }\n if ( decz>=0 ) {\n decz-=ay;\n z+=sz;\n }\n }\n } else if ( ( dx <= dz ) && ( dy <= dz ) ) {\n //dy>=dx,dy\n for (int decx=ax-dz,decy=ay-dz;\n ;\n z+=sz,decx+=ax,decy+=ay ) {\n\n mem_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n int32_t new_value = static_cast(array3[mem_ix])-CA_SG_BELIEF_UPDATE_NEG;\n array3[mem_ix] = static_cast(std::max(CA_SG_COMPLETELY_FREE, new_value));\n\n //array3[mem_ix] = ray_ctr++;\n //Bresenham step\n if ( z==end_pos[2] ) break;\n if ( decx>=0 ) {\n decx-=az;\n x+=sx;\n } if ( decy>=0 ) {\n decy-=az;\n y+=sy;\n }\n }\n }\n\n // here we are at the end of the ray.\n // here we update according to xyz\n\n mem_ix_t mem_ix = grid3.grid_to_mem(x, y, z);\n int32_t new_value = static_cast(array3[mem_ix])+CA_SG_BELIEF_UPDATE_POS;\n array3[mem_ix] = static_cast(std::min(CA_SG_COMPLETELY_OCCUPIED, new_value));\n\n}\n} /* ca\n */\n\n#endif /* end of include guard: OCC_RAYCASTING_HPP_7K2XI8HT */\n\n", "meta": {"hexsha": "a6657900b9fcfca175dca992d9eef3b2e30b47f7", "size": 8722, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dependency/scrollgrid/include/scrollgrid/occ_raycasting.hpp", "max_stars_repo_name": "ganlumomo/semantic_3d_mapping", "max_stars_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 146.0, "max_stars_repo_stars_event_min_datetime": "2018-03-15T13:54:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T07:37:55.000Z", "max_issues_repo_path": "dependency/scrollgrid/include/scrollgrid/occ_raycasting.hpp", "max_issues_repo_name": "ganlumomo/semantic_3d_mapping", "max_issues_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2018-04-28T09:33:00.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-08T23:46:00.000Z", "max_forks_repo_path": "dependency/scrollgrid/include/scrollgrid/occ_raycasting.hpp", "max_forks_repo_name": "ganlumomo/semantic_3d_mapping", "max_forks_repo_head_hexsha": "c6d2cebd26d4c08ac3f32fe151cf1db7f2d24fe5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 62.0, "max_forks_repo_forks_event_min_datetime": "2018-03-21T06:54:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T07:27:42.000Z", "avg_line_length": 23.572972973, "max_line_length": 123, "alphanum_fraction": 0.4926622334, "num_tokens": 3083, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942261220292, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6642832373797828}} {"text": "#include \"QuarticPolynomial.h\"\n\n#include \n#include \n\nusing namespace Eigen;\n\nQuarticPolynomial::QuarticPolynomial(double xs, double vxs, double axs,\n double vxe, double axe, double t):\n a0(xs), a1(vxs) {\n a2 = axs / 2.0;\n Matrix2d A;\n Vector2d B;\n A << 3 * pow(t, 2), 4 * pow(t, 3), 6 * t, 12 * pow(t, 2);\n B << vxe - a1 - 2 * a2 * t, axe - 2 * a2;\n Matrix2d A_inv = A.inverse();\n Vector2d x = A_inv * B;\n a3 = x[0];\n a4 = x[1];\n}\n\ndouble QuarticPolynomial::calc_point(double t) {\n return a0 + a1 * t + a2 * pow(t, 2) + a3 * pow(t, 3) + a4 * pow(t, 4);\n}\n\ndouble QuarticPolynomial::calc_first_derivative(double t) {\n return a1 + 2 * a2 * t + 3 * a3 * pow(t, 2) + 4 * a4 * pow(t, 3);\n}\n\ndouble QuarticPolynomial::calc_second_derivative(double t) {\n return 2 * a2 + 6 * a3 * t + 12 * a4 * pow(t, 2);\n}\n\ndouble QuarticPolynomial::calc_third_derivative(double t) {\n return 6 * a3 + 24 * a4 * t;\n}", "meta": {"hexsha": "976bd930199abcb3ed99dafa29262ef588d94ee6", "size": 962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Polynomials/QuarticPolynomial.cpp", "max_stars_repo_name": "shiveshkhaitan/frenet_optimal_trajectory_planner", "max_stars_repo_head_hexsha": "90443cf62c61f78ac0dde9507fc61e34a84136d4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 66.0, "max_stars_repo_stars_event_min_datetime": "2020-04-11T16:44:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T04:56:27.000Z", "max_issues_repo_path": "src/Polynomials/QuarticPolynomial.cpp", "max_issues_repo_name": "shiveshkhaitan/frenet_optimal_trajectory_planner", "max_issues_repo_head_hexsha": "90443cf62c61f78ac0dde9507fc61e34a84136d4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2020-05-16T11:57:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-08T07:54:17.000Z", "max_forks_repo_path": "src/Polynomials/QuarticPolynomial.cpp", "max_forks_repo_name": "shiveshkhaitan/frenet_optimal_trajectory_planner", "max_forks_repo_head_hexsha": "90443cf62c61f78ac0dde9507fc61e34a84136d4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 35.0, "max_forks_repo_forks_event_min_datetime": "2020-04-28T06:02:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-16T08:13:23.000Z", "avg_line_length": 26.7222222222, "max_line_length": 74, "alphanum_fraction": 0.5831600832, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6642529046314467}} {"text": "#include \"PoseEstimator.h\"\n#include \"PoseOptimizer.h\"\n\n#include \n#include \n#include \n\n#include \n\nnamespace MVSO\n{\n\tvoid solveICP(std::vector& points3D_t0, std::vector& points3D_t1, cv::Mat& R, cv::Mat& t)\n\t{\n\t\tcv::Point3f p1, p2; // center of mass\n\t\tint N = points3D_t0.size();\n\t\tfor (int i = 0; i < N; i++)\n\t\t{\n\t\t\tp1 += points3D_t0[i];\n\t\t\tp2 += points3D_t1[i];\n\t\t}\n\t\tp1 = cv::Point3f(cv::Vec3f(p1) / N);\n\t\tp2 = cv::Point3f(cv::Vec3f(p2) / N);\n\t\tstd::vector q1(N), q2(N); // remove the center\n\t\tfor (int i = 0; i < N; i++)\n\t\t{\n\t\t\tq1[i] = points3D_t0[i] - p1;\n\t\t\tq2[i] = points3D_t1[i] - p2;\n\t\t}\n\n\t\t// compute q1*q2^T\n\t\tEigen::Matrix3d W = Eigen::Matrix3d::Zero();\n\t\tfor (int i = 0; i < N; i++)\n\t\t{\n\t\t\tW += Eigen::Vector3d(q1[i].x, q1[i].y, q1[i].z) * Eigen::Vector3d(q2[i].x, q2[i].y, q2[i].z).transpose();\n\t\t}\n\n\t\t// SVD on W\n\t\tEigen::JacobiSVD svd(W, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\t\tEigen::Matrix3d U = svd.matrixU();\n\t\tEigen::Matrix3d V = svd.matrixV();\n\n\t\tif (U.determinant() * V.determinant() < 0)\n\t\t{\n\t\t\tfor (int x = 0; x < 3; ++x)\n\t\t\t{\n\t\t\t\tU(x, 2) *= -1;\n\t\t\t}\n\t\t}\n\n\t\tEigen::Matrix3d R_ = U * (V.transpose());\n\t\tEigen::Vector3d t_ = Eigen::Vector3d(p1.x, p1.y, p1.z) - R_ * Eigen::Vector3d(p2.x, p2.y, p2.z);\n\n\t\tcv::eigen2cv(R_, R);\n\t\tcv::eigen2cv(t_, t);\n\t}\n\n\n\tvoid solveICPRansac(std::vector& pts1, std::vector& pts2,\n\t\tcv::Mat& R, cv::Mat& t,std::vector& inliers,\n\t\tint iterationCount, float reprojectionError)\n\t{\n\t\tcv::Mat bestR = (cv::Mat_(3, 3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);\n\t\tcv::Mat bestT = (cv::Mat_(3, 1) << 0, 0, 0);\n\t\tstd::vector bestInliers;\n\t\tcv::Mat ptsMat1(pts1);\n\t\tcv::Mat ptsMat2(pts2);\n\t\tfor (int it = 0; it < iterationCount; it++)\n\t\t{\n\t\t\tstd::vector subset1;\n\t\t\tstd::vector subset2;\n\t\t\tfor (int i = 0; i < 5; i++)\n\t\t\t{\n\t\t\t\tint id = rand() % pts1.size();\n\n\t\t\t\tsubset1.push_back(pts1[id]);\n\t\t\t\tsubset2.push_back(pts2[id]);\n\t\t\t}\n\n\t\t\tcv::Mat tmpR, tmpT;\n\t\t\tsolveICP(subset1, subset2, tmpR, tmpT);\n\n\t\t\tstd::vector inliers;\n\t\t\tfor (int i = 0; i < pts1.size(); i++)\n\t\t\t{\n\t\t\t\tcv::Point3f& p1 = pts1[i];\n\t\t\t\tcv::Point3f& p2 = pts2[i];\n\t\t\t\tcv::Point3f ep2;\n\t\n\t\t\t\tep2.x = tmpR.at(0, 0) * p1.x + tmpR.at(0, 1) * p1.y + tmpR.at(0, 2) * p1.z + tmpT.at(0);\n\t\t\t\tep2.y = tmpR.at(1, 0) * p1.x + tmpR.at(1, 1) * p1.y + tmpR.at(1, 2) * p1.z + tmpT.at(1);\n\t\t\t\tep2.z = tmpR.at(2, 0) * p1.x + tmpR.at(2, 1) * p1.y + tmpR.at(2, 2) * p1.z + tmpT.at(2);\n\n\t\t\t\tfloat err = sqrt((p2.x - ep2.x)*(p2.x - ep2.x) + (p2.y - ep2.y)*(p2.y - ep2.y) + (p2.z - ep2.z));\n\t\t\t\tif (err < reprojectionError)\n\t\t\t\t{\n\t\t\t\t\tinliers.push_back(i);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (inliers.size() > bestInliers.size())\n\t\t\t{\n\t\t\t\tbestInliers = inliers;\n\t\t\t\tbestR = tmpR;\n\t\t\t\tbestT = tmpT;\n\t\t\t}\n\n\t\t}\n\t\tR = bestR;\n\t\tt = bestT;\n\t\tinliers = bestInliers;\n\t}\n\n\n\tMVSO::PoseEstimator::PoseEstimator(CameraModel & camera): camera_(camera)\n\t{\n\t}\n\n\tcv::Mat PoseEstimator::estimatePose(std::vector& pointsLeft_t0, std::vector& pointsLeft_t1, std::vector& points3D_t0)\n\t{\n\t\t// Calculate frame to frame transformation\n\t\tcv::Mat pose;\n\t\tcv::Mat rotation, translation;\n\n\t\t// -----------------------------------------------------------\n\t\t// Rotation(R) estimation using Nister's Five Points Algorithm\n\t\t// -----------------------------------------------------------\n\t\tdouble focal = camera_.fx_;\n\t\tcv::Point2d principle_point(camera_.cx_, camera_.cy_);\n\n\t\t//recovering the pose and the essential cv::matrix\n\t\tcv::Mat E, mask;\n\t\tcv::Mat translation_mono = cv::Mat::zeros(3, 1, CV_64F);\n\t\tE = cv::findEssentialMat(pointsLeft_t1, pointsLeft_t0, focal, principle_point, cv::RANSAC, 0.999, 1.0, mask);\n\t\tcv::recoverPose(E, pointsLeft_t1, pointsLeft_t0, rotation, translation_mono, focal, principle_point, mask);\n\t\t// std::cout << \"recoverPose rotation: \" << rotation << std::endl;\n\n\t\t// ------------------------------------------------\n\t\t// Translation (t) estimation by use solvePnPRansac\n\t\t// ------------------------------------------------\n\t\tcv::Mat distCoeffs = cv::Mat::zeros(4, 1, CV_64FC1);\n\t\tcv::Mat inliers;\n\t\tcv::Mat rvec = cv::Mat::zeros(3, 1, CV_64FC1);\n\n\t\tint iterationsCount = 100; // number of Ransac iterations.\n\t\tfloat reprojectionError = 1.0; // maximum allowed distance to consider it an inlier.\n\t\tfloat confidence = 0.98; // RANSAC successful confidence.\n\t\tbool useExtrinsicGuess = false;\n\t\tint flags = cv::SOLVEPNP_EPNP;\n\n\t\t//cv::Rodrigues(rotation, rvec);\n\t\tcv::solvePnPRansac(points3D_t0, pointsLeft_t1, camera_.intrinsicMat_, distCoeffs, rvec, translation,\n\t\t\tuseExtrinsicGuess, iterationsCount, reprojectionError, confidence,\n\t\t\tinliers, flags);\n\n\n\t\tstd::vector points3d;\n\t\tstd::vector points2d;\n\t\tstd::vector weights;\n\n\t\tfor (int i = 0; i < inliers.rows; i++)\n\t\t{\n\t\t\tint id = inliers.at(i, 0);\n\n\t\t\tcv::Point3f p3d = points3D_t0[id];\n\t\t\tcv::Point2f p0 = pointsLeft_t0[id], p1 = pointsLeft_t1[id];\n\t\t\tpoints3d.push_back(p3d);\n\t\t\tpoints2d.push_back(p1);\n\n\t\t\tdouble w = sqrt((p0.x - p1.x)*(p0.x - p1.x) + (p0.y - p1.y)*(p0.y - p1.y));\n\t\t\t//w *= 1/(1+exp(abs(p3d.z - 5)));\n\t\t\tif (w > 7)\n\t\t\t\tw = 7;\n\t\t\telse if (w < 1.0)\n\t\t\t\tw = 1.0;\n\t\t\tweights.push_back(exp(-w));\n\t\t}\n\n\t\tPoseOptimizer optimizer(camera_);\n\t\t//cv::Rodrigues(rvec, rotation);\n\t\t//optimizer.optimizePose(points3d, points2d, rotation, translation);\n\t\toptimizer.optimizePose(points3d, points2d, weights,rotation, translation);\n\n\n\t\t//cv::Rodrigues(rvec, rotation);\n\t\trotation = rotation.t();\n\t\ttranslation = -translation;\n\t\t// std::cout << \"inliers size: \" << inliers.size() << std::endl;\n\t\tcv::hconcat(rotation, translation, pose);\n\t\treturn pose;\n\t}\n\n\tcv::Mat PoseEstimator::estimatePose(std::vector& points_t0, std::vector& points_t1, std::vector& points3D_t0, std::vector& points3D_t1)\n\t{\n\t\t\n\t\tcv::Mat R, t;\n\t\tstd::vector inliers;\n\t\tsolveICPRansac(points3D_t0, points3D_t1, R, t, inliers, 100, 1.0);\n\n\t\tstd::vector pts1, pts2;\n\t\tfor (int n : inliers)\n\t\t{\n\t\t\tpts1.push_back(points3D_t0[n]);\n\t\t\tpts2.push_back(points3D_t1[n]);\n\t\t}\n\n\n\t\tPoseOptimizer optimizer(camera_);\n\t\toptimizer.optimizePose(pts1, pts2, R, t);\n\t\tcv::Mat pose;\n\t\tcv::hconcat(R, t, pose);\n\t\treturn pose;\n\n\t}\n\n\tPoseEstimator::~PoseEstimator()\n\t{\n\t}\n\n}\n\n", "meta": {"hexsha": "3d783fc744fd6b6b2049cedc48047e8085de060c", "size": 6523, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/PoseEstimator.cpp", "max_stars_repo_name": "lambdald/visualOdometry", "max_stars_repo_head_hexsha": "e1a93d6a91de3ae601417d77b604d27d5f9f171f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/PoseEstimator.cpp", "max_issues_repo_name": "lambdald/visualOdometry", "max_issues_repo_head_hexsha": "e1a93d6a91de3ae601417d77b604d27d5f9f171f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PoseEstimator.cpp", "max_forks_repo_name": "lambdald/visualOdometry", "max_forks_repo_head_hexsha": "e1a93d6a91de3ae601417d77b604d27d5f9f171f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.65, "max_line_length": 188, "alphanum_fraction": 0.6020236088, "num_tokens": 2382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361700013355, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6642311358396703}} {"text": "#ifndef SPLINE_HPP\n#define SPLINE_HPP\n\n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\n/**\n * A 1D polynomial of type f(t) = a + b t + c t^2 + d t^3 + ... + z t^(order)\n * that is bounded to the range t in [0; 1].\n */\ntemplate\nstruct UnitBoundedPolynomial1\n{\n static_assert(Order % 2 == 1, \"Order must be odd\");\n static_assert(Order > 0);\n\n /**\n * The number of derivates (including 0-th derivative) \n * required to fit this polynomial to start and end point\n */\n static constexpr const int RequiredValues = (Order + 1) / 2;\n\n double coeffs[Order+1];\n\n /**\n * Returns point at t on polynomial\n * @param t in [0;1]\n * @return double\n */\n double interpolate(double t) const;\n\n /**\n * Returns first derivative of polynomial at t\n * @param t in [0;1]\n * @return double\n */\n double derivative(double t) const;\n\n /**\n * Returns second derivative of polynomial at t\n * @param t in [0;1]\n * @return double\n */\n double derivative2(double t) const;\n\n /**\n * Fits the polynomial to go through start and end point\n * with specified derivatives.\n */\n static UnitBoundedPolynomial1 fit(const Matrix a, const Matrix b);\n};\n\n/**\n * A multi dimensional polynomial function. Aggregate of multiple independent 1-dimensional polynomials.\n */\ntemplate\nstruct UnitBoundedPolynomial\n{\n static_assert(Order > 0);\n static_assert(Dims > 0);\n\n typedef Matrix VectorNd;\n typedef UnitBoundedPolynomial1 Poly1;\n\n UnitBoundedPolynomial1 _dims[Dims];\n double length;\n\n VectorNd interpolate(double t) const;\n VectorNd derivative(double t) const;\n\n /**\n * Walks on the polynomial. Calls fn many times with points on the function.\n * Resolution is specified using deltatau.\n * @param deltatau Resolution with which to walk \n * @param fn Callback function\n * @param payload Gets passed to callback\n * @param a Optional, start point, can be used for extrapolation\n * @param b Optional, end point, can be used for extrapolation\n */\n void walk(const double deltatau, void (*fn)(VectorNd, double, const UnitBoundedPolynomial&, void *), void *payload = nullptr, double a = 0.0, double b = 1.0) const;\n\n /**\n * Calculates a spline.\n * @param A Matrix of point a with A[:, 0] = point, A[:, 1] = 1st derivative, A[:, 2] = 2nd derivative\n * @param B Matrix of point b with B[:, 0] = point, B[:, 1] = 1st derivative, B[:, 2] = 2nd derivative\n * @return Spline\n */\n static UnitBoundedPolynomial fit(Matrix A, \n Matrix B);\n\nprivate:\n void calculateLength();\n};\n\ntemplate\nclass SplineSolver;\n\n/**\n * A hermite spline. \n * Order and dimensionality can vary. \n * Currently only quintic and cubic splines are supported.\n */\ntemplate\nstruct HermiteSpline\n{\n static_assert(Order > 0);\n static_assert(Dims > 0);\n\n using Solver = SplineSolver;\n\n typedef Matrix VectorNd;\n typedef Matrix MatrixNXd;\n\n typedef UnitBoundedPolynomial1 Polynomial1;\n typedef UnitBoundedPolynomial Polynomial;\n\n vector children;\n double length;\n\n HermiteSpline() : length(0)\n {\n }\n\n VectorNd interpolate(double s);\n\n void walk(const double deltatau, void (*fn)(VectorNd, HermiteSpline&, double, Polynomial&, void *), void *payload = nullptr);\n void add(Polynomial sp);\n\n /**\n * Calculates the hermite spline.\n * @param values An array of required values (i.e. point, derivative, 2nd derivative, ..) x dimensions x number of points.\n * @return HermiteSpline\n */\n static HermiteSpline fit(array values);\n};\n\ntemplate\nclass BaseSplineSolver\n{\npublic:\n\n typedef typename Eigen::Matrix VectorNd;\n typedef typename Eigen::Matrix MatrixNXd;\n typedef typename MatrixNXd::RowXpr RowXpr;\n\n typedef UnitBoundedPolynomial1 Polynomial1;\n typedef UnitBoundedPolynomial Polynomial;\n\n typedef HermiteSpline Spline;\n\n HermiteSpline solve(vector points, \n Matrix start, \n Matrix end);\n\nprotected:\n\n virtual bool find_params_1d(RowXpr params[Polynomial1::RequiredValues]) = 0;\n\n};\n\n/**\n * The spline solver class implements methods\n * to compute a spline given N+1 points\n * plus start and end point slopes.\n */\ntemplate\nclass SplineSolver : public BaseSplineSolver\n{};\n\n\n// Quintic solver\n\ntemplate\nclass SplineSolver<5, Dims> : public BaseSplineSolver<5, Dims>\n{\npublic:\n\n using RowXpr = typename BaseSplineSolver<5, Dims>::RowXpr;\n\nprotected:\n\n SparseMatrix A;\n SparseLU, COLAMDOrdering> solver;\n\n bool find_params_1d(RowXpr params[3]);\n bool build_solver(const int N, const int M);\n\n};\n\n// Cubic solver\n\ntemplate\nclass SplineSolver<3, Dims> : public BaseSplineSolver<3, Dims>\n{\npublic:\n\n using RowXpr = typename BaseSplineSolver<3, Dims>::RowXpr;\n\nprotected:\n\n SparseMatrix A;\n SparseLU, COLAMDOrdering> solver;\n\n bool find_params_1d(RowXpr params[2]);\n bool build_solver(const int N, const int M);\n\n};\n\ntemplate \nusing CubicHermiteSpline = HermiteSpline<3, Dims>;\n\ntemplate \nusing QuinticHermiteSpline = HermiteSpline<5, Dims>;\n\n#endif\n", "meta": {"hexsha": "1be3b7eb589623410bef002247a4fedc5fd1be8f", "size": 6247, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "includes/spline_solver/hermite_spline.hpp", "max_stars_repo_name": "janhuenermann/quintic-spline-solver", "max_stars_repo_head_hexsha": "6f658a5f675340cec7d364bb2e900f6d2ec2b0b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-03-13T14:00:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-06T01:37:24.000Z", "max_issues_repo_path": "includes/spline_solver/hermite_spline.hpp", "max_issues_repo_name": "janhuenermann/quintic-spline-solver", "max_issues_repo_head_hexsha": "6f658a5f675340cec7d364bb2e900f6d2ec2b0b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "includes/spline_solver/hermite_spline.hpp", "max_forks_repo_name": "janhuenermann/quintic-spline-solver", "max_forks_repo_head_hexsha": "6f658a5f675340cec7d364bb2e900f6d2ec2b0b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0134529148, "max_line_length": 181, "alphanum_fraction": 0.675204098, "num_tokens": 1633, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533088603709, "lm_q2_score": 0.7122321964553656, "lm_q1q2_score": 0.6641232682616954}} {"text": "#include \"ImplicitIntegrator.h\"\n#include \"Deformation.hpp\"\n#include \"ProtoConverter.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing Eigen::MatrixXd;\n\nnamespace Deformation\n{\n using FloatT = double;\n using Mat3 = Eigen::Matrix;\n using Mat3x4 = Eigen::Matrix;\n using Mat9x12 = Eigen::Matrix;\n using Mat9 = Eigen::Matrix;\n using Mat12 = Eigen::Matrix;\n using Vec3 = Eigen::Matrix;\n using Vec9 = Eigen::Matrix;\n using Vec12 = Eigen::Matrix;\n\n Mat3 Calc_Ds(const Deformation::Tetrahedra& tet, const std::vector& vertices, bool restState)\n {\n Mat3 ds = Mat3::Zero();\n\n for (int row = 0; row < 3; row++)\n {\n for (int col = 1; col < 4; col++)\n {\n if (restState)\n\t\t\t\t\tds(row, col - 1) = vertices[tet.mIndices[col]].mMaterialCoordinates[row] - vertices[tet.mIndices[0]].mMaterialCoordinates[row];\n else\n ds(row, col - 1) = vertices[tet.mIndices[col]].mPosition[row] - vertices[tet.mIndices[0]].mPosition[row];\n }\n }\n\n return ds;\n }\n\n Mat3 Calc_DmInv(const Deformation::Tetrahedra& tet, const std::vector& vertices)\n {\n auto mat = Calc_Ds(tet, vertices, true);\n if (std::abs(mat.determinant()) < 1e-10f)\n throw std::exception(\"Small\");\n return mat.inverse();\n }\n\n Mat3 Calc_F(const Mat3& ds, const Mat3& dmInv)\n {\n return ds * dmInv;\n }\n\n Mat3 Calc_E(const Mat3& f)\n {\n return 0.5f * (f * f.transpose() - Mat3::Identity());\n }\n\n Mat3 Calc_dPsiDf(const Mat3& f, const Mat3& e)\n {\n FloatT youngsModulus = 8 * 10e8f;\n FloatT poissonRatio = 0.45f;\n FloatT lamba = youngsModulus * poissonRatio / ((1.0f + poissonRatio) * (1.0f - 2.0f * poissonRatio));\n FloatT mu = youngsModulus / (2.0f + 2.0f * poissonRatio);\n return mu * f * e + lamba * e.trace() * f;\n }\n\n Vec9 Reshape3x3(const Mat3& m)\n {\n Vec9 vec = Vec9::Zero();\n vec(0, 0) = m(0, 0);\n vec(1, 0) = m(1, 0);\n vec(2, 0) = m(2, 0);\n\n vec(3, 0) = m(0, 1);\n vec(4, 0) = m(1, 1);\n vec(5, 0) = m(2, 1);\n\n vec(6, 0) = m(0, 2);\n vec(7, 0) = m(1, 2);\n vec(8, 0) = m(2, 2);\n\n return vec;\n }\n\n Vec12 Reshape3x4(const Mat3x4& m)\n {\n Vec12 vec = Vec12::Zero();\n vec(0, 0) = m(0, 0);\n vec(1, 0) = m(1, 0);\n vec(2, 0) = m(2, 0);\n\n vec(3, 0) = m(0, 1);\n vec(4, 0) = m(1, 1);\n vec(5, 0) = m(2, 1);\n\n vec(6, 0) = m(0, 2);\n vec(7, 0) = m(1, 2);\n vec(8, 0) = m(2, 2);\n\n vec(9, 0) = m(0, 3);\n vec(10, 0) = m(1, 3);\n vec(11, 0) = m(2, 3);\n return vec;\n }\n\n Mat9x12 Calc_dFdx(const Mat3& dmInv)\n {\n auto m = dmInv(0, 0);\n auto n = dmInv(0, 1);\n auto o = dmInv(0, 2);\n auto p = dmInv(1, 0);\n auto q = dmInv(1, 1);\n auto r = dmInv(1, 2);\n auto s = dmInv(2, 0);\n auto t = dmInv(2, 1);\n auto u = dmInv(2, 2);\n\n auto t1 = -m - p - s;\n auto t2 = -n - q - t;\n auto t3 = -o - r - u;\n\n Mat9x12 dFdx = Mat9x12::Zero();\n\n dFdx(0, 0) = t1;\n dFdx(0, 3) = m;\n dFdx(0, 6) = p;\n dFdx(0, 9) = s;\n dFdx(1, 1) = t1;\n dFdx(1, 4) = m;\n dFdx(1, 7) = p;\n dFdx(1, 10) = s;\n\n dFdx(2, 2) = t1;\n dFdx(2, 5) = m;\n dFdx(2, 8) = p;\n dFdx(2, 11) = s;\n dFdx(3, 0) = t2;\n dFdx(3, 3) = n;\n dFdx(3, 6) = q;\n dFdx(3, 9) = t;\n dFdx(4, 1) = t2;\n dFdx(4, 4) = n;\n\n dFdx(4, 7) = q;\n dFdx(4, 10) = t;\n dFdx(5, 2) = t2;\n dFdx(5, 5) = n;\n dFdx(5, 8) = q;\n dFdx(5, 11) = t;\n dFdx(6, 0) = t3;\n dFdx(6, 3) = o;\n dFdx(6, 6) = r;\n dFdx(6, 9) = u;\n dFdx(7, 1) = t3;\n dFdx(7, 4) = o;\n\n dFdx(7, 7) = r;\n dFdx(7, 10) = u;\n dFdx(8, 2) = t3;\n dFdx(8, 5) = o;\n dFdx(8, 8) = r;\n dFdx(8, 11) = u;\n\n return dFdx;\n }\n\n Vec9 Calc_g_i(const Mat3& f)\n {\n Vec9 g_i = Vec9::Zero();\n g_i(0, 0) = 2 * f(0, 0);\n g_i(1, 0) = 2 * f(1, 0);\n g_i(2, 0) = 2 * f(2, 0);\n\n g_i(3, 0) = 2 * f(0, 1);\n g_i(4, 0) = 2 * f(1, 1);\n g_i(5, 0) = 2 * f(2, 1);\n\n g_i(6, 0) = 2 * f(0, 2);\n g_i(7, 0) = 2 * f(1, 2);\n g_i(8, 0) = 2 * f(2, 2);\n return g_i;\n }\n\n Mat3 Calc_dj_df(const Mat3& f)\n {\n Mat3 dj_df = Mat3::Zero();\n dj_df.col(0) = f.col(1).cross(f.col(2));\n dj_df.col(1) = f.col(2).cross(f.col(0));\n dj_df.col(2) = f.col(0).cross(f.col(1));\n\n //dj_df.block(0, 0, 3, 1) = f.col(1).cross(f.col(2));\n //dj_df.block(0, 1, 3, 1) = f.col(2).cross(f.col(0));\n //dj_df.block(0, 2, 3, 1) = f.col(0).cross(f.col(1));\n return dj_df;\n }\n\n FloatT Calc_i_c(const Mat3& f)\n {\n auto frob = f.norm();\n return frob * frob;\n }\n\n Mat9 Calc_h_i()\n {\n return 2 * Mat9::Identity();\n }\n\n Mat3 Calc_f_hat(const Vec3& f_i)\n {\n Mat3 f_hat = Mat3::Zero();\n // col 0\n f_hat(1, 0) = f_i(2);\n f_hat(2, 0) = -f_i(1);\n \n // col 1\n f_hat(0, 1) = -f_i(2);\n f_hat(2, 1) = f_i(0);\n\n // col 2\n f_hat(0, 2) = f_i(1);\n f_hat(1, 2) = -f_i(0);\n\n return f_hat;\n }\n\n Mat9 Calc_h_j(const Mat3& f)\n {\n Mat9 h_j = Mat9::Zero();\n auto f0_hat = Calc_f_hat(f.col(0));\n auto f1_hat = Calc_f_hat(f.col(1));\n auto f2_hat = Calc_f_hat(f.col(2));\n\n // col 0\n h_j.block(3, 0, 3, 3) = f2_hat;\n h_j.block(6, 0, 3, 3) = -f1_hat;\n\n // col 1\n h_j.block(0, 3, 3, 3) = -f2_hat;\n h_j.block(6, 3, 3, 3) = f0_hat;\n\n // col 2\n h_j.block(0, 6, 3, 3) = f1_hat;\n h_j.block(3, 6, 3, 3) = -f0_hat;\n \n return h_j;\n }\n\n Mat9 Calc_D(const Mat3& f)\n {\n Mat9 d = Mat9::Zero();\n const auto& f0 = f.col(0);\n const auto& f1 = f.col(1);\n const auto& f2 = f.col(2);\n\n d.block(0, 0, 3, 3) = f0 * f0.transpose();\n d.block(3, 0, 3, 3) = f0 * f1.transpose();\n d.block(6, 0, 3, 3) = f0 * f2.transpose();\n\n d.block(0, 3, 3, 3) = f1 * f0.transpose();\n d.block(3, 3, 3, 3) = f1 * f1.transpose();\n d.block(6, 3, 3, 3) = f1 * f2.transpose();\n\n d.block(0, 6, 3, 3) = f2 * f0.transpose();\n d.block(3, 6, 3, 3) = f2 * f1.transpose();\n d.block(6, 6, 3, 3) = f2 * f2.transpose();\n\n return d;\n }\n\n Mat9 KroneckerProduct(const Mat3& a, const Mat3& b)\n {\n Mat9 product = Mat9::Zero();\n product.block(0, 0, 3, 3) = a(0, 0) * b;\n product.block(3, 0, 3, 3) = a(1, 0) * b;\n product.block(6, 0, 3, 3) = a(2, 0) * b;\n\n product.block(0, 3, 3, 3) = a(0, 1) * b;\n product.block(3, 3, 3, 3) = a(1, 1) * b;\n product.block(6, 3, 3, 3) = a(2, 1) * b;\n\n product.block(0, 6, 3, 3) = a(0, 2) * b;\n product.block(3, 6, 3, 3) = a(1, 2) * b;\n product.block(6, 6, 3, 3) = a(2, 2) * b;\n\n return product;\n }\n\n Mat9 Calc_h_2(const Mat3& f, const Mat9& d)\n {\n return 4 * (KroneckerProduct(Mat3::Identity(), f * f.transpose()) + KroneckerProduct(f * f.transpose(), Mat3::Identity()) + d);\n }\n\n Mat9 Calc_vec_dPsi2_dF2(const Vec9& g_i, FloatT i_c, const Mat9& h_i, const Mat9& h_2, FloatT mu, FloatT lambda)\n {\n return lambda / 4.0f * (g_i * g_i.transpose()) + (-mu / 2.0f + lambda / 4.0f * (i_c - 3.0f)) * h_i + mu / 4.0f * h_2;\n }\n\n Mat12 Calc_dfdx(const Mat9x12& dFdx, const Mat9 & vec_dPsi2_dF2, FloatT restVol)\n {\n return -restVol * dFdx.transpose() * vec_dPsi2_dF2 * dFdx;\n }\n\n Mat3 Get_Q(int i, const std::array& epsilon, const std::array& sigma, const Mat3& u, const Mat3& v_transpose)\n {\n Mat3 d = Mat3::Zero();\n d(0, 0) = sigma[0] * sigma[2] + sigma[1] * epsilon[i];\n d(1, 1) = sigma[1] * sigma[2] + sigma[0] * epsilon[i];\n\t\td(2, 2) = epsilon[i] * epsilon[i] - sigma[2] * sigma[2];\n return 1.0f / d.norm() * u * d * v_transpose;\n }\n\n Mat3 Get_Q(const Mat3 & U, const Mat3 & V, int i)\n {\n //Mat3 q = Mat3::Zero();\n\n //if (i == 3)\n //{\n // q(0, 1) = -1;\n // q(1, 0) = 1;\n //}\n //else if (i == 4)\n //{\n // q(1, 2) = 1;\n // q(2, 1) = -1;\n //}\n //else if (i == 5)\n //{\n // q(0, 2) = 1;\n // q(2, 0) = -1;\n //}\n //else if (i == 6)\n //{\n // q(0, 1) = 1;\n // q(1, 0) = 1;\n //}\n //else if (i == 7)\n //{\n // q(1, 2) = 1;\n // q(2, 1) = 1;\n //}\n //else if (i == 8)\n //{\n // q(0, 2) = 1;\n // q(2, 0) = 1;\n //}\n\n //return 1 / sqrt(2.0f) * u * q * v_transpose;\n\n static const FloatT scale = 1.0 / std::sqrt(2.0);\n const Mat3 sV = scale * V;\n\n using M3 = Eigen::Matrix;\n\n M3 A;\n A << sV(0, 2) * U(0, 1), sV(1, 2)* U(0, 1), sV(2, 2)* U(0, 1),\n sV(0, 2)* U(1, 1), sV(1, 2)* U(1, 1), sV(2, 2)* U(1, 1),\n sV(0, 2)* U(2, 1), sV(1, 2)* U(2, 1), sV(2, 2)* U(2, 1);\n\n M3 B;\n B << sV(0, 1) * U(0, 2), sV(1, 1)* U(0, 2), sV(2, 1)* U(0, 2),\n sV(0, 1)* U(1, 2), sV(1, 1)* U(1, 2), sV(2, 1)* U(1, 2),\n sV(0, 1)* U(2, 2), sV(1, 1)* U(2, 2), sV(2, 1)* U(2, 2);\n\n M3 C;\n C << sV(0, 2) * U(0, 0), sV(1, 2)* U(0, 0), sV(2, 2)* U(0, 0),\n sV(0, 2)* U(1, 0), sV(1, 2)* U(1, 0), sV(2, 2)* U(1, 0),\n sV(0, 2)* U(2, 0), sV(1, 2)* U(2, 0), sV(2, 2)* U(2, 0);\n\n M3 D;\n D << sV(0, 0) * U(0, 2), sV(1, 0)* U(0, 2), sV(2, 0)* U(0, 2),\n sV(0, 0)* U(1, 2), sV(1, 0)* U(1, 2), sV(2, 0)* U(1, 2),\n sV(0, 0)* U(2, 2), sV(1, 0)* U(2, 2), sV(2, 0)* U(2, 2);\n\n M3 E;\n E << sV(0, 1) * U(0, 0), sV(1, 1)* U(0, 0), sV(2, 1)* U(0, 0),\n sV(0, 1)* U(1, 0), sV(1, 1)* U(1, 0), sV(2, 1)* U(1, 0),\n sV(0, 1)* U(2, 0), sV(1, 1)* U(2, 0), sV(2, 1)* U(2, 0);\n\n M3 F;\n F << sV(0, 0) * U(0, 1), sV(1, 0)* U(0, 1), sV(2, 0)* U(0, 1),\n sV(0, 0)* U(1, 1), sV(1, 0)* U(1, 1), sV(2, 0)* U(1, 1),\n sV(0, 0)* U(2, 1), sV(1, 0)* U(2, 1), sV(2, 0)* U(2, 1);\n\n if (i == 3)\n return B - A;\n else if (i == 4)\n return D - C;\n else if (i == 5)\n return F - E;\n else if (i == 6)\n return A + B;\n else if (i == 7)\n return C + D;\n else if (i == 8)\n return E + F;\n }\n\n FloatT Calc_Epsilon(int i, FloatT I2, FloatT I3)\n {\n return 2 * sqrtf(I2 / 3.0f) * cosf(1.0f / 3.0f * (acosf(3*I3/I2*sqrtf(3/I2)) + 2*glm::pi()*(i-1)));\n }\n\n void BuildTwistAndFlipEigenvectors(const Mat3& U, const Mat3& V, Mat9& Q)\n {\n static const FloatT scale = 1.0 / std::sqrt(2.0);\n const Mat3 sV = scale * V;\n\n using M3 = Eigen::Matrix;\n\n M3 A;\n A << sV(0, 2) * U(0, 1), sV(1, 2)* U(0, 1), sV(2, 2)* U(0, 1),\n sV(0, 2)* U(1, 1), sV(1, 2)* U(1, 1), sV(2, 2)* U(1, 1),\n sV(0, 2)* U(2, 1), sV(1, 2)* U(2, 1), sV(2, 2)* U(2, 1);\n\n M3 B;\n B << sV(0, 1) * U(0, 2), sV(1, 1)* U(0, 2), sV(2, 1)* U(0, 2),\n sV(0, 1)* U(1, 2), sV(1, 1)* U(1, 2), sV(2, 1)* U(1, 2),\n sV(0, 1)* U(2, 2), sV(1, 1)* U(2, 2), sV(2, 1)* U(2, 2);\n\n M3 C;\n C << sV(0, 2) * U(0, 0), sV(1, 2)* U(0, 0), sV(2, 2)* U(0, 0),\n sV(0, 2)* U(1, 0), sV(1, 2)* U(1, 0), sV(2, 2)* U(1, 0),\n sV(0, 2)* U(2, 0), sV(1, 2)* U(2, 0), sV(2, 2)* U(2, 0);\n\n M3 D;\n D << sV(0, 0) * U(0, 2), sV(1, 0)* U(0, 2), sV(2, 0)* U(0, 2),\n sV(0, 0)* U(1, 2), sV(1, 0)* U(1, 2), sV(2, 0)* U(1, 2),\n sV(0, 0)* U(2, 2), sV(1, 0)* U(2, 2), sV(2, 0)* U(2, 2);\n\n M3 E;\n E << sV(0, 1) * U(0, 0), sV(1, 1)* U(0, 0), sV(2, 1)* U(0, 0),\n sV(0, 1)* U(1, 0), sV(1, 1)* U(1, 0), sV(2, 1)* U(1, 0),\n sV(0, 1)* U(2, 0), sV(1, 1)* U(2, 0), sV(2, 1)* U(2, 0);\n\n M3 F;\n F << sV(0, 0) * U(0, 1), sV(1, 0)* U(0, 1), sV(2, 0)* U(0, 1),\n sV(0, 0)* U(1, 1), sV(1, 0)* U(1, 1), sV(2, 0)* U(1, 1),\n sV(0, 0)* U(2, 1), sV(1, 0)* U(2, 1), sV(2, 0)* U(2, 1);\n\n // Twist eigenvectors\n //std::cout << \"eigenvectors before mapping\" << std::endl;\n //std::cout << Q << std::endl;\n //std::cout << \"B-A\" << std::endl;\n //std::cout << B - A << std::endl;\n Eigen::Map(Q.data()) = B - A;\n //std::cout << \"eigenvectors after single mapping\" << std::endl;\n //std::cout << Q << std::endl;\n Eigen::Map(Q.data() + 9) = D - C;\n Eigen::Map(Q.data() + 18) = F - E;\n\n // Flip eigenvectors\n Eigen::Map(Q.data() + 27) = A + B;\n Eigen::Map(Q.data() + 36) = C + D;\n Eigen::Map(Q.data() + 45) = E + F;\n }\n\n Mat9 CalcProjectedHessian(FloatT mu, FloatT lambda, const Mat3& F, const Mat3& U, const Mat3& V, const Vec3& S)\n {\n Vec9 eigenvalues;\n Mat9 eigenvectors;\n\n const FloatT J = F.determinant();\n\n // Compute the twist and flip eigenvalues\n {\n // Twist eigenvalues\n eigenvalues.segment<3>(0) = S;\n // Flip eigenvalues\n eigenvalues.segment<3>(3) = -S;\n const FloatT evScale = lambda * (J - 1.0) - mu;\n eigenvalues.segment<6>(0) *= evScale;\n eigenvalues.segment<6>(0).array() += mu;\n }\n\n // Compute the twist and flip eigenvectors\n BuildTwistAndFlipEigenvectors(U, V, eigenvectors);\n\n // Compute the remaining three eigenvalues and eigenvectors\n {\n Mat3 A;\n const FloatT s0s0 = S(0) * S(0);\n const FloatT s1s1 = S(1) * S(1);\n const FloatT s2s2 = S(2) * S(2);\n A(0, 0) = mu + lambda * s1s1 * s2s2;\n A(1, 1) = mu + lambda * s0s0 * s2s2;\n A(2, 2) = mu + lambda * s0s0 * s1s1;\n const FloatT evScale = lambda * (2.0 * J - 1.0) - mu;\n A(0, 1) = evScale * S(2);\n A(1, 0) = A(0, 1);\n A(0, 2) = evScale * S(1);\n A(2, 0) = A(0, 2);\n A(1, 2) = evScale * S(0);\n A(2, 1) = A(1, 2);\n\n //std::cout << \"A\" << std::endl;\n //std::cout << A << std::endl;\n\n const Eigen::SelfAdjointEigenSolver Aeigs(A);\n eigenvalues.segment<3>(6) = Aeigs.eigenvalues();\n\n // std::cout << \"u\" << std::endl;\n // std::cout << U << std::endl;\n\n // std::cout << \"v\" << std::endl;\n // std::cout << V << std::endl;\n\n // std::cout << \"A eigs\" << std::endl;\n // std::cout << Aeigs.eigenvalues() << std::endl;\n // std::cout << \"Unrotated eig vectors\" << std::endl;\n\t\t\t//std::cout << Aeigs.eigenvectors() << std::endl;\n\n // std::cout << \"Rotated eigen 0 matrix\" << std::endl;\n // std::cout << U * Aeigs.eigenvectors().col(0).asDiagonal() * V.transpose() << std::endl;\n\n // std::cout << \"eigenvectors before mapping\" << std::endl;\n // std::cout << eigenvectors << std::endl;\n Eigen::Map(eigenvectors.data() + 54) = U * Aeigs.eigenvectors().col(0).asDiagonal() * V.transpose();\n //std::cout << \"eigenvectors after single mapping\" << std::endl;\n //std::cout << eigenvectors << std::endl;\n Eigen::Map(eigenvectors.data() + 63) = U * Aeigs.eigenvectors().col(1).asDiagonal() * V.transpose();\n Eigen::Map(eigenvectors.data() + 72) = U * Aeigs.eigenvectors().col(2).asDiagonal() * V.transpose();\n }\n\n // Clamp the eigenvalues\n for (int i = 0; i < 9; i++)\n {\n //std::cout << \"lambda_\" << i << \" \" << eigenvalues(i) << std::endl;\n\n if (eigenvalues(i) < 0.0)\n {\n eigenvalues(i) = 0.0;\n //eigenvalues(i) = -eigenvalues(i);\n\n }\n }\n //std::cout << \"eigenvalues\" << std::endl;\n //std::cout << eigenvalues << std::endl;\n\n //std::cout << \"eigenvectors\" << std::endl;\n //std::cout << eigenvectors << std::endl;\n\n return eigenvectors * eigenvalues.asDiagonal() * eigenvectors.transpose();\n }\n\n Mat3x4 CalcBm(const std::array& vertIndices, const std::vector& vertices)\n {\n std::vector vertices_converted;\n glm::ivec4 tetIndices({ vertIndices[0], vertIndices[1], vertIndices[2], vertIndices[3] });\n\n for (int i = 0; i < 4; i++)\n {\n const auto& pos = vertices[tetIndices[i]].mMaterialCoordinates;\n vertices_converted.push_back(Vec3(pos.x, pos.y, pos.z));\n }\n\n // TODO: Eliminate this class, it is just used to get the area normal\n class Triangle final\n {\n public:\n Triangle(const Vec3& v0, const Vec3& v1, const Vec3& v2)\n : _x0(v0)\n , _x1(v1)\n , _x2(v2)\n {}\n\n // TODO: Make this a constructor\n static Triangle GenerateFace(const int faceNum, const glm::ivec4& tet, const std::vector& verts)\n {\n assert(faceNum >= 0); assert(faceNum < 4);\n if (faceNum == 0)\n {\n return Triangle(verts[static_cast(tet[0])], verts[static_cast(tet[1])], verts[static_cast(tet[3])]);\n }\n else if (faceNum == 1)\n {\n return Triangle(verts[static_cast(tet[0])], verts[static_cast(tet[2])], verts[static_cast(tet[1])]);\n }\n else if (faceNum == 2)\n {\n return Triangle(verts[static_cast(tet[3])], verts[static_cast(tet[2])], verts[static_cast(tet[0])]);\n }\n else if (faceNum == 3)\n {\n return Triangle(verts[static_cast(tet[1])], verts[static_cast(tet[2])], verts[static_cast(tet[3])]);\n }\n else\n {\n std::cerr << \"Error, impossible code path hit.\" << std::endl;\n std::exit(EXIT_FAILURE);\n }\n }\n\n // TODO: Roll these into one computation\n Vec3 normal() const\n {\n return ((_x1 - _x0).cross(_x2 - _x0)).normalized();\n }\n FloatT area() const\n {\n return 0.5 * ((_x1 - _x0).cross(_x2 - _x0)).norm();\n }\n private:\n const Vec3& _x0;\n const Vec3& _x1;\n const Vec3& _x2;\n };\n\n Mat3x4 Bm;\n\t\tconst Triangle tri0 = Triangle::GenerateFace(0, tetIndices, vertices_converted);\n\t\tconst Triangle tri1 = Triangle::GenerateFace(1, tetIndices, vertices_converted);\n\t\tconst Triangle tri2 = Triangle::GenerateFace(2, tetIndices, vertices_converted);\n\t\tconst Triangle tri3 = Triangle::GenerateFace(3, tetIndices, vertices_converted);\n\n\t\t// Calculate the area vectors\n\t\t// v0 is incident on faces (0,1,2)\n\t\tBm.col(0) = tri0.normal() * tri0.area() + tri1.normal() * tri1.area() + tri2.normal() * tri2.area();\n\t\t// v1 is incident on faces (0,1,3)\n\t\tBm.col(1) = tri0.normal() * tri0.area() + tri1.normal() * tri1.area() + tri3.normal() * tri3.area();\n\t\t// v2 is incident on faces (1,2,3)\n\t\tBm.col(2) = tri1.normal() * tri1.area() + tri2.normal() * tri2.area() + tri3.normal() * tri3.area();\n\t\t// v3 is incident on faces (0,2,3)\n\t\tBm.col(3) = tri0.normal() * tri0.area() + tri2.normal() * tri2.area() + tri3.normal() * tri3.area();\n\t\tBm /= -3.0;\n\n return Bm;\n }\n\n Eigen::VectorXf ComputePerturbedForce(const TetraGroup& group, const Eigen::VectorXf& deltaX)\n {\n size_t numVertices = group.mVertices.size();\n Eigen::VectorXf globalForce = Eigen::VectorXf::Zero(3 * numVertices);\n\n for (const auto& pair : group.mIdToTetrahedra)\n {\n const auto& tet = pair.second;\n\n auto ds = Calc_Ds(tet, group.mVertices, false);\n auto dmInv = Calc_DmInv(tet, group.mVertices);\n auto f = Calc_F(ds, dmInv);\n\n auto j = f.determinant();\n auto dj_df = Calc_dj_df(f);\n auto g_j = Reshape3x3(dj_df);\n Mat3 dPsi_dF = group.mMu * f + (group.mLambda * (j - 1.0f) - group.mMu) * dj_df;\n\n auto dF_dx = Calc_dFdx(dmInv);\n auto dPsi_dx = dF_dx.transpose() * Reshape3x3(dPsi_dF);\n Vec12 force = -tet.mRestVolume * dPsi_dx; // 12x1 atm\n\n Eigen::JacobiSVD svd_f(f, Eigen::ComputeFullU | Eigen::ComputeFullV);\n auto sigmas = svd_f.singularValues();\n auto u = svd_f.matrixU();\n auto v = svd_f.matrixV();\n\n if (u.determinant() < 0.0)\n {\n u.col(0) *= -1.0;\n sigmas(0) *= -1.0;\n }\n if (v.determinant() < 0.0)\n {\n v.col(0) *= -1.0;\n sigmas(0) *= -1.0;\n }\n\n // Contribution to globalB\n for (size_t i = 0; i < 4; i++)\n {\n auto vert_i = tet.mIndices[i];\n globalForce(3 * vert_i + 0) += force(3 * i + 0);\n globalForce(3 * vert_i + 1) += force(3 * i + 1);\n globalForce(3 * vert_i + 2) += force(3 * i + 2);\n }\n }\n\n return globalForce;\n }\n\n bool ImplicitUpdate(TetraGroup& group, float timestep, bool saveFrame, IronGames::SimulationFrame* frame, float deltaVThreshold)\n {\n size_t numVertices = group.mVertices.size();\n Eigen::SparseMatrix globalA(3* numVertices, 3* numVertices);\n Eigen::VectorXf globalB = Eigen::VectorXf::Zero(3 * numVertices);\n\t\tEigen::VectorXf globalX = Eigen::VectorXf::Zero(3 * numVertices);\n Vec12 nodeVelocities = Vec12::Zero();\n Vec12 localB = Vec12::Zero();\n\n Eigen::VectorXf globalForce = Eigen::VectorXf::Zero(3 * numVertices);\n Eigen::VectorXf globalVelocities = Eigen::VectorXf::Zero(3 * numVertices);\n Eigen::SparseMatrix globalDfDx(3 * numVertices, 3 * numVertices);\n Eigen::SparseMatrix massMatrix(3 * numVertices, 3 * numVertices);\n\n //std::cout << \"timestep \" << timestep << std::endl;\n\n for (size_t i = 0; i < group.mVertices.size(); i++)\n {\n globalA.coeffRef(3 * i, 3 * i) = group.mVertices[i].mMass;\n globalA.coeffRef(3 * i + 1, 3 * i + 1) = group.mVertices[i].mMass;\n\t\t\tglobalA.coeffRef(3 * i + 2, 3 * i + 2) = group.mVertices[i].mMass;\n }\n\n for (const auto& pair : group.mIdToTetrahedra)\n {\n const auto& tet = pair.second;\n\n auto ds = Calc_Ds(tet, group.mVertices, false);\n //std::cout << \"ds\" << std::endl;\n //std::cout << ds << std::endl;\n auto dmInv = Calc_DmInv(tet, group.mVertices);\n //std::cout << \"dmInv\" << std::endl;\n //std::cout << dmInv << std::endl;\n auto f = Calc_F(ds, dmInv);\n //std::cout << \"f\" << std::endl;\n //std::cout << f << std::endl;\n\n // Stable Neo-hookean potential\n\t\t\tauto j = f.determinant();\n\t\t\tauto dj_df = Calc_dj_df(f); // SEEMS OK\n //std::cout << \"dj_df\" << std::endl;\n //std::cout << dj_df << std::endl;\n\t\t\tauto g_j = Reshape3x3(dj_df);\n //auto dPsi_dF = group.mMu * Reshape3x3(f) + group.mLambda * (j - 1.0f - group.mMu/group.mLambda) * g_j;\n Mat3 dPsi_dF = group.mMu * f + (group.mLambda * (j - 1.0f) - group.mMu) * dj_df;\n //auto elementForce = dPsi_dF * CalcBm(tet.mIndices, group.mVertices);\n\n\t\t\tauto dF_dx = Calc_dFdx(dmInv);\n //std::cout << \"dfdx\" << std::endl;\n //std::cout << dF_dx << std::endl;\n\t\t\tauto dPsi_dx = dF_dx.transpose() * Reshape3x3(dPsi_dF);\n\t\t\tVec12 force = -tet.mRestVolume * dPsi_dx; // 12x1 atm\n\n //std::cout << \"Force\" << std::endl;\n //std::cout << force << std::endl;\n //force = -Reshape3x4(elementForce); // 12x1 atm\n\n\t\t\tauto h_j = Calc_h_j(f);\n //std::cout << \"h_j\" << std::endl;\n //std::cout << h_j << std::endl;\n //std::cout << \"g_j * g_j^T\" << std::endl;\n //std::cout << (g_j * g_j.transpose()) << std::endl;\n\t\t\t//Mat9 dPsi2_dF2 = group.mMu * Mat9::Identity() + group.mLambda * (j - 1.0f - group.mMu / group.mLambda) * h_j + group.mLambda * g_j * g_j.transpose();\n \n Eigen::JacobiSVD svd_f(f, Eigen::ComputeFullU | Eigen::ComputeFullV);\n auto sigmas = svd_f.singularValues();\n auto u = svd_f.matrixU();\n auto v = svd_f.matrixV();\n\n if (u.determinant() < 0.0)\n {\n u.col(0) *= -1.0;\n sigmas(0) *= -1.0;\n }\n if (v.determinant() < 0.0)\n {\n v.col(0) *= -1.0;\n sigmas(0) *= -1.0;\n }\n\n auto dPsi2_dF2 = CalcProjectedHessian(group.mMu, group.mLambda, f, u, v, sigmas);\n\n\t\t\tauto dfdx = Calc_dfdx(dF_dx, dPsi2_dF2, tet.mRestVolume);\n\n //std::cout << \"dfdx\" << std::endl;\n //std::cout << dfdx << std::endl;\n\n // Contribution to globalA\n // 12 x 12 matrix df/dx\n // the force on one of the 4 vertices is a 3-vector\n // the derivative of that with respect to the spatial coordinates of all four node spatial coordinates should give me a 3x12 matrix (?)\n // then we have that for each of the nodes\n // and we get a 12x12\n // so a single element tells me how the force in coordinate (x,y,z) on node i changes with respect to the (x,y,z) position of node j, makes sense\n // and a 3x3 block tells me how the force on node i changes with respect to the position of node j\n // so it's probably easier to consider the global matrix as n x n where elements are 3x3 rather than 3n x 3n with scalar elements.\n for (size_t i = 0; i < 4; i++)\n {\n auto vert_i = tet.mIndices[i];\n\n for (size_t j = 0; j < 4; j++)\n {\n auto vert_j = tet.mIndices[j];\n\n // we want to set a 3x3 block in globalA here from (3*vertId to 3*vertId + 2, 3*otherVertId to 3*otherVertId + 2)\n // and we should draw from (3*i to 3*i + 2, 3*j to 3*j + 2)\n for (size_t sub_i = 0; sub_i < 3; sub_i++)\n {\n for (size_t sub_j = 0; sub_j < 3; sub_j++)\n {\n globalA.coeffRef(3 * vert_i + sub_i, 3 * vert_j + sub_j) -= timestep * timestep * dfdx(3 * i + sub_i, 3 * j + sub_j);\n globalDfDx.coeffRef(3 * vert_i + sub_i, 3 * vert_j + sub_j) += dfdx(3 * i + sub_i, 3 * j + sub_j);\n }\n }\n }\n }\n \n for (size_t i = 0; i < 4; i++)\n {\n nodeVelocities(3 * i + 0) = group.mVertices[tet.mIndices[i]].mVelocity.x;\n nodeVelocities(3 * i + 1) = group.mVertices[tet.mIndices[i]].mVelocity.y;\n nodeVelocities(3 * i + 2) = group.mVertices[tet.mIndices[i]].mVelocity.z;\n }\n\n localB = timestep * force + timestep * timestep * dfdx * nodeVelocities;\n\n if (isnan(localB.norm()))\n throw std::exception(\"nan detected in local forces\");\n\n // Contribution to globalB\n for (size_t i = 0; i < 4; i++)\n {\n auto vert_i = tet.mIndices[i];\n globalB(3 * vert_i + 0) += localB(3 * i + 0);\n globalB(3 * vert_i + 1) += localB(3 * i + 1);\n globalB(3 * vert_i + 2) += localB(3 * i + 2);\n\n globalForce(3 * vert_i + 0) += force(3 * i + 0);\n globalForce(3 * vert_i + 1) += force(3 * i + 1);\n globalForce(3 * vert_i + 2) += force(3 * i + 2);\n }\n }\n\n // Apply additional per-node forces\n for (int i = 0; i < group.mVertices.size(); i++)\n {\n // Gravity\n globalB(3 * i + 1) += -9.8 * timestep * group.mVertices[i].mMass;\n\n // Collision forces\n //globalB(3 * i + 0) += group.mVertices[i].mForce.x;\n //globalB(3 * i + 1) += group.mVertices[i].mForce.y;\n //globalB(3 * i + 2) += group.mVertices[i].mForce.z;\n }\n\n if (isnan(globalA.norm()))\n throw std::exception(\"Nan detected.\");\n\n if (isnan(globalB.norm()))\n throw std::exception(\"Nan detected.\");\n\n //{\n // auto denseGlobalA = globalA.toDense();\n\n // Eigen::SelfAdjointEigenSolver solver(denseGlobalA);\n // auto eigs = solver.eigenvalues();\n // auto minVal = 1000.0f;\n // for (int i = 0; i < eigs.size(); i++)\n // minVal = std::min(minVal, eigs[i]);\n\n // if (minVal < 0)\n // {\n // std::cout << \"Timestep : \" << timestep << std::endl;\n // std::cout << \"Negative eig\" << std::endl;\n // }\n //}\n\n //std::cout << \"globalA\" << std::endl;\n //std::cout << globalA << std::endl;\n\n //std::cout << \"globalB\" << std::endl;\n //std::cout << globalB << std::endl;\n\n // PCG Solver\n {\n Eigen::ConjugateGradient, Eigen::Lower | Eigen::Upper> solver;\n solver.compute(globalA);\n\n globalX = solver.solve(globalB);\n if (isnan(solver.error()))\n throw std::exception(\"Solver failed.\");\n\n //std::cout << \"globalX\" << std::endl;\n //std::cout << globalX << std::endl;\n //std::cout << \"globalX inf norm: \" << globalX.lpNorm() << std::endl;\n //if (globalX.lpNorm() > deltaVThreshold)\n // return false;\n // lets see, make the threshold value here 1\n\n std::string solverInfo;\n if (solver.info() == 0)\n solverInfo = std::string(\"Success\");\n else if (solver.info() == 1)\n solverInfo = std::string(\"Numerical issue\");\n else if (solver.info() == 2)\n solverInfo = std::string(\"No convergence\");\n else if (solver.info() == 3)\n solverInfo = std::string(\"Invalid input\");\n\n if (solver.info() != 0)\n\t\t\t\tstd::cout << \"Solver info : \" << solverInfo << std::endl;\n }\n\n // Check error against nonlinear equation\n {\n for (int i = 0; i < numVertices; i++)\n {\n globalVelocities(3 * i + 0) = group.mVertices[i].mVelocity[0];\n globalVelocities(3 * i + 1) = group.mVertices[i].mVelocity[1];\n globalVelocities(3 * i + 2) = group.mVertices[i].mVelocity[2];\n massMatrix.coeffRef(3 * i, 3 * i) = 1.0/group.mVertices[i].mMass;\n massMatrix.coeffRef(3 * i + 1, 3 * i + 1) = 1.0/group.mVertices[i].mMass;\n massMatrix.coeffRef(3 * i + 2, 3 * i + 2) = 1.0/group.mVertices[i].mMass;\n }\n\n // dv = h M^-1 (f0 + df/dx * dx)\n auto dx = timestep * (globalVelocities + globalX);\n auto perturbedForce = ComputePerturbedForce(group, dx);\n auto residual = timestep * massMatrix * perturbedForce - globalX;\n // this isn't the nonlinear eq. unfortunately, we'd need to evaluate the force with new position\n // to get that\n std::cout << \"timestep: \" << timestep << std::endl;\n std::cout << \"infinity error: \" << residual.lpNorm() << std::endl;\n std::cout << \"l2 error: \" << residual.norm() << std::endl;\n if (residual.lpNorm() > 10.0)\n {\n return false;\n }\n }\n\n // SparseLU Solver\n //{\n // Eigen::SparseLU, Eigen::COLAMDOrdering > solver;\n // solver.analyzePattern(globalA);\n // solver.factorize(globalA);\n // globalX = solver.solve(globalB);\n\n // if (isnan(globalX.norm()))\n // throw std::exception(\"Solver failed.\");\n //}\n\n // Integrate\n for (int i = 0; i < group.mVertices.size(); i++)\n {\n auto& vertex = group.mVertices[i];\n auto deltaV = glm::dvec3(globalX(3 * i + 0), globalX(3 * i + 1), globalX(3 * i + 2));\n\n if (saveFrame)\n {\n auto& vert = *frame->mutable_vertices(i);\n *vert.mutable_force() = ProtoConverter::Convert(deltaV);\n }\n\n vertex.mVelocity += deltaV;\n vertex.mPosition += (double)timestep * vertex.mVelocity;\n }\n\n return true;\n\n // things to try:\n // - 'solveWithGuess' and providing the previous timestep's change in velocities as the guess?\n // - other preconditioners, solvers\n // - the doc's have globalX = solver.solve(globalB) twice, so maybe it tries for a specified number of\n // iterations each time and refines the solution.. ?\n }\n}\n\n////////////////////////////////////////////////////////////////////////////////", "meta": {"hexsha": "6cad84faa8a001db2c34d076ee7ea1acb8d78f21", "size": 34414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Source/ImplicitIntegrator.cpp", "max_stars_repo_name": "claytonkanderson/Fractus", "max_stars_repo_head_hexsha": "c4012cc40ee81ac042edcc5461c48e02456bcbd0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/ImplicitIntegrator.cpp", "max_issues_repo_name": "claytonkanderson/Fractus", "max_issues_repo_head_hexsha": "c4012cc40ee81ac042edcc5461c48e02456bcbd0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/ImplicitIntegrator.cpp", "max_forks_repo_name": "claytonkanderson/Fractus", "max_forks_repo_head_hexsha": "c4012cc40ee81ac042edcc5461c48e02456bcbd0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.7733887734, "max_line_length": 165, "alphanum_fraction": 0.4711164061, "num_tokens": 11921, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533051062238, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.6641232598922512}} {"text": "#include \"alpha.h\"\n\n#include \n#include \n#include \n\n#include \"operationVector.h\" // ceci va chercher le fichier qui contient les operations sur les vecteurs\n\nusing namespace std;\nusing namespace boost::numeric::ublas;\n\nmatrix Alpha(matrix Obs, matrix M, std::vector pie) {\n\n// \tObs est la matrice des observations\n// \tM est la matrice de transition\n// \tpie est le vecteur de probabilite initiale\n\n\tconst int m = Obs.size2(); // Nombre detat, de cases\n\tconst int n = Obs.size1(); // Nombre dobservation, duree de la partie\n\n//\tmatrix Alpha = matrix(NbLigne= n, NbCol= m); Initialisation de la matric Alpha de tailler n*m\n\tmatrix matAlpha(n, m);\n\tauto alph = std::vector(m, 0); // Declaration d'un vecteur de longueur m remplie de 0\n\n\tfor (int i = 0; i < m; ++i) {\n\t\talph[i] = pie[i] * Obs(0, i);\n\t}\n\n\tdouble log1surc = log(sum(alph)); // J'ai ajouter la fonction sum, qui fait la somme d'une matrice ou d'un vecteur\n\n// \talph = alph * (1 / std::accumulate(alph.begin(), alph.end(), 0));\n\talph = scalarMultiplication(alph, 1.0 / sum(alph));\n\n\tfor (int i = 0; i < m; ++i) {\n\t\tmatAlpha(0, i) = log(alph[i]) + log1surc;\n\t}\n\n\tauto Alph = matrix(1, m);\n\n\tfor (int i = 0 ; i < m ; ++i) {\n\t\tAlph(0, i) = alph[i];\n\t}\n\t\n\tfor (int i = 1; i < n ; ++i) { // J'ai changer la partie \"i < n, ++j\" pour \"i < n ; ++i\"\n\t\t\n\t\tAlph = prod(Alph, M); // prod est le produit matriciel\n\n\t\tfor (int j = 0; j < m ; ++j) {\n\t\t\tAlph(0, j) = Alph(0, j) * Obs(i, j);\n\t\t}\n\n\t\tlog1surc += log(sum(Alph));\n\t\tAlph /= sum(Alph);\n\n\t\tfor (int j = 0; j < m ; ++j) {\n\t\t\tmatAlpha(i, j) = log(Alph(0, j)) + log1surc;\n\t\t}\n\n\t}\n\t\n\treturn matAlpha;\n\n}\n", "meta": {"hexsha": "e68a60383be704e37df543d17697159845d30143", "size": 1707, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/alpha.cpp", "max_stars_repo_name": "Louis-Alexandre/Captain-Markov", "max_stars_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2015-04-24T17:44:11.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-29T09:47:49.000Z", "max_issues_repo_path": "src/alpha.cpp", "max_issues_repo_name": "Louis-Alexandre/Captain-Markov", "max_issues_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/alpha.cpp", "max_forks_repo_name": "Louis-Alexandre/Captain-Markov", "max_forks_repo_head_hexsha": "386724030b33e3bf996897db6bcf8c7b7d8c5f84", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.671875, "max_line_length": 115, "alphanum_fraction": 0.618629174, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008906, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6641216228382633}} {"text": "// The template and inlines for the -*- C++ -*- finite field classes.\n// Initially implemented by Wai-Shing Luk \n//\n\n/** @file include/GF.hpp\n * This is a C++ Library header.\n */\n\n#ifndef FUN_GF_HPP\n#define FUN_GF_HPP 1\n\n#include \n#include \n\nnamespace fun {\n/**\n * @defgroup GF Finite (Galois) Field\n * @ingroup arithmetic\n *\n * Classes and functions for (extended) finite field.\n * @{\n */\n\n// Forward declarations.\ntemplate struct GF;\n\n/**\n * finite (Galois) field.\n *\n * @param p Prime number\n */\ntemplate struct GF : boost::field_operators> {\n /// Default constructor.\n constexpr GF() noexcept : _m(0) {}\n\n /// Unspecified parameters default to 0.\n explicit GF(unsigned int m) noexcept : _m(m) { assert(_m < _p); }\n\n // Lets the compiler synthesize the copy constructor\n // GF (const GF<_p>&);\n /// Copy constructor\n GF(const GF<_p> &s) noexcept : _m(s.value()) { assert(_m >= 0); }\n\n /// Return internal element of finite field.\n constexpr unsigned int value() const noexcept { return _m; }\n\n // Lets the compiler synthesize the assignment operator\n // GF<_p>& operator= (const GF<_p>&);\n /// Assign this finite field to finite field @a s.\n GF<_p> &operator=(const GF<_p> &s) {\n _m = s.value();\n return *this;\n }\n\n /// Add @a s to this finite field.\n GF<_p> &operator+=(const GF<_p> &s) {\n _m += s.value();\n _m %= _p;\n assert(_m < _p);\n return *this;\n }\n\n /// Subtract @a s from this finite field.\n GF<_p> &operator-=(const GF<_p> &s) {\n _m += _p - s.value();\n _m = _m % _p;\n assert(_m < _p);\n return *this;\n }\n\n /// Multiply @a s to this finite field.\n GF<_p> &operator*=(const GF<_p> &s) {\n _m *= s.value();\n _m %= _p;\n assert(_m < _p);\n return *this;\n }\n\nprivate:\n unsigned int _m;\n};\n\n// Operators:\n/// Return new finite field @a r plus @a s.\ntemplate inline GF<_p> operator+(GF<_p> r, const GF<_p> &s) {\n return r += s;\n}\n\n/// Return new finite field @a r minus @a s.\ntemplate inline GF<_p> operator-(GF<_p> r, const GF<_p> &s) {\n return r -= s;\n}\n\n//@{\n/// Return new finite field @a r times @a a.\ntemplate inline GF<_p> operator*(GF<_p> r, const GF<_p> &s) {\n return r *= s;\n}\n//@}\n\n/// Return @a r.\ntemplate \ninline constexpr GF<_p> operator+(const GF<_p> &r) noexcept {\n return r;\n}\n\n/// Return negation of @a r\ntemplate inline GF<_p> operator-(const GF<_p> &r) {\n if (r.value() == 0)\n return r;\n return GF<_p>(_p - r.value());\n}\n\n/// Return true if @a r is equal to @a s.\ntemplate \ninline constexpr bool operator==(const GF<_p> &r, const GF<_p> &s) noexcept {\n return r.value() == s.value();\n}\n\n/// Return false if @a r is equal to @a s.\ntemplate \ninline constexpr bool operator!=(const GF<_p> &r, const GF<_p> &s) noexcept {\n return !(r == s);\n}\n\n/// Insertion operator for finite field values.\ntemplate \n_Stream &operator<<(_Stream &os, const GF<_p> &r) {\n os << '(' << r.value() << \" mod \" << _p << ')';\n return os;\n}\n}\n\n#endif\n", "meta": {"hexsha": "6474c018ce0253d0c7860aae09c205ae5ca03d95", "size": 3185, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/include/fun/GF.hpp", "max_stars_repo_name": "luk036/fun", "max_stars_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lib/include/fun/GF.hpp", "max_issues_repo_name": "luk036/fun", "max_issues_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/include/fun/GF.hpp", "max_forks_repo_name": "luk036/fun", "max_forks_repo_head_hexsha": "ac3896eb8741767324d6b400d38573a66f0917b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5925925926, "max_line_length": 79, "alphanum_fraction": 0.6163265306, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.904650527388829, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6641216066518806}} {"text": "/** @file\n * @ingroup utils\n *\n * Utility mathematical functions that do not fit anywhere else.\n *\n * The type definitions are shorthands for declaring `Eigen::Vector`,\n * `Eigen::Matrix` and `Eigen::Quaternion` objects. At current we assume all\n * slam code development will be using double precision floating points.\n */\n\n#ifndef WAVE_UTILS_MATH_HPP\n#define WAVE_UTILS_MATH_HPP\n\n#include \n#include \n\n#include \n#include \n\n\nnamespace wave {\n/** @addtogroup utils\n * @{ */\n\n#ifndef EIGEN_TYPEDEF\n#define EIGEN_TYPEDEF\ntypedef Eigen::Matrix Vec1;\ntypedef Eigen::Vector2d Vec2;\ntypedef Eigen::Vector3d Vec3;\ntypedef Eigen::Vector4d Vec4;\ntypedef Eigen::Matrix Vec5;\ntypedef Eigen::Matrix Vec6;\ntypedef Eigen::Matrix Vec12;\ntypedef Eigen::VectorXd VecX;\n\ntypedef Eigen::Matrix2d Mat2;\ntypedef Eigen::Matrix3d Mat3;\ntypedef Eigen::Matrix4d Mat4;\ntypedef Eigen::Matrix Mat5;\ntypedef Eigen::Matrix Mat6;\ntypedef Eigen::Matrix Mat12;\ntypedef Eigen::MatrixXd MatX;\n\ntypedef Eigen::Matrix Mat34;\n\ntypedef Eigen::Matrix Vec1f;\ntypedef Eigen::Vector2f Vec2f;\ntypedef Eigen::Vector3f Vec3f;\ntypedef Eigen::Vector4f Vec4f;\ntypedef Eigen::Matrix Vec5f;\ntypedef Eigen::Matrix Vec6f;\ntypedef Eigen::Matrix Vec12f;\ntypedef Eigen::VectorXf VecXf;\n\ntypedef Eigen::Matrix2f Mat2f;\ntypedef Eigen::Matrix3f Mat3f;\ntypedef Eigen::Matrix4f Mat4f;\ntypedef Eigen::Matrix Mat5f;\ntypedef Eigen::Matrix Mat6f;\ntypedef Eigen::Matrix Mat12f;\ntypedef Eigen::MatrixXf MatXf;\n\ntypedef Eigen::Matrix Mat34f;\n\ntypedef Eigen::Affine3d Affine3;\n\ntypedef Eigen::Quaterniond Quaternion;\n#endif\n\n/**\n * Eigen vector comparator\n */\nstruct VecComparator {\n bool operator()(const VecX &a, const VecX &b) const {\n return std::lexicographical_compare(\n a.data(), a.data() + a.size(), b.data(), b.data() + b.size());\n }\n};\n\n/**\n * Eigen matrix comparator\n */\nstruct MatComparator {\n bool operator()(const MatX &a, const MatX &b) const {\n return std::lexicographical_compare(\n a.data(), a.data() + a.size(), b.data(), b.data() + b.size());\n }\n};\n\n/** Generates random integer with a upper bound `ub` and lower bound `lb` using\n * a uniform random distribution. */\nint randi(int ub, int lb);\n\n/** Generates random float with a upper bound `ub` and lower bound `lb` using a\n * uniform random distribution. */\ndouble randf(double ub, double lb);\n\n/** Compares two floating point numbers `f1` and `f2` with an error threshold\n * defined by `threshold`.\n * @return\n * - `0`: If `f1` == `f2` or the difference is less then `threshold`\n * - `1`: If `f1` > `f2`\n * - `-1`: If `f1` < `f2`\n */\nint fltcmp(double f1, double f2, double threshold = 0.0001);\n\n/** @return the median of `v`. */\ndouble median(std::vector v);\n\n/** Converts degrees to radians. */\ndouble deg2rad(double d);\n\n/** Converts radians to degrees. */\ndouble rad2deg(double r);\n\n/** Reshapes a vector `x` to matrix `y` of size `rows` and `cols` */\nvoid vec2mat(std::vector x, int rows, int cols, MatX &y);\n\n/** Reshapes a matrix to a vector*/\nvoid mat2vec(MatX A, std::vector &x);\n\n/** Wraps `euler_angle` to 180 degrees **/\ndouble wrapTo180(double euler_angle);\n\n/** Wraps `euler_angle` to 360 degrees **/\ndouble wrapTo360(double euler_angle);\n\n/** Convert euler angle to rotation matrix **/\nint euler2rot(Vec3 euler, int euler_seq, Mat3 &R);\n\n/** Convert euler angle to quaternion **/\nint euler2quat(Vec3 euler, int euler_seq, Quaternion &q);\n\n/** Convert quaternion to euler angles **/\nint quat2euler(Quaternion q, int euler_seq, Vec3 &euler);\n\n/** Convert quaternion to rotation matrix **/\nint quat2rot(Quaternion q, Mat3 &R);\n\n/** ENU to NWU coordinate system **/\nvoid enu2nwu(const Vec3 &enu, Vec3 &nwu);\n\n/** NED to ENU coordinate system **/\nvoid ned2enu(const Vec3 &ned, Vec3 &enu);\n\n/** NED to NWU coordinate system **/\nvoid ned2nwu(const Quaternion &ned, Quaternion &enu);\n\n/** NWU to ENU coordinate system **/\nvoid nwu2enu(const Vec3 &nwu, Vec3 &enu);\n\n/** NWU to NED coordinate system **/\nvoid nwu2ned(const Quaternion &nwu, Quaternion &ned);\n\n/** NWU to EDN coordinate system **/\nvoid nwu2edn(const Vec3 &nwu, Vec3 &edn);\n\n/** @} group utils */\n} // namespace wave\n\n#endif // WAVE_UTILS_MATH_HPP\n", "meta": {"hexsha": "1ce58806ec9d28c6de443d33dbd0c845fbb55c11", "size": 4458, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "wave_utils/include/wave/utils/math.hpp", "max_stars_repo_name": "Jebediah/libwave", "max_stars_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-06-13T13:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-13T14:54:35.000Z", "max_issues_repo_path": "wave_utils/include/wave/utils/math.hpp", "max_issues_repo_name": "Jebediah/libwave", "max_issues_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "wave_utils/include/wave/utils/math.hpp", "max_forks_repo_name": "Jebediah/libwave", "max_forks_repo_head_hexsha": "c04998c964f0dc7d414783c6e8cf989a2716ad54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-13T02:27:29.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T02:27:29.000Z", "avg_line_length": 27.5185185185, "max_line_length": 79, "alphanum_fraction": 0.6982951996, "num_tokens": 1272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505248181418, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.664121604764689}} {"text": "\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace ublas = boost::numeric::ublas;\n/* Matrix inversion routine.\n Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */\n\nbool InvertMatrix (const ublas::matrix& input, ublas::matrix& inverse)\n{\n using namespace boost::numeric::ublas;\n typedef permutation_matrix pmatrix;\n // create a working copy of the input\n matrix A(input);\n // create a permutation matrix for the LU-factorization\n pmatrix pm(A.size1());\n // perform LU-factorization\n int res = lu_factorize(A,pm);\n if( res != 0 ) return false;\n // create identity matrix of \"inverse\"\n inverse.assign(ublas::identity_matrix(A.size1()));\n // backsubstitute to get the inverse\n lu_substitute(A, pm, inverse);\n return true;\n}\n\n\nbool InvertMatrixGen(const ublas::matrix& input, ublas::matrix& inverse)\n{\n const int n = input.size1();\n gsl_matrix *A = gsl_matrix_alloc(n,n);\n gsl_matrix *V = gsl_matrix_alloc(n,n);\n gsl_vector *S = gsl_vector_alloc(n);\n gsl_vector *work = gsl_vector_alloc(n);\n\n for(int i = 0; i < n; ++i) {\n for(int j = 0; j < n; ++j) {\n gsl_matrix_set(A,i,j,input(i,j));\n inverse(i,j) = 0.0;\n }\n }\n\n gsl_linalg_SV_decomp(A,V,S,work);\n\n const double smax = gsl_vector_get(S,0);\n for(int k = 0; k < n; ++k) {\n const double s = gsl_vector_get(S,k);\n if(s/smax > 1.0e-8) {\n for(int i = 0; i < n; ++i) {\n\tfor(int j = 0; j < n; ++j) {\n\t inverse(i,j) += gsl_matrix_get(V,i,k) * gsl_matrix_get(A,j,k) / s;\n\t}\n }\n }\n }\n\n gsl_matrix_free(A);\n gsl_matrix_free(V);\n gsl_vector_free(S);\n gsl_vector_free(work);\n return true;\n}\n", "meta": {"hexsha": "9810d6ae1f4d11a5f7eead0f617c517e46c268cf", "size": 1969, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/InvertMatrix.cpp", "max_stars_repo_name": "arkinjo/lgm_mc", "max_stars_repo_head_hexsha": "4da0b9e492c0f312a6c199050111207f390c8cac", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/InvertMatrix.cpp", "max_issues_repo_name": "arkinjo/lgm_mc", "max_issues_repo_head_hexsha": "4da0b9e492c0f312a6c199050111207f390c8cac", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/InvertMatrix.cpp", "max_forks_repo_name": "arkinjo/lgm_mc", "max_forks_repo_head_hexsha": "4da0b9e492c0f312a6c199050111207f390c8cac", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7323943662, "max_line_length": 88, "alphanum_fraction": 0.6724225495, "num_tokens": 591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096158798117, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6640606411609803}} {"text": "#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\ntypedef CGAL::Periodic_4_hyperbolic_Delaunay_triangulation_traits_2<> Traits;\ntypedef Traits::FT NT;\ntypedef Traits::Point_2 Point;\ntypedef Traits::Circle_2 Circle;\ntypedef Traits::Euclidean_line_2 Line;\ntypedef Traits::Construct_intersection_2 Construct_intersection_2;\n\nint main(int /*argc*/, char** /*argv*/)\n{\n NT F2(2);\n\n Line ell1(NT(1), sqrt(F2 - sqrt(F2)), NT(0));\n Line ell2(NT(1), -sqrt(F2 + sqrt(F2)), NT(0));\n\n // In the Poincaré disk, all Euclidean lines pass through the origin\n NT sx = NT(0);\n NT sy = NT(0);\n Point sol(sx, sy);\n\n Point p = Construct_intersection_2()(ell1, ell2);\n std::cout << \"line-line intersection: \" << p << \", solution is: \" << sol << std::endl;\n assert(p == sol);\n std::cout << \"The solution is exact!\" << std::endl;\n\n Point pc1(NT(2)/NT(10), NT(5)/NT(10));\n Point pc2(-NT(3)/NT(10), NT(15)/NT(100));\n Point pc3(NT(20)/NT(29), NT(50)/NT(29));\n Circle c1(pc1, pc2, pc3);\n std::pair ipt = Construct_intersection_2()(ell1, c1);\n Point ip1 = ipt.first, ip2 = ipt.second;\n\n NT sq(sqrt(NT(2)));\n NT nsq( sqrt( NT(2) - sqrt(NT(2)) ) );\n NT sol1x( nsq*(NT(2438)+NT(1451)*nsq-sqrt(NT(3933846)-NT(31801)*sq+NT(7075076)*nsq))/(-NT(4320)+NT(1440)*sq) );\n NT sol1y( (-NT(2438)-NT(1451)*nsq+sqrt(NT(3933846)-NT(31801)*sq+NT(7075076)*nsq))/(-NT(4320)+NT(1440)*sq) );\n Point solution1(sol1x, sol1y);\n\n std::cout << \"Intersection of circle and line: \" << ip1 << \" and \" << ip2 << std::endl;\n std::cout << \"Solution: \" << solution1 << std::endl;\n assert(ip1 == solution1 || ip2 == solution1);\n std::cout << \"The solution is exact!\" << std::endl;\n\n Point pc4(NT(2)/NT(10), -NT(15)/NT(100));\n Circle c2(pc1, pc4, pc3);\n\n std::pair cpt = Construct_intersection_2()(c1, c2);\n ip1 = cpt.first;\n ip2 = cpt.second;\n std::cout << \"Intersection of circles: \" << ip1 << \" and \" << ip2 << std::endl;\n assert(ip1 == pc1 || ip2 == pc1);\n std::cout << \"The solution is exact!\" << std::endl;\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "38648d8603ab3b464722c68c6018ad0191e4fc94", "size": 2571, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Periodic_4_hyperbolic_triangulation_2/test/Periodic_4_hyperbolic_triangulation_2/test_p4ht2_intersections.cpp", "max_stars_repo_name": "ffteja/cgal", "max_stars_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3227.0, "max_stars_repo_stars_event_min_datetime": "2015-03-05T00:19:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:20:35.000Z", "max_issues_repo_path": "Periodic_4_hyperbolic_triangulation_2/test/Periodic_4_hyperbolic_triangulation_2/test_p4ht2_intersections.cpp", "max_issues_repo_name": "ffteja/cgal", "max_issues_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 5574.0, "max_issues_repo_issues_event_min_datetime": "2015-03-05T00:01:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:08:11.000Z", "max_forks_repo_path": "Periodic_4_hyperbolic_triangulation_2/test/Periodic_4_hyperbolic_triangulation_2/test_p4ht2_intersections.cpp", "max_forks_repo_name": "ffteja/cgal", "max_forks_repo_head_hexsha": "c1c7f4ad9a4cd669e33ca07a299062a461581812", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 1274.0, "max_forks_repo_forks_event_min_datetime": "2015-03-05T00:01:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:47:56.000Z", "avg_line_length": 39.5538461538, "max_line_length": 113, "alphanum_fraction": 0.5877090626, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6640606231658388}} {"text": "/*\n * DataSet.cpp\n *\n * Created on: 2014/06/11\n * Author: kryozahiro\n */\n\n#include \"DataSet.h\"\n\n#include \n#include \n#include \"cpputil/GenericIo.h\"\nusing namespace std;\nusing namespace cpputil;\n\nstd::vector DataSet::nguyen(int dimension, const std::vector& input) {\n\tvector output(1, 0);\n\tfor (int i = 1; i <= dimension; ++i) {\n\t\toutput[0] += pow(input[0], (double)i);\n\t}\n\treturn output;\n}\n\nstd::vector DataSet::rosenbrock(const std::vector& input) {\n\tvector output(1, 0);\n\tfor (unsigned int i = 0; i < input.size() - 1; ++i) {\n\t\toutput[0] += 100.0 * pow(input[i + 1] - input[i] * input[i], 2.0) + pow(input[i] - 1.0, 2.0);\n\t}\n\treturn output;\n}\n\nstd::vector DataSet::schwefel(const std::vector& input) {\n\tvector output(1, 418.9829 * input.size());\n\tfor (unsigned int i = 0; i < input.size(); ++i) {\n\t\toutput[0] -= input[i] * sin(sqrt(abs(input[i])));\n\t}\n\treturn output;\n}\n\nstd::vector DataSet::sphere(const std::vector& input) {\n\tvector output(1, 0);\n\tfor (unsigned int i = 0; i < input.size(); ++i) {\n\t\toutput[0] += input[i] * input[i];\n\t}\n\treturn output;\n}\n\nstd::vector DataSet::threeHumpCamel(const std::vector& input) {\n\tvector output(1, 0);\n\toutput[0] = 2.0*input[0]*input[0] - 1.05*pow(input[0], 4.0) + pow(input[0], 6.0)/6.0 + input[0]*input[1] + input[1]*input[1];\n\treturn output;\n}\n\nDataSet::DataSet() {\n}\n\nDataSet::DataSet(const ProgramType& programType) : programType(programType) {\n}\n\nDataSet::DataSet(const boost::property_tree::ptree& dataTree, mt19937_64& randomEngine) {\n\tstring name = dataTree.get(\"Name\");\n\tint dimension = dataTree.get(\"Dimension\");\n\tint size = dataTree.get(\"Size\");\n\tif (name.find(\"Nguyen\") != string::npos) {\n\t\tprogramType = ProgramType(DataType(-1, 1, 0.001, 1), DataType(DBL_MIN, DBL_MAX, 0.001, 1));\n\t\taddData(randomEngine, size, [=](const vector& input) {\n\t\t\treturn nguyen(dimension, input);\n\t\t});\n\t} else if (name.find(\"Rosenbrock\") != string::npos) {\n\t\tprogramType = ProgramType(DataType(-5, 10, 0.001, dimension), DataType(DBL_MIN, DBL_MAX, 0.001, 1));\n\t\taddData(randomEngine, size, rosenbrock);\n\t} else if(name.find(\"Schwefel\") != string::npos) {\n\t\tprogramType = ProgramType(DataType(-500, 500, 0.001, dimension), DataType(DBL_MIN, DBL_MAX, 0.001, 1));\n\t\taddData(randomEngine, size, schwefel);\n\t} else if (name.find(\"Sphere\") != string::npos) {\n\t\tprogramType = ProgramType(DataType(-5.12, 5.12, 0.001, dimension), DataType(DBL_MIN, DBL_MAX, 0.001, 1));\n\t\taddData(randomEngine, size, sphere);\n\t} else if (name.find(\"ThreeHumpCamel\") != string::npos) {\n\t\tprogramType = ProgramType(DataType(-5, 5, 0.001, 2), DataType(DBL_MIN, DBL_MAX, 0.001, 1));\n\t\taddData(randomEngine, size, threeHumpCamel);\n\t} else {\n\t\tassert(false);\n\t}\n}\n\nconst ProgramType& DataSet::getProgramType() const {\n\treturn programType;\n}\n\nint DataSet::getSize() const {\n\treturn data.size();\n}\n\npair, vector>& DataSet::operator[](int i) {\n\treturn data[i];\n}\n\nconst pair, vector>& DataSet::operator[](int i) const {\n\treturn data[i];\n}\n\nvector& DataSet::getInput(int i) {\n\treturn data[i].first;\n}\n\nvector& DataSet::getOutput(int i) {\n\treturn data[i].second;\n}\n\nvoid DataSet::addData(const vector& input, const vector& output) {\n\tdata.push_back(make_pair(input, output));\n}\n\nstring DataSet::toString() const {\n\tstring ret = \"DataSet\\n\";\n\tfor (const pair, vector>& point : data) {\n\t\tret += boost::lexical_cast(point) + \"\\n\";\n\t}\n\treturn ret;\n}\n", "meta": {"hexsha": "14904c4ed0466610a8f672d47c8f0a42d72b01ed", "size": 3638, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gamesolver/problem/DataSet.cpp", "max_stars_repo_name": "kryozahiro/gamesolver", "max_stars_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gamesolver/problem/DataSet.cpp", "max_issues_repo_name": "kryozahiro/gamesolver", "max_issues_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gamesolver/problem/DataSet.cpp", "max_forks_repo_name": "kryozahiro/gamesolver", "max_forks_repo_head_hexsha": "e5367c292cd9791c1758ac02df226efcb748cd67", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-10-06T16:06:10.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-06T16:06:10.000Z", "avg_line_length": 30.0661157025, "max_line_length": 126, "alphanum_fraction": 0.6676745465, "num_tokens": 1115, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.664017425112838}} {"text": "#include \n#include \n#include \n#include \nusing namespace std;\n\n/**********************************************************\n\nThis is the program for the bifurcation diagram! :D\nThe flow is simple: For each r value between 1 and 4 (with\nresolution of dr), 100 values of the logistic map are saved\nin the solutions vector. The values are chosen far enough\naway from the origin to remove the effects of the initial\nbehavior. The values are paired with the r value they were\ncalculated at and then sent to the plotter.\n\n**********************************************************/\n\nconst int START = 900;\nconst int CUTOFF = 1000;\t// Cutoff value for finding attractors\nconst double dr = 0.001;\nconst double x0 = 0.5;\t\t// Initial value\n\nvoid plotStuff(vector x, vector y){\t// Pretty plotting shenanigans\n\tGnuplot gp;\n\n\tgp << \"set xrange [1:4]\\n\";\n\tgp << \"set yrange [0:1]\\n\";\n\tgp << \"set term wxt font \\\"FreeSerif,12\\\"\\n\";\n\tgp << \"set title \\\"End Behavior of the Logistic Function vs. Growth Rate (x_0 = 0.5)\\\"\\n\";\n\tgp << \"set xlabel \\\"r\\\"\\n\";\n\tgp << \"set ylabel \\\"x_n\\\"\\n\";\n\tgp << \"set output \\\"plot.png\\\"\\n\";\n\tgp << \"plot '-' with dots lc rgb \\\"black\\\" notitle\\n\";\n\tgp.send1d(boost::make_tuple(x,y));\n}\n\nvector getSolutions(double r){\n\tdouble x = x0;\t\t\t\t\t\t\t// Set up x_0\n\tvector out;\t\t\t\t\t\t// All the solutions for this value of r\n\n\tfor(int i = 0; i < CUTOFF; i++){\t\t// Loop until the cutoff\n\t\tif(i >= START){out.push_back(x);}\t// Push the x value onto the vector of values, but only after a few (900) iterations to observe only the long-term behavior\n\t\tx = r*x*(1-x);\t\t\t\t\t\t// Perform the logistic map operation x_n+1 = r*x_n*(1-x_n)\n\t}\n\n\treturn out;\n}\n\nint main(){\n\tvector rvals;\t\t\t\t\t// R values (there will be lots of repeats since each r value has 100 solutions)\n\tvector solutions;\t\t\t\t// Solutions\n\n\tfor(double r = 1; r < 4; r += dr){\t\t// between r=1 and r=4\n\t\tvector s = getSolutions(r);\t// Get the solutions for that value of r\n\n\t\tfor(int i = 0; i < s.size(); i++){\t// Go through all solutions\n\t\t\tsolutions.push_back(s[i]);\t\t// Add them to the main list\n\t\t\trvals.push_back(r);\t\t\t\t// Along with the value of r they were recorded at\n\t\t}\n\t}\n\n\tcout << \"Done with calculation!\\n\";\t\t// This is for debug\n\n\tplotStuff(rvals,solutions);\t\t\t\t// Plot it!\n}", "meta": {"hexsha": "c56229b95a41a891b6af3a0bcd75cd42e1618a7d", "size": 2376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Logistic Map/FullPlot.cpp", "max_stars_repo_name": "GEslinger/PhysClass", "max_stars_repo_head_hexsha": "5e34167c34ca0e8779e4002063d95ffa24a24c9d", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Logistic Map/FullPlot.cpp", "max_issues_repo_name": "GEslinger/PhysClass", "max_issues_repo_head_hexsha": "5e34167c34ca0e8779e4002063d95ffa24a24c9d", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Logistic Map/FullPlot.cpp", "max_forks_repo_name": "GEslinger/PhysClass", "max_forks_repo_head_hexsha": "5e34167c34ca0e8779e4002063d95ffa24a24c9d", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.0, "max_line_length": 159, "alphanum_fraction": 0.6372053872, "num_tokens": 679, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8031737963569016, "lm_q2_score": 0.8267117919359419, "lm_q1q2_score": 0.6639932484222074}} {"text": "/*\n * Main.cpp\n *\n * Created on: Nov 10, 2015\n * Author: doncole\n */\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nArrayXXf InitMatrix(ArrayXXf matrix);\nArrayXf InitVector(ArrayXf vector);\nArrayXXf AddRowToMatrix(ArrayXf rowA, ArrayXXf matrixU, int i);\nArrayXf AddNumBToVectorB(float numB,ArrayXf vectorB, int j);\n\n\nint main(void){\n\n\tint squareNum = 7;\t//square matrix 7x7 and vector = 7\n\n\tArrayXXf matrixA(squareNum,squareNum);\n\tArrayXXf matrixU(squareNum,squareNum);\n\tArrayXf vectorB(squareNum);\n\tArrayXf rowA(squareNum), rowB(squareNum), solutionX(squareNum);\n\tfloat numA, numB;\n\t//Init the Matrix and Vector\n\tmatrixA = InitMatrix(matrixA);\n\tvectorB = InitVector(vectorB);\n\tmatrixU = matrixA;\n\n\tcout << \"Matrix A \" << endl << matrixA << endl;\n\tcout << \"Vector B \" << endl << vectorB << endl;\n\t//Solve by G.E.\n\t//iterate squareNum-1 times\n\tfor (int i = 0; i < squareNum -1; i++)\n\t{\n\t\trowA = matrixU.row(i);\t//Get the row\n\t\tnumA = rowA[i];\t//Get the Rows first number\n\t\trowA = rowA/numA; \t//divide the row by the number\n\t\tnumB = vectorB[i]/numA;\t//divide the Vector by the number\n\t\t//numB = vectorB[i];\t//copy the number for the rest of the vector\n\n\t\tfor (int j = i+1; j< squareNum; j++)\n\t\t{\n\t\t\trowB = rowA;\t//get the beginning Row again\n//\t\t\tcout << \"Matrix U\" << endl << matrixU << endl;\t//print the Matrix out\n\t\t\t//Multiply the Row by the Next row's first Integer\n\t\t\t//get the next rows first integer\n//\t\t\tcout << \"The next Rows integer\" << matrixU.row(j)[i] << endl;\n\t\t\trowB = rowB * (-1.0) * matrixU.row(j)[i];\n\t\t\tnumB = (numB * (-1.0) * matrixU.row(j)[i]);\n//\t\t\tcout << \"The num B \" << endl << numB << endl;\n//\t\t\tcout << \"The row multiplied By\" << endl << rowB << endl;\n\t\t\t//Add the row to the next Rows\n\t\t\tmatrixU = AddRowToMatrix(rowB, matrixU, j);\t\t//add the row to the rest of the matrix\n\t\t\tvectorB = AddNumBToVectorB(numB, vectorB, j);\t//add the number to the rest of the vector\n\t\t}\n\t}\n\tsolutionX[squareNum-1] = vectorB[squareNum-1]/matrixU.row(squareNum-1)[squareNum-1];\n//\tcout << \"Solution X\" << endl << solutionX << endl;\n\n\tfor (int i = squareNum-2; i>-1; i--)\n\t{\n\t\tfloat sum = 0;\n//\t\tcout << \"VectorB\" << endl << vectorB[i] << endl;\n//\t\tmatrixU.row(i)/matrixU.row(i)[i];\n//\t\tvectorB[i] = vectorB[i]/matrixU.row(i)[i];\n//\t\tcout << \"Matrix U\" << endl << matrixU << endl;\n//\t\tcout << \"Vector B\" << endl << vectorB << endl;\n\n\t\tfor (int j = 6; j > i; j--)\n\t\t{\n\t\t\tsum = sum + matrixU.row(i)[j] * solutionX[i+1];\n\t\t\t//cout << \"sum\" << endl << sum << endl;\n\t\t}\n\t\tsolutionX[i] = (vectorB[i] - sum)/matrixU.row(i)[i];\n//\t\tcout << \"Solution X\" << endl << solutionX << endl;\n\t}\n\t//Print the outputs\n\tcout << \"Matrix U \" << endl << matrixU << endl;\n\tcout << \"Vector B \" << endl << vectorB << endl;\n\tcout << \"The Solution Matrix \" << endl << solutionX << endl;\n\n\treturn 0;\n}\n\nArrayXf AddNumBToVectorB(float numB, ArrayXf vectorB, int row)\n{\n\t//vectorB[0] = 100.0;\n\twhile (row < 7)\n\t{\n\t\tvectorB[row] = vectorB[row] + numB;\n\t\trow++;\n\t}\n\t//print the Vector\n\t//cout << \"VectorB\" << endl << vectorB << endl;\n\treturn vectorB;\n}\n\nArrayXXf AddRowToMatrix(ArrayXf rowA, ArrayXXf matrixU, int row)\n{\n\t//we need to construct the matrices\n\t//By first adding the row to the rest of the matrix\n//\tArrayXXf tempArray(7, 7);\n//\ttempArray = matrixU.array();\n\twhile (row < 7)\n\t{\n\t\t//add to the rest of the rows\n\t\tmatrixU.row(row) += rowA;\n\t\trow++;\n\t}\n\t//print the array\n\t//cout << \"MatrixU\" << endl << matrixU << endl;\n\treturn matrixU;\n}\n\n//Initialize the Given 7x7 Matrix\nArrayXXf InitMatrix(ArrayXXf matrix)\n{\n\tint i= 0, j = 0;\n\t//First Row\n\tmatrix(i, j++) = .1897;\n\tmatrix(i, j++) = .3784;\n\tmatrix(i, j++) = .6449;\n\tmatrix(i, j++) = .7271;\n\tmatrix(i, j++) = .4449;\n\tmatrix(i, j++) = .1730;\n\tmatrix(i, j++) = .0118;\n\tj = 0;\n\ti++;\n\t//Second Row\n\tmatrix(i, j++) = .1934;\n\tmatrix(i, j++) = .8600;\n\tmatrix(i, j++) = .8180;\n\tmatrix(i, j++) = .3093;\n\tmatrix(i, j++) = .6946;\n\tmatrix(i, j++) = .9797;\n\tmatrix(i, j++) = .8939;\n\tj = 0;\n\ti++;\n\t//Third Row\n\tmatrix(i, j++) = .6822;\n\tmatrix(i, j++) = .8537;\n\tmatrix(i, j++) = .6602;\n\tmatrix(i, j++) = .8385;\n\tmatrix(i, j++) = .6213;\n\tmatrix(i, j++) = .2714;\n\tmatrix(i, j++) = .1991;\n\tj = 0;\n\ti++;\n\t//FourthRow\n\tmatrix(i, j++) = .3028;\n\tmatrix(i, j++) = .5936;\n\tmatrix(i, j++) = .3420;\n\tmatrix(i, j++) = .5681;\n\tmatrix(i, j++) = .7948;\n\tmatrix(i, j++) = .2523;\n\tmatrix(i, j++) = .2987;\n\tj = 0;\n\ti++;\n\t//Fifth Row\n\tmatrix(i, j++) = .5417;\n\tmatrix(i, j++) = .4966;\n\tmatrix(i, j++) = .2897;\n\tmatrix(i, j++) = .3704;\n\tmatrix(i, j++) = .9568;\n\tmatrix(i, j++) = .8757;\n\tmatrix(i, j++) = .6614;\n\tj = 0;\n\ti++;\n\t//6th Row\n\tmatrix(i, j++) = .1509;\n\tmatrix(i, j++) = .8998;\n\tmatrix(i, j++) = .3412;\n\tmatrix(i, j++) = .7027;\n\tmatrix(i, j++) = .5226;\n\tmatrix(i, j++) = .7373;\n\tmatrix(i, j++) = .2844;\n\tj = 0;\n\ti++;\n\t//7th Row\n\tmatrix(i, j++) = .6979;\n\tmatrix(i, j++) = .8216;\n\tmatrix(i, j++) = .5341;\n\tmatrix(i, j++) = .5466;\n\tmatrix(i, j++) = .8801;\n\tmatrix(i, j++) = .1365;\n\tmatrix(i, j++) = .4692;\n\n\treturn matrix;\n}\n\nArrayXf InitVector(ArrayXf vector){\n\tint i = 0;\n\tvector(i++) = .5000;\n\tvector(i++) = -.3000;\n\tvector(i++) = -.2000;\n\tvector(i++) = .7000;\n\tvector(i++) = -.9000;\n\tvector(i++) = .3000;\n\tvector(i++) = .1000;\n\treturn vector;\n}\n", "meta": {"hexsha": "5181d45d1fdd4d379395facab9174e63df8d7d8b", "size": 5235, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Main.cpp", "max_stars_repo_name": "DonaldCole33/Gaussian-Elimination", "max_stars_repo_head_hexsha": "c9f35630bd7778949a69e9cf780a13964a1e421c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Main.cpp", "max_issues_repo_name": "DonaldCole33/Gaussian-Elimination", "max_issues_repo_head_hexsha": "c9f35630bd7778949a69e9cf780a13964a1e421c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Main.cpp", "max_forks_repo_name": "DonaldCole33/Gaussian-Elimination", "max_forks_repo_head_hexsha": "c9f35630bd7778949a69e9cf780a13964a1e421c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.04784689, "max_line_length": 91, "alphanum_fraction": 0.5866284623, "num_tokens": 1841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6638789732318886}} {"text": "/* Last Revised Date: 13_DEC_2014 */\n/* Lastest status: All ok */\n\n/*\n det_model_hh_post.hpp : implimentation of HH system (similar but not exact for the classical HH equations) \n !!!NOTE: all units are in SI system\n\n Copyright (C) 2015 Anup Gopalakrishna Pillai, Suhita Nadkarni Lab, IISER Pune \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 .\n*/\n\n#ifndef DET_MODEL_HH_POST_HPP_INCLUDED\n#define DET_MODEL_HH_POST_HPP_INCLUDED\n\n#include \n#include \n#include \n#include \n\n//UNITS: all SI units - seconds, Volts, Ampere, Meters, Simenes, Farads\n\n//DECLARATIONS FOR HH_POST_MODEL\n\nclass DET_MODEL_HH_POST\n{\nprivate:\n const double pi = boost::math::constants::pi();\n double Cm = 1.0E-02; // F/m^2 Specific capacitance\n //----Reversal potentials for Na, K, channels in mV\n double ENa = 50.0E-03; // Reversal potential for Sodium currents in Volts\n double EK = -85.0E-03; // Reversal potential for Potassium currents in Volts\n double ELeak = -81E-03; // Reversal potential for Leak currents in Volts\n\n double GNa = 130E01; // Maximum conductance for Sodium channels S/m^2\n double GK = 36E01; // Maximum conductance for Potassium channels S/m^2\n double GLeak = 0.3E01; // Maximum conductance for Leak channels S/m^2\n\npublic:\n std::vector X;\n\n double IExt = 0.0; //extern current in Amps\n double Area = 0.0;\n double Cap = 0.0;\n double V = 0.0; // Membrane voltage V\n /* NEURON class explicit constructor */\n explicit DET_MODEL_HH_POST( std::vector X_ = {0,0,0,0},double Area_ = 8.5E-12): Area(Area_), X(X_), Cap(Cm * Area) // Area in m^2\n {\n };\n //---Equations for bouton Na Channel (Ref: Dominique Engel & Peter Jonas, 2005, Neuron)\n double alpha_Na_act(const double V);\n double beta_Na_act(const double V);\n double alpha_Na_inact(const double V);\n double beta_Na_inact(const double V);\n //---Equations for bouton K Channel (Ref: Dominique Engel & Peter Jonas, 2005, Neuron)\n double alpha_K_act(const double V);\n double beta_K_act(const double V);\n //---Declaration of the ODE solver\n template \n void operator() ( const State &x, State &dxdt , const double t );\n};\n//Function declarations\n//------------- Na+ channels --- implimented from classical HH (1952)\ndouble DET_MODEL_HH_POST::alpha_Na_act(const double V)\n{\n double a = 0.1E03;\n double b = 45.33E-03;\n double c = 10E-03;\n double val = 0.0;\n val = (- a * ( (V + b) / (exp( -(V + b) / c ) - 1 ) ) );\n return (val);\n}\ndouble DET_MODEL_HH_POST::beta_Na_act(const double V)\n{\n double a = 4;\n double b = 70.33E-03;\n double c = 18E-03;\n double val = 0.0;\n val = ( a * ( exp( - (V + b) / c )) );\n return (val);\n}\ndouble DET_MODEL_HH_POST::alpha_Na_inact(const double V)\n{\n double val = 0.0;\n val = 0.07 * exp( -( V + 70.33E-03) /20E-03 );\n return (val);\n}\ndouble DET_MODEL_HH_POST::beta_Na_inact(const double V)\n{\n double val = 0.0;\n val = ( 1 / ( exp( - (V + 40.33E-03) / 10E-03) + 1) );\n return (val);\n}\n//--------K+ channel alpha & beta\ndouble DET_MODEL_HH_POST::alpha_K_act(const double V)\n{\n double val = 0;\n val = -0.01E03 * (V + 60.33E-03) / ( exp( -(V + 60.33E-03) / 10E-03) - 1 );\n return (val);\n};\ndouble DET_MODEL_HH_POST::beta_K_act(const double V)\n{\n double val = 0.0;\n val = 0.125 * exp (- (V + 70.33E-03) / 80E-03);\n return (val);\n};\n//-------HH_PRE class ODE Function\n\ntemplate \nvoid DET_MODEL_HH_POST::operator() ( const State &x, State &dxdt , const double t )\n{\n\n dxdt[0] = 1E03 * (( alpha_Na_act(x[3]) * (1 - x[0]) ) - (beta_Na_act(x[3]) * x[0]) ); // Na activation\n dxdt[1] = 1E03 * ( ( alpha_Na_inact(x[3]) * (1 - x[1]) ) - (beta_Na_inact(x[3]) * x[1])) ; // Na inactivation\n dxdt[2] = 1E03 * ( ( alpha_K_act(x[3]) * (1 - x[2]) ) - (beta_K_act(x[3]) * x[2])); // K activation\n double INa = -(Area * GNa * pow(x[0],3) * x[1] * (x[3] - ENa) );\n double IK = -(Area * GK * pow(x[2],4) * (x[3] - EK) );\n double ILeak = -(Area * GLeak * (x[3] - ELeak) );\n dxdt[3] = (1/Cap) * (INa + IK + ILeak + (IExt * Area) );\n};\n#endif // DET_MODEL_HH_POST_HPP_INCLUDED\n", "meta": {"hexsha": "578e80798bb53463902374952cad21bc4e9c507d", "size": 4729, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/old/src/old/det_model_hh_post.hpp", "max_stars_repo_name": "anupgp/astron", "max_stars_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/old/src/old/det_model_hh_post.hpp", "max_issues_repo_name": "anupgp/astron", "max_issues_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/old/src/old/det_model_hh_post.hpp", "max_forks_repo_name": "anupgp/astron", "max_forks_repo_head_hexsha": "5ef1b113b5025f5e0477a1fb2b5202fadbc5335c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.5563909774, "max_line_length": 139, "alphanum_fraction": 0.6582787059, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6638328812628568}} {"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Schüttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearfeelementmatrix.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix 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 elem_mat;\n\n //====================\n\n // Get element matrix for negative laplacian of given cell\n lf::uscalfe::LinearFELaplaceElementMatrix prov;\n Eigen::MatrixXd A = prov.Eval(cell);\n\n // First get the area\n double K = lf::geometry::Volume(*geo_ptr);\n\n // Initialize elem. stiffness matrix\n Eigen::Matrix M;\n\n if (ref_el == lf::base::RefEl::kTria()) {\n M << 2.0, 1.0, 1.0, 0.0,\n 1.0, 2.0, 1.0, 0.0,\n 1.0, 1.0, 2.0, 0.0,\n 0.0, 0.0, 0.0, 0.0;\n M *= K/12.0;\n } else if (ref_el == lf::base::RefEl::kQuad()) {\n M << 4.0, 2.0, 1.0, 2.0,\n 2.0, 4.0, 2.0, 1.0,\n 1.0, 2.0, 4.0, 2.0,\n 2.0, 1.0, 2.0, 4.0;\n M *= K/36.0;\n }\n\n elem_mat = A + M;\n\n //====================\n\n return elem_mat;\n}\n/* SAM_LISTING_END_1 */\n} // namespace ElementMatrixComputation\n", "meta": {"hexsha": "47179916716ee0c09d74aa7a4a88cdec68919281", "size": 1764, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9411764706, "max_line_length": 64, "alphanum_fraction": 0.6224489796, "num_tokens": 605, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7772998663336157, "lm_q1q2_score": 0.6637462802890418}} {"text": "/**\n \\file conjugate_gradient.hpp\n \\brief powerll optimization method\n \\author Junhua Gu\n */\n\n#ifndef CONJUGATE_GRADIENT\n#define CONJUGATE_GRADIENT\n#define OPT_HEADER\n#include \n//#include \n#include \n#include \n#include \n#include \"../linmin/linmin.hpp\"\n#include \n#include \n#include \n\nnamespace opt_utilities\n{\n /**\n \\brief Impliment of an optimization method\n \\tparam rT return type of the object function\n \\tparam pT parameter type of the object function\n */\n template \n class conjugate_gradient\n :public opt_method\n {\n public:\n typedef pT array1d_type;\n typedef rT T;\n private:\n func_obj* p_fo;\n optimizer* p_optimizer;\n volatile bool bstop;\n //typedef blitz::Array array2d_type;\n \n const char* do_get_type_name()const\n {\n return \"conjugate gradient method\";\n }\n private:\n array1d_type start_point;\n array1d_type end_point;\n \n private:\n rT threshold;\n array1d_type g;\n array1d_type h;\n array1d_type xi;\n private:\n rT func(const pT& x)\n {\n assert(p_fo!=0);\n return p_fo->eval(x);\n }\n\n \n private:\n void clear_xi()\n {\n }\n\n void init_xi(int n)\n {\n clear_xi();\n g=array1d_type(n);\n h=array1d_type(n);\n xi=array1d_type(n);\n }\n\n\n\n void cg(array1d_type& p,const T ftol,\n\t int& iter,T& fret)\n {\n const int ITMAX=200;\n const T EPS=std::numeric_limits::epsilon();\n \n int j,its;\n int n=p.size();\n T gg,gam,fp,dgg;\n fp=func(p);\n xi=gradient(*p_fo,p);\n for(j=0;j& rhs)\n :opt_method(rhs),p_fo(rhs.p_fo),p_optimizer(rhs.p_optimizer),\n start_point(rhs.start_point),\n end_point(rhs.end_point),\n threshold(rhs.threshold),g(0),h(0),xi(0)\n {\n }\n\n conjugate_gradient& operator=(const conjugate_gradient& rhs)\n {\n threshold=rhs.threshold;\n p_fo=rhs.p_fo;\n p_optimizer=rhs.p_optimizer;\n start_point=rhs.start_point;\n end_point=rhs.end_point;\n threshold=rhs.threshold;\n }\n \n opt_method* do_clone()const\n {\n return new conjugate_gradient(*this);\n }\n \n void do_set_start_point(const array1d_type& p)\n {\n resize(start_point,get_size(p));\n opt_eq(start_point,p);\n }\n\n array1d_type do_get_start_point()const\n {\n return start_point;\n }\n\n void do_set_lower_limit(const array1d_type& p)\n {}\n\n void do_set_upper_limit(const array1d_type& p)\n {}\n\n void do_set_precision(rT t)\n {\n threshold=t;\n }\n\n rT do_get_precision()const\n {\n return threshold;\n }\n\n void do_set_optimizer(optimizer& o)\n {\n p_optimizer=&o;\n p_fo=p_optimizer->ptr_func_obj();\n }\n \n \n \n pT do_optimize()\n {\n bstop=false;\n init_xi((int)get_size(start_point));\n \n int iter=100;\n opt_eq(end_point,start_point);\n rT fret;\n#if 0\n for(int i=0;i\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\n\nusing namespace std;\n\nnamespace vc\n{\nint my_round(const unsigned type, const float value)\n{\n\tswitch (type) {\n\tcase 0:\n\t\treturn floor(value);\n\t\tbreak;\n\tcase 1:\n\t\treturn ceil(value);\n\t\tbreak;\n\tdefault:\n\t\treturn round(value);\n\t\tbreak;\n\t}\n}\n\n///\n/// \\brief computeTrilinearInterpolatedValue Compute an interpolated value at the position, considering the grid\n/// \\param grid Grid to consider for the interpolated value\n/// \\param dim Dimension of the grid\n/// \\param gridPosition Position at which to compute the interpolated value\n/// \\return Return the computed value\n///\n\nfloat computeTrilinearInterpolatedValue(std::vector const & grid, std::vector const & dim, Vector3f const & gridPosition)\n{\n\tstd::vector value;\n\tfor (unsigned pos2=0; pos2<2; pos2++)\n\t\tfor (unsigned pos3=0; pos3<2; pos3++)\n\t\t\tfor (unsigned pos1=0; pos1<2; pos1++)\n\t\t\t\tvalue.push_back(grid[(int)my_round(pos1,gridPosition(0))+dim[0]*(int)my_round(pos2,gridPosition(1))+dim[0]*dim[1]*(int)my_round(pos3,gridPosition(2))]);\n\tfloat xd = gridPosition(0) - floor(gridPosition(0));\n\tfloat yd = gridPosition(1) - floor(gridPosition(1));\n\tfloat zd = gridPosition(2) - floor(gridPosition(2));\n\n\tfloat c00 = value[0]*(1-xd)+value[1]*xd;\n\tfloat c01 = value[2]*(1-xd)+value[3]*xd;\n\tfloat c10 = value[4]*(1-xd)+value[5]*xd;\n\tfloat c11 = value[6]*(1-xd)+value[7]*xd;\n\n\tfloat c0 = c00*(1-yd)+c10*yd;\n\tfloat c1 = c01*(1-yd)+c11*yd;\n\n\tfloat val = c0*(1-zd)+c1*zd;\n\n\treturn val;\n}\n\n//positive filter\nint getSign(const float value)\n{\n\tif (value>0)\n\t\treturn 1;\n\telse\n\t\treturn 0;\n}\n\nfloat k(const float x, const float dirX, const float dimV)\n{\n\treturn (getSign(dirX) + round(x/dimV)) * dimV;\n}\n\nfloat k2(const float x, const float dirX)\n{\n\treturn floor(x) + getSign(dirX);\n}\n\n///\n/// \\brief getValueFromSegment Compute the value along a segment\n/// \\param grid Grid to consider\n/// \\param dim Dimensions of the grid\n/// \\param p1 First point of the segment\n/// \\param p2 Second point of the segment\n/// \\return Return the value of the segment\n///\n\nfloat getValueFromSegment(std::vector const & grid, std::vector const & dim, Vector3f const & p1, Vector3f const & p2)\n{\n\tVector3f direction = p2-p1;\n\tVector3f directionN = direction.normalized();\n\tfloat totalDist = direction.norm();\n\t//Number of voxels changes along each axis\n\tunsigned voxelsX = static_cast(fabs(floor(p2.x())-floor(p1.x())));\n\tunsigned voxelsY = static_cast(fabs(floor(p2.y())-floor(p1.y())));\n\tunsigned voxelsZ = static_cast(fabs(floor(p2.z())-floor(p1.z())));\n\tunsigned totalVoxelsCrossed = 1 + voxelsX + voxelsY + voxelsZ;\n\tVector3f pTemp = p1;\n\tfloat value = 0;\n\tfloat epsilon = 0.0001f;\n\tfloat gammaX, gammaY, gammaZ, gamma;\n\n\tfor (unsigned i=0; i::max();\n\t\telse\n\t\t\tgammaX = (k2(pTemp.x(), direction.x()) - pTemp.x()) / direction.x();\n\t\tif (fabs(directionN.y())::max();\n\t\telse\n\t\t\tgammaY = (k2(pTemp.y(), direction.y()) - pTemp.y()) / direction.y();\n\t\tif (fabs(directionN.z())::max();\n\t\telse\n\t\t\tgammaZ = (k2(pTemp.z(), direction.z()) - pTemp.z()) / direction.z();\n\t\tgamma = min(min(gammaX, gammaY), gammaZ);\n\t\tpTemp += (gamma) * direction;\n\t\tvalue += (grid[(int)floor(pTemp.x())+dim[0]*(int)floor(pTemp.y())+(dim[0]*dim[1]*(int)floor(pTemp.z()))]);\n\t}\n\tvalue += (grid[(int)floor(p2.x())+dim[0]*(int)floor(p2.y())+(dim[0]*dim[1]*(int)floor(p2.z()))]);\n\treturn (value / (float)(totalVoxelsCrossed));\n}\n\n///\n/// \\brief compareFA Function to compare the FA values and display the results\n/// \\param fibers1 First set of fibers\n/// \\param fibers2 Second set of fibers\n/// \\param faFilename FA file to use for FA computation\n///\n\nvoid compareFA(std::vector> const & fibers1, std::vector> const & fibers2, const string & faFilename)\n{\n\tcout << faFilename << endl;\n\tstd::vector faValues, vox;\n\tstd::vector dim;\n\tMatrixXf transform;\n\tfls::loadFAValues(faFilename, faValues, dim, transform, vox);\n\n\ttransform.conservativeResize(4,4);\n\ttransform.row(3) << 0,0,0,1;\n\ttransform = transform.inverse();\n\n\tunsigned maxThreads = std::max(unsigned(1), std::thread::hardware_concurrency());\n\tstd::vector ecartMoyenTab(maxThreads, 0);\n\tstd::vector nbPointsTab(maxThreads, 0);\n\tstd::vector ecartMaxTab(maxThreads, 0);\n\tstd::vector averageFiber1Error(maxThreads, 0);\n\tstd::vector averageFiber2Error(maxThreads, 0);\n#ifdef USE_OPENMP\n#pragma omp parallel for\n\tfor (unsigned i=0; i(0, fibers1.size(), 1, [&](unsigned i)\n\t{\n\t\tif (fibers1[i].size() == fibers2[i].size())\n\t\t{\n\t\t\tnbPointsTab[parallel.getID()] += fibers1[i].size();\n\t\t\tfor (unsigned j=0; j // size_t\n\n#include \n\nnamespace cppmath\n{\n /**\n * Implementation of the original Downhill Simplex or Nelder-Mead method for nonlinear optimization from 1965.\n * J. Nelder, R. Mead, \"A Simplex Method for Function Minimization,\" Computer Journal, 1965, 7, 308-313\n *\n * \\author cpieloth\n * \\copyright Copyright 2014 Christof Pieloth, Licensed under the Apache License, Version 2.0\n */\n template< size_t DIM >\n class DownhillSimplexMethodNM\n {\n public:\n typedef Eigen::Matrix< double, DIM, 1 > ParamsT; /**< Abbreviation for a vector of parameters. */\n\n /**\n * Enum to indicate how the optimization was converged.\n */\n enum Converged\n {\n CONVERGED_NO, /**< Optimization was not started. */\n CONVERGED_EPSILON, /**< Optimization is smaller than epsilon/threshold. */\n CONVERGED_ITERATIONS, /**< Maximum iterations was reached. */\n CONVERGED_YES /**< Optimization is converged, but not specified how. */\n };\n\n DownhillSimplexMethodNM();\n virtual ~DownhillSimplexMethodNM();\n\n /**\n * Implementation of the function to minimize.\n *\n * \\param x n-dimensional parameter vector.\n * \\return function value for vector x.\n */\n virtual double func( const ParamsT& x ) const = 0;\n\n /**\n * Indicates how the optimization was converged.\n *\n * \\return Enum::Converged\n */\n virtual Converged converged() const;\n\n double getReflectionCoeff() const;\n\n void setReflectionCoeff( double alpha );\n\n double getContractionCoeff() const;\n\n void setContractionCoeff( double beta );\n\n double getExpansionCoeff() const;\n\n void setExpansionCoeff( double gamma );\n\n size_t getMaximumIterations() const;\n\n void setMaximumIterations( size_t iterations );\n\n double getEpsilon() const;\n\n void setEpsilon( double eps );\n\n double getInitialFactor() const;\n\n void setInitialFactor( double factor );\n\n size_t getResultIterations() const;\n\n ParamsT getResultParams() const;\n\n double getResultError() const;\n\n /**\n * Starts the optimization.\n *\n * \\param initial Initial start point.\n */\n void optimize( const ParamsT& initial );\n\n protected:\n /**\n * Orders the parameters x and f(x) from min to max.\n */\n virtual void order();\n\n /**\n * Creates the initial parameter set and their function values.\n *\n * \\param initial Start parameter used to calculate initials.\n */\n virtual void createInitials( const ParamsT& initial );\n double m_initFactor; /**< Factor to create the initial parameter set. */\n\n ParamsT m_x[DIM + 1]; /**< Vector of all n+1 points. */\n double m_y[DIM + 1]; /**< Stores the function values to reduce re-calculation. */\n\n double m_epsilon; /**< Threshold or deviation for convergence. */\n size_t m_maxIterations; /**< Maximum iterations until the algorithm is canceled. */\n size_t m_iterations; /**< Iteration counter used for break condition. */\n\n const size_t DIMENSION; /**< Constant for dimension. */\n const size_t VALUES; /**< Constant for DIM+1. */\n\n private:\n enum Step\n {\n STEP_START, STEP_EXIT, STEP_REFLECTION, STEP_EXPANSION, STEP_CONTRACTION\n };\n\n double m_alpha; /**< Reflection coefficient. */\n double m_beta; /**< Contraction coefficient. */\n double m_gamma; /**< Expansion coefficient. */\n\n void centroid();\n Step reflection();\n Step expansion();\n Step contraction();\n\n ParamsT m_xo;\n ParamsT m_xr;\n double m_yr;\n };\n} /* namespace cppmath */\n\n// Load the implementation\n#include \"DownhillSimplexMethodNM-impl.hpp\"\n\n#endif // CPPMATH_OPTIMIZATION_DOWNHILLSIMPLEXMETHODNM_HPP_\n", "meta": {"hexsha": "04642d465e729951c3eb8867f76ea654693f2387", "size": 4160, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cppmath/optimization/DownhillSimplexMethodNM.hpp", "max_stars_repo_name": "cpieloth/CppMath", "max_stars_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cppmath/optimization/DownhillSimplexMethodNM.hpp", "max_issues_repo_name": "cpieloth/CppMath", "max_issues_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cppmath/optimization/DownhillSimplexMethodNM.hpp", "max_forks_repo_name": "cpieloth/CppMath", "max_forks_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1449275362, "max_line_length": 114, "alphanum_fraction": 0.6189903846, "num_tokens": 895, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677737461007, "lm_q2_score": 0.7826624890918021, "lm_q1q2_score": 0.6636725684697573}} {"text": "#pragma once\n#include \n#include \n#include \n\n#include \n#include \n\n#define SIGM 1\n#define TAHN 2\n#define RELU 3\n\nnamespace net{\n template < typename Scalar >\n class Perceptron {\n // friend class Layer;\n private:\n Scalar val;\n Scalar act;\n Scalar der;\n int id;\n public:\n Perceptron( Scalar val );\n Scalar& VAL();\n Scalar& ACT( int FUNC = SIGM );\n Scalar& DER( int FUNC = SIGM );\n int& ID() { return id; }\n void show();\n };\n\n template < typename Scalar >\n Perceptron< Scalar >::Perceptron( Scalar val ) {\n this->val = val;\n ACT();\n DER();\n }\n template < typename Scalar >\n Scalar& Perceptron< Scalar >::VAL() {\n return this->val;\n }\n template < typename Scalar >\n Scalar& Perceptron< Scalar >::ACT( int FUNC ) {\n switch( FUNC ) {\n case SIGM: this->act = 1.0 / ( 1.0 + exp( -this->val ) ); break; // sigmoid activation\n case TAHN: this->act = std::tanh( this->val ); break; // tahn activation\n case RELU: this->act = this->val > 0 ? this->val : this->val * 0.01; break; // LeakyReLU activation\n }\n return this->act;\n }\n template < typename Scalar >\n Scalar& Perceptron< Scalar >::DER( int FUNC ) {\n switch( FUNC ) {\n case SIGM: this->der = this->act * ( 1.0 - this->act ); break; // sigmoid derivation\n case TAHN: this->der = 1.0 - std::exp( std::tanh( this->val ) ); break; // tahn derivation\n case RELU: this->der = this->val >= 0 ? 1.0 : 0.01; break; // LeakyReLU derivation\n }\n return this->der;\n }\n template < typename Scalar >\n void Perceptron< Scalar >::show() {\n std::string s = fmt::format( \"\\t{0} \\t {1} \\t {2}\\n\", this->VAL(), this->ACT(), this->DER() );\n fmt::print( s ); // Python-like format string syntax\n }\n}\n", "meta": {"hexsha": "6030a04dcb0862b5b41f642935127fbc7d72f77b", "size": 2086, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mso_header_only/perceptron.hpp", "max_stars_repo_name": "bresilla/mso", "max_stars_repo_head_hexsha": "d7440a4e07af78439e621bae81cc33189543d194", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-10-26T10:44:20.000Z", "max_stars_repo_stars_event_max_datetime": "2017-10-26T10:44:20.000Z", "max_issues_repo_path": "include/mso_header_only/perceptron.hpp", "max_issues_repo_name": "bresilla/mso", "max_issues_repo_head_hexsha": "d7440a4e07af78439e621bae81cc33189543d194", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mso_header_only/perceptron.hpp", "max_forks_repo_name": "bresilla/mso", "max_forks_repo_head_hexsha": "d7440a4e07af78439e621bae81cc33189543d194", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.0923076923, "max_line_length": 114, "alphanum_fraction": 0.5086289549, "num_tokens": 553, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677660619633, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6636725495595255}} {"text": "#include \n#include \n\n#include \n\n#include \n\ntemplate class pendulum {\n\nprivate:\n /// Length of the pendulum\n double length_;\n /// Gravitational constant (little g)\n double g_;\n\npublic:\n pendulum(double l, double g = 9.81) : length_(l), g_(g) {}\n\n void operator()(const T &theta, T &dtheta_dt, const double /* t */) {\n dtheta_dt[0][0] = theta[0][1];\n dtheta_dt[0][1] = -(g_ / length_) * theta[0][0];\n }\n};\n\nclass pendulum_exact {\nprivate:\n /// Length of the pendulum\n double length_;\n /// Initial position (angle)\n double theta0_;\n /// Gravitational constant (little g)\n double g_;\n\npublic:\n pendulum_exact(double l, double theta0, double g = 9.81) : length_(l), theta0_(theta0), g_(g) {}\n double position(double t) {\n return theta0_ * std::cos(std::sqrt(g_/length_) * t);\n }\n double speed(double t) {\n return (-theta0_ * std::sqrt(g_/length_) * std::sin(std::sqrt(g_/length_) * t));\n }\n};\n\nint main() {\n using namespace std;\n using namespace boost::numeric::odeint;\n\n typedef std::vector< taylor > state_type;\n\n //[ state_initialization\n state_type x(2);\n x[0][0] = 1.0; // start at x=1.0, p=0.0\n x[0][1] = 0.0; // start at x=1.0, p=0.0\n x[1][0] = 0.0;\n x[1][1] = 0.0;\n //]\n\n double length = 10.0;\n pendulum approx(length);\n pendulum_exact exact(length, 1.0);\n\n runge_kutta4< state_type> stepper;\n\n const double dt = 0.1;\n const double tstart = 0.0;\n const double tend = 1.0;\n for( double t = tstart ; t < tend ; t += dt )\n {\n std::cout << t << \" \" << std::setprecision(16) << exact.position(t) << \" \" << std::setprecision(16) << exact.speed(t) << std::endl;\n std::cout << t << \" \" << std::setprecision(16) << x[0] << \" \" << std::setprecision(16) << x[1] << std::endl;\n stepper.do_step(approx, x, t, dt);\n }\n\n return 0;\n}\n", "meta": {"hexsha": "c21c60b236fcd5e522f4aad73233ab333d924cb0", "size": 1884, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/autodiff_odeint.cpp", "max_stars_repo_name": "robertodr/odeint-autodiff", "max_stars_repo_head_hexsha": "a6bf8b07aa6b838c26b7b6a1336f7bf9026a449b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-04-21T10:05:51.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-21T10:05:51.000Z", "max_issues_repo_path": "src/autodiff_odeint.cpp", "max_issues_repo_name": "robertodr/odeint-autodiff", "max_issues_repo_head_hexsha": "a6bf8b07aa6b838c26b7b6a1336f7bf9026a449b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/autodiff_odeint.cpp", "max_forks_repo_name": "robertodr/odeint-autodiff", "max_forks_repo_head_hexsha": "a6bf8b07aa6b838c26b7b6a1336f7bf9026a449b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.7894736842, "max_line_length": 139, "alphanum_fraction": 0.6066878981, "num_tokens": 640, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278788223264, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6635968652149559}} {"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../util/AlgorithmUtils.hpp\"\n#include \"../util/FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include \n#include \n\nnamespace fluid {\nnamespace algorithm {\n\nclass SpectralShape\n{\n\n using ArrayXd = Eigen::ArrayXd;\n\npublic:\n SpectralShape() {}\n\n void processFrame(Eigen::Ref in, double sampleRate, double minFreq,\n double maxFreq, double rolloffTarget, bool logFreq,\n bool usePower)\n {\n using namespace std;\n maxFreq = (maxFreq == -1) ? (sampleRate / 2) : min(maxFreq, sampleRate / 2);\n ArrayXd mag = in.max(epsilon);\n index nBins = mag.size();\n double binHz = sampleRate / ((nBins - 1) * 2.);\n index minBin = ceil(minFreq / binHz);\n index maxBin =\n min(static_cast(floorl(maxFreq / binHz)), (nBins - 1));\n if (maxBin <= minBin)\n {\n mOutputBuffer.setZero();\n return;\n }\n\n if (logFreq && minBin == 0)\n {\n minBin = 1;\n mag(1) += mag(0);\n }\n ArrayXd amp = usePower ? mag.square() : mag;\n amp = amp.segment(minBin, maxBin - minBin);\n double ampSum = amp.sum();\n ArrayXd freqs =\n ArrayXd::LinSpaced(maxBin - minBin, minBin * binHz, maxBin * binHz);\n if (logFreq)\n { freqs = 69 + (12 * (freqs / 440).log() * log2E); } // MIDI cents\n\n double centroid = (amp * freqs).sum() / ampSum;\n double spread = (amp * (freqs - centroid).square()).sum() / ampSum;\n double skewness = (amp * (freqs - centroid).pow(3)).sum() /\n (spread * sqrt(spread) * ampSum);\n double kurtosis =\n (amp * (freqs - centroid).pow(4)).sum() / (spread * spread * ampSum);\n\n double flatness = exp(amp.log().mean()) / amp.mean();\n double rolloff = maxBin - 1;\n double cumSum = 0;\n double target = ampSum * rolloffTarget / 100.0;\n for (index i = 0; cumSum <= target && i < amp.size(); i++)\n {\n cumSum += amp(i);\n if (cumSum >= target)\n {\n rolloff = (i == 0) ? freqs(i)\n : freqs(i) - (freqs(i) - freqs(i - 1)) *\n (cumSum - target) / amp(i);\n break;\n }\n }\n double crest = amp.maxCoeff() / amp.mean();\n\n mOutputBuffer(0) = centroid;\n mOutputBuffer(1) = sqrt(spread);\n mOutputBuffer(2) = skewness;\n mOutputBuffer(3) = kurtosis;\n mOutputBuffer(4) = rolloff;\n mOutputBuffer(5) = 20 * log10(max(flatness, epsilon));\n mOutputBuffer(6) = 20 * log10(max(crest, epsilon));\n }\n\n void processFrame(const RealVector& input, RealVectorView output,\n double sampleRate, double minFreq = 0, double maxFreq = -1,\n double rolloffTarget = 0.95, bool logFreq = false,\n bool usePower = false)\n {\n assert(output.size() == 7);\n ArrayXd in = _impl::asEigen(input);\n processFrame(in, sampleRate, minFreq, maxFreq, rolloffTarget, logFreq,\n usePower);\n output = _impl::asFluid(mOutputBuffer);\n }\n\nprivate:\n ArrayXd mOutputBuffer{7};\n};\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "43de34d5f6f7334e22bc831e1bd1034a4fb8f565", "size": 3560, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/public/SpectralShape.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/algorithms/public/SpectralShape.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-03-15T10:39:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-15T13:19:22.000Z", "max_forks_repo_path": "include/algorithms/public/SpectralShape.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5044247788, "max_line_length": 80, "alphanum_fraction": 0.5991573034, "num_tokens": 984, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167045, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.663457954396445}} {"text": "#include \"PolyMesh/IOManager.h\"\n#include \n#include \n\nusing namespace acamcad;\nusing namespace polymesh;\nusing namespace Eigen;\n\nvoid MeshInterpolation(PolyMesh* source, PolyMesh* target, double delta_t)\n{\n\tstd::string command = \"mkdir result \";\n\tsystem(command.c_str());\n\n\tint nv = source->numVertices();\n\tint nf = source->numPolygons();\n\n\tstd::vector S(nf);\n\tstd::vector xx(nf);\n\tstd::vector yy(nf);\n\tstd::vector area(nf);\n\tstd::vector angle(nf);\n\n\tMatrix2d I = MatrixXd::Identity(2, 2);\n\n\tstd::vector> v_id(nf);\n\n\t// Initial\n\tfor (FaceIter f_it = source->polyfaces_begin(); f_it != source->polyfaces_end(); ++f_it)\n\t{\n\t\tint id = (*f_it)->index();\n\t\tMHalfedge* heh = (*f_it)->halfEdge();\n\t\tMVert* v0 = heh->fromVertex();\n\t\tMVert* v1 = heh->toVertex();\n\t\tMHalfedge* next_heh = heh->next();\n\t\tMVert* v2 = next_heh->toVertex();\n\n\t\tv_id[id].push_back(v0->index());\n\t\tv_id[id].push_back(v1->index());\n\t\tv_id[id].push_back(v2->index());\n\n\t\tarea[id] = cross(v1->position() - v0->position(), v2->position()- v0->position()).norm() / 2.0;\n\t\t\n\t\txx[id] = Vector3d(v2->position()[0] - v1->position()[0], v0->position()[0] - v2->position()[0], v1->position()[0] - v0->position()[0]);\n\t\tyy[id] = Vector3d(v1->position()[1] - v2->position()[1], v2->position()[1] - v0->position()[1], v0->position()[1] - v1->position()[1]);\n\n\t\tVector3d u(target->vert(v0->index())->position()[0], target->vert(v1->index())->position()[0], target->vert(v2->index())->position()[0]);\n\t\tVector3d v(target->vert(v0->index())->position()[1], target->vert(v1->index())->position()[1], target->vert(v2->index())->position()[1]);\n\n\t\tMatrix2d J;\n\t\tJ << yy[id].dot(u) / (2 * area[id]), xx[id].dot(u) / (2 * area[id]), yy[id].dot(v) / (2 * area[id]), xx[id].dot(v) / (2 * area[id]);\n\t\tJacobiSVD svd(J, ComputeFullV | ComputeFullU);\n\n\t\tMatrix2d V = svd.matrixV();\n\t\tMatrix2d U = svd.matrixU();\n\t\tMatrix2d R = U * V.transpose();\n\n\t\tMatrix2d sigma;\n\t\tsigma(0, 1) = sigma(1, 0) = 0;\n\t\tsigma(0, 0) = svd.singularValues()[0];\n\t\tsigma(1, 1) = svd.singularValues()[1];\n\t\tS[id] = V * sigma * V.transpose();\n\t\tangle[id] = atan2(R(1, 0), R(1, 1));\n\t}\n\n\t// fix nv-1\n\tdouble u0 = source->vert(nv - 1)->position()[0];\n\tdouble v0 = source->vert(nv - 1)->position()[1];\n\n\n\tSparseMatrix A(2 * nv - 2, 2 * nv - 2);\n\tstd::vector>triplet;\n\n\tfor (FaceIter f_it = source->polyfaces_begin(); f_it != source->polyfaces_end(); ++f_it)\n\t{\n\t\tint id = (*f_it)->index();\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tif ((v_id[id][i] == nv - 1) || (v_id[id][j] == nv - 1))\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttriplet.push_back(Triplet(2 * v_id[id][i], 2 * v_id[id][j], yy[id][i] * yy[id][j] / (area[id] * area[id] * 2)));\n\t\t\t\t\ttriplet.push_back(Triplet(2 * v_id[id][i], 2 * v_id[id][j], xx[id][i] * xx[id][j] / (area[id] * area[id] * 2)));\n\t\t\t\t\ttriplet.push_back(Triplet(2 * v_id[id][i] + 1, 2 * v_id[id][j] + 1, yy[id][i] * yy[id][j] / (area[id] * area[id] * 2)));\n\t\t\t\t\ttriplet.push_back(Triplet(2 * v_id[id][i] + 1, 2 * v_id[id][j] + 1, xx[id][i] * xx[id][j] / (area[id] * area[id] * 2)));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tA.setFromTriplets(triplet.begin(), triplet.end());\n\tSparseLU> solver;\n\tsolver.analyzePattern(A);\n\tsolver.factorize(A);\n\n\tdouble t = 0;\n\twhile (t <= 1)\n\t{\n\t\tstd::cout << \"iter:\" << t << std::endl;\n\n\t\tVectorXd b(2 * nv - 2);\n\t\tb.setZero();\n\n\t\tfor (FaceIter f_it = source->polyfaces_begin(); f_it != source->polyfaces_end(); ++f_it)\n\t\t{\n\t\t\tint id = (*f_it)->index();\n\t\t\tMatrix2d A, R;\n\t\t\tdouble theta_t = angle[id] * t;\n\n\t\t\tR << cos(theta_t), -sin(theta_t), sin(theta_t), cos(theta_t);\n\t\t\tA = R * ((1.0 - t)*I + t * S[id]);\n\t\t\tfor (int i = 0; i < 3; i++)\n\t\t\t{\n\t\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t\t{\n\t\t\t\t\tif ((v_id[id][i] == nv - 1) || (v_id[id][j] == nv - 1))\n\t\t\t\t\t{\n\t\t\t\t\t\tif ((v_id[id][i] != nv - 1) && (v_id[id][j] == nv - 1))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tb[2 * v_id[id][i]] += -yy[id][i] * yy[id][j] * u0 / (area[id] * area[id] * 2);\n\t\t\t\t\t\t\tb[2 * v_id[id][i]] += -xx[id][i] * xx[id][j] * u0 / (area[id] * area[id] * 2);\n\t\t\t\t\t\t\tb[2 * v_id[id][i] + 1] += -yy[id][i] * yy[id][j] * v0 / (area[id] * area[id] * 2);\n\t\t\t\t\t\t\tb[2 * v_id[id][i] + 1] += -xx[id][i] * xx[id][j] * v0 / (area[id] * area[id] * 2);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (v_id[id][i] != nv - 1)\n\t\t\t\t{\n\t\t\t\t\tb[2 * v_id[id][i]] += yy[id][i] * A(0, 0) / area[id];\n\t\t\t\t\tb[2 * v_id[id][i]] += xx[id][i] * A(0, 1) / area[id];\n\t\t\t\t\tb[2 * v_id[id][i] + 1] += yy[id][i] * A(1, 0) / area[id];\n\t\t\t\t\tb[2 * v_id[id][i] + 1] += xx[id][i] * A(1, 1) / area[id];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tVectorXd result = solver.solve(b);\n\t\tfor (VertexIter v_it = source->vertices_begin(); v_it != source->vertices_end(); ++v_it)\n\t\t{\n\t\t\tint id = (*v_it)->index();\n\t\t\tif (id != nv - 1)\n\t\t\t{\n\t\t\t\t(*v_it)->setPosition(result[2 * id], result[2 * id + 1], 0);\n\t\t\t}\n\t\t}\n\t\t\n\t\tstd::string string_t = std::to_string(t);\n\t\twriteMesh(\"result\\\\\" + string_t + \".obj\", source);\n\t\tt += delta_t;\n\t}\n}\n\n\nint main(int argc, const char **argv)\n{\n\tif (argc != 4)\n\t{\n\t\tstd::cout << \"========== Hw8 Usage ==========\\n\";\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"blablabla.exe\tsource.obj target.obj delta_t\\n\";\n\t\tstd::cout << std::endl;\n\t\tstd::cout << \"=================================================\\n\";\n return 0;\n\t}\n\tstd::string source_path = argv[1];\n\tstd::string target_path = argv[2];\n\tstd::string t_string = argv[3];\n\n\tPolyMesh* source_mesh = new PolyMesh();\n\tPolyMesh* target_mesh = new PolyMesh();\n\tloadMesh(source_path, source_mesh);\n\tloadMesh(target_path, target_mesh);\n\tdouble delta_t = atof(t_string.c_str());\n\tMeshInterpolation(source_mesh, target_mesh, delta_t);\n return 0;\n}", "meta": {"hexsha": "13ff506034206968940544a8b327c39f07afbb4b", "size": 5734, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/src/hw8/main.cpp", "max_stars_repo_name": "fusheng-ji/Digital_Geometry_Processing", "max_stars_repo_head_hexsha": "98645268cc00e8830b0e1ce592d10e55320b3011", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2022-03-08T02:40:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T08:09:20.000Z", "max_issues_repo_path": "code/src/hw8/main.cpp", "max_issues_repo_name": "fusheng-ji/Digital_Geometry_Processing", "max_issues_repo_head_hexsha": "98645268cc00e8830b0e1ce592d10e55320b3011", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/src/hw8/main.cpp", "max_forks_repo_name": "fusheng-ji/Digital_Geometry_Processing", "max_forks_repo_head_hexsha": "98645268cc00e8830b0e1ce592d10e55320b3011", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2134831461, "max_line_length": 139, "alphanum_fraction": 0.5500523195, "num_tokens": 2111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9273632876167044, "lm_q2_score": 0.7154240018510025, "lm_q1q2_score": 0.663457954396445}} {"text": "// (C) Copyright Thomas Becker 2015. Permission to copy, use, modify, sell and\n// distribute this software is granted provided this copyright notice appears\n// in all copies. This software is provided \"as is\" without express or implied\n// warranty, and with no claim as to its suitability for any purpose.\n\n#ifndef TMB_NORMAL_DISTRIBUTION_PIVOT_09_27_2015_HPP\n#define TMB_NORMAL_DISTRIBUTION_PIVOT_09_27_2015_HPP\n\n#include \n#include \"distribution_specific_pivot_base.hpp\"\n\n/*\n * Pivot calculator for normally distributed data.\n */\n\nnamespace median_project\n{\nnamespace numerical_quick_median_detail\n{\n\n/**\n * Pivot calculator for normal distributions.\n */\nclass normal_distribution_pivot : public distribution_specific_pivot_base\n{\n private:\n virtual double cdf(double x) const override\n {\n return .5 * (1.0 + boost::math::erf((x - m_total_sequence_mean) / (sqrt(2.0) * m_total_sequence_std_dev)));\n }\n\n virtual double quantile(double x) const override\n {\n return m_total_sequence_mean + m_total_sequence_std_dev * sqrt(2.0) * boost::math::erf_inv(2.0 * x - 1.0);\n }\n};\n} // end namespace numerical_quick_median_detail\n} // end namespace median_project\n\n#endif // TMB_NORMAL_DISTRIBUTION_PIVOT_09_27_2015_HPP\n", "meta": {"hexsha": "5e2afb7a2bac1b9979ac04c37d18e8fc315df2f7", "size": 1284, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "median_algorithms/detail/pivot_calculators/normal_distribution_pivot.hpp", "max_stars_repo_name": "walkswiththebear/MedianProject", "max_stars_repo_head_hexsha": "0c65a2033f62c2ee00e628170dd4c28f75784278", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2016-04-05T21:59:28.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-05T21:59:28.000Z", "max_issues_repo_path": "median_algorithms/detail/pivot_calculators/normal_distribution_pivot.hpp", "max_issues_repo_name": "walkswiththebear/MedianProject", "max_issues_repo_head_hexsha": "0c65a2033f62c2ee00e628170dd4c28f75784278", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "median_algorithms/detail/pivot_calculators/normal_distribution_pivot.hpp", "max_forks_repo_name": "walkswiththebear/MedianProject", "max_forks_repo_head_hexsha": "0c65a2033f62c2ee00e628170dd4c28f75784278", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3170731707, "max_line_length": 115, "alphanum_fraction": 0.7593457944, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314625050654263, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6634175688298616}} {"text": "#include\n#include\n#include\n#include\n#include\n#include \n#include\"printtable.h\"\n#include \"calcSignature.hpp\"\n\nnamespace ExactSignature {\n using std::vector;\n\n typedef boost::multiprecision::cpp_rational Number;\n\n class Signature {\n public:\n vector> m_data;\n\n template\n void sigOfSegment(int d, int m, const Numeric* segment) {\n m_data.resize(m);\n auto& first = m_data[0];\n first.resize(d);\n for (int i = 0; i0; --level) {\n for (int mylevel = level - 1; mylevel>0; --mylevel) {\n int otherlevel = level - mylevel;\n auto& oth = other.m_data[otherlevel - 1];\n for (auto dest = m_data[level - 1].begin(),\n my = m_data[mylevel - 1].begin(),\n myE = m_data[mylevel - 1].end(); my != myE; ++my) {\n for (const Number& d : oth) {\n *(dest++) += d * *my;\n }\n }\n }\n auto source = other.m_data[level - 1].begin();\n for (auto dest = m_data[level - 1].begin(),\n e = m_data[level - 1].end();\n dest != e;)\n *(dest++) += *(source++);\n\n }\n }\n void swap(Signature& other) {\n m_data.swap(other.m_data);\n }\n void multiplyByConstant(Number c) {\n for (auto& a : m_data)\n for (auto& b : a)\n b *= c;\n }\n template\n void writeOut(Numeric* dest) const {\n for (auto& a : m_data)\n for (auto& b : a)\n *(dest++) = (Numeric)b;\n //*(dest++) = (Numeric)denominator(b);\n }\n };\n\n //This also calculates the concatenation product in the tensor algebra, \n //but in the case where we assume 0 instead of 1 in the zeroth level.\n //It is not in-place\n Signature concatenateWith_zeroFirstLevel(int d, int m,\n const Signature& a,\n const Signature& b) {\n Signature out;\n out.sigOfNothing(d, m);\n for (int level = m; level>0; --level) {\n for (int alevel = level - 1; alevel>0; --alevel) {\n int blevel = level - alevel;\n auto& aa = a.m_data[alevel - 1];\n auto& bb = b.m_data[blevel - 1];\n auto dest = out.m_data[level - 1].begin();\n for (const Number& c : aa) {\n for (const Number& d : bb) {\n *(dest++) += d * c;\n }\n }\n }\n }\n return out;\n }\n\n void logTensorHorner(Signature& x) {\n const int m = (int)x.m_data.size();\n const int d = (int)x.m_data[0].size();\n if (m <= 1)\n return;\n Signature s, t;\n s.sigOfNothing(d, m - 1);\n t.sigOfNothing(d, m);\n for (int depth = m; depth > 0; --depth) {\n Number constant = (Number) 1.0 / depth;\n //make t be x*s up to level (1+m-depth). [this does nothing the first time round]\n for (int lev = 2; lev <= 1 + m - depth; ++lev) {\n //t.m_data[lev - 1] = x.m_data[lev - 1];\n auto& tt = t.m_data[lev - 1];\n std::fill(tt.begin(), tt.end(), (Number) 0.0);\n for (int leftLev = 1; leftLev < lev; ++leftLev) {\n int rightLev = lev - leftLev;\n auto& aa = x.m_data[leftLev - 1];\n auto& bb = s.m_data[rightLev - 1];\n auto dest = t.m_data[lev - 1].begin();\n for (const Number& c : aa)\n for (const Number& dd : bb)\n *(dest++) += dd * c;\n }\n }\n //make s be x*constant-t up to level (1+m-depth)\n if (depth>1)\n for (int lev = 1; lev <= 1 + m - depth; ++lev) {\n auto is = s.m_data[lev - 1].begin();\n auto ix = x.m_data[lev - 1].begin();\n auto es = s.m_data[lev - 1].end();\n auto it = t.m_data[lev - 1].begin();\n for (; is != es; ++is, ++it, ++ix)\n *is = constant * *ix - *it;\n }\n }\n //x isn't modified until this next bit.\n //make x be x-t\n for (int lev = 2; lev <= m; ++lev) {\n auto it = t.m_data[lev - 1].begin();\n auto ix = x.m_data[lev - 1].begin();\n auto ex = x.m_data[lev - 1].end();\n for (; ix != ex; ++ix, ++it)\n *ix -= *it;\n }\n }\n\n}\n\nstd::mt19937 g_rnd;\nusing PathReal = double;\nstd::vector randomPath(int pathLength, int d){\n std::vector out(pathLength*d);\n std::uniform_real_distribution urd(0, 1);\n for (auto& d : out)\n d = urd(g_rnd);\n return out;\n}\n\ntemplate\nusing SignatureType = std::conditional_t;\n\n//the stroke ending at from ... the stroke ending before to\ntemplate\nSignatureType sigPiece(const std::vector& path, int d, int m, size_t from, size_t to) {\n SignatureType s1, s2;\n std::vector displacement(d);\n for (size_t i = from; i < to; ++i) {\n for (int j = 0; j < d; ++j)\n displacement[j] = path[i*d + j] - path[(i - 1)*d + j];\n s1.sigOfSegment(d, m, displacement.data());\n if (i == from) {\n s2.swap(s1);\n }\n else {\n s2.concatenateWith(d, m, s1);\n }\n }\n return s2;\n}\n\n//Calculate the signature or log signature of path,\n//using float or arbitrary precision\ntemplate\nstd::vector sig(const std::vector& path, int d, int m, bool log) {\n size_t pathLength = path.size() / d;\n auto s2 = sigPiece(path, d, m, 1, pathLength);\n if (log)\n logTensorHorner(s2);\n std::vector out(calcSigTotalLength(d, m));\n s2.writeOut(out.data());\n return out;\n}\n\n\n//like sig but split the work between processors\ntemplate\nstd::vector sigParallel(const std::vector& path, int d, int m, bool log) {\n size_t pathLength = path.size() / d;\n size_t nThreads = 4;\n size_t each = (pathLength - 1) / nThreads;\n if (each < 1)\n return sig(path, d, m, log);\n size_t start = 1;\n std::vector> pieces(nThreads);\n std::vector threads;\n for (size_t thread = 0; thread < nThreads; ++thread) {\n size_t start = thread*each + 1;\n size_t end = (thread + 1 == nThreads) ? pathLength : (thread*each + each + 1);\n threads.emplace_back([&pieces,path,d,m,start, end,thread]() {\n pieces[thread] = sigPiece(path, d, m, start, end);\n });\n }\n for (auto& t : threads)\n t.join();\n auto s2 = pieces[0];\n for (size_t i = 1; i < nThreads; ++i)\n s2.concatenateWith(d, m, pieces[i]);\n if (log)\n logTensorHorner(s2);\n std::vector out(calcSigTotalLength(d, m));\n s2.writeOut(out.data());\n return out;\n}\n\nvoid test() {\n using N = boost::multiprecision::cpp_rational;\n N a = 0.0625;\n N b = a - N(4, 5);\n std::cout << b << \" \"<<(double) b << \"\\n\";\n}\n\n\nvoid go() {\n auto d = 2, m = 4, pathLength=4;\n auto path = randomPath(pathLength, d);\n bool log = true;\n auto s1 = sig(path, d, m, log);\n //auto s2 = sig(path, d, m, log);\n auto s2 = sigParallel(path, d, m, log);\n\n //for (size_t i = 0; i < s1.size(); ++i) {\n // std::cout << s1[i] << \" \" << s2[i] << \"\\n\";\n //}\n auto diffs = diffVectors(s1, s2);\n PrintTable::printTable(s1, s2, diffs);\n std::cout << \"l2 norm \" << l2norm(s1) << \" \"<< l2norm(s2) << \"\\n\";\n std::cout << \"l2 diff \" << l2norm(diffs) << \"\\n\";\n std::cout << \"total diff \"<\n#include \n#include \n#include \n\nnamespace raytrace {\nusing Vec1 = Vec<1>;\nusing Vec2 = Eigen::Vector2d;\nusing Vec3 = Eigen::Vector3d;\nusing Mat2 = Eigen::Matrix2d;\n\ndouble cost(const Vec3 &eta, const std::vector &x, const std::vector &z) {\n const se2 T = se2::exp(eta);\n\n double error_sq = 0.0;\n for (std::size_t k = 0; k < x.size(); ++k) {\n const Vec2 error = (T * x[k]) - z[k];\n error_sq += error.squaredNorm();\n }\n\n return error_sq;\n}\n\nVec2 error(const Vec3 &eta, const std::vector &x, const std::vector &z) {\n const se2 T = se2::exp(eta);\n\n // double error_sq = 0.0;\n Vec2 error_sq = Vec2::Zero();\n for (std::size_t k = 0; k < x.size(); ++k) {\n const Vec2 error = (T * x[k]) - z[k];\n error_sq += error.array().square().matrix();\n }\n\n return error_sq;\n}\n\nstruct dExpSe2 {\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n Eigen::Matrix2d Rprime;\n Eigen::Matrix2d V;\n Eigen::Matrix2d Vprime;\n Vec3 eta;\n\n Mat<2, 3> jacobian_from_y(const Vec2 &y) const {\n Mat<2, 3> m;\n m.setZero();\n m.block<2, 2>(0, 0) = V;\n m.block<2, 1>(0, 2) = (Rprime * y) + (Vprime * eta.head<2>());\n return m;\n }\n};\n\nvoid dexp_se2(const Vec3 &eta, Out jac) {\n // todo: Use taylor exp instead of explicit sincos for stability near zero\n const double c = std::cos(eta(2));\n const double s = std::sin(eta(2));\n const double inv_theta = 1 / eta(2);\n const double inv_theta2 = inv_theta * inv_theta;\n\n const double cos_inv_theta = c * inv_theta;\n const double sin_inv_theta = s * inv_theta;\n const double sin_inv_theta2 = sin_inv_theta * inv_theta;\n\n const double cos_m1_invtheta2 = (c - 1) * inv_theta2;\n\n Eigen::Matrix2d v;\n v.row(0) << s, (c - 1);\n v.row(1) << 1 - c, s;\n v *= inv_theta;\n\n Eigen::Matrix2d dv_dtheta;\n dv_dtheta.row(0) << cos_inv_theta - (sin_inv_theta2), -sin_inv_theta - (cos_m1_invtheta2);\n dv_dtheta.row(1) << sin_inv_theta + cos_m1_invtheta2, cos_inv_theta - sin_inv_theta2;\n\n Eigen::Matrix2d dR_dtheta;\n dR_dtheta.row(0) << -s, -c;\n dR_dtheta.row(1) << c, -s;\n\n jac->Rprime = dR_dtheta;\n jac->V = v;\n jac->Vprime = dv_dtheta;\n jac->eta = eta;\n}\n\nVec3 dcost(const Vec3 &eta, const std::vector &x, const std::vector &z) {\n const se2 T = se2::exp(eta);\n dExpSe2 preJ;\n dexp_se2(eta, out(preJ));\n\n Vec3 derror_sq_total = Vec3::Zero();\n for (std::size_t k = 0; k < x.size(); ++k) {\n const Vec2 error = (T * x[k]) - z[k];\n\n const Mat<2, 3> derror_deta = preJ.jacobian_from_y(x[k]);\n const Vec3 derror_sq = (2 * error.transpose()) * derror_deta;\n derror_sq_total += derror_sq;\n }\n\n return derror_sq_total;\n}\n\ntemplate \nEigen::Matrix gauss_newton(const Eigen::Matrix &x0,\n const Callable1 &fcn,\n const Callable2 &jac,\n const double feps = 1e-6,\n const int max_iters = 15) {\n using VecX = Eigen::Matrix;\n using Gradient = Eigen::Matrix;\n VecX x = x0;\n\n double last_cost = fcn(x);\n for (int k = 0; k < max_iters; ++k) {\n // todo: llt\n const Gradient J = jac(x);\n const VecX c = (J.transpose() * J).inverse() * J.transpose() * fcn(x);\n x = x - c;\n double new_cost = fcn(x);\n\n if (std::abs(new_cost - last_cost) < feps) {\n break;\n }\n\n last_cost = new_cost;\n }\n return x;\n}\n}", "meta": {"hexsha": "8de0b84c3c0aaae269e8e27094376d7ef5c23f11", "size": 3736, "ext": "hh", "lang": "C++", "max_stars_repo_path": "raytracing/optimization.hh", "max_stars_repo_name": "jpanikulam/experiments", "max_stars_repo_head_hexsha": "be36319a89f8baee54d7fa7618b885edb7025478", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-14T11:40:28.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-14T11:40:28.000Z", "max_issues_repo_path": "raytracing/optimization.hh", "max_issues_repo_name": "IJDykeman/experiments-1", "max_issues_repo_head_hexsha": "22badf166b2ea441e953939463f751020b8c251b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2018-04-18T13:54:29.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-22T20:04:17.000Z", "max_forks_repo_path": "raytracing/optimization.hh", "max_forks_repo_name": "IJDykeman/experiments-1", "max_forks_repo_head_hexsha": "22badf166b2ea441e953939463f751020b8c251b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-12-24T03:45:47.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-24T03:45:47.000Z", "avg_line_length": 27.8805970149, "max_line_length": 92, "alphanum_fraction": 0.5885974304, "num_tokens": 1226, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336202, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6633822831989303}} {"text": "#ifndef CGWR_HPP\n#define CGWR_HPP\n\n#include \n#include \n#include \n\n//#include \n//#include \n//#include \n\n/*********************************************************************\n- CG:\n< j1 j2 m1 m2 | J M >\n\n- Wigner 3j or 6j:\n(j1,j2,j3) or {j1,j2,j3}\n(l1,l2,l3) {m1,m2,m3}\n\n- Wigner 9j:\n{j1 j2 j3}\n{j4 j5 j6}\n{j7 j8 j9}\n\n-Racah:\nW(j1 j2 l2 l1 | j3 l3)\n\nCG translated as array=[j1,j2,m1,m2,J,M] with _CGWR::C_CG token\nor\nWigner 3j translated as array=[j1,j2,j3,m1,m2,m3] with _CGWR::C_W3j token\nor\nWigner 6j translated as array=[j1,j2,j3,l1,l2,l3] with _CGWR::C_W6j token\nor\nand so on with usual notations\n\n*********************************************************************/\n\nclass _CGWR { // Clebsch-Gordan Wigner Racah\npublic:\n \n // Token\n /***********/\n static const unsigned int C_CG;\n static const unsigned int C_W3j;\n static const unsigned int C_W6j;\n static const unsigned int C_W9j;\n static const unsigned int C_RACAH;\n /***********/\n\n \n // Init the class with the coeff and the token\n /***********/\n _CGWR(double long [], unsigned int);\n /***********/\n\n _CGWR& operator= ( const _CGWR& other ); //TODO\n\n \n // Public methods\n /***********/\n double long CG(void);\n double long W3j(void);\n double long W6j(void);\n double long W9j(void); //TODO\n double long Racah(void);\n /***********/\n\nprivate:\n double long j1, j2, j3, j;\n double long l1, l2, l3, l;\n double long m1, m2 , m3, m;\n\n unsigned int selected_Symb;\n\n \n // mid computations\n /***********/\n long double fact ( long double n ); // factorial\n double long Delta(double long , double long , double long ); // triangle relation\n double long delta_k(double long , double long ); // kronecker\n \n // variadic\n template\n bool is_integer(_T n); // return true if integer\n template\n bool is_integer(_T, _args...);\n \n template\n bool is_halfinteger(_T); // return true if half integer\n template\n bool is_halfinteger(_T, _args...);\n /***********/\n\n};\n\n#endif // CGWR_HPP\n\n", "meta": {"hexsha": "d2b774378f46373574ef9e6c0d4735b7c33e5aba", "size": 2283, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/cgwr.hpp", "max_stars_repo_name": "a-lemonnier/Simple_HFS", "max_stars_repo_head_hexsha": "a7d04fc6e2c8de3ceefee4d01e66f1b11fbcb754", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-01T22:13:28.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-01T22:13:28.000Z", "max_issues_repo_path": "include/cgwr.hpp", "max_issues_repo_name": "a-lemonnier/Simple_HFS", "max_issues_repo_head_hexsha": "a7d04fc6e2c8de3ceefee4d01e66f1b11fbcb754", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/cgwr.hpp", "max_forks_repo_name": "a-lemonnier/Simple_HFS", "max_forks_repo_head_hexsha": "a7d04fc6e2c8de3ceefee4d01e66f1b11fbcb754", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2959183673, "max_line_length": 85, "alphanum_fraction": 0.5799386772, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543454, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6632983810892937}} {"text": "#include \n#include \n\n#include \"args.hxx\"\n\n#include \n#include \n\nusing ChartType = Eigen::Matrix;\nusing ChartHmType = Eigen::Matrix;\nusing CCMType = Eigen::Matrix;\n\n\nstd::vector StringSplit(const std::string &str, char sep) {\n std::vector v;\n std::stringstream ss(str);\n std::string buffer;\n while( std::getline(ss, buffer, sep) ) {\n v.push_back(buffer);\n }\n return v;\n}\n\n\nbool LoadColorchartCsv(const std::string& filename, ChartType& dst_chart) {\n std::ifstream ifs(filename);\n if (!ifs) {\n std::cout << \"Can't open \" << filename << std::endl;\n return false;\n }\n\n std::string str;\n std::getline(ifs, str); // skip first line\n\n int i = 0;\n while (std::getline(ifs, str)) {\n std::vector data_str = StringSplit(str, ',');\n dst_chart(i, 0) = std::stod(data_str[1]);\n dst_chart(i, 1) = std::stod(data_str[2]);\n dst_chart(i, 2) = std::stod(data_str[3]);\n i++;\n if (i == 24) break;\n }\n return true;\n}\n\nvoid conv_sRGB2XYZ(const ChartType &rgb, ChartType &xyz) {\n Eigen::Matrix M;\n M << 0.412391, 0.357584, 0.180481,\n 0.212639, 0.715169, 0.072192,\n 0.019331, 0.119195, 0.950532;\n xyz = (M * rgb.transpose()).transpose();\n}\n\nvoid SolveCCM(const ChartType& source_xyz, const ChartType& reference_xyz,\n CCMType &ccm) {\n // source_xyz * ccm == reference_xyz\n // (24, 3 + 1) * (4, 3) = (24 * 3)\n ChartHmType source_xyz_hm;\n source_xyz_hm.col(0) = source_xyz.col(0);\n source_xyz_hm.col(1) = source_xyz.col(1);\n source_xyz_hm.col(2) = source_xyz.col(2);\n source_xyz_hm.col(3) = Eigen::VectorXd::Ones(24);\n auto source_xyz_hm_t = source_xyz_hm.transpose();\n auto pinv = (source_xyz_hm_t * source_xyz_hm).inverse() * source_xyz_hm_t;\n ccm = pinv * reference_xyz;\n}\n\nvoid WriteCCM(const std::string &filename, const CCMType& ccm) {\n std::ofstream csv(filename);\n for (int i = 0; i < 4; i++) {\n csv << ccm(i, 0) << \",\"\n << ccm(i, 1) << \",\"\n << ccm(i, 2) << std::endl;\n }\n}\n\nbool ParseArgs(const int argc, char** argv, std::string& ref_csv,\n std::string& src_csv, std::string& out_csv, double& gamma) {\n args::ArgumentParser parser(\"Compute CCM.\");\n args::HelpFlag help(parser, \"help\", \"Display this help menu\",\n {'h', \"help\"});\n args::Positional ref_csv_arg(parser, \"reference\",\n \"reference csv file\");\n args::Positional src_csv_arg(parser, \"source\",\n \"source csv file\");\n args::Positional out_csv_arg(parser, \"output\",\n \"output csv file\", \"ccm.csv\");\n args::ValueFlag gamma_arg(parser, \"gamma\",\n \"Gamma value of reference and source data\",\n {'g', \"gamma\"}, 1.0);\n try {\n parser.ParseCLI(argc, argv);\n } catch (args::Help) {\n std::cout << parser;\n return false;\n } catch (args::ParseError e) {\n std::cerr << e.what() << std::endl;\n std::cerr << parser;\n return false;\n } catch (args::ValidationError e) {\n std::cerr << e.what() << std::endl;\n std::cerr << parser;\n return false;\n }\n if (!ref_csv_arg) {\n std::cout << \"Error: reference is not set\" << std::endl;\n std::cout << parser;\n return false;\n }\n if (!src_csv_arg) {\n std::cout << \"Error: src is not set\" << std::endl;\n std::cout << parser;\n return false;\n }\n\n ref_csv = args::get(ref_csv_arg);\n src_csv = args::get(src_csv_arg);\n out_csv = args::get(out_csv_arg);\n gamma = args::get(gamma_arg);\n\n return true;\n}\n\nint main(int argc, char** argv) {\n // Parse arguments\n std::string ref_csv, src_csv, out_csv;\n double gamma;\n if (!ParseArgs(argc, argv, ref_csv, src_csv, out_csv, gamma)) {\n return 1;\n }\n\n // Load color charts\n ChartType reference_raw, source_raw;\n if (!LoadColorchartCsv(ref_csv, reference_raw)) {\n return 1;\n }\n if (!LoadColorchartCsv(src_csv, source_raw)) {\n return 1;\n }\n\n // Degamma\n ChartType reference_linear = reference_raw.array().pow(gamma);\n ChartType source_linear = source_raw.array().pow(gamma);\n\n // XYZ\n ChartType reference_xyz, source_xyz;\n conv_sRGB2XYZ(reference_linear, reference_xyz);\n conv_sRGB2XYZ(source_linear, source_xyz);\n\n // Solve\n CCMType ccm;\n SolveCCM(source_xyz, reference_xyz, ccm);\n std::cout << \"CCM:\" << std::endl;\n std::cout << ccm << std::endl;\n\n // Save\n WriteCCM(out_csv, ccm);\n\n return 0;\n}\n", "meta": {"hexsha": "69ea3899099b56e42d572c82848bf3ac4ccf696b", "size": 4890, "ext": "cc", "lang": "C++", "max_stars_repo_path": "cpp/src/computeCCM.cc", "max_stars_repo_name": "lighttransport/colorcorrectionmatrix", "max_stars_repo_head_hexsha": "981389e1e819a42fd8b8bd11ba0a1d9886259f54", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 71.0, "max_stars_repo_stars_event_min_datetime": "2018-04-15T16:03:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T03:11:49.000Z", "max_issues_repo_path": "cpp/src/computeCCM.cc", "max_issues_repo_name": "lighttransport/colorcorrectionmatrix", "max_issues_repo_head_hexsha": "981389e1e819a42fd8b8bd11ba0a1d9886259f54", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-03-02T18:32:41.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-11T14:39:26.000Z", "max_forks_repo_path": "cpp/src/computeCCM.cc", "max_forks_repo_name": "lighttransport/colorcorrectionmatrix", "max_forks_repo_head_hexsha": "981389e1e819a42fd8b8bd11ba0a1d9886259f54", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19.0, "max_forks_repo_forks_event_min_datetime": "2018-08-13T01:50:53.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T09:52:52.000Z", "avg_line_length": 30.1851851852, "max_line_length": 80, "alphanum_fraction": 0.5701431493, "num_tokens": 1374, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543453, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6632983704565156}} {"text": "#include \n#include \n\nusing namespace std;\nusing namespace arma;\n\ndouble* diff_ts(double *y, int len, double dt)\n{\n double *dy;\n dy = new double[len];\n\n dy[0] = y[0];\n for (int i = 1; i\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"omp.h\"\n\n#include \n#include \n#include \n\n#include // see https://www.boost.org/doc/libs/1_66_0/libs/math/doc/html/quaternions.html\n\nvoid QuaternionIntegration_ForwardEuler(\n double dt,\n double omeg_x, double omeg_y, double omeg_z,\n double& q0, double& q1, double& q2, double& q3);\nvoid QuaternionIntegration_Exponential(\n double dt,\n double omeg_x, double omeg_y, double omeg_z,\n double& q0, double& q1, double& q2, double& q3);\nvoid normalizeQuaternion(double& q0, double& q1, double& q2, double& q3);\n\n#define deg2rad(x) (M_PI*x/180.f)\n#define rad2deg(x) (180.f*x/M_PI)\n\nint main(int argc, char** argv ) { \n std::string argv_str(realpath(argv[0], 0));\n std::string base = argv_str.substr(0, argv_str.find_last_of(\"/\"));\n\n double angularVelocity[3] = {0.3, 0.2, 0.1};\n double dt = 1.0/200;\n\n // Create initial quaternion for testing - using Boost Quaternions: https://www.boost.org/doc/libs/1_66_0/libs/math/doc/html/quaternions.html\n boost::math::quaternion q0(0.9848,0.1736,0,0); // w,x,y,z\n q0 = q0 / sqrt(boost::math::norm(q0)); // normalize\n\n // Convert angular velocity vector into a quaternion\n boost::math::quaternion q_omeg(0, angularVelocity[0], angularVelocity[1], angularVelocity[2]); // use as body angular velocity\n\n std::cout << \"Quaternion are printed in order: \\t(w, x, y, z)\" << std::endl << std::endl;\n\n\n /* Inertial vs Body angular velocity test */\n std::cout << \">>>>> Inertial vs Body angular velocity test <<<<<\" << std::endl;\n boost::math::quaternion q_body = q0 * boost::math::exp(0.5*dt*q_omeg); // compute the new quaternion using the quaternion exponential\n boost::math::quaternion q_inertial = boost::math::exp(0.5*dt*q_omeg) * q0; // compute the new quaternion using the quaternion exponential\n\n // Print results for comparison\n std::cout << \"q0 \\t\\t=\\t\" << q0 << std::endl;\n std::cout << \"q_omeg \\t\\t=\\t\" << q_omeg << std::endl;\n std::cout << \"q_body \\t\\t=\\t\" << q_body << std::endl;\n std::cout << \"q_inertial \\t=\\t\" << q_inertial << std::endl;\n\n std::cout << std::endl;\n\n\n /* Integration method test - methods are inspired from https://www.ashwinnarayan.com/post/how-to-integrate-quaternions/ */\n std::cout << \">>>>> Integration method test <<<<<\" << std::endl;\n // Method 1: Quaternion Exponential\n boost::math::quaternion q1_exp = q0 * boost::math::exp(0.5*dt*q_omeg);\n\n // Method 2: Manual Quaternion Exponential\n boost::math::quaternion q_exp_delta;\n if (norm(q_omeg) > 0)\n q_exp_delta = cos(0.5 * dt * sqrt(norm(q_omeg))) + q_omeg / sqrt(norm(q_omeg)) * sin(0.5 * dt * sqrt(norm(q_omeg)));\n else\n q_exp_delta = boost::math::quaternion(1, 0, 0, 0); // unit quaternion since the angular velocity is zero (no movement)\n\n boost::math::quaternion q2_exp_manual = q0 * q_exp_delta;\n\n // Method 3: Manual Quaternion Exponential\n double q_1[4] = {q0.R_component_1(), q0.R_component_2(), q0.R_component_3(), q0.R_component_4()};\n QuaternionIntegration_Exponential(dt, angularVelocity[0],angularVelocity[1],angularVelocity[2], q_1[0],q_1[1],q_1[2],q_1[3]);\n boost::math::quaternion q3_exp_manual(q_1[0],q_1[1],q_1[2],q_1[3]);\n\n // Method 4: Delta Quaternion\n boost::math::quaternion q_delta(1, 0.5*dt*angularVelocity[0], 0.5*dt*angularVelocity[1], 0.5*dt*angularVelocity[2]);\n boost::math::quaternion q4_delta = q0 * q_delta; // compute the new quaternion using body angular velocity to construct the delta quaternion (hence right multiplication)\n\n // Method 5: Forward Euler\n boost::math::quaternion dq = 0.5 * q0 * q_omeg; // quaternion derivative using body angular velocity\n //boost::math::quaternion dq = 0.5 * q_omeg * q0; // quaternion derivative using inertial angular velocity\n boost::math::quaternion q5_euler = q0 + dt*dq;\n q5_euler = q5_euler / sqrt(boost::math::norm(q5_euler)); // normalize\n\n // Method 6: Forward Euler 2\n double q_2[4] = {q0.R_component_1(), q0.R_component_2(), q0.R_component_3(), q0.R_component_4()};\n QuaternionIntegration_ForwardEuler(dt, angularVelocity[0],angularVelocity[1],angularVelocity[2], q_2[0],q_2[1],q_2[2],q_2[3]);\n boost::math::quaternion q6_euler(q_2[0],q_2[1],q_2[2],q_2[3]);\n\n // Print results for comparison\n std::cout << \"Angular Velocity \\t=\\t(\" << angularVelocity[0] << \", \" << angularVelocity[1] << \", \" << angularVelocity[2] << \")\" << std::endl;\n std::cout << \"Boost Exponential \\t=\\t\" << q1_exp << std::endl;\n std::cout << \"Manual Exponential \\t=\\t\" << q2_exp_manual << std::endl;\n std::cout << \"Delta \\t\\t\\t=\\t\" << q4_delta << std::endl;\n std::cout << \"Forward Euler \\t\\t=\\t\" << q5_euler << std::endl;\n std::cout << \"Manual Exponential my \\t=\\t\" << q3_exp_manual << std::endl;\n std::cout << \"Forward Euler my \\t=\\t\" << q6_euler << std::endl;\n\n return 0;\n}\n\nvoid QuaternionIntegration_ForwardEuler(\n double dt,\n double omeg_x, double omeg_y, double omeg_z,\n double& q0, double& q1, double& q2, double& q3)\n{\n // The angular velocity is given in body frame\n /* Forward Euler method\n * q_new = q + dt * dq\n * dq = 0.5 * q0 * q_omeg\n * q_omeg = [0,omeg_x,omeg_y,omeg_z]\n */\n\n // dq = 0.5*Phi(q0)*[0,omeg_x,omeg_y,omeg_z]\n double dq0 = 0.5 * (-q1*omeg_x -q2*omeg_y -q3*omeg_z);\n double dq1 = 0.5 * (+q0*omeg_x -q3*omeg_y +q2*omeg_z);\n double dq2 = 0.5 * (+q3*omeg_x +q0*omeg_y -q1*omeg_z);\n double dq3 = 0.5 * (-q2*omeg_x +q1*omeg_y +q0*omeg_z);\n\n q0 += dt*dq0;\n q1 += dt*dq1;\n q2 += dt*dq2;\n q3 += dt*dq3;\n\n normalizeQuaternion(q0, q1, q2, q3);\n}\n\nvoid QuaternionIntegration_Exponential(\n double dt,\n double omeg_x, double omeg_y, double omeg_z,\n double& q0, double& q1, double& q2, double& q3)\n{\n // The angular velocity is given in body frame\n /* Quaternion Exponential method\n * q_new = q0 * exp(1/2*dt*q_omeg)\n * q_omeg = [0,omeg_x,omeg_y,omeg_z]\n */\n\n double omeg_norm = sqrt(omeg_x*omeg_x + omeg_y*omeg_y + omeg_z*omeg_z);\n\n double q_exp0, q_exp1, q_exp2, q_exp3;\n\n if (omeg_norm > 0) {\n double sinOmeg = sin(0.5 * dt * omeg_norm);\n q_exp0 = cos(0.5 * dt * omeg_norm);\n q_exp1 = sinOmeg * omeg_x / omeg_norm;\n q_exp2 = sinOmeg * omeg_y / omeg_norm;\n q_exp3 = sinOmeg * omeg_z / omeg_norm;\n } else {\n // unit quaternion since the angular velocity is zero (no movement)\n q_exp0 = 1.0;\n q_exp1 = 0.0;\n q_exp2 = 0.0;\n q_exp3 = 0.0;\n }\n\n // q_new = Phi(q0) * q_exp\n double q0_new = +q0*q_exp0 -q1*q_exp1 -q2*q_exp2 -q3*q_exp3;\n double q1_new = +q1*q_exp0 +q0*q_exp1 -q3*q_exp2 +q2*q_exp3;\n double q2_new = +q2*q_exp0 +q3*q_exp1 +q0*q_exp2 -q1*q_exp3;\n double q3_new = +q3*q_exp0 -q2*q_exp1 +q1*q_exp2 +q0*q_exp3;\n\n // Update quaternion\n q0 = q0_new;\n q1 = q1_new;\n q2 = q2_new;\n q3 = q3_new;\n}\n\nvoid normalizeQuaternion(double& q0, double& q1, double& q2, double& q3)\n{\n double norm = sqrt(q0*q0 + q1*q1 + q2*q2 + q3*q3);\n q0 /= norm;\n q1 /= norm;\n q2 /= norm;\n q3 /= norm;\n}\n", "meta": {"hexsha": "244d2cd702bb555af0f4159404896895bdac3cd0", "size": 8215, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/cpp/src/QuaternionTest/main.cpp", "max_stars_repo_name": "mindThomas/JetsonCar", "max_stars_repo_head_hexsha": "74636d4da1f7f71ca9f2315a1b2347393b081eda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-11-09T08:52:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T15:18:36.000Z", "max_issues_repo_path": "src/QuaternionTest/main.cpp", "max_issues_repo_name": "mindThomas/Kugle-Misc", "max_issues_repo_head_hexsha": "4578cce7f9b319cf9bc708a434c5713e9ddb26fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/QuaternionTest/main.cpp", "max_forks_repo_name": "mindThomas/Kugle-Misc", "max_forks_repo_head_hexsha": "4578cce7f9b319cf9bc708a434c5713e9ddb26fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-03-06T10:16:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-05T13:06:43.000Z", "avg_line_length": 40.0731707317, "max_line_length": 181, "alphanum_fraction": 0.6419963481, "num_tokens": 2682, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6629714853978277}} {"text": "/**\n * @file quasiinterpolation_main.cc\n * @brief NPDE exam TEMPLATE MAIN FILE\n * @author Oliver Rietmann\n * @date 15.07.2020\n * @copyright Developed at SAM, ETH Zurich\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"iohelper.h\"\n#include \"quasiinterpolation.h\"\n\nconstexpr double PI = 3.14159265358979323846;\n// A bump function\ndouble u1(Eigen::Vector2d x) {\n double abs_x = x.norm();\n return abs_x < 0.5 ? std::cos(PI * abs_x) : 0.0;\n};\n// The gradient of the bump function\nEigen::Vector2d grad_u1(Eigen::Vector2d x) {\n double abs_x = x.norm();\n if (abs_x == 0.0 || abs_x >= 0.5)\n return Eigen::Vector2d::Zero();\n else\n return -PI * std::sin(PI * abs_x) / abs_x * x;\n};\n\n// A simplex auxiliary function\ninline double square(double y) { return y * y; }\n\n// A smoother bump function\ndouble u2(Eigen::Vector2d x) { return square(u1(x)); };\n// ... and its gradient\nEigen::Vector2d grad_u2(Eigen::Vector2d x) { return 2.0 * u1(x) * grad_u1(x); };\n\nint main(int /* argc */, char** /*argv*/) {\n // Build mesh hierarchy\n auto mesh_factory = std::make_unique(2);\n lf::io::GmshReader reader(std::move(mesh_factory),\n CURRENT_SOURCE_DIR \"/../meshes/mesh.msh\");\n std::shared_ptr base_mesh_p{reader.mesh()};\n std::shared_ptr mesh_hierarchy_p =\n lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(base_mesh_p, 6);\n\n // Compute meshwidth for each refinement\n int L = mesh_hierarchy_p->NumLevels();\n Eigen::VectorXd meshwidth(L);\n for (int k = 0; k < L; ++k) {\n std::shared_ptr mesh_p = mesh_hierarchy_p->getMesh(k);\n auto fe_space =\n std::make_shared>(mesh_p);\n meshwidth(k) = QuasiInterpolation::maxLength(mesh_p->Entities(1));\n }\n {\n // Errors for u1\n lf::mesh::utils::MeshFunctionGlobal u1_mf(u1);\n lf::mesh::utils::MeshFunctionGlobal grad_u1_mf(grad_u1);\n // Retrieve error norms\n auto [l2_error, h1_error] = QuasiInterpolation::interpolationError(\n mesh_hierarchy_p, u1_mf, grad_u1_mf);\n QuasiInterpolation::printError(meshwidth, l2_error, h1_error,\n \"errors for u1\");\n QuasiInterpolation::writeCSV(meshwidth, l2_error, h1_error,\n CURRENT_BINARY_DIR \"/convergence_u1.csv\");\n // Call a Python script to generate plots\n std::system(\"python3 \" CURRENT_SOURCE_DIR\n \"/plot_convergence.py \" CURRENT_BINARY_DIR\n \"/convergence_u1.csv \" CURRENT_BINARY_DIR\n \"/convergence_u1.eps 'Interpolation error for $u(x)=u_1(x)$'\");\n }\n {\n // Errors for u2\n lf::mesh::utils::MeshFunctionGlobal u2_mf(u2);\n lf::mesh::utils::MeshFunctionGlobal grad_u2_mf(grad_u2);\n auto [l2_error, h1_error] = QuasiInterpolation::interpolationError(\n mesh_hierarchy_p, u2_mf, grad_u2_mf);\n QuasiInterpolation::printError(meshwidth, l2_error, h1_error,\n \"errors for u2\");\n QuasiInterpolation::writeCSV(meshwidth, l2_error, h1_error,\n CURRENT_BINARY_DIR \"/convergence_u2.csv\");\n std::system(\"python3 \" CURRENT_SOURCE_DIR\n \"/plot_convergence.py \" CURRENT_BINARY_DIR\n \"/convergence_u2.csv \" CURRENT_BINARY_DIR\n \"/convergence_u2.eps 'Interpolation error for $u(x)=u_2(x)$'\");\n }\n return 0;\n}\n", "meta": {"hexsha": "9a41882044f024c6638c3504688b30546b2c06c0", "size": 3658, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/QuasiInterpolation/templates/quasiinterpolation_main.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/QuasiInterpolation/templates/quasiinterpolation_main.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/QuasiInterpolation/templates/quasiinterpolation_main.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 37.7113402062, "max_line_length": 80, "alphanum_fraction": 0.6585565883, "num_tokens": 1035, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7745833789613196, "lm_q1q2_score": 0.6629280733058207}} {"text": "#pragma once\n\n#include \n#include \n#include \n\n/* Creates a matrix that Rotate vector about the z axis\n * Currently needed for our robot relative coordinate system\n */\ntemplate \nboost::numeric::ublas::matrix rotateZMatrix(T theta);\n\n/* Creates a translation matrix\n */\ntemplate \nboost::numeric::ublas::matrix translateMatrix(T x, T y, T z);\n\n/* Creates a projection matrix\n */\ntemplate \nboost::numeric::ublas::matrix projectionMatrix(T ex, T ey,\n T ez);\n\n\n/* Creates a DH matrix used in Kinematics\n */\ntemplate \nboost::numeric::ublas::matrix createDHMatrix(T a, T alpha,\n T d, T theta);\n\n/* Function to invert matrix\n */\ntemplate \nbool invertMatrix(const boost::numeric::ublas::matrix& input,\n boost::numeric::ublas::matrix& inverse);\n\n/* Creates a 4,1 vector */\ntemplate \ninline boost::numeric::ublas::matrix\nvec4(T a, T b, T c, T d) {\n boost::numeric::ublas::matrix m(4, 1);\n m(0, 0) = a;\n m(1, 0) = b;\n m(2, 0) = c;\n m(3, 0) = d;\n return m;\n}\n\n/* Creates a 4,1 vector from a 4,1 array */\ntemplate \ninline boost::numeric::ublas::matrix\nvec4(const T a[]) {\n boost::numeric::ublas::matrix m(4, 1);\n m(0, 0) = a[0];\n m(1, 0) = a[1];\n m(2, 0) = a[2];\n m(3, 0) = a[3];\n return m;\n}\n\n#include \"utils/matrix_helpers.tcc\"\n", "meta": {"hexsha": "840481b9ea316deef5bb7b149b3130b0ab2e1db6", "size": 1553, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/External/unsw/unsw/utils/matrix_helpers.hpp", "max_stars_repo_name": "pedrohsreis/boulos", "max_stars_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T18:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T17:47:07.000Z", "max_issues_repo_path": "src/Core/External/unsw/unsw/utils/matrix_helpers.hpp", "max_issues_repo_name": "pedrohsreis/boulos", "max_issues_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-08T18:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-19T21:41:16.000Z", "max_forks_repo_path": "src/Core/External/unsw/unsw/utils/matrix_helpers.hpp", "max_forks_repo_name": "pedrohsreis/boulos", "max_forks_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-09-11T17:19:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-30T16:43:56.000Z", "avg_line_length": 25.0483870968, "max_line_length": 64, "alphanum_fraction": 0.6104314231, "num_tokens": 462, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382236515258, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6625920304112534}} {"text": "#ifndef EXPSUM_MODIFIED_PRONY_TRUNCATION_HPP\n#define EXPSUM_MODIFIED_PRONY_TRUNCATION_HPP\n\n#include \n\nnamespace expsum\n{\n\n//\n// Truncation of sum-of-exponentials with small exponents.\n//\n// This class find the optimal sum-of-exponentials with small exponents with\n// smaller number of terms using the modified Prony method proposed by Beylkin\n// and Monzon (2010).\n//\ntemplate \nclass modified_prony_truncation\n{\npublic:\n using size_type = arma::uword;\n using value_type = T;\n using real_type = typename arma::get_pod_type::result;\n using complex_type = std::complex;\n\n using vector_type = arma::Col;\n using real_vector_type = arma::Col;\n // using complex_vector_type = arma::Col;\n using complex_vector_type = arma::Col;\n\n using matrix_type = arma::Mat;\n // using complex_matrix_type = arma::Mat;\n using complex_matrix_type = arma::Mat;\n\nprivate:\n size_type size_;\n complex_vector_type exponent_;\n complex_vector_type weight_;\n\n complex_vector_type vec_work_;\n complex_matrix_type mat_work_;\n\npublic:\n template \n typename std::enable_if<(arma::is_basevec::value &&\n arma::is_basevec::value),\n void>::type\n run(const VecP& p, const VecW& w, real_type eps);\n\n void resize(size_type n)\n {\n if (exponent_.size() < n)\n {\n exponent_.set_size(n);\n weight_.set_size(n);\n vec_work_.set_size(2 * n);\n mat_work_.set_size(2 * n, n);\n }\n }\n\n //\n // @return number of terms after truncation\n //\n size_type size() const\n {\n return size_;\n }\n\n //\n // @return Vector view to the exponents.\n //\n auto exponents() const -> decltype(exponent_.head(size_))\n {\n return exponent_.head(size_);\n }\n //\n // @return Vector view to the weights.\n //\n auto weights() const -> decltype(weight_.head(size_))\n {\n return weight_.head(size_);\n }\n};\n\ntemplate \ntemplate \ntypename std::enable_if<(arma::is_basevec::value &&\n arma::is_basevec::value),\n void>::type\nmodified_prony_truncation::run(const VecP& p, const VecW& w, real_type eps)\n{\n const auto n1 = p.n_elem;\n resize(n1);\n\n if (n1 == size_type())\n {\n size_ = n1;\n return;\n }\n\n value_type* h_ptr = reinterpret_cast(mat_work_.memptr());\n value_type* v_ptr = h_ptr + n1 * n1;\n\n vector_type p_pow(h_ptr, n1, false, true);\n vector_type h_vec(v_ptr, 2 * n1, false, true);\n\n p_pow = p;\n\n h_vec(0) = arma::sum(w);\n h_vec(1) = -arma::sum(w % p_pow);\n\n size_type n2 = 1;\n auto factorial = real_type(1);\n while (n2 < n1)\n {\n p_pow %= p;\n h_vec(2 * n2) = arma::sum(w % p_pow);\n p_pow %= p;\n h_vec(2 * n2 + 1) = -arma::sum(w % p_pow);\n\n factorial *= real_type(2 * n2 * (2 * n2 + 1));\n\n if (std::abs(h_vec(2 * n2 + 1)) < eps * factorial)\n {\n // Taylor expansion converges with the tolerance eps.\n ++n2;\n break;\n }\n ++n2;\n }\n\n size_ = n2;\n //\n // Construct a Hankel matrix from the sequence h_vec, and solve the linear\n // equation, H q = b, with b = -h_vec(m:2m-1).\n //\n std::cout << \"***** Hankel matrix\" << std::endl;\n matrix_type H(h_ptr, n2, n2, false, true);\n\n for (size_type k = 0; k < n2; ++k)\n {\n H.col(k) = h_vec.subvec(k, k + n2 - 1);\n }\n\n value_type* q_ptr = reinterpret_cast(exponent_.memptr());\n vector_type q(q_ptr, n2, false, true);\n std::cout << \"***** linear solve\" << std::endl;\n q = arma::solve(H, h_vec.subvec(n2, 2 * n2 - 1));\n\n //\n // Find the roots of the Prony polynomial,\n //\n // q(z) = \\sum_{k=0}^{m-1} q_k z^{k}.\n //\n // The roots of q(z) can be obtained as the eigenvalues of the companion\n // matrix,\n //\n // (0 0 ... 0 -q[0] )\n // (1 0 ... 0 -q[1] )\n // C = (0 1 ... 0 -q[2] )\n // (.. .. ... .. .. )\n // (0 0 ... 1 -q[m-1])\n //\n std::cout << \"***** find roots\" << std::endl;\n matrix_type& C = H; // overwrite H\n C.zeros();\n for (size_type i = 0; i < n2 - 1; ++i)\n {\n C(i + 1, i) = real_type(1);\n }\n C.col(n2 - 1) = -q;\n // exponent_.head(n2) = arma::eig_gen(C);\n // exponent_.head(n2) = -exponent_.head(n2);\n auto eigvals = arma::eig_gen(C);\n exponent_.head(n2) = -arma::real(eigvals);\n\n //\n // Solve overdetermined Vandermonde system,\n //\n // V(0:2m-1,0:m-1) w(0:m-1) = h(0:2m-1)\n //\n // by the least square method.\n //\n std::cout << \"***** least squares\" << std::endl;\n complex_vector_type b2(vec_work_.memptr(), 2 * n2, false, true);\n for (size_type i = 0; i < 2 * n2; ++i)\n {\n b2(i) = h_vec(i);\n }\n // Construct Vandermonde matrix from exponents\n complex_matrix_type V(mat_work_.memptr(), 2 * n2, n2, false, true);\n for (size_type i = 0; i < n2; ++i)\n {\n // We assume all the eigenvalues are real here\n const auto z = exponent_(i);\n V(0, i) = T(1);\n for (size_type j = 1; j < V.n_rows; ++j)\n {\n V(j, i) = V(j - 1, i) * z; // z[i]**j\n }\n }\n\n weight_.subvec(0, n2 - 1) = arma::solve(V, b2);\n}\n\n} // namespace expsum\n\n#endif /* EXPSUM_MODIFIED_PRONY_TRUNCATION_HPP */\n", "meta": {"hexsha": "24a28344d8f79c31df0844ccffb77b71c22090f5", "size": 5626, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/expsum/modified_prony_truncation.hpp", "max_stars_repo_name": "hide-ikeno/expsum", "max_stars_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/expsum/modified_prony_truncation.hpp", "max_issues_repo_name": "hide-ikeno/expsum", "max_issues_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/expsum/modified_prony_truncation.hpp", "max_forks_repo_name": "hide-ikeno/expsum", "max_forks_repo_head_hexsha": "7b1be33b7c342f875d6d5e5c0cd8df9ec62abbda", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0480769231, "max_line_length": 78, "alphanum_fraction": 0.5558123, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654976, "lm_q2_score": 0.7549149868676283, "lm_q1q2_score": 0.6624203678232529}} {"text": "//\n// Copyright (c) 2016-2020 CNRS INRIA\n//\n\n#ifndef __pinocchio_math_rpy_hxx__\n#define __pinocchio_math_rpy_hxx__\n\n#include \n\n#include \"pinocchio/math/sincos.hpp\"\n\nnamespace pinocchio\n{\n namespace rpy\n {\n template\n Eigen::Matrix\n rpyToMatrix(const Scalar& r,\n const Scalar& p,\n const Scalar& y)\n {\n typedef Eigen::AngleAxis AngleAxis;\n typedef Eigen::Matrix Vector3s;\n return (AngleAxis(y, Vector3s::UnitZ())\n * AngleAxis(p, Vector3s::UnitY())\n * AngleAxis(r, Vector3s::UnitX())\n ).toRotationMatrix();\n }\n\n\n template\n Eigen::Matrix\n rpyToMatrix(const Eigen::MatrixBase & rpy)\n {\n PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE(Vector3Like, rpy, 3, 1);\n return rpyToMatrix(rpy[0], rpy[1], rpy[2]);\n }\n\n\n template\n Eigen::Matrix\n matrixToRpy(const Eigen::MatrixBase & R)\n {\n PINOCCHIO_ASSERT_MATRIX_SPECIFIC_SIZE(Matrix3Like, R, 3, 3);\n assert(R.isUnitary() && \"R is not a unitary matrix\");\n\n typedef typename Matrix3Like::Scalar Scalar;\n typedef Eigen::Matrix ReturnType;\n static const Scalar pi = PI();\n\n ReturnType res = R.eulerAngles(2,1,0).reverse();\n\n if(res[1] < -pi/2)\n res[1] += 2*pi;\n\n if(res[1] > pi/2)\n {\n res[1] = pi - res[1];\n if(res[0] < Scalar(0))\n res[0] += pi;\n else\n res[0] -= pi;\n // res[2] > 0 according to Eigen's eulerAngles doc, no need to check its sign\n res[2] -= pi;\n }\n\n return res;\n }\n\n\n template\n Eigen::Matrix\n computeRpyJacobian(const Eigen::MatrixBase & rpy, const ReferenceFrame rf)\n {\n typedef typename Vector3Like::Scalar Scalar;\n typedef Eigen::Matrix ReturnType;\n ReturnType J;\n const Scalar p = rpy[1];\n Scalar sp, cp;\n SINCOS(p, &sp, &cp);\n switch (rf)\n {\n case LOCAL:\n {\n const Scalar r = rpy[0];\n Scalar sr, cr; SINCOS(r, &sr, &cr);\n J << Scalar(1.0), Scalar(0.0), -sp,\n Scalar(0.0), cr, sr*cp,\n Scalar(0.0), -sr, cr*cp;\n return J;\n }\n case WORLD:\n case LOCAL_WORLD_ALIGNED:\n {\n const Scalar y = rpy[2];\n Scalar sy, cy; SINCOS(y, &sy, &cy);\n J << cp*cy, -sy, Scalar(0.0),\n cp*sy, cy, Scalar(0.0),\n -sp, Scalar(0.0), Scalar(1.0);\n return J;\n }\n default:\n {\n throw std::invalid_argument(\"Bad reference frame.\");\n }\n }\n }\n\n\n template\n Eigen::Matrix\n computeRpyJacobianInverse(const Eigen::MatrixBase & rpy, const ReferenceFrame rf)\n {\n typedef typename Vector3Like::Scalar Scalar;\n typedef Eigen::Matrix ReturnType;\n ReturnType J;\n const Scalar p = rpy[1];\n Scalar sp, cp;\n SINCOS(p, &sp, &cp);\n Scalar tp = sp/cp;\n switch (rf)\n {\n case LOCAL:\n {\n const Scalar r = rpy[0];\n Scalar sr, cr; SINCOS(r, &sr, &cr);\n J << Scalar(1.0), sr*tp, cr*tp,\n Scalar(0.0), cr, -sr,\n Scalar(0.0), sr/cp, cr/cp;\n return J;\n }\n case WORLD:\n case LOCAL_WORLD_ALIGNED:\n {\n const Scalar y = rpy[2];\n Scalar sy, cy; SINCOS(y, &sy, &cy);\n J << cy/cp, sy/cp, Scalar(0.0),\n -sy, cy, Scalar(0.0),\n cy*tp, sy*tp, Scalar(1.0);\n return J;\n }\n default:\n {\n throw std::invalid_argument(\"Bad reference frame.\");\n }\n }\n }\n\n template\n Eigen::Matrix\n computeRpyJacobianTimeDerivative(const Eigen::MatrixBase & rpy, const Eigen::MatrixBase & rpydot, const ReferenceFrame rf)\n {\n typedef typename Vector3Like0::Scalar Scalar;\n typedef Eigen::Matrix ReturnType;\n ReturnType J;\n const Scalar p = rpy[1];\n const Scalar dp = rpydot[1];\n Scalar sp, cp;\n SINCOS(p, &sp, &cp);\n switch (rf)\n {\n case LOCAL:\n {\n const Scalar r = rpy[0];\n const Scalar dr = rpydot[0];\n Scalar sr, cr; SINCOS(r, &sr, &cr);\n J << Scalar(0.0), Scalar(0.0), -cp*dp,\n Scalar(0.0), -sr*dr, cr*cp*dr - sr*sp*dp,\n Scalar(0.0), -cr*dr, -sr*cp*dr - cr*sp*dp;\n return J;\n }\n case WORLD:\n case LOCAL_WORLD_ALIGNED:\n {\n const Scalar y = rpy[2];\n const Scalar dy = rpydot[2];\n Scalar sy, cy; SINCOS(y, &sy, &cy);\n J << -sp*cy*dp - cp*sy*dy, -cy*dy, Scalar(0.0),\n cp*cy*dy - sp*sy*dp, -sy*dy, Scalar(0.0),\n -cp*dp, Scalar(0.0), Scalar(0.0);\n return J;\n }\n default:\n {\n throw std::invalid_argument(\"Bad reference frame.\");\n }\n }\n }\n\n } // namespace rpy\n}\n#endif //#ifndef __pinocchio_math_rpy_hxx__\n", "meta": {"hexsha": "edaff629136ef237bf16b10300a137a13a5bde8b", "size": 6049, "ext": "hxx", "lang": "C++", "max_stars_repo_path": "src/math/rpy.hxx", "max_stars_repo_name": "thanhndv212/pinocchio", "max_stars_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_stars_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_stars_count": 716.0, "max_stars_repo_stars_event_min_datetime": "2015-03-30T16:26:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T12:26:58.000Z", "max_issues_repo_path": "src/math/rpy.hxx", "max_issues_repo_name": "thanhndv212/pinocchio", "max_issues_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_issues_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_issues_count": 1130.0, "max_issues_repo_issues_event_min_datetime": "2015-02-21T17:30:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T09:06:22.000Z", "max_forks_repo_path": "src/math/rpy.hxx", "max_forks_repo_name": "thanhndv212/pinocchio", "max_forks_repo_head_hexsha": "3b4d272bf4e8a231954b71201ee7e0963c944aef", "max_forks_repo_licenses": ["BSD-2-Clause-FreeBSD"], "max_forks_count": 239.0, "max_forks_repo_forks_event_min_datetime": "2015-02-05T14:15:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T23:51:47.000Z", "avg_line_length": 31.3419689119, "max_line_length": 154, "alphanum_fraction": 0.5610844768, "num_tokens": 1750, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.909907010924213, "lm_q2_score": 0.7279754489059775, "lm_q1q2_score": 0.6623899647402501}} {"text": "#include \n#include \n\nusing namespace std;\nusing namespace arma;\n\nint main()\n{\n // Constructor\n arma::mat x,y;\n\n x << 0.1778 << 0.1203 << -0.2264 << endr\n << 0.0957 << 0.2403 << -0.3400 << endr\n << 0.1397 << 0.1925 << -0.3336 << endr\n << 0.2256 << 0.3144 << -0.8695 << endr;\n\n y << 1 << 1 << -1 << endr\n << 1 << -1 << 1 << endr\n << -1 << 1 << 1 << endr\n << 1 << 1 << 1 << endr;\n\n // Forward\n arma::mat loss_none = arma::log(1 + arma::exp(-y % x));\n double loss_sum = arma::sum(arma::sum(loss_none));\n double loss_mean = loss_sum / x.n_elem;\n\n // Backward\n arma::mat output ;\n output.set_size(size(x));\n arma::mat numerator = -y % arma::exp(-y % x);\n arma::mat denominator = 1 + arma::exp(-y % x);\n output = numerator / denominator;\n\n // Display\n cout << \"------------------------------------------------------------------\" << endl;\n cout << \"USER-PROVIDED MATRICES : \" << endl;\n cout << \"------------------------------------------------------------------\" << endl;\n cout << \"Input shape : \"<< x.n_rows << \" \" << x.n_cols << endl;\n cout << \"Input : \" << endl << x << endl;\n cout << \"Target shape : \"<< y.n_rows << \" \" << y.n_cols << endl;\n cout << \"Target : \" << endl << y << endl;\n cout << \"------------------------------------------------------------------\" << endl;\n cout << \"SUM \" << endl;\n cout << \"------------------------------------------------------------------\" << endl;\n cout << \"FORWARD : \" << endl;\n cout << \"Loss : \\n\" << loss_none << '\\n';\n cout << \"Loss (sum):\\n\" << loss_sum << '\\n';\n cout << \"BACKWARD : \" << endl;\n cout << \"Output shape : \"<< output.n_rows << \" \" << output.n_cols << endl;\n cout << \"Output (sum) : \" << endl << output << endl;\n cout << \"Sum of all values in this matrix : \" << arma::as_scalar(arma::accu(output)) << endl;\n cout << \"------------------------------------------------------------------\" << endl;\n cout << \"MEAN \" << endl;\n cout << \"------------------------------------------------------------------\" << endl;\n cout << \"FORWARD : \" << endl;\n cout << \"Loss (mean):\\n\" << loss_mean << '\\n';\n cout << \"BACKWARD : \" << endl;\n cout << \"Output shape : \"<< output.n_rows << \" \" << output.n_cols << endl;\n cout << \"Output (mean) : \" << endl << output / x.n_elem << endl;\n cout << \"Sum of all values in this matrix : \" << arma::as_scalar(arma::accu(output / x.n_elem)) << endl;\n cout << \"------------------------------------------------------------------\" << endl;\n return 0;\n}", "meta": {"hexsha": "ba168f0b6926a37fa8e7f3f4238aefa434d5151d", "size": 2517, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "soft_margin_loss/test.cpp", "max_stars_repo_name": "iamshnoo/mlpack-testing", "max_stars_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "soft_margin_loss/test.cpp", "max_issues_repo_name": "iamshnoo/mlpack-testing", "max_issues_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "soft_margin_loss/test.cpp", "max_forks_repo_name": "iamshnoo/mlpack-testing", "max_forks_repo_head_hexsha": "43f9fde18afc7f1e6d54c0a2bd59709c103eed55", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.9523809524, "max_line_length": 106, "alphanum_fraction": 0.417560588, "num_tokens": 735, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772482857833, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6623708140290082}} {"text": "#include \n#include \n#include \n#include \n\n#include \n\n\nstruct Domain {\n constexpr Domain(double start, double end) : x_start(start), x_end(end) {}\n double x_start;\n double x_end;\n};\n\n\ntemplate \nvoid init_solution(Eigen::ArrayBase& V, const Domain& domain) {\n const std::size_t nx = V.cols();\n const double hx = (domain.x_end - domain.x_start) / nx;\n const double xc = 0.5 * (domain.x_start + domain.x_end) + (nx / 8.0) * hx;\n\n for(std::size_t i=0; i < nx; ++i) {\n double x = domain.x_start + (i - 0.5) * hx;\n V(0, i) = std::abs(x - xc) < 0.2 ? 1. : 0.;\n V(1, i) = 0.;\n } \n}\n\n\nvoid compute_flux(Eigen::Array& flux, double V1, double V2, double tol)\n{\n flux(0) = V2;\n if(std::abs(V1) < tol)\n flux(1) = 0.;\n else\n flux(1) = V2 * V2 / V1 + 0.5 * 9.81 * V1 * V1;\n}\n\n\ntemplate\nvoid scheme_LaxFriedrich(ArrayType2d& V, const ArrayType2d& Vold,\n const ArrayType1d& lambdas,\n double dt, double dx, double tol)\n{\n std::size_t Nx = lambdas.cols();\n double Cx = dt / dx;\n\n Eigen::Array flux, flux1, flux2;\n compute_flux(flux1, Vold(0, 0), Vold(1, 0), tol);\n\n V(1, 0) += Cx * (flux1(1) - lambdas(0) * Vold(1, 0));\n for(std::size_t i=0; i\ndouble updateCFL(ArrayType1d& lambdas, const ArrayType2d& V,\n double dx, double tol)\n{\n std::size_t Nx = lambdas.cols();\n double M = 0.;\n\n for(std::size_t i=0; i\ndouble update_to_time(ArrayType2d& V, ArrayType2d& Vold, ArrayType1d& lambdas,\n double t, double tframe, double dx, double tol)\n \n{ \n while(t < tframe) {\n double dt = std::min(updateCFL(lambdas, V, dx, tol),\n tframe - t);\n Vold = V;\n scheme_LaxFriedrich(V, Vold, lambdas, dt, dx, tol);\n \n t += dt;\n }\n\n return t;\n}\n\n\n\nint main() {\n constexpr Domain domain(0., 1.);\n constexpr std::size_t Nx = 16384;\n constexpr double T = 2.0;\n constexpr double dx = (domain.x_end - domain.x_start) / Nx;\n constexpr double tol = 1e-15;\n\n\n Eigen::Array V(2, Nx);\n init_solution(V, domain);\n\n Eigen::Array Vold(2, Nx);\n Eigen::Array lambdas(Nx);\n \n double t = 0;\n std::cout << \"Initial time t = \" << t << std::endl;\n\n auto time_start = std::chrono::high_resolution_clock::now();\n t = update_to_time(V, Vold, lambdas, t, T, dx, tol);\n auto time_end = std::chrono::high_resolution_clock::now();\n std::chrono::duration elapsed_seconds = time_end - time_start;\n \n std::cout << \"Elapsed time: \" << elapsed_seconds.count() << \"s\" << std::endl; \n std::cout << \"End of simulation, t = \" << t << std::endl;\n \n std::cout << \"mean(h) = \" << V.row(0).mean() << std::endl;\n\n const Eigen::IOFormat to_file(Eigen::FullPrecision, Eigen::DontAlignCols, \"\\n\", \"\\n\");\n std::ofstream file(\"sol-cpu\");\n file << V.row(0).format(to_file);\n \n return 0;\n}\n", "meta": {"hexsha": "24230edd45be31d57c5fe3717837773d1f2527d0", "size": 3925, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SaintVenant/C/main1d.cpp", "max_stars_repo_name": "danielcort/benchmarks-python-julia-c", "max_stars_repo_head_hexsha": "aececc9f1fc3c368ae57f84028b0cf35a0c138e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2018-03-27T08:36:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T12:26:54.000Z", "max_issues_repo_path": "SaintVenant/C/main1d.cpp", "max_issues_repo_name": "danielcort/benchmarks-python-julia-c", "max_issues_repo_head_hexsha": "aececc9f1fc3c368ae57f84028b0cf35a0c138e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T16:44:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-09-27T06:33:09.000Z", "max_forks_repo_path": "SaintVenant/C/main1d.cpp", "max_forks_repo_name": "danielcort/benchmarks-python-julia-c", "max_forks_repo_head_hexsha": "aececc9f1fc3c368ae57f84028b0cf35a0c138e4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2018-05-29T13:27:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-27T17:49:09.000Z", "avg_line_length": 28.6496350365, "max_line_length": 113, "alphanum_fraction": 0.5533757962, "num_tokens": 1280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6623707993048674}} {"text": "//#include \n//#include \n//#include \n#include \n#include \n#include \n#include \n#include \"kv/interval.hpp\"\n// define rounding operations for double\n// if \"rdouble.hpp\" is not included, result of computation is not \"verified\" \n#include \"kv/rdouble.hpp\"\ntypedef kv::interval itv;\nnamespace ub = boost::numeric::ublas;\nitv factorial(int k){\n itv sum;\n sum=1.;\n for (int i = 1; i <= k; ++i)\n {\n sum *= i;\n }\n return sum;\n}\nint main(void){\nstd::cout.precision(17);\n int n=2,M=42;\n /* vcp::matrix< itv, vcp::imats< double > > A,B,res,sum; \n sum.zeros(n);\n A(0,0)=1.;\n A(0,1)=-3.;\n A(1,0)=-2.;\n A(1,1)=5.;\n for(int N=0;N<=M;N++){\n sum=sum*A+1/factorial(N);\n }\n norm=max(abs(A));\n error=exp(norm)*pow(norm,M+1)/factorial(M+1);\n b=max(abs(error));\n B.ones(n);\n B=B*itv(-b,b);\n */\n // use ublas\n ub::matrix< itv > A(n, n),B(n, n),res(n, n),sum(n, n),pro(n,n);\n itv error,norm;\n double b;\n for(int i=0;iabs(norm)) norm=abs(A(i1,j1));\n }\n }\n\n error=exp(norm)*pow(norm,M+1)/factorial(M+1);\n b=(abs(error)).upper();\n\n for(int k1=0;k1\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace boost::multiprecision;\n\n#include \"input.h\"\n#include \n#include \n\n// https://rosettacode.org/wiki/Modular_inverse#C.2B.2B\nint256_t modinv(int256_t a, int256_t b) {\n int256_t b0 = b, t, q;\n int256_t x0 = 0, x1 = 1;\n if (b == 1) return 1;\n while (a > 1) {\n q = a / b;\n t = b, b = a % b, a = t;\n t = x0, x0 = x1 - q * x0, x1 = t;\n }\n if (x1 < 0) x1 += b0;\n return x1;\n}\n\nenum ShuffleKind { Deal = 0, Cut = 1, DealInc = 2 };\n\nstruct Params {\n int256_t a;\n int256_t b;\n};\n\nclass Shuffle {\npublic:\n ShuffleKind kind;\n int256_t num;\n Shuffle(string s) {\n if (s.rfind(\"deal into\", 0) == 0) {\n kind = Deal;\n num = 0;\n return;\n }\n num = stoi(s.substr(s.rfind(\" \")+1));\n if (s.rfind(\"cut\", 0) == 0) {\n kind = Cut;\n } else {\n kind = DealInc;\n }\n }\n Params params(int256_t a, int256_t b, int256_t num_cards) {\n int256_t na = 0;\n int256_t nb = 0;\n switch (this->kind) {\n case Deal:\n na = -a;\n nb = -b-1;\n break;\n case Cut:\n na = a;\n nb = b - this->num;\n break;\n default:\n na = a * this->num;\n nb = b * this->num;\n }\n return Params{(na+num_cards) % num_cards, (nb+num_cards) % num_cards};\n }\n Params reverse_params(int256_t a, int256_t b, int256_t num_cards) {\n int256_t na = 0;\n int256_t nb = 0;\n switch (this->kind) {\n case Deal:\n na = -a;\n nb = -b-1;\n break;\n case Cut:\n na = a;\n nb = b + this->num;\n break;\n default:\n int256_t m = modinv(this->num, num_cards);\n na = a * m;\n nb = b * m;\n }\n return Params{(na+num_cards) % num_cards, (nb+num_cards) % num_cards};\n }\n};\n\nint256_t modpow(int256_t b, int256_t e, int256_t m) {\n int256_t res = 1;\n while (e > 0) {\n if ((e%2) == 1) {\n res = (res * b) % m;\n }\n e = e / 2;\n b = (b * b) % m;\n }\n return res;\n}\n\nclass Game {\n vector shuffles;\n int256_t cards;\npublic:\n Game(vector &inp, int256_t num_cards) {\n for (auto l : inp) {\n shuffles.push_back(Shuffle(l));\n }\n cards = num_cards;\n }\n Params params() {\n int256_t a = 1;\n int256_t b = 0;\n for (auto s : this->shuffles) {\n Params p = s.params(a, b, this->cards);\n a = p.a;\n b = p.b;\n }\n return Params{a, b};\n }\n int256_t forward(int256_t card) {\n Params p = this->params();\n return (((p.a * card) + p.b) % this->cards);\n }\n Params reverse_params() {\n int256_t a = 1;\n int256_t b = 0;\n BOOST_REVERSE_FOREACH(auto s, this->shuffles) {\n Params p = s.reverse_params(a, b, this->cards);\n a = p.a;\n b = p.b;\n }\n return Params{a, b};\n }\n int256_t backward(int256_t card, int256_t rounds) {\n Params p = this->reverse_params();\n int256_t exp = modpow(p.a, rounds, this->cards);\n int256_t im = modinv(p.a-1, this->cards);\n return ((((exp-1) * im) * p.b) + (exp * card)) % this->cards;\n }\n};\n\nvoid tests() {\n}\n\nvoid run(unsigned int inp_len, unsigned char* inp, bool is_bench) {\n vector ln = lines(inp_len, inp);\n Game* game = new Game(ln, 10007);\n auto p1 = game->forward(2019);\n game = new Game(ln, 119315717514047);\n int256_t rounds = 101741582076661;\n auto p2 = game->backward(2020, rounds);\n if (!is_bench) {\n cout << \"Part 1: \" << p1 << \"\\n\";\n cout << \"Part 2: \" << p2 << \"\\n\";\n }\n}\n\nint main(int argc, char **argv) {\n if (is_test()) { tests(); }\n benchme(argc, argv, input_txt_len, input_txt, run);\n}\n", "meta": {"hexsha": "93e464eb0792dbd5fdc08085924f165d62658b7d", "size": 3747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/22/cpp/aoc.cpp", "max_stars_repo_name": "beanz/advent", "max_stars_repo_head_hexsha": "d5ceeae48483d25b81aaf06ef3faf79521af14b1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2019/22/cpp/aoc.cpp", "max_issues_repo_name": "beanz/advent", "max_issues_repo_head_hexsha": "d5ceeae48483d25b81aaf06ef3faf79521af14b1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2019/22/cpp/aoc.cpp", "max_forks_repo_name": "beanz/advent", "max_forks_repo_head_hexsha": "d5ceeae48483d25b81aaf06ef3faf79521af14b1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.9122807018, "max_line_length": 74, "alphanum_fraction": 0.5580464371, "num_tokens": 1273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197768, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6623704679687661}} {"text": "#include \n#include \n\n#include \n\n#include \"vice/integrate.h\"\n#include \"vice/functors.h\"\n\n\nint main () {\n double texp = 0.1;\n\n //double depth = 0.1;\n //double duration = 0.1;\n //double ingress = 0.2;\n //vice::functors::TrapFunctor func(depth, duration, ingress);\n\n double tau = 0.5;\n double r = 0.1;\n double b = 0.5;\n Eigen::VectorXd u(2);\n u << 0.3, 0.2;\n vice::functors::StarryFunctor func(u, r, b, tau);\n\n //double tmin = -duration - 2*ingress;\n //double tmax = duration + 2*ingress;\n double tmin = -tau - texp;\n double tmax = tau + texp;\n int npts = 500;\n double dt = (tmax - tmin) / (npts - 1);\n\n int neval = 15;\n double tol = 1e-9;\n\n std::cout << \"time,flux,truth,reimann,n_reimann,trap_fixed,n_trap_fixed,simp_fixed,n_simp_fixed,trap_adapt,n_trap_adapt,simp_adapt,n_simp_adapt,\\n\";\n std::cout.precision(25);\n std::cout << std::scientific;\n\n for (int i = 0; i < npts; ++i) {\n double t = tmin + i * dt;\n double lower = t - 0.5*texp;\n double upper = t + 0.5*texp;\n\n func.reset();\n double flux = func(t);\n double truth = func.integrate(lower, upper) / texp;\n\n std::cout << t << \",\" << flux << \",\" << truth << \",\";\n\n func.reset();\n double f_reimann = vice::reimann::integrate_fixed(func, lower, upper, neval) / texp;\n std::cout << f_reimann << \",\" << func.get_n_eval() << \",\";\n\n func.reset();\n double f_trap_fixed = vice::trapezoid::integrate_fixed(func, lower, upper, neval) / texp;\n std::cout << f_trap_fixed << \",\" << func.get_n_eval() << \",\";\n\n func.reset();\n double f_simp_fixed = vice::simpson::integrate_fixed(func, lower, upper, neval) / texp;\n std::cout << f_simp_fixed << \",\" << func.get_n_eval() << \",\";\n\n func.reset();\n double f_trap_adapt = vice::trapezoid::integrate_adapt(func, lower, upper, tol, 50) / texp;\n std::cout << f_trap_adapt << \",\" << func.get_n_eval() << \",\";\n\n func.reset();\n double f_simp_adapt = vice::simpson::integrate_adapt(func, lower, upper, tol, 50) / texp;\n std::cout << f_simp_adapt << \",\" << func.get_n_eval() << \",\";\n\n std::cout << \"\\n\";\n }\n}\n", "meta": {"hexsha": "f181c9adf5187dc91a8407926c26b2d5ef13b985", "size": 2127, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/demo.cc", "max_stars_repo_name": "dfm/confessional", "max_stars_repo_head_hexsha": "24e0088602ec03cb31bbd1a27bd20465793dcfa4", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/demo.cc", "max_issues_repo_name": "dfm/confessional", "max_issues_repo_head_hexsha": "24e0088602ec03cb31bbd1a27bd20465793dcfa4", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-02T12:00:51.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-02T12:00:51.000Z", "max_forks_repo_path": "src/demo.cc", "max_forks_repo_name": "dfm/confessional", "max_forks_repo_head_hexsha": "24e0088602ec03cb31bbd1a27bd20465793dcfa4", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1369863014, "max_line_length": 150, "alphanum_fraction": 0.6046074283, "num_tokens": 707, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9059898279984214, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6623316359097686}} {"text": "#include \n#include \n#include \n#include \n#include \"nn.h\"\n#include \n#include \n#include \n\nusing namespace std;\n\nint main(int argc, const char *argv[])\n{\n\tstring filename(argv[1]);\n\tifstream fin;\n\tstring directory(\"../Datasets/\");\n\tstring filepath = directory + filename;\n\tfin.open(filepath);\n\n\tstring str;\n\tint n_input = 0; // input dimensionality\n\tint n_output = 0; // output dimensionality\n\tint n_sample = 0; // number of training samples\n\n\twhile (fin >> str)\n\t{\n\t\tn_sample++;\n\t}\n\n\tstringstream sst(str);\n\tdouble each_input;\n\twhile (sst >> each_input)\n\t{\n\t\tn_input++;\n\t\tif (sst.peek() == ',')\n\t\t\tsst.ignore();\n\t}\n\tn_output = atoi(argv[2]);\n\tn_input = n_input - n_output;\n\t//cout << n_input << \" \" << n_output;\n\t\n\tint n_layer = 3;\t\t // number of layers\n\tint max_steps = 5;\t // number of optimization steps\n\tint n_epoch = max_steps;\n\tdouble lambda = 0.000001; // regularization parameter\n\n\tmatrix_t X(n_sample, n_input);\n\tmatrix_t Y(n_sample, n_output);\n\n\tfin.clear();\n\tfin.seekg(0, ios::beg);\n\tint row = 0;\n\twhile (fin >> str)\n\t{\n\t\tint col = 0;\n\t\tdouble data;\n\t\tstringstream ss(str);\n\t\twhile (ss >> data)\n\t\t{\n\t\t\tif (col < n_input)\n\t\t\t{\n\t\t\t\tX(row, col) = data;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tint pos = col - n_input;\n\t\t\t\tY(row, pos) = data;\n\t\t\t}\n\t\t\tif (ss.peek() == ',')\n\t\t\t{\n\t\t\t\tss.ignore();\n\t\t\t}\n\t\t\tcol++;\n\t\t}\n\t\trow++;\n\t}\n\tfin.close();\n\n\t// cout << \"training input: \" << endl\n\t// \t << X << endl;\n\t// cout << \"training output: \" << endl\n\t// \t << Y << endl;\n\n\t// specify network topology\n\tEigen::VectorXi topo(n_layer);\n\ttopo << n_input, n_input, n_output;\n\t// cout << \"topology: \" << endl\n\t// \t << topo << endl;\n\n\t// initialize a neural network with given topology\n\tNeuralNet nn(topo);\n\n\tnn.autoscale(X, Y);\n\t// train the network\n\tstd::cout << \"starting training\" << endl;\n\tdouble err;\n\tdouble prevAccuracy = 0;\n\tdouble accuracy;\n\tfor (int i = 0; i < max_steps; ++i)\n\t{\n\t\terr = nn.loss(X, Y, lambda);\n\t\tnn.rprop();\n\t\t//nn.forward_pass(X);\n\t\tmatrix_t Y_prime = nn.get_activation();\n\t\taccuracy = nn.measure_accuracy(Y, Y_prime);\n\t\t//cout << \"Accuracys: \" << accuracy << \" Step No: \" << i<90)\n\t\t{\n\t\t\tn_epoch = i;\n\t\t\tbreak;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tprevAccuracy = accuracy;\n\t\t}\n\t\t//printf(\"%3i %4.4f\\n\", i, err);\n\t}\n\n\t// write model to disk\n\tnn.write(\"example.nn\");\n\n\t// read model from disk\n\tNeuralNet nn2(\"example.nn\");\n\n\t// testing\n\tnn2.forward_pass(X);\n\tmatrix_t Y_test = nn2.get_activation();\n\n\t//std::cout << \"test input:\" << endl\n\t// << X << endl;\n\t//std::cout << \"test output:\" << endl\n\t// << Y_test << endl;\n\tint correct = 0;\n\tfor (int i = 0; i < n_sample; i++)\n\t{\n\t\tint j = 0;\n\t\tfor (; j < n_output; j++)\n\t\t{\n\t\t\tint out = Y_test(i, j) > 0.7 ? 1 : 0;\n\t\t\t//printf(\"%3i %4.4f\", (int)Y(i, j), Y_test(i, j));\n\t\t\tif (out != Y(i, j))\n\t\t\t\tbreak;\n\t\t}\n\t\t//cout << endl;\n\t\tif (j == n_output)\n\t\t\tcorrect++;\n\t}\n\tcout<< \"Dataset: \" << filename << endl;\n\tcout << \"Correct answer \" << correct << \" among \" << n_sample << \" test\" << endl;\n\tcout << \"Accuracy: \" << (double)correct / (double)n_sample * 100 << \"%\" << endl;\n\tcout << \"Step Count: \" << n_epoch << endl;\n\treturn 0;\n}\n", "meta": {"hexsha": "1a5d7765b13f665b19bdc0c205c90c19456f6937", "size": 3204, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "rprop.cpp", "max_stars_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_stars_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "rprop.cpp", "max_issues_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_issues_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "rprop.cpp", "max_forks_repo_name": "Shahriar-Sazid/Study-on-Backpropagation-and-Its-Variants", "max_forks_repo_head_hexsha": "b70db459e47f14aa760e34f59627ff7ce48ba02f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6709677419, "max_line_length": 82, "alphanum_fraction": 0.5820848939, "num_tokens": 1017, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.905989822921759, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6623316215811501}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \"utils.h\"\n\n// Define aliases with using declarations\nusing Matrix = utils::Matrix;\nusing Vector = utils::Vector;\nusing VectorXcd = utils::VectorXcd;\n\n// Construct Toeplitz matrix from column (symmetric)\nMatrix utils::buildToep(const Vector & col, const Vector & row)\n{\n auto n = static_cast(col.rows());\n Matrix toep(n,n);\n for (auto i : boost::irange(0,n))\n {\n toep.diagonal(i) = Eigen::VectorXd::Ones(n-i)*row[i];\n toep.diagonal(-i) = Eigen::VectorXd::Ones(n-i)*col[i];\n }\n return toep;\n};\n\n// Construct Toeplitz matrix from column (symmetric)\nMatrix utils::buildToep(const Vector & col) { return buildToep(col, col); };\n\n// Embed Toeplitz matrix into column of circulant matrix (general) \nvoid utils::embedToep(Vector & toepCol, Vector & toepRow, VectorXcd & eigVals)\n{\n // Specify first column of circulant matrix embedding\n auto n = static_cast(toepCol.rows());\n Vector embedCol(2*n);\n embedCol.head(n) = toepCol;\n embedCol.tail(n-1) = toepRow.tail(n-1).reverse();\n\n // Compute eigenvalues of cirulant matrix\n Eigen::FFT fft;\n fft.fwd(eigVals, embedCol);\n};\n\n\n// Embed Toeplitz matrix into column of circulant matrix (symmetric)\nvoid utils::embedToep(Vector & toepCol, VectorXcd & eigVals) { embedToep(toepCol, toepCol, eigVals); };\n\n\n// Define matvec product for circular matrix using FFT (non-symmetric / complex eigVals)\nvoid utils::circMatVec(const VectorXcd & eigVals, Vector & x, Vector & result)\n{\n VectorXcd freqvec;\n Eigen::FFT fft;\n fft.fwd(freqvec,x);\n freqvec = eigVals.cwiseProduct(freqvec);\n fft.inv(result,freqvec);\n};\n\n\n// Define matvec product for Toeplitz matrix using FFT (non-symmetric)\nVector utils::toepMatVec(Vector & col, Vector & row, Vector & x, bool sym)\n{\n auto n = static_cast(col.rows());\n Vector xembed = Eigen::VectorXd::Zero(2*n);\n xembed.head(n) = x;\n VectorXcd eigVals(2*n);\n Vector result(2*n);\n embedToep(col, row, eigVals);\n\n // Note: Should be possible to optimize this better using\n // the fact that eigVals is real in the symmetric case\n if (sym)\n circMatVec(eigVals.real(), xembed, result);\n else\n circMatVec(eigVals, xembed, result);\n\n return result.head(n);\n\n};\n\n// Define matvec product for Toeplitz matrix using FFT (symmetric)\nVector utils::toepMatVec(Vector & col, Vector & x) { return toepMatVec(col, col, x, true); };\n\n\n\n// NOTE: the \"fast\" version avoids extra function calls and\n// is marginally faster than the more pedagogical \"toepMatVec\"\n\n// Define matvec product for Toeplitz matrix using FFT (non-symmetric)\nVector utils::fastToepMatVec(Vector & toepCol, Vector & toepRow, Vector & x)\n{\n auto n = static_cast(toepCol.rows());\n Vector result(2*n);\n\n // Embed RHS into 2n-vector with trailing zeros\n Vector xembed = Eigen::VectorXd::Zero(2*n);\n xembed.head(n) = x;\n\n // Specify first column of circulant matrix embedding\n Vector embedCol(2*n);\n embedCol.head(n) = toepCol;\n embedCol.tail(n-1) = toepRow.tail(n-1).reverse();\n\n // Compute eigenvalues of cirulant matrix\n Eigen::FFT fft;\n VectorXcd eigVals(2*n), freqvec(2*n);\n fft.fwd(eigVals, embedCol);\n\n // Apply component-wise multiplication in frequency space\n fft.fwd(freqvec, xembed);\n freqvec = eigVals.cwiseProduct(freqvec);\n fft.inv(result,freqvec);\n\n // Return first n values corresponding to the original system\n return result.head(n);\n\n};\n\n// Define matvec product for Toeplitz matrix using FFT (symmetric)\nVector utils::fastToepMatVec(Vector & col, Vector & x) { return fastToepMatVec(col, col, x); };\n\n\n\n// Define matvec product for Toeplitz matrix using FFT (non-symmetric)\nMatrix utils::fastToepMatMat(Vector & toepCol, Vector & toepRow, Matrix & X)\n{\n auto n = static_cast(toepCol.rows());\n auto m = static_cast(X.cols());\n Matrix result(n,m);\n for (auto i : boost::irange(0,m))\n {\n Vector X_i = X.col(i);\n result.col(i) = fastToepMatVec(toepCol, toepRow, X_i);\n }\n return result;\n}\n\n// Define matvec product for Toeplitz matrix using FFT (non-symmetric)\nMatrix utils::fastToepMatMat(Vector & toepCol, Matrix & X) { return fastToepMatMat(toepCol, toepCol, X); };\n\n\n\n// Compute Lanczos vectors for matrix-vector pair (A,v)\nvoid utils::Lanczos(Matrix & A, Vector & v, Matrix & Q, Matrix & T, int N)\n{\n // Use full decomposition if step count N is not specified\n auto n = static_cast(A.rows());\n if (N == 0)\n N = n;\n\n // Initialize the algorithm's vectors and parameters\n Vector q = v/v.norm();\n auto alpha = static_cast( (A*q).dot(q) );\n Vector r = A*q - alpha*q;\n Q.col(0) = q;\n T(0,0) = alpha;\n Vector u;\n\n // Define orthogonality and vector norm tolerances\n //double epsilon = 1.0e-15;\n //double eta = std::pow(epsilon, 0.75);\n double tolerance = 0.00001;\n\n for (auto j : boost::irange(1,N))\n {\n auto beta = static_cast(r.norm()); \n if (beta < tolerance)\n {\n std::cout << \"\\nStopped Early\\n\";\n Q.resize(n,j);\n break;\n }\n\n // Basic implementation\n //v_k = vt_k/beta;\n //alpha = v_k.transpose().dot(A*v_k);\n //vt_k = A*v_k - alpha*v_k - beta*Q.col(k-1);\n\n // Improved stability implementation \n q = r/beta;\n u = A*q - beta*Q.col(j-1);\n alpha = q.transpose().dot(u);\n r = u - alpha*q;\n\n // Complete re-orthogonalization [ roughly ~ O(n^3) for combined iterations ]\n r = r - Q*(Q.transpose()*r);\n\n /*\n // Check if additional re-orthogonalization is necessary\n for (auto k : boost::irange(0,j))\n {\n if ( std::abs((r/r.norm()).dot(Q.col(k))) > eta )\n {\n //std::cout << \"Reorthogonalizing...\" << std::endl;\n r = r/r.norm();\n r = r - Q*(Q.transpose()*r);\n break;\n }\n }\n */\n\n // Assign Lanczos vector and tridiagonal entries\n Q.col(j) = q;\n T(j,j) = alpha;\n T(j,j-1) = T(j-1,j) = beta;\n\n }\n\n};\n", "meta": {"hexsha": "d2cc252a3f55a51d63eac1ac3672b8e5c35c8f82", "size": 6107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/utils.cpp", "max_stars_repo_name": "nw2190/CppGPs", "max_stars_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T02:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T16:22:49.000Z", "max_issues_repo_path": "misc/utils.cpp", "max_issues_repo_name": "nw2190/CppGPs", "max_issues_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-10T07:40:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-10T07:40:50.000Z", "max_forks_repo_path": "misc/utils.cpp", "max_forks_repo_name": "nw2190/CppGPs", "max_forks_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T15:07:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T12:44:46.000Z", "avg_line_length": 29.080952381, "max_line_length": 107, "alphanum_fraction": 0.6500736859, "num_tokens": 1740, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6623002150265664}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nint fuel(int mass) {\n return int(floor(mass / 3.0)) - 2;\n}\n\nint improved_fuel(int mass) {\n int f = fuel(mass);\n if (f > 0) {\n // Calculate the additional fuel required for this additional fuel\n return f + improved_fuel(f);\n }\n return 0;\n}\n\nint main() {\n ifstream file (\"2019/1.txt\");\n if (!file.is_open()) {\n cout << \"Failed to open file: \" << strerror(errno) << endl;\n return -1;\n }\n\n int answer1 = 0;\n int answer2 = 0;\n\n string line; \n while (getline(file, line, '\\n')) {\n boost::trim(line);\n\n if (line == \"\") {\n continue;\n }\n\n int mass = stoi(line);\n answer1 += fuel(mass);\n answer2 += improved_fuel(mass);\n }\n\n /*\n cout << improved_fuel(12) << endl;\n cout << improved_fuel(14) << endl;\n cout << improved_fuel(1969) << endl;\n cout << improved_fuel(100756) << endl;\n */\n\n cout << \"Answer 1.1: \" << answer1 << endl;\n cout << \"Answer 1.2: \" << answer2 << endl;\n\n file.close();\n}", "meta": {"hexsha": "a14fde4b25382db8f1c261ba5e3119fe3187b40f", "size": 1194, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2019/1.cpp", "max_stars_repo_name": "bramp/aoc", "max_stars_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "2019/1.cpp", "max_issues_repo_name": "bramp/aoc", "max_issues_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2019/1.cpp", "max_forks_repo_name": "bramp/aoc", "max_forks_repo_head_hexsha": "e6e2bf343786e58b3e0513dc88858e54c06f1cf6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.5862068966, "max_line_length": 74, "alphanum_fraction": 0.5469011725, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7772998611746912, "lm_q1q2_score": 0.6622227946973569}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n typedef Matrix Matrix5x3;\ntypedef Matrix Matrix5x5;\nMatrix5x3 m = Matrix5x3::Random();\ncout << \"Here is the matrix m:\" << endl << m << endl;\nEigen::FullPivLU lu(m);\ncout << \"Here is, up to permutations, its LU decomposition matrix:\"\n << endl << lu.matrixLU() << endl;\ncout << \"Here is the L part:\" << endl;\nMatrix5x5 l = Matrix5x5::Identity();\nl.block<5,3>(0,0).triangularView() = lu.matrixLU();\ncout << l << endl;\ncout << \"Here is the U part:\" << endl;\nMatrix5x3 u = lu.matrixLU().triangularView();\ncout << u << endl;\ncout << \"Let us now reconstruct the original matrix m:\" << endl;\ncout << lu.permutationP().inverse() * l * u * lu.permutationQ().inverse() << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "b49702a6e994fae91b598c3115ff074c121a3e0c", "size": 883, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_class_FullPivLU.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_class_FullPivLU.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_class_FullPivLU.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4482758621, "max_line_length": 82, "alphanum_fraction": 0.6602491506, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232808, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.6622203760941356}} {"text": "#ifndef helpers_hpp\n#define helpers_hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nconst double PI = 3.14159265358979;\n\nusing namespace std;\nusing namespace boost::math;\nusing namespace boost::random;\nusing namespace boost::math::tools;\n\ntypedef vector > Table;\ntypedef vector > > Table3D;\n\ntypedef boost::variate_generator > RandUnif;\ntypedef boost::variate_generator > RandNorm;\ntypedef boost::variate_generator > RandIntUnif;\n\nclass RandomSampleHelper\n{\npublic:\n RandomSampleHelper(long seedval) : rng(seedval) {}\n double sampleBeta(double alpha, double beta) \n {\n boost::gamma_distribution<> xgamma(alpha);\n boost::gamma_distribution<> ygamma(beta);\n boost::variate_generator > xgen(rng, xgamma);\n boost::variate_generator > ygen(rng, ygamma);\n double xsample = xgen();\n double ysample = ygen();\n return xsample/(xsample+ysample);\n } \n\n double sampleGaussian(double mu, double sigma)\n {\n boost::normal_distribution<> normdist(mu, sigma);\n boost::variate_generator > sgen(rng, normdist);\n return sgen();\n }\nprivate:\n boost::mt19937 rng;\n};\n\n/* courtesy of http://stackoverflow.com/questions/12774207/fastest-way-to-check-if-a-file-exist-using-standard-c-c11-c */\ninline bool exists_file(const std::string& name) {\n struct stat buffer; \n return (stat (name.c_str(), &buffer) == 0); \n}\n\nvoid loadFromCSV( const std::string& filename, std::vector< std::vector >& matrix, const int maxrows, const int maxcols)\n{\n if( !exists_file(filename) )\n {\n cerr << \"cannot find required file \" << filename << \" to load.\" << endl;\n exit(1);\n }\n std::ifstream file( filename.c_str() );\n std::vector row;\n std::string line;\n std::string cell;\n int rows = 0;\n while( file && rows < maxrows )\n {\n std::getline(file,line);\n std::stringstream lineStream(line);\n row.clear();\n int cols = 0;\n while( std::getline( lineStream, cell, ',' ) && cols < maxcols)\n {\n double number = strtod(cell.c_str(), NULL);\n row.push_back(number);\n ++cols;\n }\n\n if( !row.empty() )\n {\n matrix.push_back(row);\n }\n ++rows;\n }\n}\n\nvoid loadLineFromCSV( const std::string& filename, std::vector& arrs, const int maxentries)\n{\n std::ifstream file( filename.c_str() );\n std::string line;\n std::string cell;\n std::getline(file,line);\n std::stringstream lineStream(line);\n int idx = 0;\n while( std::getline( lineStream, cell, ',' ) && idx < maxentries)\n {\n double number = strtod(cell.c_str(), NULL);\n arrs[idx] = number;\n ++idx;\n }\n}\n\ndouble kl(double p1, double p2)\n{\n return p1*log(p1/p2)+(1-p1)*log((1-p1)/(1-p2));\n}\n\ndouble maxkl(double n, double muh, double delta)\n{\n double begin = muh + 1e-10;\n double end = 1.0-1e-10;\n double mid = (begin+end)/2.0;\n while (begin < end - 1e-10)\n {\n if (n*kl(muh, mid) > delta)\n {\n end = mid;\n }\n else\n {\n begin = mid;\n }\n mid = (begin + end)/2.0;\n }\n return mid;\n} \n\nconst int NUM_AGI_ITERS = 9;\n\ndouble computeAGI(const double gamma, const double a, const double nn)\n{\n double p = double(a)/double(nn);\n const double b = nn - a;\n const double r = ((double)a/(double)nn);\n \n for(int k = 0; k < NUM_AGI_ITERS; ++k)\n {\n if((p > 1 || p < r || p != p))\n {\n cerr << \"Found that p = \" << p << \". invalid value\" << endl;\n cerr << \"a = \" << a << endl;\n cerr << \"b = \" << b << endl;\n cerr << \"gamma = \" << gamma << endl;\n exit(1);\n }\n const double safe = p/(1-gamma);\n\n const double lhs = r*(1-ibeta(a+1,b,p));\n const double expmax = lhs + p*ibeta((double)a,b,p); \n const double risky = r+ gamma/(1-gamma)*expmax;\n\n const double orig = risky - safe;\n const double deriv = gamma/(1-gamma)*ibeta(a,b,p) - 1/(1-gamma);\n p -= orig/deriv;\n }\n return p;\n}\n\ndouble computeAGIGaussian(const double gamma, const double mu, const double sigma)\n{\n double lam = mu;\n boost::math::normal_distribution<> normdist(mu,sigma);\n for(int k = 0; k < NUM_AGI_ITERS; ++k)\n {\n double plam = cdf(normdist, lam);\n double flam = pdf(normdist, lam);\n double f = mu + gamma*sigma/(sqrt(2*PI))*exp(-pow(lam-mu,2)/(2*sigma*sigma)) + gamma*(lam-mu)*plam - lam; \n double fp = -gamma*(lam - mu)/(sqrt(2*PI)*sigma)*exp(-pow((lam-mu),2)/(2*sigma*sigma)) + gamma*plam + gamma*(lam-mu)*flam - 1;\n lam -= f/fp;\n }\n return lam;\n}\n\ndouble computeDummyProblemVal(double lambda, double gamma, double a, double b, int k, bool take_max = false)\n{\n double xbar = a/(a+b);\n double result = 0.0;\n if (k == 1)\n {\n result += xbar;\n result += gamma/(1.0-gamma) * (xbar * (1.0 - ibeta(a+1, b, lambda)) + lambda*ibeta(a,b,lambda));\n return take_max ? max(result,lambda/(1.0 - gamma)) : result;\n }\n result += xbar * computeDummyProblemVal(lambda, gamma, a+1, b, k-1, true);\n result += (1.0 - xbar) * computeDummyProblemVal(lambda, gamma, a, b+1, k-1, true);\n result = xbar + gamma * result;\n return take_max ? max(result,lambda/(1.0 - gamma)) : result;\n}\n\ndouble computeApproxGI(double gamma, double a, double b, int k, double prec = 0.0001)\n{\n if (k == 1)\n {\n return computeAGI(gamma, a, a + b);\n }\n double start = a/(a+b);\n for (double lambda = start; lambda < 1.0; lambda += prec) \n {\n double rightVal = computeDummyProblemVal(lambda, gamma, a, b, k, false);\n double leftVal = lambda / (1.0 - gamma);\n if (leftVal > rightVal)\n {\n return lambda - prec/2.0;\n }\n }\n return 1.0;\n}\n\nvoid computeIndices(const int a0, const int b0, const int n, const double step, const double beta, vector >& indices)\n{\n vector > tmpindices(n-1, vector(n-1, 0));\n for(int a = 1; a < n; ++a)\n {\n tmpindices[a-1][n-a-1] = computeAGI(beta, a0 + a - 1, n + a0 + b0 - 2);\n }\n for(double p=(step/2.0); p <= 1.0; p+=step)\n {\n const double safe = p/(1-beta);\n for(int nn = n-1; nn >= 2; --nn)\n {\n for(int a = 1; a <= nn-1; ++a)\n {\n const double r = (double(a - 1 + a0)/double(nn + a0 + b0 - 2));\n const double risky = r*(1 + beta*tmpindices[a][nn-a-1]) + (1-r)*beta*tmpindices[a-1][nn-a];\n if(indices[a-1][nn-a-1] == 0 && safe > risky)\n {\n indices[a-1][nn-a-1] = p - step/2.0;\n }\n tmpindices[a-1][nn-a-1] = max(safe,risky);\n }\n }\n }\n}\n\n#endif\n\n", "meta": {"hexsha": "adb1f00b310afbe3d420b46a564f4307ade675d3", "size": 6732, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cpp/helpers.hpp", "max_stars_repo_name": "gutin/FastGittins", "max_stars_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-10-10T12:51:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-29T16:14:34.000Z", "max_issues_repo_path": "cpp/helpers.hpp", "max_issues_repo_name": "gutin/FastGittins", "max_issues_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/helpers.hpp", "max_forks_repo_name": "gutin/FastGittins", "max_forks_repo_head_hexsha": "65e64ac802d8769d30f10d49489f93a6527a8111", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-09-28T02:40:39.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-28T02:40:39.000Z", "avg_line_length": 28.1673640167, "max_line_length": 132, "alphanum_fraction": 0.6140819964, "num_tokens": 2089, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6621639788130895}} {"text": "#include \n#include \n#include \n\n#ifndef _Included_simianquant_strata_jnibridge_AtomicFunction\n#define _Included_simianquant_strata_jnibridge_AtomicFunction\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nJNIEXPORT jdouble JNICALL Java_simianquant_strata_jnibridge_AtomicFunction_normalCdf\n (JNIEnv * env, jobject obj, jdouble arg){\n \treturn (0.5 * erfc(-arg * M_SQRT1_2));\n }\n\nJNIEXPORT jdouble JNICALL Java_simianquant_strata_jnibridge_AtomicFunction_normalQuantile\n (JNIEnv * env, jobject obj, jdouble arg){\n \treturn -M_SQRT2 * boost::math::erfc_inv(2 * arg);\n }\n\n#ifdef __cplusplus\n}\n#endif\n#endif", "meta": {"hexsha": "eebc6843841b17bef73b10314f49ba45fef88bdb", "size": 649, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jnibridgeimpl/src/native/library.cpp", "max_stars_repo_name": "SimianQuant/stratabench", "max_stars_repo_head_hexsha": "3852358625c322d5c2d1f4fe8907e4e8e041339f", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "jnibridgeimpl/src/native/library.cpp", "max_issues_repo_name": "SimianQuant/stratabench", "max_issues_repo_head_hexsha": "3852358625c322d5c2d1f4fe8907e4e8e041339f", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jnibridgeimpl/src/native/library.cpp", "max_forks_repo_name": "SimianQuant/stratabench", "max_forks_repo_head_hexsha": "3852358625c322d5c2d1f4fe8907e4e8e041339f", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0416666667, "max_line_length": 89, "alphanum_fraction": 0.7966101695, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9381240177362488, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6621138917781533}} {"text": "/**\n * @date Fri Feb 10 20:02:07 2012 +0200\n * @author Laurent El Shafey \n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include \n#include \n\n#include \n\n/**\n * Computes log(a+b)=log(exp(log(a))+exp(log(b))) from log(a) and log(b),\n * while dealing with numerical issues\n */\ndouble bob::math::Log::logAdd(double log_a, double log_b)\n{\n if(log_a < log_b)\n {\n double tmp = log_a;\n log_a = log_b;\n log_b = tmp;\n }\n\n double minusdif = log_b - log_a;\n //#ifdef DEBUG\n if(std::isnan(minusdif))\n {\n boost::format m(\"logadd: minusdif (%f) log_b (%f) or log_a (%f) is nan\");\n m % minusdif % log_b % log_a;\n throw std::runtime_error(m.str());\n }\n //#endif\n if(minusdif < MINUS_LOG_THRESHOLD) return log_a;\n else return log_a + log1p(exp(minusdif));\n}\n\n/**\n * Computes log(a-b)=log(exp(log(a))-exp(log(b))) from log(a) and log(b),\n * while dealing with numerical issues\n */\ndouble bob::math::Log::logSub(double log_a, double log_b)\n{\n double minusdif;\n\n if(log_a < log_b)\n {\n boost::format m(\"logsub: log_a (%f) should be greater than log_b(%f)\");\n m % log_a % log_b;\n throw std::runtime_error(m.str());\n }\n\n minusdif = log_b - log_a;\n //#ifdef DEBUG\n if(std::isnan(minusdif))\n {\n boost::format m(\"logsub: minusdif (%f) log_b (%f) or log_a (%f) is nan\");\n m % minusdif % log_b % log_a;\n throw std::runtime_error(m.str());\n }\n //#endif\n if(log_a == log_b) return bob::math::Log::LogZero;\n else if(minusdif < MINUS_LOG_THRESHOLD) return log_a;\n else return log_a + log1p(-exp(minusdif));\n}\n", "meta": {"hexsha": "dd27f8c3f59003ef6bcf5221a51c4066ab8bea4e", "size": 1635, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/math/cpp/log.cpp", "max_stars_repo_name": "bioidiap/bob.math", "max_stars_repo_head_hexsha": "e0efcd51a609755e55b723e97dca2b5eac6b7976", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "bob/math/cpp/log.cpp", "max_issues_repo_name": "bioidiap/bob.math", "max_issues_repo_head_hexsha": "e0efcd51a609755e55b723e97dca2b5eac6b7976", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2015-12-02T01:42:32.000Z", "max_issues_repo_issues_event_max_datetime": "2016-05-26T16:37:07.000Z", "max_forks_repo_path": "bob/math/cpp/log.cpp", "max_forks_repo_name": "bioidiap/bob.math", "max_forks_repo_head_hexsha": "e0efcd51a609755e55b723e97dca2b5eac6b7976", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4029850746, "max_line_length": 77, "alphanum_fraction": 0.6354740061, "num_tokens": 509, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424489603726, "lm_q2_score": 0.7826624789529375, "lm_q1q2_score": 0.6620874141548441}} {"text": "/*\n * File: dht.hpp\n * Created Date: 2019-12-29\n * Author: Lei Pan\n * Contact: \n *\n * Last Modified: Sunday December 29th 2019 12:00:12 pm\n *\n * MIT License\n *\n * Copyright (c) 2019 Lei Pan\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the 'Software'), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n * -----\n * HISTORY:\n * Date \t By\tComments\n * ----------\t---\n * ----------------------------------------------------------\n */\n\n#ifndef DHT_DHT_H_\n#define DHT_DHT_H_\n\n#include \n\nclass DiscreteHankelTransform {\n\npublic:\n DiscreteHankelTransform(int order, int nr);\n ~DiscreteHankelTransform();\n\n Eigen::VectorXd r_sampling(double rmax);\n Eigen::VectorXd k_sampling(double rmax); // k is rho in the paper\n\n Eigen::VectorXd forward(const Eigen::Ref &fr);\n Eigen::VectorXd backward(const Eigen::Ref &fk);\n\n Eigen::VectorXd shift(const Eigen::Ref &raw, int m);\n\n Eigen::MatrixXd tmatrix() const;\n\nprotected:\n int order_;\n double rmax_;\n int nr_;\n\n Eigen::VectorXd roots_;\n Eigen::MatrixXd tmatrix_;\n};\n\n#endif", "meta": {"hexsha": "ff6897df4b0433aaf8bab1ab8fca503c4ce4cd37", "size": 2088, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dht.hpp", "max_stars_repo_name": "pan3rock/discrete-hankel-transform", "max_stars_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/dht.hpp", "max_issues_repo_name": "pan3rock/discrete-hankel-transform", "max_issues_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dht.hpp", "max_forks_repo_name": "pan3rock/discrete-hankel-transform", "max_forks_repo_head_hexsha": "708d3d32e1c4170ed68322e53e26267f93e0ab9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T09:56:44.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T09:56:44.000Z", "avg_line_length": 31.1641791045, "max_line_length": 80, "alphanum_fraction": 0.7059386973, "num_tokens": 487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680977182186, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6620627243758415}} {"text": "#include \"RBF.h\"\n\n#include \n\nnamespace Chaf\n{\n\tRBFInterpolation::RBFInterpolation(const std::vector& points, double d) :\n\t\tm_d(d)\n\t{\n\t\tEigen::VectorXd y(points.size());\n\t\tEigen::MatrixXd A(points.size(), points.size());\n\t\tm_ps.resize(points.size());\n\t\tm_params.resize(points.size());\n\n\t\tm_constant = 0.f;\n\n\t\tfor (uint32_t i = 0; i < points.size(); i++)\n\t\t{\n\t\t\tm_ps[i] = points[i].x;\n\t\t\ty(i) = points[i].y;\n\t\t\tm_constant += points[i].y;\n\t\t}\n\n\t\tm_constant /= static_cast(points.size());\n\t\ty = y.array() - m_constant;\n\n\t\tfor (uint32_t i = 0; i < points.size(); i++)\n\t\t{\n\t\t\tfor (uint32_t j = 0; j < points.size(); j++)\n\t\t\t{\n\t\t\t\tA(i, j) = 1.f / ((points[i].x - m_ps[j]) * (points[i].x - m_ps[j]) + m_d);\n\t\t\t}\n\t\t}\n\n\t\tEigen::VectorXd x = A.colPivHouseholderQr().solve(y);\n\n\t\tfor (uint32_t i = 0; i < points.size(); i++)\n\t\t{\n\t\t\tm_params[i] = x(i);\n\t\t}\n\t}\n\n\tdouble RBFInterpolation::evaluate(double x)\n\t{\n\t\tdouble result = m_constant;\n\n\t\tfor (uint32_t i = 0; i < m_params.size(); i++)\n\t\t{\n\t\t\tresult += m_params[i] / ((x - m_ps[i]) * (x - m_ps[i]) + m_d);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tstd::vector RBFInterpolation::evaluate(const std::vector& x)\n\t{\n\t\tstd::vector result(x.size());\n\n\t\tfor (uint32_t i = 0; i < result.size(); i++)\n\t\t{\n\t\t\tresult[i] = evaluate(x[i]);\n\t\t}\n\t\treturn result;\n\t}\n}", "meta": {"hexsha": "0a0f78ec1f04396f0a8476bcfad407bc42307a70", "size": 1336, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Homework/Homeworks/Homework1/RBF.cpp", "max_stars_repo_name": "Chaphlagical/CAGD", "max_stars_repo_head_hexsha": "55b79364a13fe062f6f7b8d061fb7bed236aa61d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-10-01T14:05:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T14:05:50.000Z", "max_issues_repo_path": "Homework/Homeworks/Homework1/RBF.cpp", "max_issues_repo_name": "Chaphlagical/CAGD", "max_issues_repo_head_hexsha": "55b79364a13fe062f6f7b8d061fb7bed236aa61d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Homework/Homeworks/Homework1/RBF.cpp", "max_forks_repo_name": "Chaphlagical/CAGD", "max_forks_repo_head_hexsha": "55b79364a13fe062f6f7b8d061fb7bed236aa61d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-01T14:47:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-01T14:47:48.000Z", "avg_line_length": 20.5538461538, "max_line_length": 88, "alphanum_fraction": 0.5808383234, "num_tokens": 455, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451834, "lm_q2_score": 0.7634837635542925, "lm_q1q2_score": 0.6619677355224839}} {"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n// QuickBook Example\n\n// Copyright (c) 2020 Digvijay Janartha, Hamirpur, India.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n//[touches_two_geometries\n//` Checks if two geometries have at least one touching point (tangent - non overlapping)\n\n#include \n\n#include \n#include \n#include \n\nnamespace bg = boost::geometry; /*< Convenient namespace alias >*/\n\nint main()\n{\n // Checks if the two geometries touch\n bg::model::polygon > poly1;\n bg::read_wkt(\"POLYGON((0 0,0 4,4 4,4 0,0 0))\", poly1);\n bg::model::polygon > poly2;\n bg::read_wkt(\"POLYGON((0 0,0 -4,-4 -4,-4 0,0 0))\", poly2);\n bool check_touches = bg::touches(poly1, poly2);\n if (check_touches) {\n std::cout << \"Touches: Yes\" << std::endl;\n } else {\n std::cout << \"Touches: No\" << std::endl;\n }\n\n bg::model::polygon > poly3;\n bg::read_wkt(\"POLYGON((1 1,0 -4,-4 -4,-4 0,1 1))\", poly3);\n check_touches = bg::touches(poly1, poly3);\n if (check_touches) {\n std::cout << \"Touches: Yes\" << std::endl;\n } else {\n std::cout << \"Touches: No\" << std::endl;\n }\n\n return 0;\n}\n\n//]\n\n\n//[touches_two_geometries_output\n/*`\nOutput:\n[pre\nTouches: Yes\n\n[$img/algorithms/touches_two_geometries.png]\n\nTouches: No\n]\n*/\n//]\n", "meta": {"hexsha": "1edba94ccbf345212290ded1fd3cb969b99607be", "size": 1634, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "doc/src/examples/algorithms/touches_two_geometries.cpp", "max_stars_repo_name": "jkerkela/geometry", "max_stars_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "doc/src/examples/algorithms/touches_two_geometries.cpp", "max_issues_repo_name": "jkerkela/geometry", "max_issues_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "doc/src/examples/algorithms/touches_two_geometries.cpp", "max_forks_repo_name": "jkerkela/geometry", "max_forks_repo_head_hexsha": "4034ac88b214da0eab8943172eff0f1200b0a6cc", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 26.3548387097, "max_line_length": 89, "alphanum_fraction": 0.6493268054, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8006919925839875, "lm_q2_score": 0.8267117940706734, "lm_q1q2_score": 0.6619415136871306}} {"text": "#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n/* vertex of lie algebra */\nclass VertexSE3LieAlgebra : public g2o::BaseVertex<6, Sophus::SE3>\n{\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n \n bool read(std::istream& is) {}\n bool write(std::ostream& os) const {}\n \n virtual void setToOriginImpl()\n {\n _estimate = Sophus::SE3();\n }\n \n /* update */\n virtual void oplusImpl(const double* update)\n {\n Sophus::SE3 up(\n Sophus::SO3(update[3], update[4], update[5]),\n Eigen::Vector3d(update[0], update[1], update[2])\n );\n \n setEstimate(up * _estimate); // or _estimate = up * _estimate;\n }\n \n};\n\nclass VertexPoint3D : public g2o::BaseVertex<3, Eigen::Vector3d>\n{\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n \n virtual bool read(std::istream& is) {}\n virtual bool write(std::ostream& os) const {}\n \n virtual void setToOriginImpl()\n {\n _estimate.fill(0);\n }\n\n virtual void oplusImpl(const double* update)\n {\n Eigen::Map v(update);\n _estimate += v;\n }\n};\n\nclass EdgeProject3D22D : public g2o::BaseBinaryEdge<2, Eigen::Vector2d, VertexPoint3D, VertexSE3LieAlgebra>\n{\npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n \n EdgeProject3D22D()\n {\n _cam = nullptr;\n resizeParameters(1);\n installParameter(_cam, 0);\n }\n \n virtual bool read(std::istream& is) {}\n virtual bool write(std::ostream& os) const {}\n \n void computeError()\n {\n Eigen::Vector3d point3d = static_cast(_vertices[0])->estimate();\n Sophus::SE3 pose = static_cast(_vertices[1])->estimate();\n \n const g2o::CameraParameters * cam = static_cast(parameter(0));\n \n _error = _measurement - cam->cam_map(pose * point3d);\n }\n \n void linearizeOplus()\n {\n Eigen::Vector3d point3d = static_cast(_vertices[0])->estimate();\n Sophus::SE3 pose = static_cast(_vertices[1])->estimate();\n \n Eigen::Vector3d xyz_trans(pose * point3d);\n \n double x = xyz_trans[0];\n double y = xyz_trans[1];\n double z = xyz_trans[2];\n double z_2 = z * z;\n \n const g2o::CameraParameters * cam = static_cast(parameter(0));\n \n Eigen::Matrix tmp;\n tmp(0, 0) = -cam->focal_length / z;\n tmp(0, 1) = 0;\n tmp(0, 2) = cam->focal_length * x / z_2;\n tmp(1, 0) = 0;\n tmp(1, 1) = -cam->focal_length / z;\n tmp(1, 2) = cam->focal_length * y / z_2;\n \n _jacobianOplusXi = tmp * pose.rotation_matrix();\n \n _jacobianOplusXj(0, 0) = cam->focal_length * x * y / z_2;\n _jacobianOplusXj(0, 1) = -cam->focal_length * (1 + x*x/z_2);\n _jacobianOplusXj(0, 2) = cam->focal_length * y / z;\n _jacobianOplusXj(0, 3) = -cam->focal_length / z;\n _jacobianOplusXj(0, 4) = 0;\n _jacobianOplusXj(0, 5) = cam->focal_length * x / z_2;\n \n _jacobianOplusXj(1, 0) = cam->focal_length * (1 + y*y/z_2);\n _jacobianOplusXj(1, 1) = -cam->focal_length * x * y / z_2;\n _jacobianOplusXj(1, 2) = -cam->focal_length * x / z;\n _jacobianOplusXj(1, 3) = 0;\n _jacobianOplusXj(1, 4) = -cam->focal_length / z;\n _jacobianOplusXj(1, 5) = cam->focal_length * y / z_2;\n }\n \n g2o::CameraParameters* _cam;\n};\n\n/* find the two photo feature matches points */\nvoid find_feature_matches(const cv::Mat&, const cv::Mat&, std::vector&, std::vector&, std::vector&);\n\n/* Converts the pixel coordinate system to the normalized imaging plane coordinate system */\ncv::Point2d pixel2cam(const cv::Point2d&, const cv::Mat&);\n\nvoid bundleAdjustment( const std::vector, const std::vector, const cv::Mat&, cv::Mat&, cv::Mat&);\n\nint main(int argc, char** argv)\n{\n if (argc != 5) {\n std::cout << \"usage: pose_estimation_3d2d img1 img2 depth1 depth2.\" << std::endl;\n return 1;\n }\n \n //-- 1st, read photo\n cv::Mat img_1 = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);\n cv::Mat img_2 = cv::imread(argv[2], CV_LOAD_IMAGE_COLOR);\n \n if (img_1.empty() || img_2.empty()) {\n std::cout << \"img1 or img2 is no find.\" << std::endl;\n return 1;\n }\n \n //-- 2nd, find the two photo feature matches points\n std::vector keypoints_1, keypoints_2;\n std::vector matches;\n find_feature_matches(img_1, img_2, keypoints_1, keypoints_2, matches);\n std::cout << \"feature matches points total is \" << matches.size() << std::endl;\n \n //-- 3rd, create 3 dimensions point correspondences\n cv::Mat d1 = cv::imread(argv[3], CV_LOAD_IMAGE_UNCHANGED); // 深度图为16位无符号数,单通道图像\n cv::Mat K = (cv::Mat_(3, 3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1);\n std::vector pts_3d;\n std::vector pts_2d;\n for (cv::DMatch m:matches) {\n ushort d = d1.ptr(int (keypoints_1[m.queryIdx].pt.y))[int (keypoints_1[m.queryIdx].pt.x)];\n \n if (d == 0) { /* bad depth */\n continue;\n }\n float dd = d/5000.0;\n cv::Point2d p1 = pixel2cam(keypoints_1[m.queryIdx].pt, K);\n pts_3d.push_back(cv::Point3d (p1.x*dd, p1.y*dd, dd));\n pts_2d.push_back(keypoints_2[m.trainIdx].pt);\n }\n std::cout << \"3d-2d pairs: \" << pts_3d.size() << std::endl;\n \n //-- 4th, use PnP or bundle adjustment compute camera pose.\n cv::Mat r, t;\n cv::solvePnP(pts_3d, pts_2d, K, cv::Mat(), r, t, false); // 调用OpenCV 的 PnP 求解,可选择EPNP,DLS等方法\n cv::Mat R;\n cv::Rodrigues(r, R); // r为旋转向量形式,用Rodrigues公式转换为矩阵\n \n std::cout << \"R = \" << std::endl << R << std::endl;\n std::cout << \"t = \" << std::endl << t << std::endl;\n \n std::cout << \"calling bundle adjustment\" << std::endl;\n \n bundleAdjustment(pts_3d, pts_2d, K, R, t);\n \n return 0;\n}\n\n/**\n * find the two photo feature matches points\n */\nvoid find_feature_matches(const cv::Mat& img_1, const cv::Mat& img_2, std::vector& keypoints_1, std::vector& keypoints_2, std::vector& matches)\n{\n //-- Initialize\n cv::Mat descriptors_1, descriptors_2;\n cv::Ptr detector = cv::ORB::create();\n cv::Ptr descriptor = cv::ORB::create();\n cv::Ptr matcher = cv::DescriptorMatcher::create(\"BruteForce-Hamming\");\n \n //-- 1st: detect Oriented FAST KeyPoint \n detector->detect(img_1, keypoints_1);\n detector->detect(img_2, keypoints_2);\n \n //-- 2nd: Calculates BRIEF descriptors with KeyPoint's coordinate\n descriptor->compute(img_1, keypoints_1, descriptors_1);\n descriptor->compute(img_2, keypoints_2, descriptors_2);\n \n //-- 3rd: 对两幅图像中的BRIEF描述子进行匹配,使用 Hamming 距离\n std::vector match;\n matcher->match(descriptors_1, descriptors_2, match);\n \n //-- 4th: 匹配点对筛选\n double min_dist = 10000, max_dist = 0;\n \n /* 找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离 */\n for (int i = 0; i < descriptors_1.rows; i++) {\n double dist = match[i].distance;\n if (dist < min_dist) {\n min_dist = dist;\n }\n if (dist > max_dist) {\n max_dist = dist;\n }\n }\n \n printf(\"-- Max distance : %f \\r\\n\", max_dist);\n printf(\"-- Min distance : %f \\r\\n\", min_dist);\n \n // 当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.但有时候最小距离会非常小,设置一个经验值30作为下限.\n for (int i = 0; i < descriptors_2.rows; i ++) {\n if (match[i].distance <= std::max(2*min_dist, 30.0)) {\n matches.push_back(match[i]);\n }\n }\n}\n\n/**\n * Converts the pixel coordinate system to the normalized imaging plane coordinate system\n */\ncv::Point2d pixel2cam(const cv::Point2d& p, const cv::Mat& K)\n{\n return cv::Point2d\n (\n (p.x - K.at(0, 2)) / K.at(0, 0),\n (p.y - K.at(1, 2)) / K.at(1, 1)\n );\n}\n\nvoid bundleAdjustment(\n const std::vector points_3d, \n const std::vector points_2d,\n const cv::Mat& K,\n cv::Mat& R,\n cv::Mat& t )\n{\n // Initialize g2o\n typedef g2o::BlockSolver> Block; // pose 维度为 6, landmark 维度为 3\n Block::LinearSolverType* linear_solver = new g2o::LinearSolverCSparse(); // 线性方程求解器\n Block* solver_ptr = new Block((std::unique_ptr)(linear_solver));\n g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg((std::unique_ptr)solver_ptr);\n g2o::SparseOptimizer optimizer;\n optimizer.setAlgorithm(solver);\n \n // vertex\n VertexSE3LieAlgebra * pose = new VertexSE3LieAlgebra(); // camera pose\n Eigen::Matrix3d R_mat;\n R_mat << \\\n R.at(0, 0), R.at(0, 1), R.at(0, 2), \\\n R.at(1, 0), R.at(1, 1), R.at(1, 2), \\\n R.at(2, 0), R.at(2, 1), R.at(2, 2);\n pose->setId(0);\n pose->setEstimate(\n Sophus::SE3(\n R_mat, \n Eigen::Vector3d(t.at(0, 0), t.at(1, 0), t.at(2, 0))\n )\n );\n optimizer.addVertex(pose);\n \n int index = 1;\n for (const cv::Point3f p:points_3d) {\n VertexPoint3D* point = new VertexPoint3D();\n point->setId(index ++);\n point->setEstimate(Eigen::Vector3d(p.x, p.y, p.z));\n point->setMarginalized(true); // g2o 中必须设置 marg \n optimizer.addVertex(point);\n }\n \n // parameter : camera intrinsics\n g2o::CameraParameters* camera = new g2o::CameraParameters(\n K.at(0, 0), Eigen::Vector2d(K.at(0, 2), K.at(1, 2)), 0\n );\n camera->setId(0);\n optimizer.addParameter(camera);\n \n // edges\n index = 1;\n for (const cv::Point2f p:points_2d) {\n EdgeProject3D22D* edge = new EdgeProject3D22D();\n edge->setId(index);\n edge->setVertex(0, dynamic_cast(optimizer.vertex(index)));\n edge->setVertex(1, pose);\n edge->setMeasurement(Eigen::Vector2d(p.x, p.y));\n edge->setParameterId(0, 0);\n edge->setInformation(Eigen::Matrix2d::Identity());\n optimizer.addEdge(edge);\n index++;\n }\n \n std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();\n optimizer.setVerbose(true);\n optimizer.initializeOptimization();\n optimizer.optimize(10);\n std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();\n std::chrono::duration time_used = std::chrono::duration_cast>(t2 - t1);\n std::cout << \"optimization costs time: \" << time_used.count() << \" seconds.\" << std::endl;\n \n std::cout << std::endl << \"after optimization: \" << std::endl;\n std::cout << \"T = \" << std::endl << pose->estimate().matrix() << std::endl;\n}\n\n\n\n\n\n\n\n\n", "meta": {"hexsha": "0312bd513b7012cdb155c905f7b50f9810db3478", "size": 11637, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pose_estimation_3d2d/src/pose_estimation_3d2d_lie_algebra.cpp", "max_stars_repo_name": "LSXiang/slam_learning_journey", "max_stars_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-03-22T00:25:10.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-01T05:23:27.000Z", "max_issues_repo_path": "pose_estimation_3d2d/src/pose_estimation_3d2d_lie_algebra.cpp", "max_issues_repo_name": "LSXiang/slam_learning_journey", "max_issues_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pose_estimation_3d2d/src/pose_estimation_3d2d_lie_algebra.cpp", "max_forks_repo_name": "LSXiang/slam_learning_journey", "max_forks_repo_head_hexsha": "1173bbab4e50a29a61d3affb23ceca32bcc0bf97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1260997067, "max_line_length": 183, "alphanum_fraction": 0.6092635559, "num_tokens": 3725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813453, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6617434213491064}} {"text": "#pragma once\n\n#include \n#include \n#include \n#include \n#include \"types/Point.hpp\"\n\nstruct RRCoord {\n /**\n * RRCoord\n * If any param is set to NAN this implies that the value is either\n * not known or irrelevant to the particular context.\n *\n * @param heading heading from robot to object\n * @param distance distance from robot to object\n * @param orientation angle between robot front and object front\n */\n RRCoord(float distance, float heading = NAN, float orientation = NAN)\n : vec(distance, heading, orientation)\n {\n var.setZero();\n }\n\n Point toCartesian() const {\n return Point(distance()*cosf(heading()), distance()*sinf(heading()));\n }\n\n RRCoord() {\n vec.setZero();\n var.setZero();\n }\n \n RRCoord(const RRCoord &other) {\n this->vec = other.vec;\n this->var = other.var;\n }\n\n RRCoord& operator=(const RRCoord &other) {\n for (unsigned i = 0; i < 3; i++) {\n this->vec(i, 0) = other.vec(i, 0);\n }\n for (unsigned i = 0; i < 9; i++) {\n this->var[i] = other.var[i];\n }\n \n return *this;\n }\n \n Eigen::Vector3f vec;\n Eigen::Matrix var;\n\n /* Distance to object */\n const float distance() const {\n return vec[0];\n }\n\n float &distance() {\n return vec[0];\n }\n\n /* Heading to object */\n const float heading() const {\n return vec[1];\n }\n\n float &heading() {\n return vec[1];\n }\n\n /* Angle between robot's front and object's front */\n const float orientation() const {\n return vec[2];\n }\n\n float &orientation() {\n return vec[2];\n }\n\n bool operator== (const RRCoord &other) const {\n return vec == other.vec;\n }\n\n template\n void serialize(Archive &ar, const unsigned int file_version);\n};\n\ninline std::ostream& operator<<(std::ostream& os, const RRCoord& coord) {\n for (unsigned i = 0; i < 3; i++) {\n float a = coord.vec[i];\n os.write((char*) &a, sizeof(float));\n }\n \n for (unsigned i = 0; i < 9; i++) {\n float a = coord.var[i];\n os.write((char*) &a, sizeof(float));\n }\n return os;\n}\n\ninline std::istream& operator>>(std::istream& is, RRCoord& coord) {\n for (unsigned i = 0; i < 3; i++) {\n float a;\n is.read((char*) &a, sizeof(float));\n coord.vec[i] = a;\n }\n \n for (unsigned i = 0; i < 9; i++) {\n float a;\n is.read((char*) &a, sizeof(float));\n coord.var[i] = a;\n }\n\n return is;\n}\n\ntypedef enum {\n DIST,\n HEADING,\n ORIENTATION,\n} RRCoordEnum;\n\n#include \"types/RRCoord.tcc\"\n\n", "meta": {"hexsha": "ce1b82cecc0e37156fd9a08a2ac2559f850c3dbb", "size": 2651, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/Core/External/unsw/unsw/types/RRCoord.hpp", "max_stars_repo_name": "pedrohsreis/boulos", "max_stars_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-09-18T18:05:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-23T17:47:07.000Z", "max_issues_repo_path": "src/Core/External/unsw/unsw/types/RRCoord.hpp", "max_issues_repo_name": "pedrohsreis/boulos", "max_issues_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-06-08T18:48:32.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-19T21:41:16.000Z", "max_forks_repo_path": "src/Core/External/unsw/unsw/types/RRCoord.hpp", "max_forks_repo_name": "pedrohsreis/boulos", "max_forks_repo_head_hexsha": "a5b68a32cad8cc1fb9f6fbf47fc487ef99d3166e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2018-09-11T17:19:16.000Z", "max_forks_repo_forks_event_max_datetime": "2019-07-30T16:43:56.000Z", "avg_line_length": 21.208, "max_line_length": 75, "alphanum_fraction": 0.5654470011, "num_tokens": 728, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593495, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6617434092434981}} {"text": "#include \n#include \n#include \n\nusing namespace codegenvar;\n\nint main()\n{\n const Symbol x(\"x\"), y(\"y\"), dx(\"dx\"), dy(\"dy\"), a(\"a\");\n \n const Vec2 p(x, y);\n const Vec3 P = p.homogeneous();\n const Vec2 diff(dx, dy);\n\n std::cout << \"p = \" << p.transpose() << std::endl;\n std::cout << \"translate by \" << diff.transpose() << std::endl;\n std::cout << \"rotate by \" << a << std::endl << std::endl;\n std::cout << \"P = \" << P.transpose() << std::endl << std::endl;\n\n Mat23 t;\n t << Symbol(1), Symbol(0), diff(0),\n Symbol(0), Symbol(1), diff(1);\n\n std::cout << \"p + diff = \" << (p+diff).transpose() << std::endl << std::endl;\n std::cout << \"t = \" << std::endl << t << std::endl << std::endl;\n std::cout << \"t*P = \" << (t*P).transpose() << std::endl << std::endl;\n\n Mat3 T;\n T << t(0, 0), t(0, 1), t(0, 2),\n t(1, 0), t(1, 1), t(1, 2),\n Symbol(0), Symbol(0), Symbol(1);\n\n std::cout << \"T = \" << std::endl << T << std::endl << std::endl;\n std::cout << \"T*P = \" << (T*P).transpose() << std::endl << std::endl;\n\n Mat2 r;\n r << cos(a), -sin(a),\n sin(a), cos(a);\n\n std::cout << \"r = \" << std::endl << r << std::endl << std::endl;\n std::cout << \"r*p = \" << (r*p).transpose() << std::endl << std::endl;\n\n Mat3 R;\n R << r(0, 0) , r(0, 1), Symbol(0),\n r(1, 0) , r(1, 1), Symbol(0),\n Symbol(0), Symbol(0), Symbol(1);\n\n std::cout << \"R = \" << std::endl << R << std::endl << std::endl;\n std::cout << \"R*P = \" << (R*P).transpose() << std::endl << std::endl;\n\n std::cout << \"T*R = \" << std::endl << T*R << std::endl << std::endl;\n std::cout << \"T*R*P = \" << (T*R*P).transpose() << std::endl << std::endl;\n\n std::cout << \"R*T = \" << std::endl << R*T << std::endl << std::endl;\n std::cout << \"R*T*P = \" << (R*T*P).transpose() << std::endl << std::endl;\n\n return 0;\n}", "meta": {"hexsha": "cac2563e46f2138efc6fe54934946099ef721ffd", "size": 1924, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/eigen.cpp", "max_stars_repo_name": "bjornpiltz/CppCodeGenVar", "max_stars_repo_head_hexsha": "4f4707c88202695300e55db8909af29107bdc157", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-01-23T09:41:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-03T05:44:14.000Z", "max_issues_repo_path": "examples/eigen.cpp", "max_issues_repo_name": "bjornpiltz/CppCodeGenVar", "max_issues_repo_head_hexsha": "4f4707c88202695300e55db8909af29107bdc157", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2018-01-18T13:16:20.000Z", "max_issues_repo_issues_event_max_datetime": "2018-02-25T21:42:34.000Z", "max_forks_repo_path": "examples/eigen.cpp", "max_forks_repo_name": "bjornpiltz/CppCodeGenVar", "max_forks_repo_head_hexsha": "4f4707c88202695300e55db8909af29107bdc157", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1724137931, "max_line_length": 81, "alphanum_fraction": 0.4641372141, "num_tokens": 690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896824119662, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6616743025183384}} {"text": "\n#include \n\nNTL_CLIENT\n\nint main()\n{\n mat_ZZ B;\n long s;\n\n#if 1\n cin >> B;\n#else\n long i, j;\n long n;\n cerr << \"n: \";\n cin >> n;\n\n long m;\n cerr << \"m: \";\n cin >> m;\n\n long k;\n cerr << \"k: \";\n cin >> k;\n\n B.SetDims(n, m);\n for (i = 1; i <= n; i++)\n for (j = 1; j <= m; j++) {\n RandomLen(B(i,j), k);\n if (RandomBnd(2)) negate(B(i,j), B(i,j));\n }\n\n\n#endif\n\n mat_ZZ U, B0, B1, B2;\n\n B0 = B;\n\n double t;\n ZZ d;\n\n B = B0;\n cerr << \"LLL_FP...\";\n t = GetTime();\n s = LLL_FP(B, U, 0.99);\n cerr << (GetTime()-t) << \"\\n\";\n mul(B1, U, B0);\n if (B1 != B) Error(\"bad LLLTest (1)\");\n LLL(d, B, 90, 100);\n if (B1 != B) Error(\"bad LLLTest (2)\");\n\n B = B0;\n cerr << \"LLL_QP...\";\n t = GetTime();\n s = LLL_QP(B, U, 0.99);\n cerr << (GetTime()-t) << \"\\n\";\n mul(B1, U, B0);\n if (B1 != B) Error(\"bad LLLTest (1)\");\n LLL(d, B, 90, 100);\n if (B1 != B) Error(\"bad LLLTest (2)\");\n\n\n B = B0;\n cerr << \"LLL_XD...\";\n t = GetTime();\n s = LLL_XD(B, U, 0.99);\n cerr << (GetTime()-t) << \"\\n\";\n mul(B1, U, B0);\n if (B1 != B) Error(\"bad LLLTest (1)\");\n LLL(d, B, 90, 100);\n if (B1 != B) Error(\"bad LLLTest (2)\");\n\n B = B0;\n cerr << \"LLL_RR...\";\n t = GetTime();\n s = LLL_RR(B, U, 0.99);\n cerr << (GetTime()-t) << \"\\n\";\n mul(B1, U, B0);\n if (B1 != B) Error(\"bad LLLTest (1)\");\n LLL(d, B, 90, 100);\n if (B1 != B) Error(\"bad LLLTest (2)\");\n\n B = B0;\n cerr << \"G_LLL_FP...\";\n t = GetTime();\n s = G_LLL_FP(B, U, 0.99);\n cerr << (GetTime()-t) << \"\\n\";\n mul(B1, U, B0);\n if (B1 != B) Error(\"bad LLLTest (1)\");\n LLL(d, B, 90, 100);\n if (B1 != B) Error(\"bad LLLTest (2)\");\n\n B = B0;\n cerr << \"G_LLL_QP...\";\n t = GetTime();\n s = G_LLL_QP(B, U, 0.99);\n cerr << (GetTime()-t) << \"\\n\";\n mul(B1, U, B0);\n if (B1 != B) Error(\"bad LLLTest (1)\");\n LLL(d, B, 90, 100);\n if (B1 != B) Error(\"bad LLLTest (2)\");\n\n B = B0;\n cerr << \"G_LLL_XD...\";\n t = GetTime();\n s = G_LLL_XD(B, U, 0.99);\n cerr << (GetTime()-t) << \"\\n\";\n mul(B1, U, B0);\n if (B1 != B) Error(\"bad LLLTest (1)\");\n LLL(d, B, 90, 100);\n if (B1 != B) Error(\"bad LLLTest (2)\");\n\n B = B0;\n cerr << \"G_LLL_RR...\";\n t = GetTime();\n s = G_LLL_RR(B, U, 0.99);\n cerr << (GetTime()-t) << \"\\n\";\n mul(B1, U, B0);\n if (B1 != B) Error(\"bad LLLTest (1)\");\n LLL(d, B, 90, 100);\n if (B1 != B) Error(\"bad LLLTest (2)\");\n\n\n B = B0;\n cerr << \"LLL...\";\n t = GetTime();\n s = LLL(d, B, U);\n cerr << (GetTime()-t) << \"\\n\";\n mul(B1, U, B0);\n if (B1 != B) Error(\"bad LLLTest (1)\");\n\n cout << \"rank = \" << s << \"\\n\";\n cout << \"det = \" << d << \"\\n\";\n cout << \"B = \" << B << \"\\n\";\n cout << \"U = \" << U << \"\\n\";\n}\n\n", "meta": {"hexsha": "66bf1efd3a0bed608491a19bc7320a774df752dd", "size": 2732, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RUNETag/WinNTL/tests/LLLTest.cpp", "max_stars_repo_name": "vshesh/RUNEtag", "max_stars_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RUNETag/WinNTL/tests/LLLTest.cpp", "max_issues_repo_name": "vshesh/RUNEtag", "max_issues_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RUNETag/WinNTL/tests/LLLTest.cpp", "max_forks_repo_name": "vshesh/RUNEtag", "max_forks_repo_head_hexsha": "800e93fb7c0560ea5a6261ffc60c02638a8cc8c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5142857143, "max_line_length": 50, "alphanum_fraction": 0.4245973646, "num_tokens": 1169, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896758909757, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6616742978323912}} {"text": "// Copyright (c) 2016 Copyright Holder All Rights Reserved.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace boost;\n\ntypedef adjacency_list>\n Graph;\n\ntypedef graph_traits::vertex_descriptor vertex_descriptor;\ntypedef graph_traits::edge_descriptor edge_descriptor;\n\nint main(int argc, char const *argv[]) {\n std::ifstream fin(\"../priv/edges.txt\");\n int num_of_nodes, num_of_edges;\n\n fin >> num_of_nodes >> num_of_edges;\n std::cout << \"Nodes \" << num_of_nodes << \" Edges \" << num_of_edges\n << std::endl;\n Graph g(num_of_nodes);\n // std::vector weights(num_of_nodes);\n\n for (auto i = 0; i < num_of_edges; ++i) {\n int u, v;\n int64_t weight;\n fin >> u >> v >> weight;\n // std::cout << u << \" -> \" << v < p(num_vertices(g));\n // prim_minimum_spanning_tree(g, &p[0]);\n\n std::vector spanning_tree;\n kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));\n\n for (auto it = spanning_tree.begin(); it != spanning_tree.end(); ++it) {\n std::cout << source(*it, g) << \" -- \" << target(*it, g) << \";\" << std::endl;\n // std::cout << get(edge_weight, g, *it) << std::endl;\n }\n\n int64_t mst_weights = std::accumulate(\n spanning_tree.begin(), spanning_tree.end(), 0,\n [g](int64_t acc, auto b) { return acc + get(edge_weight, g, b); });\n\n std::cout << \"MST weights: \" << mst_weights << std::endl;\n\n /*for (std::size_t i = 0; i != p.size(); ++i)\n if (p[i] != i)\n std::cout << \"parent[\" << i << \"] = \" << p[i] << std::endl;\n else\n std::cout << \"parent[\" << i << \"] = no parent\" << std::endl;\n*/\n // write_graphviz(std::cout, g);\n /*\n graph_traits::edge_iterator ei, eend;\n for (boost::tie(ei, eend) = edges(g); ei != eend; ++ei) {\n std::cout << \"E: \" << *ei << \" \" << std::endl;\n }*/\n\n /*graph_traits::vertex_iterator vi, vend;\n for (boost::tie(vi, vend) = vertices(g); vi != vend; ++vi) {\n std::cout << \"V: \" << *vi << std::endl;\n }*/\n\n // std::cout << num_edges(g) << std::endl;\n return 0;\n}\n", "meta": {"hexsha": "91d72838430c10b6be099009ce809d2e4e409bef", "size": 2590, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp-mmgraph/graph.cpp", "max_stars_repo_name": "andelf/codeplay", "max_stars_repo_head_hexsha": "de148cc48f5c1d436978b14876ee1c871e692e11", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-10-10T04:01:10.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-10T08:31:17.000Z", "max_issues_repo_path": "cpp-mmgraph/graph.cpp", "max_issues_repo_name": "andelf/codeplay", "max_issues_repo_head_hexsha": "de148cc48f5c1d436978b14876ee1c871e692e11", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp-mmgraph/graph.cpp", "max_forks_repo_name": "andelf/codeplay", "max_forks_repo_head_hexsha": "de148cc48f5c1d436978b14876ee1c871e692e11", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.2048192771, "max_line_length": 80, "alphanum_fraction": 0.6154440154, "num_tokens": 755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339676722393, "lm_q2_score": 0.7879312006227324, "lm_q1q2_score": 0.6616525933516783}} {"text": "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace discreture\n{\n\ntemplate \nvoid UNUSED(T&& /*unused*/)\n{}\n\n//////////////////////////////////////////\n/// \\brief This is what operator% should be but isn't (!).\n///\n/// C++ modulo operator%is dumb for negative integers: (-7)%3 returns -1,\n/// instead of 2. This fixes it.\n/// \\return an integer in [0,b)\n//////////////////////////////////////////\ntemplate \ninline IntType modulo(IntType a, IntType b)\n{\n IntType r = a%b;\n if (r < 0)\n r += b;\n return r;\n}\n\n//////////////////////////////////////////\n/// \\brief This is what operator %= should be but isn't (!).\n///\n/// C++ modulo operator %= is dumb for negative integers: (-7)%3 returns -1,\n/// instead of 2. This fixes it.\n//////////////////////////////////////////\ntemplate \ninline void reduce_modulo(IntType& a, IntType b)\n{\n a %= b;\n if (a < 0)\n a += b;\n}\n\ntemplate \ninline T pow(T a, std::uint64_t n)\n{\n T r = 1;\n\n while (n > 0)\n {\n auto division = std::div(n, 2);\n if (division.rem == 1) // if odd\n r *= a;\n\n n = division.quot;\n a *= a;\n }\n\n return r;\n}\n\n// Deprecated in c++17. Here for use in c++14.\ntemplate \nT gcd(T a, T b)\n{\n while (b != 0)\n {\n T r = a%b;\n a = b;\n b = r;\n }\n return a;\n}\n\ntemplate \nT reduce_fraction(Container Numerator, Container Denominator)\n{\n for (auto& b : Denominator)\n {\n for (auto& a : Numerator)\n {\n auto d = gcd(a, b);\n a /= d;\n b /= d;\n if (b == 1)\n break;\n }\n }\n\n T result = 1;\n for (auto a : Numerator)\n result *= a;\n return result;\n}\n\n} // namespace discreture\n", "meta": {"hexsha": "e5acbb73db566a7d6b74a317fd51bb6f43983d9a", "size": 1986, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/Discreture/Misc.hpp", "max_stars_repo_name": "remz1337/discreture", "max_stars_repo_head_hexsha": "f15227a3e5c4faf04621bc9b2adad937aee06898", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 53.0, "max_stars_repo_stars_event_min_datetime": "2016-08-25T07:40:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-26T09:27:31.000Z", "max_issues_repo_path": "include/Discreture/Misc.hpp", "max_issues_repo_name": "remz1337/discreture", "max_issues_repo_head_hexsha": "f15227a3e5c4faf04621bc9b2adad937aee06898", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27.0, "max_issues_repo_issues_event_min_datetime": "2020-06-06T18:32:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-02T22:16:49.000Z", "max_forks_repo_path": "sources/include/external/Discreture/Misc.hpp", "max_forks_repo_name": "greati/logicantsy", "max_forks_repo_head_hexsha": "11d1f33f57df6fc77c3c18b506fc98f9b9a88794", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12.0, "max_forks_repo_forks_event_min_datetime": "2018-03-12T05:42:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-13T23:18:32.000Z", "avg_line_length": 19.6633663366, "max_line_length": 76, "alphanum_fraction": 0.5005035247, "num_tokens": 522, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388167733099, "lm_q2_score": 0.7981867705385763, "lm_q1q2_score": 0.661647997134357}} {"text": "//=======================================================================\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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace boost;\r\n\r\ntemplate < typename Graph, typename ParentMap > \r\nstruct edge_writer\r\n{\r\n edge_writer(const Graph & g, const ParentMap & p)\r\n : m_g(g), m_parent(p)\r\n {\r\n }\r\n\r\n template < typename Edge >\r\n void operator() (std::ostream & out, const Edge & e) const\r\n {\r\n out << \"[label=\\\"\" << get(edge_weight, m_g, e) << \"\\\"\";\r\n typename graph_traits < Graph >::vertex_descriptor\r\n u = source(e, m_g), v = target(e, m_g);\r\n if (m_parent[v] == u)\r\n out << \", color=\\\"black\\\"\";\r\n else\r\n out << \", color=\\\"grey\\\"\";\r\n out << \"]\";\r\n }\r\n const Graph & m_g;\r\n ParentMap m_parent;\r\n};\r\ntemplate < typename Graph, typename Parent >\r\nedge_writer < Graph, Parent >\r\nmake_edge_writer(const Graph & g, const Parent & p)\r\n{\r\n return edge_writer < Graph, Parent > (g, p);\r\n}\r\n\r\nstruct EdgeProperties {\r\n int weight;\r\n};\r\n\r\nint\r\nmain()\r\n{\r\n enum { u, v, x, y, z, N };\r\n char name[] = { 'u', 'v', 'x', 'y', 'z' };\r\n typedef std::pair < int, int >E;\r\n const int n_edges = 10;\r\n E edge_array[] = { E(u, y), E(u, x), E(u, v), E(v, u),\r\n E(x, y), E(x, v), E(y, v), E(y, z), E(z, u), E(z,x) };\r\n int weight[n_edges] = { -4, 8, 5, -2, 9, -3, 7, 2, 6, 7 };\r\n\r\n typedef adjacency_list < vecS, vecS, directedS,\r\n no_property, EdgeProperties> Graph;\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n // VC++ can't handle the iterator constructor\r\n Graph g(N);\r\n for (std::size_t j = 0; j < n_edges; ++j)\r\n add_edge(edge_array[j].first, edge_array[j].second, g);\r\n#else\r\n Graph g(edge_array, edge_array + n_edges, N);\r\n#endif\r\n graph_traits < Graph >::edge_iterator ei, ei_end;\r\n property_map::type \r\n weight_pmap = get(&EdgeProperties::weight, g);\r\n int i = 0;\r\n for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei, ++i)\r\n weight_pmap[*ei] = weight[i];\r\n\r\n std::vector distance(N, (std::numeric_limits < short >::max)());\r\n std::vector parent(N);\r\n for (i = 0; i < N; ++i)\r\n parent[i] = i;\r\n distance[z] = 0;\r\n\r\n#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300\r\n bool r = bellman_ford_shortest_paths\r\n (g, int(N), weight_pmap, &parent[0], &distance[0], \r\n closed_plus(), std::less(), default_bellman_visitor());\r\n#else\r\n bool r = bellman_ford_shortest_paths\r\n (g, int (N), weight_map(weight_pmap).distance_map(&distance[0]).\r\n predecessor_map(&parent[0]));\r\n#endif\r\n\r\n if (r)\r\n for (i = 0; i < N; ++i)\r\n std::cout << name[i] << \": \" << std::setw(3) << distance[i]\r\n << \" \" << name[parent[i]] << std::endl;\r\n else\r\n std::cout << \"negative cycle\" << std::endl;\r\n\r\n std::ofstream dot_file(\"figs/bellman-eg.dot\");\r\n dot_file << \"digraph D {\\n\"\r\n << \" rankdir=LR\\n\"\r\n << \" size=\\\"5,3\\\"\\n\"\r\n << \" ratio=\\\"fill\\\"\\n\"\r\n << \" edge[style=\\\"bold\\\"]\\n\" << \" node[shape=\\\"circle\\\"]\\n\";\r\n\r\n {\r\n for (boost::tie(ei, ei_end) = edges(g); ei != ei_end; ++ei) {\r\n graph_traits < Graph >::edge_descriptor e = *ei;\r\n graph_traits < Graph >::vertex_descriptor\r\n u = source(e, g), v = target(e, g);\r\n // VC++ doesn't like the 3-argument get function, so here\r\n // we workaround by using 2-nested get()'s.\r\n dot_file << name[u] << \" -> \" << name[v]\r\n << \"[label=\\\"\" << get(get(&EdgeProperties::weight, g), e) << \"\\\"\";\r\n if (parent[v] == u)\r\n dot_file << \", color=\\\"black\\\"\";\r\n else\r\n dot_file << \", color=\\\"grey\\\"\";\r\n dot_file << \"]\";\r\n }\r\n }\r\n dot_file << \"}\";\r\n return EXIT_SUCCESS;\r\n}\r\n", "meta": {"hexsha": "1b61e2533cd77c4e5ec2e7bb5dc5bb7782c446d3", "size": 4120, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/bellman-example.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/graph/example/bellman-example.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/graph/example/bellman-example.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 31.9379844961, "max_line_length": 75, "alphanum_fraction": 0.5487864078, "num_tokens": 1215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391602943619, "lm_q2_score": 0.7662936324115011, "lm_q1q2_score": 0.6616114876132543}} {"text": "#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#define DEBUG 0\n\n#define MAX_W 100\n#define MAX_L 100\n\ntypedef tuple quad;\ntemplate<> struct hash {\n size_t operator()(const quad& q) const noexcept {\n size_t seed = 0;\n boost::hash_combine(seed, get<0>(q));\n boost::hash_combine(seed, get<1>(q));\n boost::hash_combine(seed, get<2>(q));\n boost::hash_combine(seed, get<3>(q));\n return seed;\n }\n};\n\nclass AvoidRoads {\nprivate:\n long dp[MAX_W+1][MAX_L+1] = { 0 };\n unordered_mapbad_m;\n\npublic:\n long numWays(int w, int l, vector bad) {\n preparebad(bad);\n\n dp[0][0] = 1;\n\n // Initialize bottom row\n for (int i = 1; i < w + 1; ++i) {\n quad p = make_tuple(i - 1, 0, i, 0);\n if (bad_m.find(p) == bad_m.end()) {\n dp[i][0] = dp[i-1][0];\n }\n int j = 0;\n // cout << \"i: \" << i << \", j: \" << j << \", dp[i][j]: \" << dp[i][j] << endl;\n }\n // Initialize left column\n for (int j = 1; j < l + 1; ++j) {\n quad p = make_tuple(0, j - 1, 0, j);\n if (bad_m.find(p) == bad_m.end()) {\n dp[0][j] = dp[0][j-1];\n }\n int i = 0;\n // cout << \"i: \" << i << \", j: \" << j << \", dp[i][j]: \" << dp[i][j] << endl;\n }\n for (int i = 1; i < w + 1; ++i) {\n for (int j = 1; j < l + 1; ++j) {\n if (bad_m.find(make_tuple(i - 1, j, i, j)) == bad_m.end()) {\n dp[i][j] += dp[i-1][j];\n }\n if (bad_m.find(make_tuple(i, j - 1, i, j)) == bad_m.end()) {\n dp[i][j] += dp[i][j-1];\n }\n // cout << \"i: \" << i << \", j: \" << j << \", dp[i][j]: \" << dp[i][j] << endl;\n }\n }\n\n // Only for debug\n // printf(\"\\n\");\n // for (int j = l; j >= 0; --j) {\n // for (int i = 0; i < w + 1; ++i) {\n // printf(\"%5ld\", dp[i][j]);\n // }\n // printf(\"\\n\");\n // }\n return dp[w][l];\n }\n\n void preparebad(vector bad) {\n for(auto &s : bad) {\n // NOTE: read int from bad string\n int l = s.size();\n vector space;\n for (int i = 0; i < l; ++i) {\n if (s[i] == ' ') {\n space.push_back(i);\n }\n }\n\n vector pos_list;\n pos_list.push_back(stoi(s));\n for(auto &p : space) {\n pos_list.push_back(stoi(s.substr(p + 1)));\n }\n\n quad p;\n if (pos_list[0] < pos_list[2] || pos_list[1] < pos_list[3]) {\n p = make_tuple(pos_list[0], pos_list[1], pos_list[2], pos_list[3]);\n } else {\n p = make_tuple(pos_list[2], pos_list[3], pos_list[0], pos_list[1]);\n }\n bad_m[p] = 1;\n }\n }\n};\n\nint main(int argc, char** argv) {\n AvoidRoads a0;\n vector bad0 = {\"0 0 0 1\", \"6 6 5 6\"};\n std::cout << \"a0: Expected 252, Got \" << a0.numWays(6, 6, bad0) << \"\" << std::endl;\n\n AvoidRoads a1;\n vector bad1 = {};\n std::cout << \"a1: Expected 2, Got \" << a1.numWays(1, 1, bad1) << \"\" << std::endl;\n\n AvoidRoads a2;\n vector bad2 = {};\n std::cout << \"a1: Expected 6406484391866534976, Got \" << a2.numWays(35, 31, bad2) << \"\" << std::endl;\n\n AvoidRoads a3;\n vector bad3 = {\"0 0 1 0\", \"1 2 2 2\", \"1 1 2 1\"};\n std::cout << \"a1: Expected 0, Got \" << a3.numWays(2, 2, bad3) << \"\" << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "cf7e60f16598bb5cd6fbc14efa47418d726b21f0", "size": 3310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AvoidRoads.cpp", "max_stars_repo_name": "south37/topcoder", "max_stars_repo_head_hexsha": "9edee3f723189ccdbecb1cbc5c186a99f392e6dd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AvoidRoads.cpp", "max_issues_repo_name": "south37/topcoder", "max_issues_repo_head_hexsha": "9edee3f723189ccdbecb1cbc5c186a99f392e6dd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AvoidRoads.cpp", "max_forks_repo_name": "south37/topcoder", "max_forks_repo_head_hexsha": "9edee3f723189ccdbecb1cbc5c186a99f392e6dd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.48, "max_line_length": 103, "alphanum_fraction": 0.4827794562, "num_tokens": 1198, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.853912760387131, "lm_q2_score": 0.7745833841649232, "lm_q1q2_score": 0.6614266357222751}} {"text": "#include \"Normals.h\"\n\n#include \n\nvoid perVertexNormals(const Eigen::MatrixXd &vertices,\n\tconst Eigen::MatrixXi &triangles,\n\tEigen::MatrixXd &normals,\n\tWeightType::Type weightType)\n{\n\tnormals.setZero(vertices.rows(), vertices.cols());\n\tstd::vector weightSum(vertices.cols(), 0.0);\n\n\tfor (int tri = 0; tri < triangles.cols(); tri++)\n\t{\n\t\tstd::array vIdcs = { triangles(0, tri), triangles(1, tri), triangles(2, tri) };\n\t\tstd::array v;\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tif (vIdcs[i] < 0 || vIdcs[i] >= vertices.cols()) {\n\t\t\t\tthrow std::logic_error(\"err\");\n\t\t\t}\n\t\t\tv[i] = vertices.col(vIdcs[i]);\n\t\t}\n\t\tEigen::Vector3d normal = (v[1] - v[0]).cross(v[2] - v[0]);\n\t\tdouble twiceArea = normal.norm();\n\t\tnormal /= twiceArea;\n\t\tfor (int i = 0; i < 3; i++)\n\t\t{\n\t\t\tEigen::Vector3d e1 = v[(i + 1) % 3] - v[i];\n\t\t\tEigen::Vector3d e2 = v[(i + 2) % 3] - v[i];\n\t\t\tdouble angleBetween = std::acos(std::min(1.0, std::max(-1.0, e1.normalized().dot(e2.normalized()))));\n\t\t\tdouble weight;\n\t\t\tswitch (weightType)\n\t\t\t{\n\t\t\tcase WeightType::CONSTANT:\n\t\t\t\tweight = 1.0;\n\t\t\t\tbreak;\n\t\t\tcase WeightType::AREA:\n\t\t\t\tweight = twiceArea;\n\t\t\t\tbreak;\n\t\t\tcase WeightType::ANGLE:\n\t\t\t\tweight = angleBetween;\n\t\t\t\tbreak;\n\t\t\tcase WeightType::ANGLE_AREA:\n\t\t\t\tweight = twiceArea * angleBetween;\n\t\t\t\tbreak;\n\t\t\tdefault: assert(false);\n\t\t\t}\n\t\t\t//double weight = 1.0;\n\t\t\tEigen::Vector3d wn = weight*normal;\n\t\t\tnormals.col(vIdcs[i]) += wn;\n\t\t\tweightSum[vIdcs[i]] += weight;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < vertices.cols(); i++)\n\t{\n\t\tif (weightSum[i] != 0.0)\n\t\t{\n\t\t\tnormals.col(i) /= weightSum[i];\n\t\t}\n\t}\n}\n", "meta": {"hexsha": "acab7fc239634c0531bcb4e4b807483d586c83ae", "size": 1606, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Normals.cpp", "max_stars_repo_name": "JonasZehn/YAPS", "max_stars_repo_head_hexsha": "df1fea7d43e0a7e658086d3be42cc4675e7a547a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Normals.cpp", "max_issues_repo_name": "JonasZehn/YAPS", "max_issues_repo_head_hexsha": "df1fea7d43e0a7e658086d3be42cc4675e7a547a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Normals.cpp", "max_forks_repo_name": "JonasZehn/YAPS", "max_forks_repo_head_hexsha": "df1fea7d43e0a7e658086d3be42cc4675e7a547a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.4920634921, "max_line_length": 104, "alphanum_fraction": 0.599003736, "num_tokens": 555, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6614266286469825}} {"text": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT license.\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"hand_eigen_d.h\"\n#include \"../../shared/defs.h\"\n#include \"../../shared/utils.h\"\n#include \"../../shared/hand_eigen_model.h\"\n\nusing std::vector;\nusing std::unordered_map;\nusing std::string;\nusing Eigen::Map;\nusing Eigen::Vector3d;\nusing Eigen::Matrix3Xd;\nusing Eigen::Matrix4d;\nusing Eigen::aligned_allocator;\nusing Eigen::AngleAxisd;\nusing Eigen::Matrix3d;\nusing Eigen::MatrixXd;\n\nvoid angle_axis_to_rotation_matrix_d(\n const Vector3d& angle_axis,\n Matrix3d* R,\n vector* pdR)\n{\n auto& dR = *pdR;\n double sqnorm = angle_axis.squaredNorm();\n double norm = sqrt(sqnorm);\n if (norm < .0001)\n {\n R->setIdentity();\n for (int i = 0; i < 3; i++)\n dR[i].setZero();\n return;\n }\n double inv_norm = 1. / norm;\n double inv_sqnorm = 1. / sqnorm;\n Vector3d d_norm = angle_axis * inv_norm;\n\n double x = angle_axis(0) * inv_norm;\n double y = angle_axis(1) * inv_norm;\n double z = angle_axis(2) * inv_norm;\n Vector3d dx, dy, dz;\n for (int i = 0; i < 3; i++)\n {\n dx(i) = -angle_axis(0) * d_norm(i) * inv_sqnorm;\n dy(i) = -angle_axis(1) * d_norm(i) * inv_sqnorm;\n dz(i) = -angle_axis(2) * d_norm(i) * inv_sqnorm;\n }\n dx(0) += norm * inv_sqnorm;\n dy(1) += norm * inv_sqnorm;\n dz(2) += norm * inv_sqnorm;\n\n double s = sin(norm);\n double c = cos(norm);\n Vector3d dc, ds;\n ds = c * d_norm;\n dc = -s * d_norm;\n\n *R << x * x + (1 - x * x) * c, x* y* (1 - c) - z * s, x* z* (1 - c) + y * s,\n x* y* (1 - c) + z * s, y* y + (1 - y * y) * c, y* z* (1 - c) - x * s,\n x* z* (1 - c) - y * s, z* y* (1 - c) + x * s, z* z + (1 - z * z) * c;\n\n for (int i = 0; i < 3; i++)\n {\n dR[i] << 2 * x * dx(i) - 2 * x * dx(i) * c + (1 - x * x) * dc(i),\n dx(i) * y * (1 - c) + x * dy(i) * (1 - c) - x * y * dc(i) - dz(i) * s - z * ds(i),\n dx(i) * z * (1 - c) + x * dz(i) * (1 - c) - x * z * dc(i) + dy(i) * s + y * ds(i),\n dx(i)* y* (1 - c) + x * dy(i) * (1 - c) - x * y * dc(i) + dz(i) * s + z * ds(i),\n 2 * y * dy(i) - 2 * y * dy(i) * c + (1 - y * y) * dc(i),\n dy(i) * z * (1 - c) + y * dz(i) * (1 - c) - y * z * dc(i) - dx(i) * s - x * ds(i),\n dx(i)* z* (1 - c) + x * dz(i) * (1 - c) - x * z * dc(i) - dy(i) * s - y * ds(i),\n dz(i)* y* (1 - c) + z * dy(i) * (1 - c) - z * y * dc(i) + dx(i) * s + x * ds(i),\n 2 * z * dz(i) - 2 * z * dz(i) * c + (1 - z * z) * dc(i);\n }\n}\n\nvoid apply_global_transform_d(\n const vector& corresp,\n const Matrix3Xd& pose_params,\n Matrix3Xd* ppositions,\n double* pJ,\n Matrix3d* pR)\n{\n auto& R = *pR;\n auto& positions = *ppositions;\n vector dR(3);\n const Vector3d& global_rotation = pose_params.col(0);\n angle_axis_to_rotation_matrix_d(global_rotation, &R, &dR);\n R.noalias() = (R.array().rowwise() * pose_params.col(1).transpose().array()).matrix();\n for (int i = 0; i < 3; i++)\n dR[i].noalias() = (dR[i].array().rowwise() * pose_params.col(1).transpose().array()).matrix();\n\n // global rotation\n size_t npts = corresp.size();\n for (int i_param = 0; i_param < 3; i_param++)\n {\n Map J_glob_rot(&pJ[i_param * 3 * npts], 3, npts);\n for (size_t i_pt = 0; i_pt < npts; i_pt++)\n {\n J_glob_rot.col(i_pt).noalias() = -dR[i_param] * positions.col(corresp[i_pt]);\n }\n }\n\n // global translation\n Map J_glob_translation(&pJ[3 * 3 * npts], 3 * npts, 3);\n for (size_t i = 0; i < npts; i++)\n {\n J_glob_translation.middleRows(i * 3, 3).setIdentity();\n }\n J_glob_translation *= -1.;\n\n positions = (R * positions).colwise() + pose_params.col(2);\n}\n\nvoid apply_global_transform_d(\n const double* const us,\n const vector& triangles,\n const vector& corresp,\n const Matrix3Xd& pose_params,\n Matrix3Xd* ppositions,\n double* pJ,\n Matrix3d* pR)\n{\n auto& R = *pR;\n auto& positions = *ppositions;\n vector dR(3);\n const Vector3d& global_rotation = pose_params.col(0);\n angle_axis_to_rotation_matrix_d(global_rotation, &R, &dR);\n R.noalias() = (R.array().rowwise() * pose_params.col(1).transpose().array()).matrix();\n for (int i = 0; i < 3; i++)\n dR[i].noalias() = (dR[i].array().rowwise() * pose_params.col(1).transpose().array()).matrix();\n\n // global rotation\n size_t npts = corresp.size();\n for (int i_param = 0; i_param < 3; i_param++)\n {\n Map J_glob_rot(&pJ[i_param * 3 * npts], 3, npts);\n for (size_t i_pt = 0; i_pt < npts; i_pt++)\n {\n const auto& verts = triangles[corresp[i_pt]].verts;\n const double* const u = &us[2 * i_pt];\n\n Vector3d tmp = u[0] * positions.col(verts[0]) + u[1] * positions.col(verts[1])\n + (1. - u[0] - u[1]) * positions.col(verts[2]);\n\n J_glob_rot.col(i_pt).noalias() = -dR[i_param] * tmp;\n }\n }\n\n // global translation\n Map J_glob_translation(&pJ[3 * 3 * npts], 3 * npts, 3);\n for (size_t i = 0; i < npts; i++)\n {\n J_glob_translation.middleRows(i * 3, 3).setIdentity();\n }\n J_glob_translation *= -1.;\n\n positions = (R * positions).colwise() + pose_params.col(2);\n}\n\nvoid relatives_to_absolutes_d(\n const avector& relatives,\n const avector& relatives_d,\n const vector& parents,\n avector* pabsolutes,\n vector>* pabsolutes_d)\n{\n auto& absolutes = *pabsolutes;\n auto& absolutes_d = *pabsolutes_d;\n absolutes.resize(parents.size());\n absolutes_d.resize(parents.size());\n int rel_d_tail = 0;\n for (size_t i = 0; i < parents.size(); i++)\n {\n if (parents[i] == -1)\n absolutes[i].noalias() = relatives[i];\n else\n absolutes[i].noalias() = absolutes[parents[i]] * relatives[i];\n\n int n_finger_bone = (i - 1) % 4;\n if (i > 0 && i < parents.size() - 1 && n_finger_bone > 0)\n {\n absolutes_d[i].resize(n_finger_bone + 1);\n int curr_tail = 0;\n\n for (const auto& absolute_d_parent : absolutes_d[parents[i]])\n absolutes_d[i][curr_tail++].noalias() = absolute_d_parent * relatives[i];\n\n absolutes_d[i][curr_tail++].noalias() = absolutes[parents[i]] * relatives_d[rel_d_tail++];\n if (n_finger_bone == 1)\n absolutes_d[i][curr_tail++].noalias() = absolutes[parents[i]] * relatives_d[rel_d_tail++];\n }\n }\n}\n\nvoid euler_angles_to_rotation_matrix(\n const Vector3d& xzy,\n Matrix3d* pR,\n Matrix3d* pdR0,\n Matrix3d* pdR1)\n{\n double tx = xzy(0), ty = xzy(2), tz = xzy(1);\n Matrix3d Rx = Matrix3d::Identity(),\n Ry = Matrix3d::Identity(),\n Rz = Matrix3d::Identity();\n Rx(1, 1) = cos(tx);\n Rx(2, 1) = sin(tx);\n Rx(1, 2) = -Rx(2, 1);\n Rx(2, 2) = Rx(1, 1);\n\n Ry(0, 0) = cos(ty);\n Ry(0, 2) = sin(ty);\n Ry(2, 0) = -Ry(0, 2);\n Ry(2, 2) = Ry(0, 0);\n\n Rz(0, 0) = cos(tz);\n Rz(1, 0) = sin(tz);\n Rz(0, 1) = -Rz(1, 0);\n Rz(1, 1) = Rz(0, 0);\n\n Matrix3d RzRy = Rz * Ry;\n if (pdR0)\n {\n Matrix3d dRx = Matrix3d::Zero();\n dRx(1, 1) = -Rx(2, 1);\n dRx(2, 1) = Rx(1, 1);\n dRx(1, 2) = -dRx(2, 1);\n dRx(2, 2) = dRx(1, 1);\n pdR0->noalias() = RzRy * dRx;\n }\n if (pdR1)\n {\n Matrix3d dRz = Matrix3d::Zero();\n dRz(0, 0) = -Rz(1, 0);\n dRz(1, 0) = Rz(0, 0);\n dRz(0, 1) = -dRz(1, 0);\n dRz(1, 1) = dRz(0, 0);\n pdR1->noalias() = dRz * Ry * Rx;\n }\n\n pR->noalias() = RzRy * Rx;\n}\n\nvoid get_posed_relatives_d(\n const HandModelEigen& model,\n const Matrix3Xd& pose_params,\n avector* prelatives,\n avector* prelatives_d)\n{\n auto& relatives = *prelatives;\n auto& relatives_d = *prelatives_d;\n relatives.resize(model.base_relatives.size());\n relatives_d.resize(4 * 5); // 4 parameters in every finger\n\n int offset = 3;\n int tail = 0;\n for (size_t i = 0; i < model.bone_names.size(); i++)\n {\n Matrix4d tr = Matrix4d::Identity();\n\n Matrix3d R;\n int n_finger_bone = (i - 1) % 4;\n if (i == 0 || i == model.bone_names.size() - 1 || n_finger_bone == 0)\n {\n euler_angles_to_rotation_matrix(pose_params.col(i + offset), &R);\n }\n else\n {\n Matrix4d dtr0 = Matrix4d::Zero();\n Matrix3d dR0;\n if (n_finger_bone == 1)\n {\n Matrix4d dtr1 = Matrix4d::Zero();\n Matrix3d dR1;\n euler_angles_to_rotation_matrix(pose_params.col(i + offset), &R, &dR0, &dR1);\n dtr1.block(0, 0, 3, 3) = dR1;\n relatives_d[tail + 1].noalias() = model.base_relatives[i] * dtr1;\n }\n else\n euler_angles_to_rotation_matrix(pose_params.col(i + offset), &R, &dR0);\n dtr0.block(0, 0, 3, 3) = dR0;\n relatives_d[tail++].noalias() = model.base_relatives[i] * dtr0;\n if (n_finger_bone == 1)\n tail++;\n }\n tr.block(0, 0, 3, 3) = R;\n\n relatives[i].noalias() = model.base_relatives[i] * tr;\n }\n}\n\nvoid get_skinned_vertex_positions_d_common(\n const HandModelEigen& model,\n const Matrix3Xd& pose_params,\n const vector& corresp,\n Matrix3Xd* positions,\n vector* positions_d,\n double* pJ,\n bool apply_global)\n{\n avector relatives, absolutes, transforms;\n avector relatives_d;\n vector> absolutes_d, transforms_d;\n get_posed_relatives_d(model, pose_params, &relatives, &relatives_d);\n relatives_to_absolutes_d(relatives, relatives_d, model.parents, &absolutes, &absolutes_d);\n\n // Get bone transforms.\n transforms.resize(absolutes.size());\n transforms_d.resize(absolutes.size());\n for (size_t i = 0; i < absolutes.size(); i++)\n {\n transforms[i].noalias() = absolutes[i] * model.inverse_base_absolutes[i];\n transforms_d[i].resize(absolutes_d[i].size());\n for (size_t j = 0; j < absolutes_d[i].size(); j++)\n transforms_d[i][j].noalias() = absolutes_d[i][j] * model.inverse_base_absolutes[i];\n }\n\n // Transform vertices by necessary transforms. + apply skinning\n *positions = Matrix3Xd::Zero(3, model.base_positions.cols());\n positions_d->resize(4 * 5, Matrix3Xd::Zero(3, model.base_positions.cols()));\n for (int i = 0; i < (int)transforms.size(); i++)\n {\n *positions +=\n ((transforms[i] * model.base_positions.colwise().homogeneous()).array()\n .rowwise() * model.weights.row(i)).matrix()\n .topRows(3);\n\n int i_finger = (i - 1) / 4;\n for (int j = 0; j < (int)transforms_d[i].size(); j++)\n {\n int i_param = j + 4 * i_finger;\n (*positions_d)[i_param] +=\n ((transforms_d[i][j] * model.base_positions.colwise().homogeneous()).array()\n .rowwise() * model.weights.row(i)).matrix()\n .topRows(3);\n }\n }\n\n if (model.is_mirrored)\n positions->row(0) = -positions->row(0);\n}\n\nvoid get_skinned_vertex_positions_d(\n const HandModelEigen& model,\n const Matrix3Xd& pose_params,\n const vector& corresp,\n Matrix3Xd* positions,\n double* pJ,\n bool apply_global)\n{\n vector positions_d;\n get_skinned_vertex_positions_d_common(model, pose_params, corresp, positions,\n &positions_d, pJ, apply_global);\n\n Matrix3d Rglob = Matrix3d::Identity();\n if (apply_global)\n apply_global_transform_d(corresp, pose_params, positions, pJ, &Rglob);\n\n // finger parameters\n size_t ncorresp = corresp.size();\n for (int i = 0; i < 4 * 5; i++)\n {\n Map curr_J(&pJ[(6 + i) * 3 * ncorresp], 3, ncorresp);// 6 is offset (global params)\n for (int j = 0; j < curr_J.cols(); j++)\n {\n curr_J.col(j).noalias() = -Rglob * positions_d[i].col(corresp[j]);\n }\n }\n}\n\nvoid get_skinned_vertex_positions_d(\n const double* const us,\n const HandModelEigen& model,\n const Matrix3Xd& pose_params,\n const vector& corresp,\n Matrix3Xd* positions,\n double* pJ,\n bool apply_global)\n{\n vector positions_d;\n\n get_skinned_vertex_positions_d_common(model, pose_params, corresp, positions,\n &positions_d, pJ, apply_global);\n\n Matrix3d Rglob = Matrix3d::Identity();\n if (apply_global)\n apply_global_transform_d(us, model.triangles, corresp, pose_params, positions, pJ, &Rglob);\n\n // finger parameters\n size_t ncorresp = corresp.size();\n Vector3d tmp;\n for (int i = 0; i < 4 * 5; i++)\n {\n Map curr_J(&pJ[(6 + i) * 3 * ncorresp], 3, ncorresp); // 6 is offset (global params)\n for (int j = 0; j < curr_J.cols(); j++)\n {\n const auto& verts = model.triangles[corresp[j]].verts;\n const double* const u = &us[2 * j];\n\n tmp = u[0] * positions_d[i].col(verts[0]) + u[1] * positions_d[i].col(verts[1])\n + (1. - u[0] - u[1]) * positions_d[i].col(verts[2]);\n\n curr_J.col(j).noalias() = -Rglob * tmp;\n }\n }\n}\n\nvoid to_pose_params_d(const double* const theta,\n const vector& bone_names,\n Matrix3Xd* ppose_params)\n{\n auto& pose_params = *ppose_params;\n pose_params.resize(3, bone_names.size() + 3);\n pose_params.setZero();\n\n pose_params.col(0) = Map(&theta[0]);\n pose_params.col(1).setOnes();\n pose_params.col(2) = Map(&theta[3]);\n\n int i_theta = 6;\n int i_pose_params = 5;\n int n_fingers = 5;\n for (int i_finger = 0; i_finger < n_fingers; i_finger++)\n {\n for (int i = 2; i <= 4; i++)\n {\n pose_params(0, i_pose_params) = theta[i_theta++];\n if (i == 2)\n {\n pose_params(1, i_pose_params) = theta[i_theta++];\n }\n i_pose_params++;\n }\n i_pose_params++;\n }\n}\n\nvoid hand_objective_d(\n const double* const theta,\n const HandDataEigen& data,\n double* perr,\n double* pJ)\n{\n Matrix3Xd pose_params;\n to_pose_params_d(theta, data.model.bone_names, &pose_params);\n\n Matrix3Xd vertex_positions;\n get_skinned_vertex_positions_d(data.model, pose_params, data.correspondences, &vertex_positions, pJ);\n\n size_t npts = data.correspondences.size();\n Map err(perr, 3, npts);\n for (size_t i = 0; i < data.correspondences.size(); i++)\n {\n err.col(i) = data.points.col(i) - vertex_positions.col(data.correspondences[i]);\n }\n}\n\nvoid hand_objective_d(\n const double* const theta,\n const double* const us,\n const HandDataEigen& data,\n double* perr,\n double* pJ)\n{\n Matrix3Xd pose_params;\n to_pose_params_d(theta, data.model.bone_names, &pose_params);\n\n size_t npts = data.correspondences.size();\n Matrix3Xd vertex_positions;\n get_skinned_vertex_positions_d(us, data.model, pose_params, data.correspondences, &vertex_positions, &pJ[2 * 3 * npts]);\n\n Map err(perr, 3, npts);\n Map du0(&pJ[0], 3, npts), du1(&pJ[3 * npts], 3, npts);\n Vector3d hand_point;\n for (size_t i = 0; i < data.correspondences.size(); i++)\n {\n const auto& verts = data.model.triangles[data.correspondences[i]].verts;\n const double* const u = &us[2 * i];\n\n du0.col(i) = -(vertex_positions.col(verts[0]) - vertex_positions.col(verts[2]));\n du1.col(i) = -(vertex_positions.col(verts[1]) - vertex_positions.col(verts[2]));\n\n hand_point = u[0] * vertex_positions.col(verts[0]) + u[1] * vertex_positions.col(verts[1])\n + (1. - u[0] - u[1]) * vertex_positions.col(verts[2]);\n err.col(i) = data.points.col(i) - hand_point;\n }\n}\n", "meta": {"hexsha": "2717dc3f8bfb8efcba7fba0e49d56d98a3a0774f", "size": 16107, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/modules/manualEigen/hand_eigen_d.cpp", "max_stars_repo_name": "dsyme/ADBench", "max_stars_repo_head_hexsha": "87af0219a568807f8432754688ceb636efac12c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 58.0, "max_stars_repo_stars_event_min_datetime": "2019-12-30T16:22:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-23T12:26:51.000Z", "max_issues_repo_path": "src/cpp/modules/manualEigen/hand_eigen_d.cpp", "max_issues_repo_name": "dsyme/ADBench", "max_issues_repo_head_hexsha": "87af0219a568807f8432754688ceb636efac12c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 112.0, "max_issues_repo_issues_event_min_datetime": "2019-05-25T07:26:58.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-28T13:55:33.000Z", "max_forks_repo_path": "src/cpp/modules/manualEigen/hand_eigen_d.cpp", "max_forks_repo_name": "dsyme/ADBench", "max_forks_repo_head_hexsha": "87af0219a568807f8432754688ceb636efac12c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T16:37:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T10:14:37.000Z", "avg_line_length": 32.4737903226, "max_line_length": 124, "alphanum_fraction": 0.5641646489, "num_tokens": 5201, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6613525305890846}} {"text": "#pragma once\n\n#include \n#include \n\n/** @class RobotEstimator\n * This class implements a Kalman Filter in order to estimate a robot's current state.\n * The estimated state is then used in motion control to assign wheel velocities accordingly\n *\n * Explanations:\n * - https://www.bzarg.com/p/how-a-kalman-filter-works-in-pictures/\n * - https://en.wikipedia.org/wiki/Kalman_filter\n * - https://www.mathworks.com/videos/series/understanding-kalman-filters.html\n */\nclass RobotEstimator {\nprivate:\n /**\n * Number of tracked states (number of states in state vector, x_hat)\n *\n * 3 Total:\n * - X and Y: linear velocities of robot body (m/s)\n * - W: angular velocity of robot body around z axis (rad/s)\n */\n static constexpr int numStates = 3;\n\n /**\n * Number of applied inputs (number of control inputs in control vector, u)\n *\n * 4 total:\n * - Motor duty cycle for each motor (% max), controls average applied voltage\n */\n static constexpr int numInputs = 4;\n\n /**\n * Number of tracked measurable outputs (number of outputs in output vector, y)\n *\n * 5 total:\n * - 4 wheel motor encoders (rad/s)\n * - Gyro angular velocity (rad/s)\n */\n static constexpr int numOutputs = 5;\n\npublic:\n /**\n * @param dt_us Expected period of the controller in us\n */\n RobotEstimator(uint32_t dt_us);\n\n /**\n * Using the previous state and the next input\n * We can guess where we are this time step\n * \n * @param u Last motor command\n */\n void predict(Eigen::Matrix u);\n\n /**\n * Using the next measurements, we can move our prediction\n * closer to the true target\n * \n * @param z Encoders 1-4 then gyro\n */\n void update(Eigen::Matrix z);\n\n /**\n * @param state Matrix that the current guess will be saved into\n */\n void getState(Eigen::Matrix& state);\n\nprivate:\n\n static constexpr float processNoise = 0.05; /**< State noise from unmodeled influences (model errors/omissions) */\n static constexpr float encoderNoise = 0.04; /**< Measurement noise in the encoder */\n static constexpr float gyroNoise = 0.005; /**< Measurement noise in the gyro */\n static constexpr float initCovariance = 0.1; /**< The initial covariance value in each entry of `P` */\n\n /**\n * State Transition Matrix/Prediction Matrix\n *\n * Predict our next state based on our current state using dynamics\n */\n Eigen::Matrix F;\n\n /**\n * Control Input Matrix\n *\n * Corrects our next state prediction by mapping control input (known influences, `u`) to our next state\n */\n Eigen::Matrix B;\n\n /**\n * Observation Matrix\n *\n * Predicts the measurements from our sensors (`z`) from our current state (`x_hat`).\n */\n Eigen::Matrix H;\n\n /**\n * Covariance Matrix for Process Noise\n *\n * A matrix whose entries are the estimated covariances between any two state variables.\n * Entries represent uncertainty in our state vector (`x_hat`) due to unmodeled influences.\n */\n Eigen::Matrix Q;\n\n /**\n * Covariance Matrix for Observation Noise\n *\n * A matrix whose entries are the estimated covariances between any two state variables.\n * Entries represent uncertainty in our measurements (`z`) due to random noise\n */\n Eigen::Matrix R;\n\n /**\n * Covariance Estimate Matrix\n *\n * A matrix whose entries are the estimated covariances between any two state variables.\n * Entries represent our overall uncertainty in our state vector (`x_hat`).\n */\n Eigen::Matrix P;\n\n /**\n * Identity Matrix\n *\n * A square matrix with only 1s on the diagonals\n */\n Eigen::Matrix I;\n\n /**\n * Current State Vector Estimate\n *\n * What the robot estimator believes our current state to be\n */\n Eigen::Matrix x_hat;\n};", "meta": {"hexsha": "f49e9ad45e0b361b5f5f97a54fdbfb92091c1322", "size": 4213, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "control/include/robocup/motion-control/RobotEstimator.hpp", "max_stars_repo_name": "RRRekkitRalph/robocup-firmware", "max_stars_repo_head_hexsha": "a1502fdb3401e7e998a29c5fae22ef597dcc2dc5", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 26.0, "max_stars_repo_stars_event_min_datetime": "2016-07-06T11:25:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-27T00:24:02.000Z", "max_issues_repo_path": "control/include/robocup/motion-control/RobotEstimator.hpp", "max_issues_repo_name": "RRRekkitRalph/robocup-firmware", "max_issues_repo_head_hexsha": "a1502fdb3401e7e998a29c5fae22ef597dcc2dc5", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 98.0, "max_issues_repo_issues_event_min_datetime": "2016-07-04T22:43:46.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-10T00:12:02.000Z", "max_forks_repo_path": "control/include/robocup/motion-control/RobotEstimator.hpp", "max_forks_repo_name": "RRRekkitRalph/robocup-firmware", "max_forks_repo_head_hexsha": "a1502fdb3401e7e998a29c5fae22ef597dcc2dc5", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 16.0, "max_forks_repo_forks_event_min_datetime": "2016-07-07T10:50:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-06T11:20:28.000Z", "avg_line_length": 31.2074074074, "max_line_length": 119, "alphanum_fraction": 0.6482316639, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.7122321903471565, "lm_q1q2_score": 0.6612426307355493}} {"text": "/**\n * Copyright Matthias Walter 2010.\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n **/\n\n#include \"../config.h\"\n#include \n#include \n\n#include \n#include \n\n#include \"total_unimodularity.hpp\"\n#include \"combinations.hpp\"\n\nnamespace unimod\n{\n\n /**\n * Calculates a subdeterminant of the given matrix.\n *\n * @param matrix A given integer matrix\n * @param submatrix Matrix-indices describing a submatrix\n * @return The submatrix' determinant\n */\n\n int submatrix_determinant(const integer_matrix& matrix, const submatrix_indices& submatrix)\n {\n typedef boost::numeric::ublas::matrix_indirect indirect_matrix_t;\n\n assert (submatrix.rows.size() == submatrix.columns.size());\n\n const indirect_matrix_t indirect_matrix(matrix, submatrix.rows, submatrix.columns);\n\n boost::numeric::ublas::matrix float_matrix(indirect_matrix);\n boost::numeric::ublas::permutation_matrix permutation_matrix(float_matrix.size1());\n\n /// LU-factorize\n int result = boost::numeric::ublas::lu_factorize(float_matrix, permutation_matrix);\n if (result != 0)\n return 0;\n\n /// Calculate the determinant as a product of the diagonal entries, taking the permutation matrix into account.\n float det = 1.0f;\n for (size_t i = 0; i < float_matrix.size1(); ++i)\n {\n det *= float_matrix(i, i);\n if (i != permutation_matrix(i))\n det = -det;\n }\n\n return (int) det;\n }\n\n /**\n * Checks Camion's criterion for total unimodularity.\n *\n * @param matrix A given integer matrix\n * @param submatrix Matrix-indices describing a submatrix B of A\n * @return true iff B is not Eulerian or 1^T * B * 1 = 0 (mod 4)\n */\n\n bool submatrix_camion(const integer_matrix& matrix, const submatrix_indices& submatrix)\n {\n typedef boost::numeric::ublas::matrix_indirect indirect_matrix_t;\n\n assert (submatrix.rows.size() == submatrix.columns.size());\n\n const indirect_matrix_t indirect_matrix(matrix, submatrix.rows, submatrix.columns);\n\n // Test whether submatrix is eulerian.\n for (size_t row = 0; row < indirect_matrix.size1(); ++row)\n {\n size_t count = 0;\n for (size_t column = 0; column < indirect_matrix.size2(); ++column)\n count += indirect_matrix(row, column);\n if (count % 2 == 1)\n return true;\n }\n for (size_t column = 0; column < indirect_matrix.size2(); ++column)\n {\n size_t count = 0;\n for (size_t row = 0; row < indirect_matrix.size1(); ++row)\n count += indirect_matrix(row, column);\n if (count % 2 == 1)\n return true;\n }\n\n // Matrix is eulerian.\n size_t count = 0;\n for (size_t row = 0; row < indirect_matrix.size1(); ++row)\n {\n for (size_t column = 0; column < indirect_matrix.size2(); ++column)\n count += indirect_matrix(row, column);\n }\n return (count % 4 == 0);\n }\n\n /**\n * Checks all subdeterminants to test a given matrix for total unimodularity.\n *\n * @param matrix The given matrix\n * @return true if and only if this matrix is totally unimdular\n */\n\n bool determinant_is_totally_unimodular(const integer_matrix& matrix)\n {\n submatrix_indices indices;\n\n return determinant_is_totally_unimodular(matrix, indices);\n }\n\n /**\n * Checks all subdeterminants to test a given matrix for total unimodularity.\n * If this is not the case, violator describes a violating submatrix.\n *\n * @param matrix The given matrix\n * @param violator The violating submatrix, if the result is false\n * @return true if and only if the this matrix is totally unimodular\n */\n\n bool determinant_is_totally_unimodular(const integer_matrix& matrix, submatrix_indices& violator)\n {\n for (size_t size = 1; size <= matrix.size1(); ++size)\n {\n combination row_combination(matrix.size1(), size);\n while (true)\n {\n combination column_combination(matrix.size2(), size);\n while (true)\n {\n submatrix_indices sub;\n submatrix_indices::vector_type indirect_array(size);\n for (size_t i = 0; i < size; ++i)\n indirect_array[i] = row_combination[i];\n sub.rows = submatrix_indices::indirect_array_type(size, indirect_array);\n for (size_t i = 0; i < size; ++i)\n {\n indirect_array[i] = column_combination[i];\n }\n sub.columns = submatrix_indices::indirect_array_type(size, indirect_array);\n\n /// Examine the determinant\n bool camion = submatrix_camion(matrix, sub);\n\n#ifndef NDEBUG\n int det = submatrix_determinant(matrix, sub);\n bool is_violator = det < -1 || det > +1;\n assert((is_violator && !camion) || (!is_violator && camion));\n#pragma message(\"\\n\\n\\nWARNING: Submatrix Test uses subdeterminants for verification and is much slower!\\n\\n \")\n#endif\n if (!camion)\n {\n violator = sub;\n return false;\n }\n\n if (column_combination.is_last())\n break;\n column_combination.next();\n }\n if (row_combination.is_last())\n break;\n row_combination.next();\n }\n }\n return true;\n }\n\n}\n", "meta": {"hexsha": "6e6d3e6f9c81ee2ade4785555e1ef15b500de373", "size": 5464, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "unimodularity-library-1.2c/src/determinant.cpp", "max_stars_repo_name": "vios-fish/CompetitiveProgramming", "max_stars_repo_head_hexsha": "6953f024e4769791225c57ed852cb5efc03eb94b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2016-07-05T21:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-08T01:33:12.000Z", "max_issues_repo_path": "src/determinant.cpp", "max_issues_repo_name": "vbraun/unimodularity-library", "max_issues_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/determinant.cpp", "max_forks_repo_name": "vbraun/unimodularity-library", "max_forks_repo_head_hexsha": "d329571908a84ed98713721a2fe873ad534901c8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5838150289, "max_line_length": 132, "alphanum_fraction": 0.6504392387, "num_tokens": 1360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284087965937712, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6612426250646337}} {"text": "/*=============================================================================\n\n SKSURGERYOPENCVCPP: Image-guided surgery functions, in C++, using OpenCV.\n\n Copyright (c) University College London (UCL). All rights reserved.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE.\n\n See LICENSE.txt in the top level directory for details.\n\n=============================================================================*/\n\n#include \"sksTriangulate.h\"\n#include \"sksExceptionMacro.h\"\n\n#include \n#include \n#include \n\nnamespace sks\n{\n\n//-----------------------------------------------------------------------------\ndouble Norm(const cv::Point3d& p1)\n{\n return std::sqrt(p1.x * p1.x + p1.y * p1.y + p1.z * p1.z);\n}\n\n\n//-----------------------------------------------------------------------------\ncv::Point3d CrossProduct(const cv::Point3d& p1, const cv::Point3d& p2)\n{\n cv::Point3d cp;\n cp.x = p1.y * p2.z - p1.z * p2.y;\n cp.y = p1.z * p2.x - p1.x * p2.z;\n cp.z = p1.x * p2.y - p1.y * p2.x;\n return cp;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble DotProduct(const cv::Point3d& p1, const cv::Point3d& p2)\n{\n return p1.x * p2.x + p1.y * p2.y + p1.z * p2.z;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble DistanceToLine(const std::pair& line, const cv::Point3d& x0 )\n{\n // Courtesy of Wolfram Mathworld\n cv::Point3d x1;\n cv::Point3d x2;\n\n x1 = line.first;\n x2 = line.second;\n\n cv::Point3d d1 = x1-x0;\n cv::Point3d d2 = x2-x1;\n\n return sks::Norm(sks::CrossProduct(d2, d1)) / (sks::Norm(d2));\n}\n\n\n//-----------------------------------------------------------------------------\ndouble DistanceBetweenLines(const cv::Point3d& P0, const cv::Point3d& u,\n const cv::Point3d& Q0, const cv::Point3d& v,\n cv::Point3d& midpoint)\n{\n // Method 1. Solve for shortest line joining two rays, then get midpoint.\n // Taken from: http://geomalgorithms.com/a07-_distance.html\n double sc, tc, a, b, c, d, e;\n double distance;\n\n cv::Point3d Psc;\n cv::Point3d Qtc;\n cv::Point3d W0;\n\n // Difference of two origins\n W0.x = P0.x - Q0.x;\n W0.y = P0.y - Q0.y;\n W0.z = P0.z - Q0.z;\n\n a = u.x*u.x + u.y*u.y + u.z*u.z;\n b = u.x*v.x + u.y*v.y + u.z*v.z;\n c = v.x*v.x + v.y*v.y + v.z*v.z;\n d = u.x*W0.x + u.y*W0.y + u.z*W0.z;\n e = v.x*W0.x + v.y*W0.y + v.z*W0.z;\n sc = (b*e - c*d) / (a*c - b*b);\n tc = (a*e - b*d) / (a*c - b*b);\n\n if ( boost::math::isnan(sc) || boost::math::isnan(tc) || boost::math::isinf(sc) || boost::math::isinf(tc) )\n {\n // Lines are parallel\n distance = sks::DistanceToLine ( std::pair ( P0, P0 + u ), Q0 );\n midpoint.x = std::numeric_limits::quiet_NaN();\n midpoint.y = std::numeric_limits::quiet_NaN();\n midpoint.z = std::numeric_limits::quiet_NaN();\n return distance;\n }\n Psc.x = P0.x + sc*u.x;\n Psc.y = P0.y + sc*u.y;\n Psc.z = P0.z + sc*u.z;\n Qtc.x = Q0.x + tc*v.x;\n Qtc.y = Q0.y + tc*v.y;\n Qtc.z = Q0.z + tc*v.z;\n\n distance = std::sqrt((Psc.x - Qtc.x)*(Psc.x - Qtc.x)\n +(Psc.y - Qtc.y)*(Psc.y - Qtc.y)\n +(Psc.z - Qtc.z)*(Psc.z - Qtc.z));\n\n midpoint.x = (Psc.x + Qtc.x)/2.0;\n midpoint.y = (Psc.y + Qtc.y)/2.0;\n midpoint.z = (Psc.z + Qtc.z)/2.0;\n\n return distance;\n}\n\n\n//-----------------------------------------------------------------------------\ndouble ComputeRMSBetweenCorrespondingPoints(const cv::Mat& a, const cv::Mat& b)\n{\n double rms = 0;\n double diff = 0;\n double squaredDiff = 0;\n\n if (a.rows != b.rows)\n {\n sksExceptionThrow() << \"a has \" << a.rows << \" rows, but b has \" << b.rows;\n }\n\n if (a.cols != 3)\n {\n sksExceptionThrow() << \"a does not have 3 columns.\";\n }\n\n if (b.cols != 3)\n {\n sksExceptionThrow() << \"b does not have 3 columns.\";\n }\n\n for (unsigned int r = 0; r < a.rows; r++)\n {\n for (unsigned int c = 0; c < a.cols; c++)\n {\n diff = (b.at(r, c) - a.at(r, c));\n squaredDiff = diff * diff;\n rms += squaredDiff;\n }\n }\n rms /= static_cast(a.rows);\n rms = std::sqrt(rms);\n return rms;\n}\n\n} // end namespace\n", "meta": {"hexsha": "8291c13b3b530f6e571357867f2f595519b88ea8", "size": 4388, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Code/Lib/sksMaths.cpp", "max_stars_repo_name": "UCL/scikit-surgeryopencvcpp", "max_stars_repo_head_hexsha": "6c2748afa8e3ac54677a8922bf755548d9a9bbf6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Code/Lib/sksMaths.cpp", "max_issues_repo_name": "UCL/scikit-surgeryopencvcpp", "max_issues_repo_head_hexsha": "6c2748afa8e3ac54677a8922bf755548d9a9bbf6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 26.0, "max_issues_repo_issues_event_min_datetime": "2019-02-23T13:09:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-04T14:19:56.000Z", "max_forks_repo_path": "Code/Lib/sksMaths.cpp", "max_forks_repo_name": "UCL/scikit-surgeryopencvcpp", "max_forks_repo_head_hexsha": "6c2748afa8e3ac54677a8922bf755548d9a9bbf6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-05-31T11:28:24.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-07T20:27:18.000Z", "avg_line_length": 27.5974842767, "max_line_length": 109, "alphanum_fraction": 0.4958979034, "num_tokens": 1353, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094003735664, "lm_q2_score": 0.7401743505760728, "lm_q1q2_score": 0.6612047052850055}} {"text": "/*\nCopyright 2020 Standard Cyborg\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n#include \"standard_cyborg/algorithms/PointToPointAlignment.hpp\"\n\n#include \"standard_cyborg/util/IncludeEigen.hpp\"\n\n#include \"standard_cyborg/math/Vec3.hpp\"\n#include \"standard_cyborg/math/Mat3x4.hpp\"\n\n#pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wdocumentation\"\n#include \n#pragma clang diagnostic pop\n\nnamespace standard_cyborg {\n\nnamespace algorithms {\n\nstandard_cyborg::math::Mat3x4 PointToPointAlignment(const std::vector& sourcePositions, const std::vector& targetPositions)\n{\n int N = (int)sourcePositions.size();\n \n Eigen::Matrix3Xf p = Eigen::Matrix3Xf(3, N);\n Eigen::Matrix3Xf q = Eigen::Matrix3Xf(3, N);\n Eigen::MatrixXf avgP, avgQ, pNorm, qNorm, C, R, t;\n \n for (int iv = 0; iv < N; ++iv) {\n p.col(iv) = Eigen::Vector3f(sourcePositions[iv].x, sourcePositions[iv].y, sourcePositions[iv].z);\n q.col(iv) = Eigen::Vector3f(targetPositions[iv].x, targetPositions[iv].y, targetPositions[iv].z);\n }\n \n avgP = p.rowwise().mean();\n avgQ = q.rowwise().mean();\n \n pNorm = p - avgP.replicate(1, p.cols());\n qNorm = q - avgQ.replicate(1, q.cols());\n \n C = pNorm * qNorm.transpose();\n Eigen::JacobiSVD svd(C, Eigen::ComputeThinU | Eigen::ComputeThinV);\n \n // rotation\n R = svd.matrixV() * svd.matrixU().transpose();\n \n // translation\n t = avgQ - R * avgP;\n \n standard_cyborg::math::Mat3x4 r = {\n R(0, 0), R(0, 1), R(0, 2), t(0),\n R(1, 0), R(1, 1), R(1, 2), t(1),\n R(2, 0), R(2, 1), R(2, 2), t(2),\n };\n \n return r;\n}\n\n}\n\n}\n", "meta": {"hexsha": "4b57bbc68e549cd461fb4fe34bb696143264f042", "size": 2207, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "scsdk/c++/scsdk/standard_cyborg/algorithms/PointToPointAlignment.cpp", "max_stars_repo_name": "StandardCyborg/scsdk", "max_stars_repo_head_hexsha": "92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2020-11-26T01:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-14T07:45:19.000Z", "max_issues_repo_path": "scsdk/c++/scsdk/standard_cyborg/algorithms/PointToPointAlignment.cpp", "max_issues_repo_name": "StandardCyborg/scsdk", "max_issues_repo_head_hexsha": "92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scsdk/c++/scsdk/standard_cyborg/algorithms/PointToPointAlignment.cpp", "max_forks_repo_name": "StandardCyborg/scsdk", "max_forks_repo_head_hexsha": "92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6527777778, "max_line_length": 181, "alphanum_fraction": 0.672405981, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096112990285, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6611958991452033}} {"text": "/**\n * \\file Chebyshev1Filter.cpp\n */\n\n#include \n\n#include \"Chebyshev1Filter.h\"\n#include \"helpers.h\"\n#include \"IIRFilter.h\"\n\nnamespace\n{\n template\n void create_chebyshev1_analog_coefficients(int order, DataType ripple, std::vector >& z, std::vector >& p, DataType& k)\n {\n z.clear(); // no zeros for this filter type\n p.clear();\n if(ripple == 0)\n {\n return;\n }\n if(order == 0)\n {\n k = static_cast(std::pow(10, (-ripple / 20)));\n return;\n }\n \n DataType eps = static_cast(std::sqrt(std::pow(10, (0.1 * ripple)) - 1.0));\n DataType mu = static_cast(1.0 / order * boost::math::asinh(1 / eps));\n \n for(int i = -order+1; i < order; i += 2)\n {\n DataType theta = boost::math::constants::pi() * i / (2*order);\n p.push_back(-std::sinh(std::complex(mu, theta)));\n }\n\n std::complex f = 1;\n \n for(int i = 0; i < p.size(); ++i)\n {\n f *= -p[i];\n }\n k = f.real();\n if(order % 2 == 0)\n {\n k = k / std::sqrt((1 + eps * eps));\n }\n }\n \n template\n void create_default_chebyshev1_coeffs(size_t order, DataType ripple, DataType Wn, std::vector& coefficients_in, std::vector& coefficients_out)\n {\n std::vector > z;\n std::vector > p;\n DataType k;\n \n int fs = 2;\n create_chebyshev1_analog_coefficients(static_cast(order), ripple, z, p, k);\n DataType warped = 2 * fs * std::tan(boost::math::constants::pi() * Wn / fs);\n zpk_lp2lp(warped, z, p, k);\n zpk_bilinear(fs, z, p, k);\n \n boost::math::tools::polynomial b;\n boost::math::tools::polynomial a;\n \n zpk2ba(fs, z, p, k, b, a);\n \n for(size_t i = 0; i < std::min(order + 1, b.size()); ++i)\n {\n coefficients_in[i] = b[i];\n }\n for(size_t i = 0; i < std::min(order, a.size()-1); ++i)\n {\n coefficients_out[i] = -a[i];\n }\n }\n \n template\n void create_bp_chebyshev1_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, std::vector& coefficients_in, std::vector& coefficients_out)\n {\n std::vector > z;\n std::vector > p;\n DataType k;\n \n int fs = 2;\n create_chebyshev1_analog_coefficients(static_cast(order/2), ripple, z, p, k);\n wc1 = 2 * fs * std::tan(boost::math::constants::pi() * wc1 / fs);\n wc2 = 2 * fs * std::tan(boost::math::constants::pi() * wc2 / fs);\n \n zpk_lp2bp(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);\n zpk_bilinear(fs, z, p, k);\n \n boost::math::tools::polynomial b;\n boost::math::tools::polynomial a;\n \n zpk2ba(fs, z, p, k, b, a);\n \n for(size_t i = 0; i < std::min(order + 1, b.size()); ++i)\n {\n coefficients_in[i] = b[i];\n }\n for(size_t i = 0; i < std::min(order, a.size()-1); ++i)\n {\n coefficients_out[i] = -a[i];\n }\n }\n \n template\n void create_bs_chebyshev1_coeffs(size_t order, DataType ripple, DataType wc1, DataType wc2, std::vector& coefficients_in, std::vector& coefficients_out)\n {\n std::vector > z;\n std::vector > p;\n DataType k;\n \n int fs = 2;\n create_chebyshev1_analog_coefficients(static_cast(order/2), ripple, z, p, k);\n wc1 = 2 * fs * std::tan(boost::math::constants::pi() * wc1 / fs);\n wc2 = 2 * fs * std::tan(boost::math::constants::pi() * wc2 / fs);\n \n zpk_lp2bs(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);\n zpk_bilinear(fs, z, p, k);\n \n boost::math::tools::polynomial b;\n boost::math::tools::polynomial a;\n \n zpk2ba(fs, z, p, k, b, a);\n \n for(size_t i = 0; i < std::min(order + 1, b.size()); ++i)\n {\n coefficients_in[i] = b[i];\n }\n for(size_t i = 0; i < std::min(order, a.size()-1); ++i)\n {\n coefficients_out[i] = -a[i];\n }\n }\n}\n\nnamespace ATK\n{\n template \n Chebyshev1LowPassCoefficients::Chebyshev1LowPassCoefficients(int nb_channels)\n :Parent(nb_channels, nb_channels), cut_frequency(0), ripple(0), in_order(1), out_order(1)\n {\n }\n \n template \n void Chebyshev1LowPassCoefficients::set_ripple(DataType_ ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n DataType_ Chebyshev1LowPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n \n template \n void Chebyshev1LowPassCoefficients::set_cut_frequency(DataType_ cut_frequency)\n {\n this->cut_frequency = cut_frequency;\n setup();\n }\n \n template \n DataType_ Chebyshev1LowPassCoefficients::get_cut_frequency() const\n {\n return cut_frequency;\n }\n \n template \n void Chebyshev1LowPassCoefficients::set_order(int order)\n {\n in_order = out_order = order;\n setup();\n }\n \n template \n void Chebyshev1LowPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n create_default_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequency / input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template \n Chebyshev1HighPassCoefficients::Chebyshev1HighPassCoefficients(int nb_channels)\n :Parent(nb_channels, nb_channels), cut_frequency(0), ripple(0), in_order(1), out_order(1)\n {\n }\n \n template \n void Chebyshev1HighPassCoefficients::set_cut_frequency(DataType_ cut_frequency)\n {\n this->cut_frequency = cut_frequency;\n setup();\n }\n \n template \n DataType_ Chebyshev1HighPassCoefficients::get_cut_frequency() const\n {\n return cut_frequency;\n }\n \n template \n void Chebyshev1HighPassCoefficients::set_ripple(DataType_ ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n DataType_ Chebyshev1HighPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n\n template \n void Chebyshev1HighPassCoefficients::set_order(int order)\n {\n in_order = out_order = order;\n setup();\n }\n \n template \n void Chebyshev1HighPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n create_default_chebyshev1_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) / input_sampling_rate, coefficients_in, coefficients_out);\n for(int i = in_order - 1; i >= 0; i -= 2)\n {\n coefficients_in[i] = - coefficients_in[i];\n coefficients_out[i] = - coefficients_out[i];\n }\n }\n \n template \n Chebyshev1BandPassCoefficients::Chebyshev1BandPassCoefficients(int nb_channels)\n :Parent(nb_channels, nb_channels), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)\n {\n }\n \n template \n void Chebyshev1BandPassCoefficients::set_cut_frequencies(std::pair cut_frequencies)\n {\n this->cut_frequencies = cut_frequencies;\n setup();\n }\n \n template \n void Chebyshev1BandPassCoefficients::set_cut_frequencies(DataType_ f0, DataType_ f1)\n {\n this->cut_frequencies = std::make_pair(f0, f1);\n setup();\n }\n \n template \n std::pair Chebyshev1BandPassCoefficients::get_cut_frequencies() const\n {\n return cut_frequencies;\n }\n \n template \n void Chebyshev1BandPassCoefficients::set_ripple(DataType_ ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n DataType_ Chebyshev1BandPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n\n template \n void Chebyshev1BandPassCoefficients::set_order(int order)\n {\n in_order = out_order = 2 * order;\n setup();\n }\n \n template \n void Chebyshev1BandPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n create_bp_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template \n Chebyshev1BandStopCoefficients::Chebyshev1BandStopCoefficients(int nb_channels)\n :Parent(nb_channels, nb_channels), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)\n {\n }\n \n template \n void Chebyshev1BandStopCoefficients::set_cut_frequencies(std::pair cut_frequencies)\n {\n this->cut_frequencies = cut_frequencies;\n setup();\n }\n \n template \n void Chebyshev1BandStopCoefficients::set_cut_frequencies(DataType_ f0, DataType_ f1)\n {\n this->cut_frequencies = std::make_pair(f0, f1);\n setup();\n }\n \n template \n std::pair Chebyshev1BandStopCoefficients::get_cut_frequencies() const\n {\n return cut_frequencies;\n }\n \n template \n void Chebyshev1BandStopCoefficients::set_ripple(DataType_ ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n DataType_ Chebyshev1BandStopCoefficients::get_ripple() const\n {\n return ripple;\n }\n\n template \n void Chebyshev1BandStopCoefficients::set_order(int order)\n {\n in_order = out_order = 2 * order;\n setup();\n }\n \n template \n void Chebyshev1BandStopCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n create_bs_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first / input_sampling_rate, 2 * cut_frequencies.second / input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template class Chebyshev1LowPassCoefficients;\n template class Chebyshev1LowPassCoefficients;\n template class Chebyshev1HighPassCoefficients;\n template class Chebyshev1HighPassCoefficients;\n template class Chebyshev1BandPassCoefficients;\n template class Chebyshev1BandPassCoefficients;\n template class Chebyshev1BandStopCoefficients;\n template class Chebyshev1BandStopCoefficients;\n \n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n \n}\n", "meta": {"hexsha": "9be878475d814f3d94623048a00f8015c0836647", "size": 11492, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ATK/EQ/Chebyshev1Filter.cpp", "max_stars_repo_name": "apohl79/AudioTK", "max_stars_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2018-05-17T15:29:05.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-19T22:26:08.000Z", "max_issues_repo_path": "ATK/EQ/Chebyshev1Filter.cpp", "max_issues_repo_name": "apohl79/AudioTK", "max_issues_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ATK/EQ/Chebyshev1Filter.cpp", "max_forks_repo_name": "apohl79/AudioTK", "max_forks_repo_head_hexsha": "05ac241b0bc6a8f841d93257b4d81e5961b1f627", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-04-21T13:43:57.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-28T19:10:14.000Z", "avg_line_length": 30.6453333333, "max_line_length": 184, "alphanum_fraction": 0.6907413853, "num_tokens": 3311, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418178895029, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6611532432396262}} {"text": "#include \"ematrix.h\"\n\n#include \"defines.h\"\n#include \"fmatrix.h\"\n#include \"triangulation.h\"\n\n#include \n#include \n#include \n\nnamespace {\n\n // essential matrix must have exactly two equal non zero singular values\n void ensureSpectralProperty(matrix3d &Ecv)\n {\n Eigen::MatrixXd E;\n copy(Ecv, E);\n\n Eigen::JacobiSVD svd(E, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n Eigen::MatrixXd U = svd.matrixU();\n Eigen::VectorXd s = svd.singularValues();\n Eigen::MatrixXd V = svd.matrixV();\n\n Eigen::MatrixXd S = Eigen::MatrixXd(3, 3);\n S.setZero();\n\n S(0, 0) = 1.0;\n S(1, 1) = 1.0;\n S(2, 2) = 0.0;\n\n E = U * S * V.transpose();\n\n copy(E, Ecv);\n }\n\n}\n\ncv::Matx33d phg::fmatrix2ematrix(const cv::Matx33d &F, const phg::Calibration &calib0, const phg::Calibration &calib1)\n{\n // TODO check that correct conversion (transpose ok)\n\n // TODO add separate test for fmatrix (check 1) reprojection errors 2) f matrix singular value property)\n // TODO add separate test for ematrix (check 1) reprojection errors of normalized coordinates 2) e matrix singular value property)\n // TODO add separate test for ematrix decomposition: 1) check angle between cameras 2) check translation direction between cameras\n\n matrix3d E = calib1.K().t() * F * calib0.K();\n\n ensureSpectralProperty(E);\n\n return E;\n}\n\nnamespace {\n\n matrix34d composeP(const Eigen::MatrixXd &R, const Eigen::VectorXd &t)\n {\n matrix34d result;\n\n result(0, 0) = R(0, 0);\n result(0, 1) = R(0, 1);\n result(0, 2) = R(0, 2);\n result(1, 0) = R(1, 0);\n result(1, 1) = R(1, 1);\n result(1, 2) = R(1, 2);\n result(2, 0) = R(2, 0);\n result(2, 1) = R(2, 1);\n result(2, 2) = R(2, 2);\n\n result(0, 3) = t[0];\n result(1, 3) = t[1];\n result(2, 3) = t[2];\n\n return result;\n }\n\n double getDepth(const vector2d &m0, const vector2d &m1, const phg::Calibration &calib0, const phg::Calibration &calib1, const matrix34d &P0, const matrix34d &P1)\n {\n vector3d p0 = calib0.unproject(m0);\n vector3d p1 = calib1.unproject(m1);\n\n vector3d ps[2] = {p0, p1};\n matrix34d Ps[2] = {P0, P1};\n\n vector4d X = phg::triangulatePoint(Ps, ps, 2);\n if (X[3] != 0) {\n X /= X[3];\n }\n\n return p0.dot(P0 * X) > 0 && p1.dot(P1 * X) > 0;\n }\n}\n\n// Матрицы камер для фундаментальной матрицы определены с точностью до проективного преобразования\n// То есть, можно исказить трехмерный мир (применив 4-мерную однородную матрицу), и одновременно поменять матрицы P0, P1 так, что проекции в пикселях не изменятся\n// Если мы знаем калибровки камер (матрицы K0, K1 в структуре матриц P0, P1), то можем наложить дополнительные ограничения, в частности, известно, что\n// существенная матрица (Essential matrix = K1t * F * K0) имеет ровно два совпадающих ненулевых сингулярных значения, тогда как для фундаментальной матрицы они могут различаться\n// Это дополнительное ограничение позволяет разложить существенную матрицу с точностью до 4 решений, вместо произвольного проективного преобразования (см. Hartley & Zisserman p.258)\n// Обычно мы можем использовать одну общую калибровку, более менее верную для большого количества реальных камер и с ее помощью выполнить\n// первичное разложение существенной матрицы (а из него, взаимное расположение камер) для последующего уточнения методом нелинейной оптимизации\nvoid phg::decomposeEMatrix(cv::Matx34d &P0, cv::Matx34d &P1, const cv::Matx33d &Ecv, const std::vector &m0, const std::vector &m1, const Calibration &calib0, const Calibration &calib1, bool verbose)\n{\n if (m0.size() != m1.size()) {\n throw std::runtime_error(\"decomposeEMatrix : m0.size() != m1.size()\");\n }\n\n using mat = Eigen::MatrixXd;\n using vec = Eigen::VectorXd;\n \n mat E;\n copy(Ecv, E);\n\n // (см. Hartley & Zisserman p.258)\n\n Eigen::JacobiSVD svd(E, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\n mat U = svd.matrixU();\n vec s = svd.singularValues();\n mat V = svd.matrixV();\n\n // U, V must be rotation matrices, not just orthogonal\n if (U.determinant() < 0) U = -U;\n if (V.determinant() < 0) V = -V;\n\n if (verbose) {\n std::cout << \"U:\\n\" << U << std::endl;\n std::cout << \"s:\\n\" << s << std::endl;\n std::cout << \"V:\\n\" << V << std::endl;\n }\n\n mat W(3, 3);\n W << 0, -1, 0, 1, 0, 0, 0, 0, 1;\n\n mat Z(3, 3);\n Z << 0, 1, 0, -1, 0, 0, 0, 0, 0;\n\n if (verbose) {\n std::cout << \"W:\\n\" << W << std::endl;\n std::cout << \"Z:\\n\" << Z << std::endl;\n }\n\n mat R0 = U * W * V.transpose();\n mat R1 = U * W.transpose() * V.transpose();\n\n if (verbose) {\n std::cout << \"R0:\\n\" << R0 << std::endl;\n std::cout << \"R1:\\n\" << R1 << std::endl;\n }\n\n vec t0 = U.col(2);\n vec t1 = -t0;\n\n if (verbose) {\n std::cout << \"t0:\\n\" << t0 << std::endl;\n }\n\n P0 = matrix34d::eye();\n\n // 4 possible solutions\n matrix34d P10 = composeP(R0, t0);\n matrix34d P11 = composeP(R0, t1);\n matrix34d P12 = composeP(R1, t0);\n matrix34d P13 = composeP(R1, t1);\n matrix34d P1s[4] = {P10, P11, P12, P13};\n\n // need to select best of 4 solutions: 3d points should be in front of cameras (positive depths)\n int best_count = 0;\n int best_idx = -1;\n for (int i = 0; i < 4; ++i) {\n int count = 0;\n for (int j = 0; j < (int) m0.size(); ++j) {\n if (getDepth(m0[j], m1[j], calib0, calib1, P0, P1s[i]) > 0) {\n ++count;\n }\n }\n if (verbose) {\n std::cout << \"decomposeEMatrix: count: \" << count << std::endl;\n }\n if (count > best_count) {\n best_count = count;\n best_idx = i;\n }\n }\n\n if (best_count == 0) {\n throw std::runtime_error(\"decomposeEMatrix : can't decompose ematrix\");\n }\n\n P1 = P1s[best_idx];\n\n if (verbose) {\n std::cout << \"best idx: \" << best_idx << std::endl;\n std::cout << \"P0: \\n\" << P0 << std::endl;\n std::cout << \"P1: \\n\" << P1 << std::endl;\n }\n}\n\nvoid phg::decomposeUndistortedPMatrix(cv::Matx33d &R, cv::Vec3d &O, const cv::Matx34d &P)\n{\n R = P.get_minor<3, 3>(0, 0);\n\n cv::Matx31d O_mat = -R.t() * P.get_minor<3, 1>(0, 3);\n O(0) = O_mat(0);\n O(1) = O_mat(1);\n O(2) = O_mat(2);\n\n if (cv::determinant(R) < 0) {\n R *= -1; \n }\n}\n\ncv::Matx33d phg::composeEMatrixRT(const cv::Matx33d &R, const cv::Vec3d &T)\n{\n return skew(T) * R;\n}\n\ncv::Matx34d phg::composeCameraMatrixRO(const cv::Matx33d &R, const cv::Vec3d &O)\n{\n vector3d T = -R * O;\n return make34(R, T);\n}\n", "meta": {"hexsha": "e13f9843e528a9f0c5d0ac14de76896870f2867e", "size": 6785, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/phg/sfm/ematrix.cpp", "max_stars_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_stars_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/phg/sfm/ematrix.cpp", "max_issues_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_issues_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/phg/sfm/ematrix.cpp", "max_forks_repo_name": "kpilyugin/PhotogrammetryTasks2021", "max_forks_repo_head_hexsha": "7da69f04909075340a220a7021efeeb42283d9dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.5630630631, "max_line_length": 220, "alphanum_fraction": 0.5808400884, "num_tokens": 2452, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6611503964932771}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main()\n{\n ArrayXXf m(2,2);\n ArrayXXf n(2,2);\n \n ArrayXXf result(2,2);\n\n //initialize arrays\n m << 1,2,\n 3,4;\n\n n << 5,6,\n 7,8;\n\n \n // --> array multiplication\n result = m * n;\n\n cout << \"-- Array m*n: --\" << endl\n << result << endl << endl;\n\n\n // --> Matrix multiplication\n result = m.matrix() * n.matrix();\n \n cout << \"-- Matrix m*n: --\" << endl\n << result << endl << endl;\n}\n", "meta": {"hexsha": "c2cb6bf3f482181892ff195332491beeb2a2f67c", "size": 503, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_ArrayClass_interop_array.cpp", "max_stars_repo_name": "dailysoap/CSMM.104x", "max_stars_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-04-01T17:18:35.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T05:23:23.000Z", "max_issues_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_ArrayClass_interop_array.cpp", "max_issues_repo_name": "dailysoap/CSMM.104x", "max_issues_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-05-24T13:36:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T06:44:20.000Z", "max_forks_repo_path": "t1m1/include/eigen/doc/examples/Tutorial_ArrayClass_interop_array.cpp", "max_forks_repo_name": "dailysoap/CSMM.104x", "max_forks_repo_head_hexsha": "4515b30ab5f60827a9011b23ef155a3063584a9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-09-20T01:07:39.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T14:55:38.000Z", "avg_line_length": 14.3714285714, "max_line_length": 37, "alphanum_fraction": 0.5268389662, "num_tokens": 160, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.76908023177796, "lm_q1q2_score": 0.6611503964932771}} {"text": "#include \n#include \n#include \n#include \"elements.h\"\n\nusing Eigen::Vector3d;\n\nnamespace elements\n{\n VectorXd elements(Vector3d r, Vector3d v, double mu)\n {\n auto r_mag = r.norm();\n auto v_mag = v.norm();\n auto v_mag2 = v_mag * v_mag;\n auto h = r.cross(v);\n auto h_mag = h.norm();\n Vector3d k(0,0,1);\n auto n = k.cross(h);\n auto n_mag = n.norm();\n auto xi = v_mag2/2 - mu/r_mag;\n auto e = ((v_mag2-mu/r_mag)*r - v*r.dot(v))/mu;\n auto ecc = e.norm();\n double sma;\n if (ecc != 1) {\n sma = -mu/(2*xi);\n } else {\n sma = pow(h_mag,2)/mu;\n }\n auto inc = acos(h.z()/h_mag);\n auto node = acos(n.x()/n_mag);\n auto peri = acos(n.dot(e)/(ecc*n_mag));\n auto ano = acos(e.dot(r)/(ecc*r_mag));\n if (n.y() < 0) {\n node = M_PI*2 - node;\n }\n if (e.z() < 0) {\n peri = M_PI*2 - peri;\n }\n if (r.dot(v) < 0) {\n ano = M_PI*2 - ano;\n }\n VectorXd out(6); out << sma, ecc, inc, node, peri, ano;\n return out;\n }\n\n void benchmark(int times) {\n auto mu = 3.986004418e5;\n Vector3d r(8.59072560e+02, -4.13720368e+03, 5.29556871e+03);\n Vector3d v(7.37289205e+00, 2.08223573e+00, 4.39999794e-01);\n\n auto best = std::numeric_limits::infinity();\n auto worst = -std::numeric_limits::infinity();\n double all = 0;\n for (auto i=0; i < times; i++) {\n auto begin = std::chrono::high_resolution_clock::now();\n\n elements(r, v, mu);\n\n auto end = std::chrono::high_resolution_clock::now();\n auto current = std::chrono::duration_cast(end-begin).count()/1e9;\n all += current;\n if (current < best) {\n best = current;\n }\n if (current > worst) {\n worst = current;\n }\n }\n std::cout << \"[\" << all/times << \",\" << best << \",\" << worst << \"]\" << std::endl;\n }\n}\n", "meta": {"hexsha": "ddf84da99789fabf014a2d5b8121c3f0cb95377e", "size": 2131, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/src/elements.cpp", "max_stars_repo_name": "helgee/icatt-2016", "max_stars_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2016-05-07T19:09:15.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-06T14:31:44.000Z", "max_issues_repo_path": "cpp/src/elements.cpp", "max_issues_repo_name": "OpenAstrodynamics/benchmarks", "max_issues_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-05-05T14:36:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-08T09:18:55.000Z", "max_forks_repo_path": "cpp/src/elements.cpp", "max_forks_repo_name": "OpenAstrodynamics/benchmarks", "max_forks_repo_head_hexsha": "0fb1012b3639a6d6c53d80cd00b43b72a67b8022", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T12:13:04.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-13T14:19:13.000Z", "avg_line_length": 29.5972222222, "max_line_length": 103, "alphanum_fraction": 0.4800563116, "num_tokens": 617, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870013740061, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6611447278120284}} {"text": "/**\n * Includes\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"string.h\"\n/**\n * Compiler const\n */\n#define deflationMethod 1\n#define deflationMethod2 2\n#define mullerMethod 3\n#define laguerreMethod 4\n#define debug\n\nnamespace po = boost::program_options;\nnamespace anpi {\n\t/**\n\t * Deflation class\n\t */\n\ttemplate class deflation {\n\t\tpublic :\n\t\t\t/**\n\t\t\t * Deflation class operator () overload\n\t\t\t * @param poly: the polynomial array it can be almost any numerical type.\n\t\t\t * @param root: a known root of the polynomial, has to be the same type as poly.\n\t\t\t * @param order: the size of the polynomial -1, has to be a int.\n\t\t\t * @return\n\t\t\t */\n\t\t\tinline std::vector operator () ( std::vector& poly, T& root, T& res, int order) {\n\t\t\t\tres =poly[order];\n\t\t\t\tpoly[order]=0;\n\t\t\t\t#ifdef debug\n\t\t\t\t\tstd::cout << \"Deflation method started.\" << std::endl;\n\t\t\t\t#endif\n\t\t\t\tfor (int i=order-1;i>=0;i--){\n\t\t\t\t\tT s = poly[i];\n\t\t\t\t\tpoly[i]=res;\n\t\t\t\t\tres=s+res*root;\n\t\t\t\t\tstd::cout << poly[i] << \"x^\" << i;\n\t\t\t\t\tif(i!=0) std::cout << \" + \";\n\t\t\t\t}\n\t\t\t\tstd::cout << \"\\n\";\n\t\t\t\t#ifdef debug\n\t\t\t\t\tstd::cout << \"Deflation method ended.\" << std::endl;\n\t\t\t\t#endif\n\t\t\t\treturn poly;\n\t\t\t}\n\t};\n\t/**\n\t * Deflation2 class, for the case that both complex conjugate roots have to be deleted \n\t */\n\ttemplate class deflation2 {\n\t\tpublic :\n\t\t\t/**\n\t\t\t * Deflation2 class operator () overload\n\t\t\t * @param poly: the polynomial array, has to be a complex type.\n\t\t\t * @param root: a known root of the polynomial, has to be the same type as poly.\n\t\t\t * @param order: the size of the polynomial -1, has to be a int.\n\t\t\t * @return\n\t\t\t */\n\t\t\tinline std::vector operator () (std::vector& poly, T& root, T& res, int order) {\n\t\t\t\tres =poly[order];\n\t\t\t\tpoly[order]=0;\n\t\t\t\t#ifdef debug\n\t\t\t\t\tstd::cout << \"Deflation method 2 started.\" << std::endl;\n\t\t\t\t#endif\n\t\t\t\tfor (int i=order-1;i>=0;i--){\n\t\t\t\t\tT s = poly[i];\n\t\t\t\t\tpoly[i]=res;\n\t\t\t\t\tres=s+res*root;\n\t\t\t\t}\n\t\t\t\tres =poly[--order];\n\t\t\t\troot=std::conj(root);\n\t\t\t\tpoly[order]=0;\n\t\t\t\tfor (int i=order-1;i>=0;i--){\n\t\t\t\t\tT s = poly[i];\n\t\t\t\t\tpoly[i]=res;\n\t\t\t\t\tres=s+res*root;\n\t\t\t\t\tstd::cout << poly[i] << \"x^\" << i;\n\t\t\t\t\tif(i!=0) std::cout << \" + \";\n\t\t\t\t}\n\t\t\t\tstd::cout << \"\\n\";\n\t\t\t\t#ifdef debug\n\t\t\t\t\tstd::cout << \"Deflation method 2 ended.\" << std::endl;\n\t\t\t\t#endif\n\t\t\t\treturn poly;\n\t\t\t}\n\t};\n\t/**\n\t * Muller class\n\t */\n\ttemplate \n\tclass muller{\n\t\tpublic:\n\t\t\t/**\n\t\t\t * Muller class operator () overload\n\t\t\t * @param x0: \n\t\t\t * @param x1: \n\t\t\t * @param x2: \n\t\t\t * @param coefs:\n\t\t\t * @param max:\n\t\t\t * @param pTolerance:\n\t\t\t * @return\n\t\t\t */\n\t\t\tstd::vector > operator()(T x0, T x1, T x2,const std::vector< std::complex >& coefs,unsigned int max, double pTolerance) {\n\t\t\tstd::vector > res;\n\t\t\tstd::vector > q = coefs;\n\t\t\tstd::complex z;\n\t\t\twhile (q.size() > 2) {\n\t\t\t z = polinom_zero(x0, x1, x2, q, max, pTolerance);\n\t\t\t //z = polinom_zero(p, z);\n\t\t\t q = horner(q, z);\n\t\t\t res.push_back(z);\n\t\t\t }\n\t\t\t res.push_back(-q[0] / q[1]);\n\t\t\t return res;\n\t\t\t} \n\n\t\t\tstd::complex evaluatePol(std::vector >& coef, std::complex * x){\n\t\t\t\tstd::complex result = 0;\n\t\t\t\tfor (int ite = 0; ite > horner(const std::vector > &a, std::complex x0) {\n\t\t\t int n = a.size();\n\t\t\t std::vector > b(std::max(1, n - 1),0);\n\n\t\t\t for(int i = n - 1; i > 0; i--)\n\t\t\t b[i - 1] = a[i] + (i < n - 1 ? b[i] * x0 : 0);\n\t\t\t return b;\n\t\t\t}\n\n\t\t\tstd::complex polinom_zero (T x0, T x1, T x2,std::vector< std::complex >& coefs,unsigned int max, double pTolerance){\n\t\t\t\tstd::complex xi0, xi1, xi2,xi3, h0,h1,q0,q1,A, B, C,result, tmp1, tmp2;\n\t\t\t\tlong double err;\n\t\t\t\txi0=x0;\n\t\t\t\txi1=x1;\n\t\t\t\txi2=x2;\n\t\t\t\terr=2;\n\t\t\t\ttmp1=0;\n\t\t\t\ttmp2=0;\n\t\t\t\tint ite =0;\n\t\t\t\twhile(ite= pTolerance){\n\n\n\t\t\t\t\th0=xi1-xi0;\n\t\t\t\t\th1=xi2-xi1;\n\t\t\t\t\tq0=(evaluatePol(coefs, &xi1)-evaluatePol(coefs, &xi0))/h0;\n\t\t\t\t\tq1=(evaluatePol(coefs, &xi2)-evaluatePol(coefs, &xi1))/h1;\n\t\t\t\t\t\n\t\t\t\t\tA=(q1-q0)/(h1+h0);\n\t\t\t\t\tB=A*h1+q1;\n\t\t\t\t\tC=(evaluatePol(coefs, &xi2));\n\t\t\t\t\n\t\t\t\t\ttmp1=xi2+((std::complex )-2*C)/(B+std::sqrt(B*B-(std::complex )4*A*C));\n\t\t\t\t\ttmp2=xi2+((std::complex )-2*C)/(B-std::sqrt(B*B-(std::complex )4*A*C));\n\t\t\t\t\t\n\t\t\t\t\tif(B.real()>=0)\n\t\t\t\t\t\txi3=tmp1;\n\t\t\t\t\telse\n\t\t\t\t\t\txi3=tmp2;\n\t\t\t\t\terr=std::abs((((xi3-xi2)/xi3)).real())*100;\n\n\t\t\t\t\txi0=xi1;\n\t\t\t\t\txi1=xi2;\n\t\t\t\t\txi2=xi3;\n\t\t\t\t\tite++;\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\treturn xi3;\n\t\t\t};\n\t\t\n\t};\n\ttypedef std::complex cdouble;\n\ttypedef std::vector polyn;\n\t/**\n\t * Laguerre class\n\t */\n\tstd::pair horner(const polyn &a, cdouble x0) {\n\t int n = a.size();\n\t polyn b = polyn(std::max(1, n - 1));\n\n\t for(int i = n - 1; i > 0; i--)\n\t b[i - 1] = a[i] + (i < n - 1 ? b[i] * x0 : 0);\n\t return make_pair(b, a[0] + b[0] * x0);\n\t}\n\n\tcdouble eval(const polyn &p, cdouble x) {\n\t return horner(p, x).second;\n\t}\n\n\tpolyn derivative(const polyn &p) {\n\t int n = p.size();\n\t polyn r = polyn(std::max(1, n - 1));\n\t for(int i = 1; i < n; i++)\n\t r[i - 1] = p[i] * cdouble(i);\n\t return r;\n\t}\n\n\tconst double EPS = 1e-9;\n\n\tint cmp(cdouble x, cdouble y) {\n\t double diff = abs(x) - abs(y);\n\t return diff < -EPS ? -1 : (diff > EPS ? 1 : 0);\n\t}\n\n\tcdouble find_one_root(const polyn &p0, cdouble x) {\n\t int n = p0.size() - 1;\n\t polyn p1 = derivative(p0);\n\t polyn p2 = derivative(p1);\n\t for (int step = 0; step < 10000; step++) {\n\t cdouble y0 = eval(p0, x);\n\t if (cmp(y0, 0) == 0) break;\n\t cdouble G = eval(p1, x) / y0;\n\t cdouble H = G * G - eval(p2, x) - y0;\n\t cdouble R = sqrt(cdouble(n - 1) * (H * cdouble(n) - G * G));\n\t cdouble D1 = G + R;\n\t cdouble D2 = G - R;\n\t cdouble a = cdouble(n) / (cmp(D1, D2) > 0 ? D1 : D2);\n\t x -= a;\n\t if (cmp(a, 0) == 0) break;\n\t }\n\t return x;\n\t}\n\n\tstd::vector find_all_roots(const polyn &p) {\n\t std::vector res;\n\t polyn q = p;\n\t while (q.size() > 2) {\n\t cdouble z(rand() / double(RAND_MAX), rand() / double(RAND_MAX));\n\t z = find_one_root(q, z);\n\t z = find_one_root(p, z);\n\t q = horner(q, z).first;\n\t res.push_back(z);\n\t }\n\t res.push_back(-q[0] / q[1]);\n\t return res;\n\t}\n}\n\n/**\n * Auxiliar method for the main\n * @param method Which method will be run (number from 1 to 4 or none for default).\n * @param poly The polynomial that the method will be run in.\n * @param order The orther of the polynomial.\n * @param root The root of the polinomial (use for deflation).\n * @param X The positions where the method will be started.\n * @param maxIt The max times the method will be run(muller).\n * @param tolerance The tolerance the method will have(muller).\n * @param singlePrecision Single precision flag.\n * @param polish Polish flag.\n */\nvoid mainAux(unsigned short method, std::vector& poly, short order, double root, std::vector X, int maxIt=50, double tolerance=0.00001, bool singlePrecision=0,bool polish=0){\n\tif(poly.size()==0 and method!=0){\n\t\tstd::cout << \"To use a method you need to enter a polynomial with the option --polynomial and the coeficients.\"<< std::endl;\n\t\treturn;\n\t}\n\tswitch(method){\n\t\tcase deflationMethod: //Deflation\n\t\t{\n\t\t\tif(singlePrecision){\n\t\t\t\tstd::complex res =*(new std::complex(0,0));\n\t\t\t\tstd::complex roots=*(new std::complex(root,0));\n\t\t\t\tstd::vector > polys;\n\t\t\t\tanpi::deflation > defla;\n\t\t\t\tfor(int i=0; i tmp=*(new std::complex(poly[i],0));\n\t\t\t\t\tpolys.push_back(tmp);\n\t\t\t\t}\n\t\t\t\tdefla(polys,roots, res, (int)order);\n\t\t\t}else{\n\t\t\t\tstd::complex res =*(new std::complex(0,0));\n\t\t\t\tstd::complex rootd=*(new std::complex(root,0));\n\t\t\t\tstd::vector > polyd;\n\t\t\t\tanpi::deflation > defla;\n\t\t\t\tfor(int i=0; i tmp=*(new std::complex(poly[i],0));\n\t\t\t\t\tpolyd.push_back(tmp);\n\t\t\t\t}\n\t\t\t\tdefla(polyd,rootd, res, (int)order);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase deflationMethod2: //Deflation2\n\t\t{\n\t\t\tif(singlePrecision){\n\t\t\t\tstd::complex res =*(new std::complex(0,0));\n\t\t\t\tstd::complex roots=*(new std::complex(root,0));\n\t\t\t\tstd::vector > polys;\n\t\t\t\tanpi::deflation2 > defla;\n\t\t\t\tfor(int i=0; i tmp=*(new std::complex(poly[i],0));\n\t\t\t\t\tpolys.push_back(tmp);\n\t\t\t\t}\n\t\t\t\tdefla(polys,roots, res, (int)order);\n\t\t\t}else{\n\t\t\t\tstd::complex res =*(new std::complex(0,0));\n\t\t\t\tstd::complex rootd=*(new std::complex(root,0));\n\t\t\t\tstd::vector > polyd;\n\t\t\t\tanpi::deflation2 > defla;\n\t\t\t\tfor(int i=0; i tmp=*(new std::complex(poly[i],0));\n\t\t\t\t\tpolyd.push_back(tmp);\n\t\t\t\t}\n\t\t\t\tdefla(polyd,rootd, res, (int)order);\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase mullerMethod: //Muller\n\t\t{\n\n\t\t\tif(X.size()!=3){\n\t\t\t\tstd::cout << \"Three positions has to be set to use this method. Use the option: --position and the positions space separated.\" << std::endl;\n\t\t\t\treturn ;\n\t\t\t}\n\t\t\tif(singlePrecision){\n\t\t\t\tanpi::muller mull;\n\t\t\t\tstd::vector > polyd;\n\t\t\t\tfor(int i=0; i tmp=*(new std::complex(poly[i],0));\n\t\t\t\t\tpolyd.push_back(tmp);\n\t\t\t\t}\n\t\t\t\tstd::vector > res;\n\t\t\t\tres = mull((float)X[0], \n\t\t\t\t\t\t\t\t(float)X[1], \n\t\t\t\t\t\t\t\t(float)X[2], \n\t\t\t\t\t\t\t\tpolyd, \n\t\t\t\t\t\t\t\t(unsigned int)maxIt,\n\t\t\t\t\t\t\t\t(float)tolerance);\n\t\t\t\tfor(int i = 0; i < res.size(); i++){\n\t\t\t\t\tstd::cout<< \"x\" << i <<\": \" << res[i] << std::endl; \n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}else{\n\t\t\t\tanpi::muller mull;\n\t\t\t\tstd::vector > polyd;\n\t\t\t\tfor(int i=0; i tmp=*(new std::complex(poly[i],0));\n\t\t\t\t\tpolyd.push_back(tmp);\n\t\t\t\t}\n\t\t\t\tstd::vector > res;\n\t\t\t\tres = mull((double)X[0], \n\t\t\t\t\t\t\t\t(double)X[1], \n\t\t\t\t\t\t\t\t(double)X[2], \n\t\t\t\t\t\t\t\tpolyd, \n\t\t\t\t\t\t\t\t(unsigned int)maxIt,\n\t\t\t\t\t\t\t\t(double)tolerance);\n\t\t\t\tfor(int i = 0; i < res.size(); i++){\n\t\t\t\t\tstd::cout<< \"x\" << i <<\": \" << res[i] << std::endl; \n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcase laguerreMethod:\n\t\t{\n\t\t\tanpi::polyn p;\n\t\t\t// x^3 - 8x^2 - 13x + 140 = (x+4)(x-5)(x-7)\n\t\t\t//X**3 + 2x**2 -109x -110 = (x+11)(x+8)(x-4)\n\t\t\tfor(int i=0; i roots = anpi::find_all_roots(p);\n\n\t\t\tfor(size_t i = 0; i < roots.size(); i++) {\n\t\t\t\tif (abs(roots[i].real()) < anpi::EPS) roots[i] -= anpi::cdouble(roots[i].real(), 0);\n\t\t\t\t\tif (abs(roots[i].imag()) < anpi::EPS) roots[i] -= anpi::cdouble(0, roots[i].imag());\n\t\t\t\t\t\tstd::cout << std::setprecision(3) << roots[i] << std::endl;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault:\n\t\t{\n\t\t\t//Deflation method\n\t\t\tstd::cout << \"Deflation of 1x^3+3x^2+4x+12, with 2i as root.\" < > polyd;\n\t\t\tstd::complex tmp= *(new std::complex(12,0));\n\t\t\tpolyd.push_back(tmp);\n\t\t\ttmp= *(new std::complex(4,0));\n\t\t\tpolyd.push_back(tmp);\n\t\t\ttmp= *(new std::complex(3,0));\n\t\t\tpolyd.push_back(tmp);\n\t\t\ttmp= *(new std::complex(1,0));\n\t\t\tpolyd.push_back(tmp);\n\t\t\tstd::complex rootd =*(new std::complex(0,2));\n\t\t\tstd::complex res =*(new std::complex(0,0)); \n\t\t\tanpi::deflation > defla;\n\t\t\tdefla(polyd,rootd, res, (int)order);\n\t\t\t//Deflation method 2\n\t\t\tstd::cout << \"Deflation method 2 of 1x^3+3x^2+4x+12, with 2i as root.\" <(0,2));\n\t\t\tres =*(new std::complex(0,0)); \n\t\t\tanpi::deflation2 > defla2;\n\t\t\tdefla2(polyd,rootd, res, (int)order);\n\t\t\t//Muller method\n\t\t\tstd::cout << \"Muller method roots of 1x^3+2x^2+-5x+-6.\" < mull;\n\t\t\tstd::vector >coefs;\n\t\t\ttmp=-6;\n\t\t\tcoefs.push_back(tmp);\n\t\t\ttmp=-5;\n\t\t\tcoefs.push_back(tmp);\n\t\t\ttmp=2;\n\t\t\tcoefs.push_back(tmp);\n\t\t\ttmp=1;\n\t\t\tcoefs.push_back(tmp);\n\t\t\tstd::vector > result;\n\t\t\tresult = mull((double)-4, \n\t\t\t\t\t\t\t(double)-2, \n\t\t\t\t\t\t\t(double)0, \n\t\t\t\t\t\t\tcoefs, \n\t\t\t\t\t\t\t(unsigned int)50,\n\t\t\t\t\t\t\t(long double)0.000001);\n\t\t\tfor(int i = 0; i < result.size(); i++){\n\t\t\t\tstd::cout<< \"x\" << i <<\": \" << result[i] << std::endl; \n\t\t\t}\n\t\t\t\n\t\t\t//Laguerre method\n\t\t\tstd::cout << \"Laguerre roots of 1x^3-2x^2+-109x+-110.\" < roots = anpi::find_all_roots(p);\n\n\t\t\tfor(size_t i = 0; i < roots.size(); i++) {\n\t\t\t\tif (abs(roots[i].real()) < anpi::EPS) roots[i] -= anpi::cdouble(roots[i].real(), 0);\n\t\t\t\t\tif (abs(roots[i].imag()) < anpi::EPS) roots[i] -= anpi::cdouble(0, roots[i].imag());\n\t\t\t\t\t\tstd::cout << std::setprecision(3) << roots[i] << std::endl;\n\t\t\t}\n\t\t}\n\t\t\n\t}\n}\n\n/**\n * Main method, runs all the methods with a default or you can enter options\n * @param Uses program options, call the program plus --help to see detailed description\n * @return the return is depending which method is called\n */\nint main(int argc, char** argv){\n\tusing boost::lexical_cast;\n\tusing boost::bad_lexical_cast;\n\t//Default values for the methods:\n\tshort order=3;\n\tunsigned short method=0;\n\tdouble tolerance=0.000001;\n\tint maxIt=50;\n\tstd::vector poly;\n\tdouble root;\n\tstd::vector position;\n\tbool polish=0;\n\tbool singlePrecision=0;\n\t//Program options definitions\n\tpo::options_description description(\"Project1 Usage\");\n\tdescription.add_options()\n\t(\"help\", \"Display this help message\")\n\t(\"polynomial\", po::value >(&poly)->multitoken(), \"The polynomial that the program will use, just add the coeficients space separated.\")\n\t(\"position\", po::value >(&position)->multitoken(), \"The positions to start the method space separated.\")\n\t(\"root\", po::value(&root), \"The root to find.\")\n\t(\"order\", po::value(&order), \"The order of the polynomial.\")\n\t(\"muller\", \"Use this option to use the muller method.\")\n\t(\"deflation\", \"Use this option to use deflation method.\")\n\t(\"deflation2\", \"Use this option to use deflation2 method.\")\n\t(\"laguerre\", \"Use this option to use laguerre method.\")\n\t(\"polish\", \"Use this option to polish the roots.\")\n\t(\"tolerance\", po::value(&tolerance), \"The order of the polynomial.\")\n\t(\"maxIterations\", po::value(&maxIt), \"The order of the polynomial.\")\n\t(\"singlePrecision\", \"Use this to set the methods to double singlePrecision, otherwise double precision will be used.\");\n\tpo::positional_options_description p;\n\tp.add(\"file\", -1);\n\tpo::variables_map vm;\n\t//Try to use the entered options\n\ttry {\n\t\tpo::store(po::parse_command_line(argc, argv, description, po::command_line_style::unix_style ^ po::command_line_style::allow_short), vm);\t\tpo::notify(vm);\n\t\tif(vm.count(\"help\")){\n\t\t\tstd::cout << description;\n\t\t\treturn 0;\n\t\t}\n\t\tif(vm.count(\"order\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Polynomial order changed to: \" << order << std::endl;\n\t\t\t#endif\n\t\t\tif(order<0){\n\t\t\t\tstd::cout << \"The order has to be a positive number.\" << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tif(vm.count(\"tolerance\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"The tolerance for the method will be: \" << tolerance << std::endl;\n\t\t\t#endif\n\t\t\tif(tolerance<0){\n\t\t\t\tstd::cout << \"The tolerance has to be a positive number.\" << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t}\n\t\tif(vm.count(\"maxIterations\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Max iterations will be changed to: \" << maxIt << std::endl;\n\t\t\t#endif\n\t\t\tif(maxIt<0){\n\t\t\t\tstd::cout << \"The iterations has to be a positive number.\" << std::endl;\n\t\t\t\treturn -1;\n\t\t\t}\n\n\t\t}\n\t\tif(vm.count(\"singlePrecision\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Polynomial order changed to: \" << singlePrecision << std::endl;\n\t\t\t#endif\n\t\t\tsinglePrecision = 1;\n\t\t}\n\t\tif(vm.count(\"deflation\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Deflation method will be used.\" << std::endl;\n\t\t\t#endif\n\t\t\tmethod = deflationMethod;\n\t\t}\n\t\tif(vm.count(\"deflation2\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Deflation method 2 will be used.\" << std::endl;\n\t\t\t#endif\n\t\t\tmethod = deflationMethod2;\n\t\t}\n\t\tif(vm.count(\"muller\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Muller method will be used.\" << std::endl;\n\t\t\t#endif\n\t\t\tmethod = mullerMethod;\n\t\t}\n\t\tif(vm.count(\"laguerre\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"Laguerre method will be used.\" << std::endl;\n\t\t\t#endif\n\t\t\tmethod = laguerreMethod;\n\t\t}\n\t\tif(vm.count(\"poly\")){\n\t\t\t#ifdef debug\n\t\t\t\tstd::cout << \"A custom polynomial will be used. With size: \" <\n#ifdef DEBUG\n #include \n#endif\n#include \n#include \"pca.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\nint Pca::Calculate(vector &x, \n const unsigned int &nrows, \n const unsigned int &ncols, \n const bool is_corr, \n const bool is_center, \n const bool is_scale) {\n _ncols = ncols;\n _nrows = nrows;\n _is_corr = is_corr;\n _is_center = is_center;\n _is_scale = is_scale;\n if (x.size()!= _nrows*_ncols) {\n return -1;\n }\n if ((1 == _ncols) || (1 == nrows)) {\n return -1;\n }\n // Convert vector to Eigen 2-dimensional matrix\n //Map _xXf(x.data(), _nrows, _ncols);\n _xXf.resize(_nrows, _ncols);\n for (unsigned int i = 0; i < _nrows; ++i) {\n for (unsigned int j = 0; j < _ncols; ++j) {\n _xXf(i, j) = x[j + i*_ncols];\n }\n }\n // Mean and standard deviation for each column\n VectorXf mean_vector(_ncols);\n mean_vector = _xXf.colwise().mean();\n VectorXf sd_vector(_ncols);\n unsigned int zero_sd_num = 0;\n float denom = static_cast((_nrows > 1)? _nrows - 1: 1);\n for (unsigned int i = 0; i < _ncols; ++i) {\n VectorXf curr_col = VectorXf::Constant(_nrows, mean_vector(i)); // mean(x) for column x\n curr_col = _xXf.col(i) - curr_col; // x - mean(x)\n curr_col = curr_col.array().square(); // (x-mean(x))^2 \n sd_vector(i) = sqrt((curr_col.sum())/denom);\n if (0 == sd_vector(i)) {\n zero_sd_num++;\n }\n }\n // If colums with sd == 0 are too many,\n // don't continue calculations\n if (1 > _ncols-zero_sd_num) {\n return -1;\n }\n // Delete columns where sd == 0\n MatrixXf tmp(_nrows, _ncols-zero_sd_num);\n VectorXf tmp_mean_vector(_ncols-zero_sd_num);\n unsigned int curr_col_num = 0;\n for (unsigned int i = 0; i < _ncols; ++i) {\n if (0 != sd_vector(i)) {\n tmp.col(curr_col_num) = _xXf.col(i);\n tmp_mean_vector(curr_col_num) = mean_vector(i);\n curr_col_num++;\n } else {\n _eliminated_columns.push_back(i);\n }\n }\n _ncols -= zero_sd_num;\n _xXf = tmp;\n mean_vector = tmp_mean_vector;\n tmp.resize(0, 0); tmp_mean_vector.resize(0);\n // Shift to zero\n if (true == _is_center) {\n for (unsigned int i = 0; i < _ncols; ++i) {\n _xXf.col(i) -= VectorXf::Constant(_nrows, mean_vector(i));\n }\n }\n // Scale to unit variance\n if ( (false == _is_corr) || (true == _is_scale)) {\n for (unsigned int i = 0; i < _ncols; ++i) {\n _xXf.col(i) /= sqrt(_xXf.col(i).array().square().sum()/denom);\n }\n }\n #ifdef DEBUG\n cout << \"\\nScaled matrix:\\n\";\n cout << _xXf << endl;\n cout << \"\\nMean before scaling:\\n\" << mean_vector.transpose();\n cout << \"\\nStandard deviation before scaling:\\n\" << sd_vector.transpose();\n #endif\n // When _nrows < _ncols then svd will be used.\n // If corr is true and _nrows > _ncols then will be used correlation matrix\n // (TODO): What about covariance?\n if ( (_nrows < _ncols) || (false == _is_corr)) { // Singular Value Decomposition is on\n _method = \"svd\";\n JacobiSVD svd(_xXf, ComputeThinV);\n VectorXf eigen_singular_values = svd.singularValues();\n VectorXf tmp_vec = eigen_singular_values.array().square();\n float tmp_sum = tmp_vec.sum();\n tmp_vec /= tmp_sum;\n // PC's standard deviation and\n // PC's proportion of variance\n _kaiser = 0;\n unsigned int lim = (_nrows < _ncols)? _nrows : _ncols;\n for (unsigned int i = 0; i < lim; ++i) {\n _sd.push_back(eigen_singular_values(i)/sqrt(denom));\n if (_sd[i] >= 1) {\n _kaiser = i + 1;\n }\n _prop_of_var.push_back(tmp_vec(i));\n }\n #ifdef DEBUG\n cout << \"\\n\\nStandard deviations for PCs:\\n\";\n copy(_sd.begin(), _sd.end(),std::ostream_iterator(std::cout,\" \")); \n cout << \"\\n\\nKaiser criterion: PC #\" << _kaiser << endl;\n #endif\n tmp_vec.resize(0);\n // PC's cumulative proportion\n _thresh95 = 1;\n _cum_prop.push_back(_prop_of_var[0]); \n for (unsigned int i = 1; i < _prop_of_var.size(); ++i) {\n _cum_prop.push_back(_cum_prop[i-1]+_prop_of_var[i]);\n if (_cum_prop[i] < 0.95) {\n _thresh95 = i+1;\n }\n }\n #ifdef DEBUG\n cout << \"\\nCumulative proportion:\\n\";\n copy(_cum_prop.begin(), _cum_prop.end(),std::ostream_iterator(std::cout,\" \")); \n cout << \"\\n\\nThresh95 criterion: PC #\" << _thresh95 << endl;\n #endif\n // Scores\n MatrixXf eigen_scores = _xXf * svd.matrixV();\n #ifdef DEBUG\n cout << \"\\n\\nRotated values (scores):\\n\" << eigen_scores;\n #endif\n _scores.reserve(lim*lim);\n for (unsigned int i = 0; i < lim; ++i) {\n for (unsigned int j = 0; j < lim; ++j) {\n _scores.push_back(eigen_scores(i, j));\n }\n }\n eigen_scores.resize(0, 0);\n #ifdef DEBUG\n cout << \"\\n\\nScores in vector:\\n\";\n copy(_scores.begin(), _scores.end(),std::ostream_iterator(std::cout,\" \")); \n cout << \"\\n\"; \n #endif\n } else { // COR OR COV MATRICES ARE HERE\n _method = \"cor\";\n // Calculate covariance matrix\n MatrixXf eigen_cov; // = MatrixXf::Zero(_ncols, _ncols);\n VectorXf sds;\n // (TODO) Should be weighted cov matrix, even if is_center == false\n eigen_cov = (1.0 /(_nrows/*-1*/)) * _xXf.transpose() * _xXf;\n sds = eigen_cov.diagonal().array().sqrt();\n MatrixXf outer_sds = sds * sds.transpose();\n eigen_cov = eigen_cov.array() / outer_sds.array();\n outer_sds.resize(0, 0);\n // ?If data matrix is scaled, covariance matrix is equal to correlation matrix\n #ifdef DEBUG\n cout << eigen_cov << endl;\n #endif\n EigenSolver edc(eigen_cov);\n VectorXf eigen_eigenvalues = edc.eigenvalues().real();\n #ifdef DEBUG\n cout << endl << eigen_eigenvalues.transpose() << endl;\n #endif\n MatrixXf eigen_eigenvectors = edc.eigenvectors().real();\t\n #ifdef DEBUG\n cout << endl << eigen_eigenvectors << endl;\n #endif\n // The eigenvalues and eigenvectors are not sorted in any particular order.\n // So, we should sort them\n typedef pair eigen_pair;\n vector ep;\t\n for (unsigned int i = 0 ; i < _ncols; ++i) {\n\t ep.push_back(make_pair(eigen_eigenvalues(i), i));\n }\n sort(ep.begin(), ep.end()); // Ascending order by default\n // Sort them all in descending order\n MatrixXf eigen_eigenvectors_sorted = MatrixXf::Zero(eigen_eigenvectors.rows(), eigen_eigenvectors.cols());\n VectorXf eigen_eigenvalues_sorted = VectorXf::Zero(_ncols);\n int colnum = 0;\n int i = ep.size()-1;\n for (; i > -1; i--) {\n eigen_eigenvalues_sorted(colnum) = ep[i].first;\n eigen_eigenvectors_sorted.col(colnum++) += eigen_eigenvectors.col(ep[i].second);\n }\n #ifdef DEBUG\n cout << endl << eigen_eigenvalues_sorted.transpose() << endl;\n cout << endl << eigen_eigenvectors_sorted << endl;\n #endif \n // We don't need not sorted arrays anymore\n eigen_eigenvalues.resize(0);\n eigen_eigenvectors.resize(0, 0);\n \n _sd.clear(); _prop_of_var.clear(); _kaiser = 0;\n float tmp_sum = eigen_eigenvalues_sorted.sum();\n for (unsigned int i = 0; i < _ncols; ++i) {\n _sd.push_back(sqrt(eigen_eigenvalues_sorted(i)));\n if (_sd[i] >= 1) {\n _kaiser = i + 1;\n }\n _prop_of_var.push_back(eigen_eigenvalues_sorted(i)/tmp_sum);\n }\n #ifdef DEBUG\n cout << \"\\nStandard deviations for PCs:\\n\";\n copy(_sd.begin(), _sd.end(), std::ostream_iterator(std::cout,\" \")); \n cout << \"\\nProportion of variance:\\n\";\n copy(_prop_of_var.begin(), _prop_of_var.end(), std::ostream_iterator(std::cout,\" \")); \n cout << \"\\nKaiser criterion: PC #\" << _kaiser << endl;\n #endif\n // PC's cumulative proportion\n _cum_prop.clear(); _thresh95 = 1;\n _cum_prop.push_back(_prop_of_var[0]);\n for (unsigned int i = 1; i < _prop_of_var.size(); ++i) {\n _cum_prop.push_back(_cum_prop[i-1]+_prop_of_var[i]);\n if (_cum_prop[i] < 0.95) {\n _thresh95 = i+1;\n }\n } \n #ifdef DEBUG\n cout << \"\\n\\nCumulative proportions:\\n\";\n copy(_cum_prop.begin(), _cum_prop.end(), std::ostream_iterator(std::cout,\" \")); \n cout << \"\\n\\n95% threshold: PC #\" << _thresh95 << endl;\n #endif\n // Scores for PCA with correlation matrix\n // Scale before calculating new values\n for (unsigned int i = 0; i < _ncols; ++i) {\n _xXf.col(i) /= sds(i);\n }\n sds.resize(0);\n MatrixXf eigen_scores = _xXf * eigen_eigenvectors_sorted;\n #ifdef DEBUG\n cout << \"\\n\\nRotated values (scores):\\n\" << eigen_scores;\n #endif\n _scores.clear();\n _scores.reserve(_ncols*_nrows);\n for (unsigned int i = 0; i < _nrows; ++i) {\n for (unsigned int j = 0; j < _ncols; ++j) {\n _scores.push_back(eigen_scores(i, j));\n }\n }\n eigen_scores.resize(0, 0);\n #ifdef DEBUG\n cout << \"\\n\\nScores in vector:\\n\";\n copy(_scores.begin(), _scores.end(), std::ostream_iterator(std::cout,\" \")); \n cout << \"\\n\"; \n #endif\n }\n\n return 0;\n}\nstd::vector Pca::sd(void) { return _sd; }; \nstd::vector Pca::prop_of_var(void) {return _prop_of_var; };\nstd::vector Pca::cum_prop(void) { return _cum_prop; };\nstd::vector Pca::scores(void) { return _scores; };\nstd::vector Pca::eliminated_columns(void) { return _eliminated_columns; }\nstring Pca::method(void) { return _method; }\nunsigned int Pca::kaiser(void) { return _kaiser; };\nunsigned int Pca::thresh95(void) { return _thresh95; };\nunsigned int Pca::ncols(void) { return _ncols; }\nunsigned int Pca::nrows(void) { return _nrows; }\nbool Pca::is_scale(void) { return _is_scale; }\nbool Pca::is_center(void) { return _is_center; }\nPca::Pca(void) {\n _nrows = 0;\n _ncols = 0;\n // Variables will be scaled by default\n _is_center = true;\n _is_scale = true; \n // By default will be used singular value decomposition\n _method = \"svd\";\n _is_corr = false;\n\n _kaiser = 0;\n _thresh95 = 1;\n}\nPca::~Pca(void) { \n _xXf.resize(0, 0);\n _x.clear();\n}\n\n", "meta": {"hexsha": "60ee5a4111abe3d42fce6ceb34a27b548878efa5", "size": 10093, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pca.cpp", "max_stars_repo_name": "vigor-ish/riskjs", "max_stars_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-08-31T08:33:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-23T04:26:16.000Z", "max_issues_repo_path": "src/pca.cpp", "max_issues_repo_name": "vigor-ish/riskjs", "max_issues_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-09-02T02:33:13.000Z", "max_issues_repo_issues_event_max_datetime": "2021-09-02T02:33:13.000Z", "max_forks_repo_path": "src/pca.cpp", "max_forks_repo_name": "vigor-ish/riskjs", "max_forks_repo_head_hexsha": "6f0aa646821272f64959553ea042819b74a21efc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-11-19T18:21:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-23T04:26:17.000Z", "avg_line_length": 34.9238754325, "max_line_length": 110, "alphanum_fraction": 0.6161696225, "num_tokens": 3117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467801752451, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6611294328722247}} {"text": "#include \"CEGO/CEGO.hpp\"\n#include \n#include \n\nstd::atomic_size_t Ncalls(0);\n\nusing CEGO::EArray;\n\nauto linfit_coeffs(const EArray& x, const EArray& y, const std::size_t Nnum, const std::size_t Nden) {\n Eigen::MatrixXd A(x.size(), Nnum + Nden);\n Eigen::MatrixXd b = y;\n for (auto i = 0; i < Nnum; ++i) {\n A.col(i) = x.pow(i);\n }\n for (auto i = 0; i < Nden; ++i) {\n A.col(i + Nnum) = -y*x.pow(i+1);\n }\n auto c = A.colPivHouseholderQr().solve(b).eval();\n auto ycheck = (A * c).eval();\n return c;\n}\n\nclass RatPoly {\npublic:\n EArray m_T, B2, m_LHS, m_x;\n std::size_t m_Nnum, m_Nden;\n \n RatPoly(const std::size_t Nnum, const std::size_t Nden) : m_Nnum(Nnum), m_Nden(Nden)\n {\n // Data from second virial coefficient from Garberoglio for water, DOI: 10.1039/C8FD00092A\n m_T.resize(21);\n B2.resize(21);\n m_T << 200, 225, 250, 273.15, 300, 325, 350, 375, 400, 450, 500, 550, 600, 700, 800, 900, 1000, 1250, 1500, 1750, 2000;\n B2 << -2.3825E-02, -8.6200E-03, -3.9850E-03, -2.2590E-03, -1.3301E-03, -8.9350E-04, -6.3650E-04, -4.7840E-04, -3.7240E-04, -2.4480E-04, -1.7240E-04, -1.2830E-04, -9.8700E-05, -6.2460E-05, -4.1280E-05, -2.7580E-05, -1.8550E-05, -5.0400E-06, 2.0800E-06, 6.2000E-06, 8.8800E-06;\n m_LHS = B2;\n m_x = 200/m_T;\n //solve_linear();\n }\n void solve_linear() {\n std::cout << \"----------- LINEAR --------- \" << std::endl;\n Eigen::ArrayXi indices = Eigen::ArrayXi::LinSpaced(m_Nnum + m_Nden, 0L, static_cast(m_x.size()-1));\n EArray xx = m_x(indices), yy = m_LHS(indices);\n EArray c = linfit_coeffs(xx, yy, m_Nnum, m_Nden);\n std::cout << c << std::endl;\n double o = objective(c);\n std::cout << \"objective: \" << o << std::endl;\n EArray devs = abs_rel_deviations(c).eval() * 100;\n std::cout << \"relative(%) devs: \" << devs << std::endl;\n }\n template EArray eval_RHS(const EArray& x, const EArray &c) {\n EArray num = EArray::Zero(x.size()), \n den = EArray::Zero(x.size());\n assert(m_Nnum + m_Nden == c.size());\n for (auto i = 0; i < m_Nnum; ++i) {\n num += c[i]*x.pow(i);\n }\n for (auto i = 0; i < m_Nden; ++i) {\n den += c[m_Nnum+i]*x.pow(i+1);\n }\n return num/(1+den);\n }\n template TYPE objective(const EArray& c) {\n return ((eval_RHS(m_x, c) - m_LHS)/m_LHS).square().sum();\n }\n template EArray abs_rel_deviations(const EArray& c) {\n return ((eval_RHS(m_x, c) - m_LHS)/m_LHS).eval();\n }\n double objective(const CEGO::AbstractIndividual *pind) {\n const auto &c = dynamic_cast*>(pind)->get_coeff_array();\n return objective(c);\n } \n};\n\nint do_one()\n{\n //std::srand((unsigned int)time(0));\n std::size_t Nnum = 3, Nden = 5;\n\n // Construct the bounds\n std::vector bounds;\n for (auto i = 0; i < Nnum; ++i) { \n bounds.push_back(CEGO::Bound(std::pair(-1000, 1000)));\n }\n for (auto i = 0; i < Nden; ++i){\n bounds.push_back(CEGO::Bound(std::pair(-1000, 1000))); \n } \n RatPoly rp(Nnum, Nden);\n \n auto Ncalls = 0;\n CEGO::CostFunction 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(cost_wrapper, bounds.size(), Ntotal_individuals/Nlayers, Nlayers, 3);\n layers.parallel = true;\n layers.parallel_threads = 6;\n layers.set_bounds(bounds);\n layers.set_generation_mode(CEGO::GenerationOptions::LHS);\n layers.set_builtin_evolver(CEGO::BuiltinEvolvers::differential_evolution_best1bin);\n auto f = [&rp](const CEGO::EArray& c) {return rp.objective(c); };\n auto f2 = [&rp](const CEGO::EArray>& c) {return rp.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.1;\n flags[\"CR\"] = 0.9;\n layers.set_evolver_flags(flags);\n\n std::vector best_costs; \n const double VTR = 2e-4;\n auto startTime = std::chrono::system_clock::now();\n bool success = false;\n for (auto counter = 0; counter < 15000; ++counter) {\n layers.do_generation();\n\n if (counter % 1000 == 0) {\n layers.gradient_minimizer();\n }\n \n auto [best_cost, best_coeffs] = layers.get_best();\n if (counter % 50 == 0) {\n std::cout << counter << \": best: \" << best_cost << std::endl;\n //std::cout << counter << \": best coeffs: \" << c << \"||\" << std::endl;\n //std::cout << counter << \": obj again: \" << rp.objective(c) << \"||\" << std::endl;\n }\n if (best_cost < VTR) { success = true; break; }\n }\n auto best_layer = layers.get_best();\n auto best_coeffs = std::get<1>(best_layer);\n std::cout << rp.abs_rel_deviations(best_coeffs)*100 << std::endl;\n auto endTime = std::chrono::system_clock::now();\n double elap = std::chrono::duration(endTime - startTime).count();\n std::cout << \"run:\" << elap << \" s\\n\";\n std::cout << \"NFE:\" << Ncalls << std::endl;\n return success;\n}\n\nint main() {\n int N = (CEGO::is_CI() ? 3 : 100);\n int good = 0;\n for (auto i = 0; i < N; ++i) {\n good += do_one();\n }\n std::cout << \"success:\" << good << \"/\" << N << std::endl;\n}", "meta": {"hexsha": "9b919ae4e42840db175b3c0a2773daeff8edbf0d", "size": 5745, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/fit_ratpoly_virial.cxx", "max_stars_repo_name": "usnistgov/CEGO", "max_stars_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2018-12-27T23:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-01T02:23:40.000Z", "max_issues_repo_path": "src/fit_ratpoly_virial.cxx", "max_issues_repo_name": "usnistgov/CEGO", "max_issues_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-03-17T19:27:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-17T15:27:44.000Z", "max_forks_repo_path": "src/fit_ratpoly_virial.cxx", "max_forks_repo_name": "usnistgov/CEGO", "max_forks_repo_head_hexsha": "ef957d17c56f95f37918bf3762f634d7a1eab06a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-02-27T18:01:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-05-29T19:44:15.000Z", "avg_line_length": 39.3493150685, "max_line_length": 283, "alphanum_fraction": 0.5730200174, "num_tokens": 1905, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6610154315678062}} {"text": "/*\n * elliptic_functions.cpp\n *\n * Copyright 2009-2012 Karsten Ahnert\n * Copyright 2009-2012 Mario Mulansky\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n\n\n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\ntypedef boost::array< double , 3 > state_type;\n\n/*\n * x1' = x2*x3\n * x2' = -x1*x3\n * x3' = -m*x1*x2\n */\n\nvoid rhs( const state_type &x , state_type &dxdt , const double t )\n{\n static const double m = 0.51;\n\n dxdt[0] = x[1]*x[2];\n dxdt[1] = -x[0]*x[2];\n dxdt[2] = -m*x[0]*x[1];\n}\n\nofstream out;\n\nvoid write_out( const state_type &x , const double t )\n{\n out << t << '\\t' << x[0] << '\\t' << x[1] << '\\t' << x[2] << endl;\n}\n\nint main()\n{\n bulirsch_stoer_dense_out< state_type > stepper( 1E-9 , 1E-9 , 1.0 , 0.0 );\n\n state_type x1 = {{ 0.0 , 1.0 , 1.0 }};\n\n double t = 0.0;\n double dt = 0.01;\n\n out.open( \"elliptic1.dat\" );\n out.precision(16);\n integrate_const( stepper , rhs , x1 , t , 100.0 , dt , write_out );\n out.close();\n\n state_type x2 = {{ 0.0 , 1.0 , 1.0 }};\n\n out.open( \"elliptic2.dat\" );\n out.precision(16);\n integrate_adaptive( stepper , rhs , x2 , t , 100.0 , dt , write_out );\n out.close();\n\n typedef runge_kutta_dopri5< state_type > dopri5_type;\n typedef controlled_runge_kutta< dopri5_type > controlled_dopri5_type;\n typedef dense_output_runge_kutta< controlled_dopri5_type > dense_output_dopri5_type;\n\n\n dense_output_dopri5_type dopri5 = make_dense_output( 1E-9 , 1E-9 , dopri5_type() );\n //dense_output_dopri5_type dopri5( controlled_dopri5_type( default_error_checker< double >( 1E-9 , 0.0 , 0.0 , 0.0 ) ) );\n\n state_type x3 = {{ 0.0 , 1.0 , 1.0 }};\n\n out.open( \"elliptic3.dat\" );\n out.precision(16);\n integrate_adaptive( dopri5 , rhs , x3 , t , 100.0 , dt , write_out );\n out.close();\n}\n", "meta": {"hexsha": "fa9dbc6934489007f9f24fb3c90c4bebe0d889bd", "size": 2219, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/elliptic_functions.cpp", "max_stars_repo_name": "Drona-Org/Drona-DMR", "max_stars_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T14:49:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T06:53:28.000Z", "max_issues_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/elliptic_functions.cpp", "max_issues_repo_name": "Dronacharya-Org/Dronacharya", "max_issues_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/elliptic_functions.cpp", "max_forks_repo_name": "Dronacharya-Org/Dronacharya", "max_forks_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-12-15T20:18:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T19:26:57.000Z", "avg_line_length": 24.6555555556, "max_line_length": 126, "alphanum_fraction": 0.6421811627, "num_tokens": 767, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.7490872075132152, "lm_q1q2_score": 0.6610154216819453}} {"text": "#include \"geometrycentral/surface/trace_geodesic.h\"\n\n#include \"geometrycentral/surface/barycentric_coordinate_helpers.h\"\n#include \"geometrycentral/surface/vertex_position_geometry.h\"\n\n#include \n\n#include \n\nusing std::cout;\nusing std::endl;\n\nnamespace geometrycentral {\nnamespace surface {\n\n// The default trace options\nconst TraceOptions defaultTraceOptions;\n\n// Helper functions which support tracing\nnamespace {\n\n\n// === Geometric subroutines for tracing\n\n// a few parameters\nconst double TRACE_EPS_TIGHT = 1e-12;\nconst double TRACE_EPS_LOOSE = 1e-9;\nconst bool TRACE_PRINT = false;\n\ninline std::array vertexCoordinatesInTriangle(IntrinsicGeometryInterface& geom, Face face) {\n return {Vector2{0., 0.}, geom.halfedgeVectorsInFace[face.halfedge()],\n -geom.halfedgeVectorsInFace[face.halfedge().next().next()]};\n}\n\ninline Vector3 faceCoordsToBaryCoords(const std::array& vertCoords, Vector2 faceCoord) {\n\n // Warning: bakes in assumption that vertCoords[0] == (0,0)\n\n // Invert the system to solve for coordinates\n double b2 = faceCoord.y / vertCoords[2].y;\n b2 = clamp(b2, 0.0, 1.0); // comment these to get useful errors rather than clamping\n double b1 = (faceCoord.x - b2 * vertCoords[2].x) / vertCoords[1].x;\n b1 = clamp(b1, 0.0, 1.0 - b2);\n double b0 = 1.0 - b1 - b2;\n b0 = clamp(b0, 0.0, 1.0);\n Vector3 result{b0, b1, b2};\n\n return result;\n}\n\ninline Vector2 baryCoordsToFaceCoords(const std::array& vertCoords, Vector3 baryCoord) {\n return vertCoords[0] * baryCoord.x + vertCoords[1] * baryCoord.y + vertCoords[2] * baryCoord.z;\n}\n\ninline Vector2 barycentricDisplacementToCartesian(const std::array& vertCoords, Vector3 baryVec) {\n // Note: happens to be the same as baryCoordsToFaceCoords()\n return vertCoords[0] * baryVec.x + vertCoords[1] * baryVec.y + vertCoords[2] * baryVec.z;\n}\n\ninline Vector3 cartesianVectorToBarycentric(const std::array& vertCoords, Vector2 faceVec) {\n\n\n // Build matrix for linear transform problem\n // (last constraint comes from chosing the displacement vector with sum = 0)\n Eigen::Matrix3d A;\n Eigen::Vector3d rhs;\n const std::array& c = vertCoords; // short name\n A << c[0].x, c[1].x, c[2].x, c[0].y, c[1].y, c[2].y, 1., 1., 1.;\n rhs << faceVec.x, faceVec.y, 0.;\n\n // Solve\n Eigen::Vector3d result = A.colPivHouseholderQr().solve(rhs);\n Vector3 resultBary{result(0), result(1), result(2)};\n\n resultBary = normalizeBarycentricDisplacement(resultBary);\n\n if (TRACE_PRINT) {\n cout << \" cartesianVectorToBarycentric() \" << endl;\n cout << \" input = \" << faceVec << endl;\n cout << \" positions = \" << vertCoords[0] << \" \" << vertCoords[1] << \" \" << vertCoords[2] << endl;\n cout << \" transform result = \" << resultBary << endl;\n cout << \" transform back = \" << barycentricDisplacementToCartesian(vertCoords, resultBary) << endl;\n cout << \" A = \" << endl << A << endl;\n cout << \" rhs = \" << endl << rhs << endl;\n cout << \" Ax = \" << endl << A * result << endl;\n }\n\n return resultBary;\n}\n\n// Converts tCross from halfedge to edge coordinates, handling sign conventions\ninline double convertTToEdge(Halfedge he, double tCross) {\n if (he == he.edge().halfedge()) return tCross;\n return 1.0 - tCross;\n}\n// Converts vectors in halfedge basis from halfedge to edge coordinates, handling sign conventions\ninline Vector2 convertVecToEdge(Halfedge he, Vector2 halfedgeVec) {\n if (he == he.edge().halfedge()) return halfedgeVec;\n return -halfedgeVec;\n}\n\n\n// === Tracing subroutines\n\n\n// Return type from tracing subroutines\n// When trace ends, will set newFace = Face() and newVector = Vector3::zero(). only then is incomingDirToPoint populated\nstruct TraceSubResult {\n // Did the trace end?\n bool terminated;\n\n // One of the two sets of values will be defined:\n\n // If the trace continues (terminated == false)\n Halfedge crossHe; // halfedge we crossed over from (crossHe.twin().face() is new face)\n double tCross; // t along crossHe\n Vector2 traceVectorInHalfedgeDir; // vector to keep tracing, measured against crossHe\n double traceVectorInHalfedgeLen; // vector to keep tracing, measured against crossHe\n\n // If the trace ends (terminated == true)\n SurfacePoint endPoint; // ending location\n Vector2 incomingDirToPoint; // final incoming direction\n};\n\n\n// General form for tracing barycentrically within a face\n// Assumes that approriate projects have already been performed such that startPoint and vectors are valid (inside\n// triangle and pointing in the right direction)\n//\n// This function is tightly coupled with the routines which call it. They prepare the values startPoint, vecBary, and\n// vecCartesian, ensuring that those values satisify basic properties (essentially that the trace points in a vallid\n// direction).\n//\n// Note that this expects to be given the trace vector in both barycentric _and_ cartesian coordinates. These are two\n// different representations of the same data! This is useful the barycentric representation is good for relilably\n// performing tracing, while the cartesian representation is good for transforming the trace vector between triangles.\ninline TraceSubResult traceInFaceBarycentric(IntrinsicGeometryInterface& geom, Face face, Vector3 startPoint,\n Vector3 vecBary, Vector2 vecCartesianDir, double vecCartesianLen,\n std::array edgeIsHittable, const TraceOptions& traceOptions) {\n\n // Gather values\n std::array vertexCoords = vertexCoordinatesInTriangle(geom, face);\n Vector3 triangleLengths{geom.edgeLengths[face.halfedge().edge()], geom.edgeLengths[face.halfedge().next().edge()],\n geom.edgeLengths[face.halfedge().next().next().edge()]};\n\n if (sum(startPoint) < 0.5) {\n if (TRACE_PRINT) {\n cout << \" bad bary point: \" << startPoint << endl;\n }\n if (traceOptions.errorOnProblem) {\n throw std::runtime_error(\"bad bary point\");\n }\n }\n\n if (TRACE_PRINT) {\n cout << \" general trace in face: \" << endl;\n cout << \" face: \" << face << \" startPoint \" << startPoint << \" vecBary = \" << vecBary << \" vecCartesian \"\n << vecCartesianDir << \" \" << vecCartesianLen << endl;\n }\n\n if (TRACE_PRINT) {\n cout << \" vec bary = \" << vecBary << endl;\n cout << \" reconvert = \" << cartesianVectorToBarycentric(vertexCoords, vecCartesianDir) * vecCartesianLen << endl;\n }\n\n // Test if the vector ends in the triangle\n Vector3 endPoint = startPoint + vecBary;\n if (TRACE_PRINT) {\n cout << \" endpoint: \" << endPoint << endl;\n }\n\n /*\n if (isInsideTriangle(endPoint)) {\n // Fancy test if ending on edges\n // (to detect when we're within eps of edge)\n bool foundEpsEdge = false;\n if (traceOptions.allowEndOnEdge) {\n double A = 0.5 * cross(vertexCoords[1] - vertexCoords[0], vertexCoords[2] - vertexCoords[0]);\n Halfedge endHe = face.halfedge();\n for (int i = 0; i < 3; i++) {\n double dist = 2. * endPoint[i] * A / triangleLengths[i]; // perp distance to edge\n if (endPoint[i] > 0 && dist < traceOptions.allowEndOnEdgeEps) {\n // force the process below to hit this edge, let other logic proceed\n edgeIsHittable[i] = true;\n edgeIsHittable[(i + 1) % 3] = false;\n edgeIsHittable[(i + 2) % 3] = false;\n foundEpsEdge = true;\n break;\n }\n }\n }\n // Simple test if not ending on edges\n if (!foundEpsEdge) {\n // The trace ended! Call it a day.\n TraceSubResult result;\n result.terminated = true;\n result.endPoint = SurfacePoint(face, endPoint);\n result.incomingDirToPoint = vecCartesian;\n return result;\n }\n }\n */\n\n if (isInsideTriangle(endPoint)) {\n // The trace ended! Call it a day.\n TraceSubResult result;\n result.terminated = true;\n result.endPoint = SurfacePoint(face, endPoint);\n result.incomingDirToPoint = vecCartesianDir;\n return result;\n }\n\n\n // The vector did not end in this triangle. Pick an appropriate point along some edge\n double tRay = std::numeric_limits::infinity();\n Halfedge crossHe = Halfedge();\n int iOppVertEnd = -777;\n Halfedge currHe = face.halfedge();\n for (int i = 0; i < 3; i++) {\n currHe = currHe.next(); // always opposite the i'th vertex\n\n // Check the crossing\n double tRayThisRaw = -startPoint[i] / vecBary[i];\n double tRayThis = clamp(tRayThisRaw, 0., 1. - TRACE_EPS_LOOSE);\n\n if (TRACE_PRINT) {\n cout << \" considering intersection:\" << endl;\n cout << std::boolalpha;\n cout << \" hittable[(i+1)%3]: \" << edgeIsHittable[(i + 1) % 3] << endl;\n cout << \" vecBary[i]: \" << vecBary[i] << endl;\n cout << \" startPoint[i]: \" << startPoint[i] << endl;\n cout << \" tRayThisRaw: \" << tRayThisRaw << endl;\n cout << \" tRayThis: \" << tRayThis << endl;\n }\n\n\n if (!edgeIsHittable[(i + 1) % 3] || vecBary[i] >= 0) {\n // note should ALWAYS satisfy precondition that vecBary[i] is negative for at least one hittable edge.\n // if not, fix projection of inputs in caller\n continue;\n }\n\n if (tRayThisRaw < tRay) {\n // This is the new closest intersection\n tRay = tRayThisRaw;\n crossHe = currHe;\n iOppVertEnd = i;\n }\n }\n\n if (TRACE_PRINT) {\n cout << \" selected intersection:\" << endl;\n cout << \" crossHe: \" << crossHe << endl;\n cout << \" tRay: \" << tRay << endl;\n cout << \" iOppVertEnd: \" << iOppVertEnd << endl;\n }\n\n // Clamp to a sane range\n tRay = clamp(tRay, 0., 1. - TRACE_EPS_LOOSE);\n\n\n if (crossHe == Halfedge()) {\n if (traceOptions.errorOnProblem) {\n throw std::logic_error(\"no halfedge intersection was selected, precondition problem?\");\n }\n if (TRACE_PRINT) {\n cout << \" PROBLEM PROBLEM NO INTERSECTION:\" << endl;\n }\n\n // End immediately\n TraceSubResult result;\n result.terminated = true;\n result.endPoint = SurfacePoint(face, startPoint);\n result.incomingDirToPoint = vecCartesianDir;\n return result;\n }\n\n // Compute some useful info about the endpoint\n Vector3 endPointOnEdge = startPoint + tRay * vecBary;\n double tCross = endPointOnEdge[(iOppVertEnd + 2) % 3] /\n (endPointOnEdge[(iOppVertEnd + 1) % 3] + endPointOnEdge[(iOppVertEnd + 2) % 3]);\n if (TRACE_PRINT) {\n cout << \" end point on edge: \" << endPointOnEdge << endl;\n cout << \" tCross raw: \" << tCross << endl;\n }\n tCross = clamp(tCross, 0., 1.);\n\n // Rotate the vector in to the frame of crossHe and shorten it\n double lenRemaining = (1.0 - tRay) * vecCartesianLen;\n Vector2 crossingEdgeVec = (vertexCoords[(iOppVertEnd + 2) % 3] - vertexCoords[(iOppVertEnd + 1) % 3]);\n Vector2 remainingDirInHalfedge = vecCartesianDir / crossingEdgeVec.normalize();\n if (!isfinite(remainingDirInHalfedge)) {\n if (TRACE_PRINT) {\n cout << \" NON FINITE REMAINING TRACE\" << endl;\n cout << \" lenRemaining = \" << lenRemaining << endl;\n cout << \" crossingEdgeVec = \" << crossingEdgeVec << endl;\n cout << \" remainingDirInHalfedge = \" << remainingDirInHalfedge << endl;\n }\n\n if (traceOptions.errorOnProblem) {\n throw std::runtime_error(\"bad value transforming to new edge. is there a zero-length edge?\");\n }\n }\n\n\n // Stop tracing if we hit a boundary\n if (!crossHe.twin().isInterior() || (traceOptions.barrierEdges && (*traceOptions.barrierEdges)[crossHe.edge()])) {\n // Build the result\n TraceSubResult result;\n result.terminated = true;\n result.endPoint = SurfacePoint(crossHe.edge(), convertTToEdge(crossHe, tCross));\n result.incomingDirToPoint = remainingDirInHalfedge;\n\n return result;\n }\n\n // Build the result\n TraceSubResult result;\n result.terminated = false;\n result.crossHe = crossHe;\n result.tCross = tCross;\n result.traceVectorInHalfedgeDir = remainingDirInHalfedge;\n result.traceVectorInHalfedgeLen = lenRemaining;\n return result;\n}\n\n// Trace within a face towards a given edge. The trace is assumed to start at the vertex opposite towardsHe.\n// - towardsHe: the halfedge we are tracing towards (opposite the source vertex)\n// - vecCartesian: vector to trace, in the cartesian basis of the face\ninline TraceSubResult traceInFaceTowardsEdge(IntrinsicGeometryInterface& geom, Halfedge towardsHe,\n Vector2 vecCartesianDir, double vecCartesianLen,\n const TraceOptions& traceOptions) {\n\n // Gather some values\n Face face = towardsHe.face();\n Halfedge rootHe = towardsHe.next().next();\n std::array vertexCoords = vertexCoordinatesInTriangle(geom, face);\n\n if (TRACE_PRINT) {\n cout << \" face trace towards edge \" << towardsHe << \" vec = \" << vecCartesianDir << endl;\n cout << \" wedge vec right = \" << geom.halfedgeVectorsInFace[towardsHe.next().next()] << endl;\n cout << \" wedge vec left = \" << -geom.halfedgeVectorsInFace[towardsHe.next()] << endl;\n cout << \" wedge vec opp = \" << geom.halfedgeVectorsInFace[towardsHe] << endl;\n }\n\n // TODO do some reasonable angular projection on the cartesian vector\n\n // Convert to barycentric\n Vector3 vecBaryCanonical = cartesianVectorToBarycentric(vertexCoords, vecCartesianDir) * vecCartesianLen;\n Vector3 vecBaryFromRoot = permuteBarycentricFromCanonical(vecBaryCanonical, towardsHe.next().next());\n\n if (TRACE_PRINT) {\n cout << \" canonical bary vec\" << vecBaryCanonical << endl;\n cout << \" bary vec before projection \" << vecBaryFromRoot << endl;\n }\n\n { // Project to ensure the vector is inside the triangle\n vecBaryFromRoot.x = std::fmin(vecBaryFromRoot.x, TRACE_EPS_TIGHT);\n vecBaryFromRoot.y = std::fmax(vecBaryFromRoot.y, 0.);\n vecBaryFromRoot.z = std::fmax(vecBaryFromRoot.z, 0.);\n\n // Manual displacement projection to sum to 0 while perserving above properties\n double diff = -sum(vecBaryFromRoot);\n if (diff > 0) {\n vecBaryFromRoot.y += diff / 2;\n vecBaryFromRoot.z += diff / 2;\n } else {\n vecBaryFromRoot.x += diff;\n }\n }\n\n if (TRACE_PRINT) {\n cout << \" bary vec after projection \" << vecBaryFromRoot << endl;\n }\n\n // Assemble data to call the general trace function\n int iHe = halfedgeIndexInTriangle(towardsHe.next().next());\n Vector3 startPoint{0., 0., 0.};\n startPoint[iHe] = 1.0;\n Vector3 vecBaryCanonicalFixed = permuteBarycentricToCanonical(vecBaryFromRoot, rootHe);\n std::array hittable = {{false, false, false}};\n hittable[(iHe + 1) % 3] = true;\n\n return traceInFaceBarycentric(geom, face, startPoint, vecBaryCanonicalFixed, vecCartesianDir, vecCartesianLen,\n hittable, traceOptions);\n}\n\n\n// Trace within a face away from a given edge. The trace must hit one of the two opposite edges\n// - fromHe: the halfedge we enter from along the face\n// - tCrossFrom: t value in [0, 1] along fromHe we we enter the face\n// - traceVecInHalfedge: vector to trace, in the basis of fromHe\ninline TraceSubResult traceInFaceFromEdge(IntrinsicGeometryInterface& geom, Halfedge fromHe, double tCrossFrom,\n Vector2 traceVecInHalfedgeDir, double traceVecInHalfedgeLen,\n const TraceOptions& traceOptions) {\n\n // Possibly terminate at this edge\n /*\n std::cout << \" norm tracevec = \" << norm(traceVecInHalfedge) << std::endl;\n if (traceOptions.allowEndOnEdge && norm(traceVecInHalfedge) < traceOptions.allowEndOnEdgeEps) {\n std::cout << \"TERMINATING AT EDGE\" << std::endl;\n TraceSubResult result;\n result.terminated = true;\n result.endPoint = SurfacePoint(fromHe, tCrossFrom);\n result.incomingDirToPoint = traceVecInHalfedge;\n if (fromHe != fromHe.edge().halfedge()) result.incomingDirToPoint *= -1.;\n return result;\n }\n */\n\n // Gather some values\n Halfedge faceHe = fromHe.twin(); // the halfedge in hte face we're heading in to\n Face face = faceHe.face();\n std::array vertexCoords = vertexCoordinatesInTriangle(geom, face);\n\n if (TRACE_PRINT) cout << \" face trace from edge \" << fromHe << \" vec = \" << traceVecInHalfedgeDir << endl;\n\n\n // Project the cartesian vector to definitely point in the right direction\n Vector2 traceVecInFaceHalfedgeDir = -traceVecInHalfedgeDir;\n if (TRACE_PRINT) cout << \" vec in face before project \" << traceVecInFaceHalfedgeDir << endl;\n traceVecInFaceHalfedgeDir.y = std::fmax(traceVecInFaceHalfedgeDir.y, TRACE_EPS_LOOSE);\n if (TRACE_PRINT) cout << \" vec in face after project \" << traceVecInFaceHalfedgeDir << endl;\n\n // Convert to face coordinates\n Vector2 heDir = geom.halfedgeVectorsInFace[faceHe].normalize();\n Vector2 traceVecInFaceDir = heDir * traceVecInFaceHalfedgeDir;\n if (TRACE_PRINT) cout << \" traceVec in face \" << traceVecInFaceDir << endl;\n\n // Convert to barycentric\n Vector3 vecBaryCanonicalDir = cartesianVectorToBarycentric(vertexCoords, traceVecInFaceDir);\n if (TRACE_PRINT) cout << \" vecBaryCanonical \" << vecBaryCanonicalDir << endl;\n Vector3 vecBaryFromEdgeDir = permuteBarycentricFromCanonical(vecBaryCanonicalDir, faceHe);\n\n if (TRACE_PRINT) cout << \" vec bary before project \" << vecBaryFromEdgeDir << endl;\n { // Project to ensure the vector is in the right direction\n vecBaryFromEdgeDir.z = std::fmax(vecBaryFromEdgeDir.z, TRACE_EPS_TIGHT);\n\n // Manual displacement projection to sum to 0 which perserves above properties\n double diff = -sum(vecBaryFromEdgeDir);\n if (diff > 0) {\n vecBaryFromEdgeDir.z += diff;\n } else {\n vecBaryFromEdgeDir.x += diff / 3.;\n vecBaryFromEdgeDir.y += diff / 3.;\n vecBaryFromEdgeDir.z += diff / 3.;\n }\n }\n if (TRACE_PRINT) cout << \" vec bary after project \" << vecBaryFromEdgeDir << endl;\n\n // Project ensure tCrossFrom is valid\n tCrossFrom = clamp(tCrossFrom, 0., 1.);\n\n\n // Assemble data to call the general trace function\n int iHe = halfedgeIndexInTriangle(faceHe);\n Vector3 startPoint{0., 0., 0.};\n startPoint[iHe] = tCrossFrom; // notice: switched from what you'd expect becasue tCrossFrom is defined on twin\n startPoint[(iHe + 1) % 3] = 1.0 - tCrossFrom;\n Vector3 vecBaryCanonicalFixedDir = permuteBarycentricToCanonical(vecBaryFromEdgeDir, faceHe);\n if (TRACE_PRINT) {\n cout << \" iHe = \" << iHe << endl;\n cout << \" startPoint = \" << startPoint << endl;\n cout << \" canonical bary \" << vecBaryCanonicalFixedDir << endl;\n }\n std::array hittable = {{true, true, true}};\n hittable[iHe] = false;\n\n return traceInFaceBarycentric(geom, face, startPoint, vecBaryCanonicalFixedDir * traceVecInHalfedgeLen,\n traceVecInFaceDir, traceVecInHalfedgeLen, hittable, traceOptions);\n}\n\n\n// Trace starting from an edge\ninline TraceSubResult traceGeodesic_fromEdge(IntrinsicGeometryInterface& geom, Edge currEdge, double tEdge,\n Vector2 currVecDir, double currVecLen, const TraceOptions& traceOptions) {\n\n if (TRACE_PRINT) cout << \" edge trace \" << currEdge << \" tEdge = \" << tEdge << \" edge vec = \" << currVecDir << endl;\n\n // Project to ensure tEdge is valid\n tEdge = clamp(tEdge, 0., 1.);\n\n // Find coordinates in adjacent face\n\n // Check which side of the face we're exiting\n Halfedge traceHe;\n Vector2 halfedgeTraceDir;\n if (currVecDir.y >= 0.) {\n traceHe = currEdge.halfedge().twin();\n halfedgeTraceDir = -currVecDir;\n tEdge = 1.0 - tEdge;\n } else {\n traceHe = currEdge.halfedge();\n\n // Can't go anyywhere if boundary halfedge\n if (!traceHe.twin().isInterior() || (traceOptions.barrierEdges && (*traceOptions.barrierEdges)[traceHe.edge()])) {\n TraceSubResult result;\n result.terminated = true;\n result.endPoint = SurfacePoint(currEdge, tEdge);\n result.incomingDirToPoint = currVecDir;\n\n return result;\n }\n\n halfedgeTraceDir = currVecDir;\n }\n\n return traceInFaceFromEdge(geom, traceHe, tEdge, halfedgeTraceDir, currVecLen, traceOptions);\n}\n\n// Trace starting from a face\ninline TraceSubResult traceGeodesic_fromFace(IntrinsicGeometryInterface& geom, Face currFace, Vector3 faceBary,\n Vector2 currVecDir, double currVecLen, const TraceOptions& traceOptions) {\n\n // Convert the vector to barycentric\n std::array vertexCoords = vertexCoordinatesInTriangle(geom, currFace);\n Vector3 vecBary = cartesianVectorToBarycentric(vertexCoords, currVecDir) * currVecLen;\n\n return traceInFaceBarycentric(geom, currFace, faceBary, vecBary, currVecDir, currVecLen, {true, true, true},\n traceOptions);\n}\n\n\n// Trace starting from a vertex (with a rescaled cartesian vector)\ninline TraceSubResult traceGeodesic_fromVertex(IntrinsicGeometryInterface& geom, Vertex currVert, Vector2 currVecDir,\n double currVecLen, const TraceOptions& traceOptions) {\n if (TRACE_PRINT) cout << \" vertex trace \" << currVert << \" edge vec = \" << currVecDir << endl;\n\n // Find the halfedge opening the wedge where tracing will start\n Halfedge wedgeHe;\n Vector2 traceDirRelativeToStart;\n\n // Normally, one of the interval tests below will return positive and we'll simply launch the trace in to that\n // interval. However, due to numerical misfortune, it is possible that none of the intervals will test positive. In\n // that case, we'll simply launch along whichever halfedge was closest.\n double minCross = std::numeric_limits::infinity();\n Halfedge minCrossHalfedge;\n Vector2 minCrossHalfedgeDir; // the trace vector in this closest halfedge\n\n Halfedge currHe = currVert.halfedge();\n do {\n\n // Once we hit the boundary we're done\n // (and traversal below doesn't work on boundary loop, so need to exit specially)\n if (!currHe.isInterior()) {\n break;\n }\n\n Halfedge nextHe = currHe.next().next().twin();\n\n // The interval spanned by this edge, which we are currently testing\n Vector2 intervalStart = geom.halfedgeVectorsInVertex[currHe].normalize();\n Vector2 intervalEnd = geom.halfedgeVectorsInVertex[nextHe].normalize();\n\n if (TRACE_PRINT) {\n cout << \" testing wedge \" << intervalStart << \" -- \" << intervalEnd << endl;\n cout << \" testing wedge (un norm) \" << geom.halfedgeVectorsInVertex[currHe] << \" -- \"\n << geom.halfedgeVectorsInVertex[nextHe] << endl;\n cout << \" corner angle \" << geom.cornerAngles[currHe.corner()] << endl;\n cout << \" corner \" << currHe.corner() << endl;\n Vector2 relAngle = intervalEnd / intervalStart;\n cout << \" wedge width \" << relAngle << \" radians: \" << relAngle.arg() << endl;\n }\n\n\n // Check if our trace vector lies within the interval\n double crossStart = cross(intervalStart, currVecDir);\n double crossEnd = cross(intervalEnd, currVecDir);\n if (crossStart > 0. && crossEnd <= 0.) {\n wedgeHe = currHe;\n traceDirRelativeToStart = currVecDir / intervalStart;\n if (TRACE_PRINT) cout << \" wedge match! relative angle \" << traceDirRelativeToStart << endl;\n if (TRACE_PRINT) cout << \" cross start = \" << crossStart << \" cross end = \" << crossEnd << endl;\n break;\n }\n\n // Keep track of the closest halfedge, as described above\n if (std::fabs(crossStart) < minCross) {\n minCross = std::fabs(crossStart);\n minCrossHalfedge = currHe;\n minCrossHalfedgeDir = Vector2{1, TRACE_EPS_TIGHT};\n }\n if (std::fabs(crossEnd) < minCross) {\n minCross = std::fabs(crossEnd);\n minCrossHalfedge = nextHe;\n minCrossHalfedgeDir = Vector2{1, -TRACE_EPS_TIGHT};\n }\n\n currHe = nextHe;\n } while (currHe != currVert.halfedge());\n\n // None of the interval tests passed (probably due to unfortunate numerics), so just trace along the closest\n // halfedge\n if (wedgeHe == Halfedge()) {\n if (TRACE_PRINT) cout << \" no wedge worked. following closest edge with dir \" << minCrossHalfedgeDir << endl;\n // Convert to edge coordinates\n currVecDir = convertVecToEdge(minCrossHalfedge, minCrossHalfedgeDir);\n return traceGeodesic_fromEdge(geom, minCrossHalfedge.edge(), convertTToEdge(minCrossHalfedge, 0.), currVecDir,\n currVecLen, traceOptions);\n }\n\n // Compute the actual starting face point, slightly inside and adjacent face\n Face startFace = wedgeHe.face();\n int iHe = halfedgeIndexInTriangle(wedgeHe);\n\n // Need to convert from \"powered\" representation to flat vector in face\n double sum = currVert.isBoundary() ? M_PI : 2. * M_PI;\n traceDirRelativeToStart = traceDirRelativeToStart.pow(geom.vertexAngleSums[currVert] / sum);\n traceDirRelativeToStart = traceDirRelativeToStart.normalize();\n\n // Compute the starting vector\n Vector2 startDirInFace = geom.halfedgeVectorsInFace[wedgeHe].normalize();\n Vector2 traceDirInFace = traceDirRelativeToStart * startDirInFace;\n if (TRACE_PRINT) {\n cout << \" starting vector\" << endl;\n cout << \" start wedge vec \" << geom.halfedgeVectorsInFace[wedgeHe] << endl;\n cout << \" start wedge vec unit \" << geom.halfedgeVectorsInFace[wedgeHe].normalize() << endl;\n cout << \" trace dir in face \" << traceDirInFace << endl;\n }\n\n\n return traceInFaceTowardsEdge(geom, wedgeHe.next(), traceDirInFace, currVecLen, traceOptions);\n}\n\n\n// Run tracing iteratively in faces, after on of the variants below has gotten it started.\n// Will internally add the point path point encoded by prevTraceEnd, don't add beforehand.\nvoid traceGeodesic_iterative(IntrinsicGeometryInterface& geom, TraceGeodesicResult& result, TraceSubResult prevTraceEnd,\n const TraceOptions& traceOptions) {\n\n // Now, points are always in faces. Trace until termination.\n size_t iter = 0;\n while (!prevTraceEnd.terminated) {\n\n // Terminate on iterations\n if (traceOptions.maxIters != INVALID_IND && iter >= traceOptions.maxIters) {\n\n // Use the last trace as ending data\n result.endPoint = SurfacePoint(prevTraceEnd.crossHe, prevTraceEnd.tCross);\n result.endingDir = prevTraceEnd.traceVectorInHalfedgeDir;\n\n return;\n }\n\n\n // Construct a point where the previous trace ended\n if (traceOptions.includePath) {\n SurfacePoint currPoint(prevTraceEnd.crossHe.edge(), convertTToEdge(prevTraceEnd.crossHe, prevTraceEnd.tCross));\n result.pathPoints.push_back(currPoint);\n }\n\n if (TRACE_PRINT) {\n cout << \"> tracing from \" << prevTraceEnd.crossHe << \" t = \" << prevTraceEnd.tCross\n << \" dir = \" << prevTraceEnd.traceVectorInHalfedgeDir << endl;\n }\n\n // Execute the next step of tracing\n prevTraceEnd =\n traceInFaceFromEdge(geom, prevTraceEnd.crossHe, prevTraceEnd.tCross, prevTraceEnd.traceVectorInHalfedgeDir,\n prevTraceEnd.traceVectorInHalfedgeLen, traceOptions);\n iter++;\n }\n\n // Add the final ending point\n if (traceOptions.includePath) {\n result.pathPoints.push_back(prevTraceEnd.endPoint);\n }\n result.endPoint = prevTraceEnd.endPoint;\n result.endingDir = prevTraceEnd.incomingDirToPoint;\n\n // if (std::abs(norm(result.endingDir) - 1.) > .1) throw std::runtime_error(\"norm problem\");\n\n if (prevTraceEnd.endPoint.type == SurfacePointType::Edge) {\n result.hitBoundary = true;\n }\n}\n\n\n} // namespace\n\nTraceGeodesicResult traceGeodesic(IntrinsicGeometryInterface& geom, SurfacePoint startP, Vector2 traceVec,\n const TraceOptions& traceOptions) {\n geom.requireVertexAngleSums();\n geom.requireHalfedgeVectorsInVertex();\n geom.requireHalfedgeVectorsInFace();\n\n // The output data\n TraceGeodesicResult result;\n result.hasPath = traceOptions.includePath;\n if (traceOptions.includePath) {\n result.pathPoints.push_back(startP);\n }\n\n if (TRACE_PRINT) cout << \"\\n>>> Trace query from \" << startP << \" vec = \" << traceVec << endl;\n\n // Quick out with a zero vector\n if (traceVec.norm2() == 0) {\n geom.unrequireVertexAngleSums();\n geom.unrequireHalfedgeVectorsInVertex();\n geom.unrequireHalfedgeVectorsInFace();\n\n result.endingDir = Vector2::zero();\n\n // probably want to ensure we still return a point in a face...\n if (traceOptions.errorOnProblem) {\n throw std::runtime_error(\"zero vec passed to trace, do something good here\");\n }\n\n return result;\n }\n\n\n // Trace the first point, based on what kind of input we got\n TraceSubResult prevTraceEnd;\n switch (startP.type) {\n case SurfacePointType::Vertex: {\n prevTraceEnd = traceGeodesic_fromVertex(geom, startP.vertex, unit(traceVec), norm(traceVec), traceOptions);\n break;\n }\n case SurfacePointType::Edge: {\n prevTraceEnd =\n traceGeodesic_fromEdge(geom, startP.edge, startP.tEdge, unit(traceVec), norm(traceVec), traceOptions);\n break;\n }\n case SurfacePointType::Face: {\n prevTraceEnd =\n traceGeodesic_fromFace(geom, startP.face, startP.faceCoords, unit(traceVec), norm(traceVec), traceOptions);\n break;\n }\n }\n\n // Keep tracing through triangles until finished\n traceGeodesic_iterative(geom, result, prevTraceEnd, traceOptions);\n\n geom.unrequireVertexAngleSums();\n geom.unrequireHalfedgeVectorsInVertex();\n geom.unrequireHalfedgeVectorsInFace();\n\n return result;\n}\n\n\nTraceGeodesicResult traceGeodesic(IntrinsicGeometryInterface& geom, Face startFace, Vector3 startBary,\n Vector3 traceBaryVec, const TraceOptions& traceOptions) {\n\n\n geom.requireVertexAngleSums();\n geom.requireHalfedgeVectorsInVertex();\n geom.requireHalfedgeVectorsInFace();\n\n // The output data\n TraceGeodesicResult result;\n result.hasPath = traceOptions.includePath;\n if (traceOptions.includePath) {\n result.pathPoints.push_back(SurfacePoint(startFace, startBary));\n }\n\n if (TRACE_PRINT) {\n cout << \"\\n>>> Trace query (barycentric) from \" << startFace << \" \" << startBary << \" vec = \" << traceBaryVec\n << endl;\n }\n\n // Early-out if zero\n if (traceBaryVec.norm2() == 0) {\n geom.unrequireVertexAngleSums();\n geom.unrequireHalfedgeVectorsInVertex();\n geom.unrequireHalfedgeVectorsInFace();\n\n // probably want to ensure we still return a point in a face...\n if (traceOptions.errorOnProblem) {\n throw std::runtime_error(\"zero vec passed to trace, do something good here\");\n }\n\n result.endingDir = Vector2::zero();\n return result;\n }\n\n // Make sure the input is sane\n startBary = projectInsideTriangle(startBary);\n traceBaryVec -= Vector3::constant(sum(traceBaryVec) / 3);\n\n // Construct the cartesian equivalent\n std::array vertexCoords = vertexCoordinatesInTriangle(geom, startFace);\n Vector2 traceVectorCartesian = barycentricDisplacementToCartesian(vertexCoords, traceBaryVec);\n\n // Trace the first point starting inside the face\n TraceSubResult prevTraceEnd =\n traceInFaceBarycentric(geom, startFace, startBary, traceBaryVec, unit(traceVectorCartesian),\n norm(traceVectorCartesian), {true, true, true}, traceOptions);\n\n // Keep tracing through triangles until finished\n traceGeodesic_iterative(geom, result, prevTraceEnd, traceOptions);\n\n geom.unrequireVertexAngleSums();\n geom.unrequireHalfedgeVectorsInVertex();\n geom.unrequireHalfedgeVectorsInFace();\n\n return result;\n}\n\nbool trimTraceResult(TraceGeodesicResult& traceResult, Vertex targetVertex) {\n\n while (traceResult.pathPoints.size() > 1) {\n SurfacePoint& b = traceResult.pathPoints.back();\n\n // Remove any edge crossings connected to the target vertex: they're numerical noise because we're already in the\n // 1-ring\n if (b.type == SurfacePointType::Edge &&\n (b.edge.halfedge().vertex() == targetVertex || b.edge.halfedge().twin().vertex() == targetVertex)) {\n traceResult.pathPoints.pop_back();\n traceResult.endingDir = Vector2::undefined();\n continue;\n }\n\n // Always trim face points\n if (b.type == SurfacePointType::Face) {\n traceResult.pathPoints.pop_back();\n traceResult.endingDir = Vector2::undefined();\n continue;\n }\n\n // Always trim vertex points\n if (b.type == SurfacePointType::Vertex) {\n traceResult.pathPoints.pop_back();\n traceResult.endingDir = Vector2::undefined();\n continue;\n }\n\n // we're done here\n break;\n }\n\n\n // Check success\n if (traceResult.pathPoints.empty()) return false;\n\n SurfacePoint& b = traceResult.pathPoints.back();\n\n switch (b.type) {\n case SurfacePointType::Vertex: {\n if (b.vertex == targetVertex) return true;\n for (Vertex n : b.vertex.adjacentVertices()) {\n if (n == targetVertex) return true;\n }\n break;\n }\n case SurfacePointType::Edge: {\n Halfedge bHe = b.edge.halfedge();\n if (bHe.vertex() == targetVertex) return true;\n if (bHe.twin().vertex() == targetVertex) return true;\n if (bHe.next().next().vertex() == targetVertex) return true;\n if (bHe.twin().next().next().vertex() == targetVertex) return true;\n return false;\n break;\n }\n case SurfacePointType::Face: {\n for (Vertex v : b.face.adjacentVertices()) {\n if (v == targetVertex) return true;\n }\n return false;\n break;\n }\n }\n\n return false;\n}\n\n\n} // namespace surface\n} // namespace geometrycentral\n", "meta": {"hexsha": "2cbaa9057a3bd5287446b11a528b6f7147bac83d", "size": 33307, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/surface/trace_geodesic.cpp", "max_stars_repo_name": "softwarecapital/geometry-central", "max_stars_repo_head_hexsha": "b4743b4662018d8fa483b31ff4a3af5699db3e93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 539.0, "max_stars_repo_stars_event_min_datetime": "2018-02-19T16:38:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:56:22.000Z", "max_issues_repo_path": "src/surface/trace_geodesic.cpp", "max_issues_repo_name": "softwarecapital/geometry-central", "max_issues_repo_head_hexsha": "b4743b4662018d8fa483b31ff4a3af5699db3e93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 88.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T13:19:35.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T18:40:33.000Z", "max_forks_repo_path": "src/surface/trace_geodesic.cpp", "max_forks_repo_name": "softwarecapital/geometry-central", "max_forks_repo_head_hexsha": "b4743b4662018d8fa483b31ff4a3af5699db3e93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 74.0, "max_forks_repo_forks_event_min_datetime": "2018-05-12T17:57:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T15:01:26.000Z", "avg_line_length": 38.2399540758, "max_line_length": 120, "alphanum_fraction": 0.6775752845, "num_tokens": 8852, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246035907932, "lm_q2_score": 0.793105941403651, "lm_q1q2_score": 0.6609146942257003}} {"text": "//#define EIGEN_RUNTIME_NO_MALLOC\n\n#include \"linmath.h\"\n#include \"sv_matrix.h\"\n#include \n#include \n#include \n#include \n\n#include \n\n#ifdef EIGEN_RUNTIME_NO_MALLOC\n#define EIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(v) EIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(v)\n#else\n#define EIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(v)\n#endif\n\n#ifdef SV_MATRIX_IS_COL_MAJOR\ntypedef Eigen::Matrix MatrixType;\n#else\ntypedef Eigen::Matrix MatrixType;\n#endif\ntypedef Eigen::Map MapType;\n\n#define CONVERT_TO_EIGEN(A) MapType(A ? SV_FLT_PTR(A) : 0, A ? (A)->rows : 0, A ? (A)->cols : 0)\n\ndouble svInvert(const SvMat *srcarr, SvMat *dstarr, enum svInvertMethod method) {\n\tauto src = CONVERT_TO_EIGEN(srcarr);\n\tauto dst = CONVERT_TO_EIGEN(dstarr);\n\n\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\tif (method == SV_INVERT_METHOD_LU) {\n\t\tdst.noalias() = src.inverse();\n\t} else {\n\t\tdst.noalias() = src.completeOrthogonalDecomposition().pseudoInverse();\n\t}\n\treturn 0;\n}\n\nextern \"C\" void svGEMM(const SvMat *_src1, const SvMat *_src2, double alpha, const SvMat *_src3, double beta,\n\t\t\t\t\t SvMat *_dst, enum svGEMMFlags tABC) {\n\tauto src1 = CONVERT_TO_EIGEN(_src1);\n\tauto src2 = CONVERT_TO_EIGEN(_src2);\n\n\tauto dst = CONVERT_TO_EIGEN(_dst);\n\n\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\tif (tABC & SV_GEMM_FLAG_A_T)\n\t\tif (tABC & SV_GEMM_FLAG_B_T)\n\t\t\tdst.noalias() = alpha * src1.transpose() * src2.transpose();\n\t\telse\n\t\t\tdst.noalias() = alpha * src1.transpose() * src2;\n\telse {\n\t\tif (tABC & SV_GEMM_FLAG_B_T)\n\t\t\tdst.noalias() = alpha * src1 * src2.transpose();\n\t\telse\n\t\t\tdst.noalias() = alpha * src1 * src2;\n\t}\n\n\tif (_src3) {\n\t\tauto src3 = CONVERT_TO_EIGEN(_src3);\n\t\tif (tABC & SV_GEMM_FLAG_C_T)\n\t\t\tdst.noalias() += beta * src3.transpose();\n\t\telse\n\t\t\tdst.noalias() += beta * src3;\n\t}\n}\n\nconst int DECOMP_SVD = 1;\nconst int DECOMP_LU = 2;\n\nextern \"C\" int svSolve(const SvMat *_Aarr, const SvMat *_Barr, SvMat *_xarr, enum svInvertMethod method) {\n\tauto Aarr = CONVERT_TO_EIGEN(_Aarr);\n\tauto Barr = CONVERT_TO_EIGEN(_Barr);\n\tauto xarr = CONVERT_TO_EIGEN(_xarr);\n\n\tif (method == SV_INVERT_METHOD_LU) {\n\t\txarr.noalias() = Aarr.partialPivLu().solve(Barr);\n\t} else if (method == SV_INVERT_METHOD_QR) {\n\t\txarr.noalias() = Aarr.colPivHouseholderQr().solve(Barr);\n\t} else {\n\t\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(true);\n\t\tauto svd = Aarr.bdcSvd(\n\t\t\tEigen::ComputeFullU |\n\t\t\tEigen::ComputeFullV); // Eigen::JacobiSVD(Aarr, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\t\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\t\txarr.noalias() = svd.solve(Barr);\n\t}\n\treturn 0;\n}\n\nextern \"C\" void svSVD(SvMat *aarr, SvMat *warr, SvMat *uarr, SvMat *varr, enum svSVDFlags flags) {\n\tauto aarrEigen = CONVERT_TO_EIGEN(aarr);\n\tauto warrEigen = CONVERT_TO_EIGEN(warr);\n\n\tint options = 0;\n\tif (uarr)\n\t\toptions |= Eigen::ComputeFullU;\n\tif (varr)\n\t\toptions |= Eigen::ComputeFullV;\n\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(true);\n\tauto svd = aarrEigen.bdcSvd(options);\n\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\n\tif (warrEigen.cols() == 1) {\n\t\twarrEigen.noalias() = svd.singularValues();\n\t} else if (warrEigen.rows() == 1) {\n\t\twarrEigen.noalias() = svd.singularValues().transpose();\n\t} else {\n\t\twarrEigen.diagonal().noalias() = svd.singularValues();\n\t}\n\n\tif (uarr) {\n\t\tauto uarrEigen = CONVERT_TO_EIGEN(uarr);\n\t\tif (flags & SV_SVD_U_T)\n\t\t\tuarrEigen.noalias() = svd.matrixU().transpose();\n\t\telse\n\t\t\tuarrEigen.noalias() = svd.matrixU();\n\t}\n\n\tif (varr) {\n\t\tauto varrEigen = CONVERT_TO_EIGEN(varr);\n\t\tif (flags & SV_SVD_V_T)\n\t\t\tvarrEigen.noalias() = svd.matrixV().transpose();\n\t\telse\n\t\t\tvarrEigen.noalias() = svd.matrixV();\n\t}\n}\n\nvoid svMulTransposed(const SvMat *src, SvMat *dst, int order, const SvMat *delta, double scale) {\n\tauto srcEigen = CONVERT_TO_EIGEN(src);\n\tauto dstEigen = CONVERT_TO_EIGEN(dst);\n\n\tif (delta) {\n\t\tauto deltaEigen = CONVERT_TO_EIGEN(delta);\n\t\tif (order == 0)\n\t\t\tdstEigen.noalias() = scale * (srcEigen - deltaEigen) * (srcEigen - deltaEigen).transpose();\n\t\telse\n\t\t\tdstEigen.noalias() = scale * (srcEigen - deltaEigen).transpose() * (src - delta);\n\t} else {\n\t\tif (order == 0)\n\t\t\tdstEigen.noalias() = scale * srcEigen * srcEigen.transpose();\n\t\telse\n\t\t\tdstEigen.noalias() = scale * srcEigen.transpose() * srcEigen;\n\t}\n}\n\nvoid svTranspose(const SvMat *M, SvMat *dst) {\n\tauto src = CONVERT_TO_EIGEN(M);\n\tauto dstEigen = CONVERT_TO_EIGEN(dst);\n\tif (SV_FLT_PTR(M) == SV_FLT_PTR(dst))\n\t\tdstEigen = src.transpose().eval();\n\telse\n\t\tdstEigen.noalias() = src.transpose();\n}\n\nvoid print_mat(const SvMat *M);\n\ndouble svDet(const SvMat *M) {\n\tEIGEN_RUNTIME_SET_IS_MALLOC_ALLOWED(false);\n\tauto MEigen = CONVERT_TO_EIGEN(M);\n\treturn MEigen.determinant();\n}", "meta": {"hexsha": "81c418c30aed01b3cafefb5abafeeb9dae7dbfc0", "size": 4777, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "redist/sv_matrix.eigen.cpp", "max_stars_repo_name": "humbletim/libsurvive", "max_stars_repo_head_hexsha": "0919a615f2ded7bbdaa4cd9895d68cb6a3ef19d7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-31T04:02:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-31T04:02:37.000Z", "max_issues_repo_path": "redist/sv_matrix.eigen.cpp", "max_issues_repo_name": "rheaplex/libsurvive", "max_issues_repo_head_hexsha": "66e531e7900a64d832ecf86fce65168c4c99a5d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "redist/sv_matrix.eigen.cpp", "max_forks_repo_name": "rheaplex/libsurvive", "max_forks_repo_head_hexsha": "66e531e7900a64d832ecf86fce65168c4c99a5d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3067484663, "max_line_length": 109, "alphanum_fraction": 0.710069081, "num_tokens": 1499, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425399873764, "lm_q2_score": 0.7185943925708562, "lm_q1q2_score": 0.6608499724045481}} {"text": "/** @file main.cpp Demonstrates purely functional, tail-recursive,\n * arbitrary-precision factorial and Fibonacci functions using\n * Boost.Multiprecision.\n * \n * @note This implementation uses a concise style, passing and returning\n * objects by value.\n */\n\n#include \n#include \n\nusing BigInt = boost::multiprecision::cpp_int;\n\nBigInt factorial(int n, BigInt r =1) {\n return n ? factorial(n - 1, r * n) : r;\n}\n\nBigInt fibonacci(int n, BigInt a =1, BigInt b =1) {\n return n ? fibonacci(n - 1, b, a + b) : a;\n}\n\nint main() {\n for (int i = 0; i < 100; ++i)\n std::cout << i << ' ' << factorial(i) << ' ' << fibonacci(i) << '\\n';\n}\n", "meta": {"hexsha": "cbc95d37a3721e1c01abd537eac4f2a7e2c58126", "size": 692, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pretty.cpp", "max_stars_repo_name": "jeffs/fac-fib", "max_stars_repo_head_hexsha": "53b93389f123c726e28424bf8b0c31058366317b", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pretty.cpp", "max_issues_repo_name": "jeffs/fac-fib", "max_issues_repo_head_hexsha": "53b93389f123c726e28424bf8b0c31058366317b", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pretty.cpp", "max_forks_repo_name": "jeffs/fac-fib", "max_forks_repo_head_hexsha": "53b93389f123c726e28424bf8b0c31058366317b", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6153846154, "max_line_length": 77, "alphanum_fraction": 0.6329479769, "num_tokens": 194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.919642526773001, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6608499573665269}} {"text": "#pragma once\n\n// C++ standard library\n#include \n#include \n#include \n\n// Armadillo\n#include \n\n// Mantella\n#include \n\nnamespace mant{\n namespace itd{\n \n double stumpffC(\n const double parameter){\n if(parameter > 0){\n return (1.0 - std::cos(std::sqrt(parameter))) / parameter;\n }else if (parameter < 0){\n return (std::cosh(std::sqrt(-parameter)) - 1.0) / -parameter;\n }else{\n return 0.5;\n }\n }\n \n double stumpffS(\n const double parameter){\n \n if(parameter > 0){\n return (std::sqrt(parameter) - std::sin(std::sqrt(parameter))) / std::pow(std::sqrt(parameter), 3.0);\n }else if (parameter < 0){\n return (std::sinh(std::sqrt(-parameter)) - std::sqrt(-parameter)) / std::pow(std::sqrt(-parameter), 3.0);\n }else{ \n return 1.0 / 6.0; \n }\n }\n \n std::pair::fixed<3>, arma::Col::fixed<3>> lambert(\n const arma::Col::fixed<3> &startPosition,\n const arma::Col::fixed<3> &endPosition,\n const double flightTime,\n const bool isPrograde){\n \n double startPositionNorm = arma::norm(startPosition);\n double endPositionNorm = arma::norm(endPosition);\n \n arma::Col positionsCrossProduct = arma::cross(startPosition, endPosition);\n double theta = std::acos(arma::norm_dot(startPosition, endPosition));\n \n if(isPrograde){\n if(positionsCrossProduct(2) < 0){\n theta = 2.0 * arma::datum::pi - theta;\n }\n }else{\n if(positionsCrossProduct(2) >= 0){\n theta = 2.0 * arma::datum::pi - theta;\n }\n }\n\n double a = std::sin(theta) * std::sqrt((startPositionNorm * endPositionNorm) / (1.0 - std::cos(theta)));\n \n std::function yFunction = [&](\n const double parameter){ \n return startPositionNorm + endPositionNorm + a * ((parameter * stumpffS(parameter) - 1.0) / std::sqrt(stumpffC(parameter)));\n };\n \n double z = mant::brent(\n [&](\n const double parameter) { \n\n return stumpffS(parameter) * std::pow(yFunction(parameter) / stumpffC(parameter), 3.0/2.0) + a * std::sqrt(yFunction(parameter)) - std::sqrt(3.986e+5) * flightTime; //heliocentric should be 1.32712440018e11\n \n }, -2.0, 2.0, 100); //TODO: remove magic numbers\n \n double y = yFunction(z);\n\n double f = 1.0 - y / startPositionNorm;\n double g = a * std::sqrt(y / 3.986e+5); //heliocentric should be 1.32712440018e11\n double gDot = 1.0 - y / endPositionNorm;\n \n return {{(1.0 / g) * (endPosition - f * startPosition)}, {(1.0 / g) * (gDot * endPosition - startPosition)}};\n \n }\n \n \n std::pair::fixed<3>, arma::Col::fixed<3>> positionAndVelocityOnOrbit(\n const arma::Col::fixed<6>& keplerValues,\n const arma::Col::fixed<6>& dKeplerValues,\n const arma::Col::fixed<6>& date) {\n // parameters\n // -keplerValues as known (a, e, i, omega, w, L)\n // -date in [yyyy,(mon)mon, (d)d, (h)h, (min)min, (s)s]\n \n double jd = 367.0 * date(0) - std::trunc((7.0 * (date(0) + std::trunc((date(1) + 9.0) / 12.0))) / 4.0) + std::trunc(275.0 * date(1) / 9.0) + date(2) + 1721013.5 + (date(3) + date(4) / 60.0 + date(5) / 3600.0) / 24;\n \n double t0 = (jd - 2451545.0) / 36525.0; \n \n arma::Col::fixed<6> keplerValAtTime = keplerValues + dKeplerValues * t0;\n keplerValAtTime(0) = keplerValAtTime(0) * 149597871.464; //au to km\n keplerValAtTime(2) = std::fmod(keplerValAtTime(2), 360.0) * arma::datum::pi / 180.0;\n keplerValAtTime(3) = std::fmod(keplerValAtTime(3), 360.0) * arma::datum::pi / 180.0;\n keplerValAtTime(4) = std::fmod(keplerValAtTime(4), 360.0) * arma::datum::pi / 180.0;\n keplerValAtTime(5) = std::fmod(keplerValAtTime(5), 360.0) * arma::datum::pi / 180.0; \n \n double angularMomentum = std::sqrt(1.32712440018e11 * keplerValAtTime(0) * (1.0 - std::pow(keplerValAtTime(1), 2.0))); //sun gravity!!!\n \n double argumentPerihelion = keplerValAtTime(4) - keplerValAtTime(3);\n double meanAnomaly = keplerValAtTime(5) - keplerValAtTime(4); \n \n double eccentricAnomaly0;\n if(meanAnomaly < arma::datum::pi) { \n eccentricAnomaly0 = meanAnomaly + keplerValAtTime(1) / 2.0; \n } else { \n eccentricAnomaly0 = meanAnomaly - keplerValAtTime(1) / 2.0; \n }\n \n double eccentricAnomaly = mant::brent(\n [&](\n const double parameter) {\n\n return parameter - keplerValAtTime(1) * std::sin(parameter) - meanAnomaly;\n \n }, -10.0, 10.0, 100); //TODO: remove magic numbers \n \n double trueAnomaly = std::fmod(2.0 * std::atan(std::sqrt((1.0 + keplerValAtTime(1)) / (1.0 - keplerValAtTime(1))) * std::tan(eccentricAnomaly / 2.0)), 2.0 * arma::datum::pi);\n \n arma::Col::fixed<3> helperVectorPos = {std::cos(trueAnomaly), std::sin(trueAnomaly), 0};\n arma::Col::fixed<3> perifocalPosition = (std::pow(angularMomentum, 2.0) / 1.32712440018e11) * (1.0 / (1.0 + keplerValAtTime(1) * std::cos(trueAnomaly))) * helperVectorPos; //sun gravity!!!\n \n arma::Col::fixed<3> helperVectorVel = {-std::sin(trueAnomaly), (keplerValAtTime(1) + std::cos(trueAnomaly)), 0};\n arma::Col::fixed<3> perifocalVelocity = (1.32712440018e11 / angularMomentum) * helperVectorVel; //sun gravity!!! \n \n arma::Mat::fixed<3, 3> R3_W = {\n {std::cos(keplerValAtTime(3)), std::sin(keplerValAtTime(3)), 0.0}, \n {-std::sin(keplerValAtTime(3)), std::cos(keplerValAtTime(3)), 0.0}, \n {0.0, 0.0, 1.0}\n };\n \n arma::Mat::fixed<3, 3> R1_i = {\n {1.0, 0.0, 0.0}, \n {0.0, std::cos(keplerValAtTime(2)), std::sin(keplerValAtTime(2))}, \n {0.0, std::sin(keplerValAtTime(2)), std::cos(keplerValAtTime(2))}\n };\n \n arma::Mat::fixed<3, 3> R3_w = {\n {std::cos(argumentPerihelion), std::sin(argumentPerihelion), 0.0}, \n {-std::sin(argumentPerihelion), std::cos(argumentPerihelion), 0.0}, \n {0.0, 0.0, 1.0}\n };\n \n arma::Mat::fixed<3, 3> Q_pX = (R3_w * R1_i * R3_W).t();\n \n return {{Q_pX * perifocalPosition},{Q_pX * perifocalVelocity}};\n }\n \n }\n}\n", "meta": {"hexsha": "28d88af2e821f67d42198a07bf4963ebb18e54bd", "size": 6629, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "myWorkspace/orbitalMechanics.hpp", "max_stars_repo_name": "OpusV/AstroMechanics", "max_stars_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-08T22:06:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-08T22:06:56.000Z", "max_issues_repo_path": "myWorkspace/orbitalMechanics.hpp", "max_issues_repo_name": "OpusV/AstroMechanics", "max_issues_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "myWorkspace/orbitalMechanics.hpp", "max_forks_repo_name": "OpusV/AstroMechanics", "max_forks_repo_head_hexsha": "3fe7a5462fce575c465be372d1c69bf788784297", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.43125, "max_line_length": 220, "alphanum_fraction": 0.5685623774, "num_tokens": 2153, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362849986365571, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6608159280318531}} {"text": "#pragma once\n\n#include \"constants.hpp\"\n#include \n\nnamespace math {\ntemplate \nT to_radians(T degree) {\n return degree / static_cast(180.0) * pi;\n}\n\ntemplate \nEigen::Matrix to_radians(Eigen::Matrix degree) {\n return degree / static_cast(180.0) * pi;\n}\n\ntemplate \nT to_degree(T radians) {\n return radians * static_cast(180.0) / pi;\n}\n\ntemplate \nEigen::Matrix to_degree(Eigen::Matrix radians) {\n return radians * static_cast(180.0) / pi;\n}\n} // namespace math\n", "meta": {"hexsha": "622a012cc87c6fa075600fca89c3785031823539", "size": 652, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/vgl/math/math_utils.hpp", "max_stars_repo_name": "alexsr/vgl", "max_stars_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-18T18:27:19.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-18T18:27:19.000Z", "max_issues_repo_path": "src/vgl/math/math_utils.hpp", "max_issues_repo_name": "alexsr/vgl", "max_issues_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/vgl/math/math_utils.hpp", "max_forks_repo_name": "alexsr/vgl", "max_forks_repo_head_hexsha": "51fe9d990de4049bf3219b21a9ca930738a5c638", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1481481481, "max_line_length": 78, "alphanum_fraction": 0.6763803681, "num_tokens": 185, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511543206819, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6605831530721817}} {"text": "#pragma once\n\n// -*- C++ -*-\n\n// The MIT License (MIT)\n//\n// Copyright (c) 2017 Alexander Samoilov\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n#include \n#include \n#include \n#include \"math_consts.hpp\"\n\n/*! \\file elliptic_integral.h\n \\brief computation of elliptic integrals of the first and second kinds by iteration method\n\n Details.\n*/\n\n/**\n * \\f$ F\\left(k\\right)\\equiv\\int_0^{\\pi/2}\\frac{d\\eta}{\\sqrt{1-k^2\\cos^2\\eta}} \\f$\n */\ntemplate \nvoid elliptic_integral (T const& rk2, T& f, T& e)\n{\n constexpr T ACCURACY = T(1.0e-6);\n T rk = std::sqrt(rk2), g = ONE, b = rk, c, d;\n\n f = HALF * PI;\n e = ONE;\n do {\n c = std::sqrt(ONE - b*b);\n b = (ONE - c) / (ONE + c);\n d = f*b;\n f += d;\n g = HALF*g*b;\n e += g;\n } while (std::fabs(d) > ACCURACY);\n e = f * (ONE - HALF*rk2*e);\n}\n\ntemplate \nvoid elliptic_integral_new (T const& rk2, T& f, T& e)\n{\n T srk = std::sqrt(rk2);\n f = boost::math::ellint_1(srk);\n e = boost::math::ellint_2(srk);\n // `std::comp_ellint_1` and `std::comp_ellint_2` are too slow\n // f = std::comp_ellint_1(srk);\n // e = std::comp_ellint_2(srk);\n}\n", "meta": {"hexsha": "7f035f11205c0dce1a0c7faf3eaac76da3ef827e", "size": 2326, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "body_ax/src/elliptic_integral.hpp", "max_stars_repo_name": "alsam/cpp-samples", "max_stars_repo_head_hexsha": "abb14634b32dec9cfdfa8090ebee3df5e8479e6a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-04-14T15:42:59.000Z", "max_stars_repo_stars_event_max_datetime": "2017-08-18T10:51:29.000Z", "max_issues_repo_path": "body_ax/src/elliptic_integral.hpp", "max_issues_repo_name": "alsam/cpp-samples", "max_issues_repo_head_hexsha": "abb14634b32dec9cfdfa8090ebee3df5e8479e6a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "body_ax/src/elliptic_integral.hpp", "max_forks_repo_name": "alsam/cpp-samples", "max_forks_repo_head_hexsha": "abb14634b32dec9cfdfa8090ebee3df5e8479e6a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-10-29T13:57:21.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-29T13:57:21.000Z", "avg_line_length": 33.2285714286, "max_line_length": 94, "alphanum_fraction": 0.6633705933, "num_tokens": 662, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511506439707, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6605831412509422}} {"text": "///////////////////////////////////////////////////////////////////////////////\n// kurtosis.hpp\n//\n// Copyright 2006 Olivier Gygi, Daniel Egloff. Distributed under the Boost\n// Software License, Version 1.0. (See accompanying file\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_ACCUMULATORS_STATISTICS_KURTOSIS_HPP_EAN_28_10_2005\n#define BOOST_ACCUMULATORS_STATISTICS_KURTOSIS_HPP_EAN_28_10_2005\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace boost { namespace accumulators\n{\n\nnamespace impl\n{\n ///////////////////////////////////////////////////////////////////////////////\n // kurtosis_impl\n /**\n @brief Kurtosis estimation\n\n The kurtosis of a sample distribution is defined as the ratio of the 4th central moment and the square of the 2nd central\n moment (the variance) of the samples, minus 3. The term \\f$ -3 \\f$ is added in order to ensure that the normal distribution\n has zero kurtosis. The kurtosis can also be expressed by the simple moments:\n\n \\f[\n \\hat{g}_2 =\n \\frac\n {\\widehat{m}_n^{(4)}-4\\widehat{m}_n^{(3)}\\hat{\\mu}_n+6\\widehat{m}_n^{(2)}\\hat{\\mu}_n^2-3\\hat{\\mu}_n^4}\n {\\left(\\widehat{m}_n^{(2)} - \\hat{\\mu}_n^{2}\\right)^2} - 3,\n \\f]\n\n where \\f$ \\widehat{m}_n^{(i)} \\f$ are the \\f$ i \\f$-th moment and \\f$ \\hat{\\mu}_n \\f$ the mean (first moment) of the\n \\f$ n \\f$ samples.\n */\n template\n struct kurtosis_impl\n : accumulator_base\n {\n // for boost::result_of\n typedef typename numeric::functional::average::result_type result_type;\n\n kurtosis_impl(dont_care) {}\n\n template\n result_type result(Args const &args) const\n {\n return numeric::average(\n moment<4>(args)\n - 4. * moment<3>(args) * mean(args)\n + 6. * moment<2>(args) * mean(args) * mean(args)\n - 3. * mean(args) * mean(args) * mean(args) * mean(args)\n , ( moment<2>(args) - mean(args) * mean(args) )\n * ( moment<2>(args) - mean(args) * mean(args) )\n ) - 3.;\n }\n };\n\n} // namespace impl\n\n///////////////////////////////////////////////////////////////////////////////\n// tag::kurtosis\n//\nnamespace tag\n{\n struct kurtosis\n : depends_on, moment<3>, moment<4> >\n {\n /// INTERNAL ONLY\n ///\n typedef accumulators::impl::kurtosis_impl impl;\n };\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// extract::kurtosis\n//\nnamespace extract\n{\n extractor const kurtosis = {};\n}\n\nusing extract::kurtosis;\n\n// So that kurtosis can be automatically substituted with\n// weighted_kurtosis when the weight parameter is non-void\ntemplate<>\nstruct as_weighted_feature\n{\n typedef tag::weighted_kurtosis type;\n};\n\ntemplate<>\nstruct feature_of\n : feature_of\n{\n};\n\n}} // namespace boost::accumulators\n\n#endif\n", "meta": {"hexsha": "cb384f17b3e7dfc128604a7ce1c69facd89d2850", "size": 3575, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/accumulators/statistics/kurtosis.hpp", "max_stars_repo_name": "mike-code/boost_1_38_0", "max_stars_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2016-04-23T04:55:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-19T10:26:27.000Z", "max_issues_repo_path": "boost/accumulators/statistics/kurtosis.hpp", "max_issues_repo_name": "mike-code/boost_1_38_0", "max_issues_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2016-03-31T20:56:08.000Z", "max_issues_repo_issues_event_max_datetime": "2016-04-18T08:56:40.000Z", "max_forks_repo_path": "boost/accumulators/statistics/kurtosis.hpp", "max_forks_repo_name": "mike-code/boost_1_38_0", "max_forks_repo_head_hexsha": "7ff8b2069344ea6b0b757aa1f0778dfb8526df3c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2016-04-26T13:16:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T06:13:14.000Z", "avg_line_length": 32.2072072072, "max_line_length": 131, "alphanum_fraction": 0.5756643357, "num_tokens": 890, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9073122188543454, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.660501014463713}} {"text": "#include \n#include \n#include \"../Optimizer/optimizer\"\nusing namespace std;\nusing namespace Eigen;\n\ndouble func (double x) {\n return pow(x + 10, 2);\n}\n\ndouble func2 (VectorXd x) {\n return x.squaredNorm();\n}\n\nint main () {\n cout << \"Using Function: (x + 10)^2 for single variable algorithms testing.\" << endl;\n cout << \"Test Bounding Phase:\" << endl;\n double ipt = 5.4;\n Vector2d range = BoundingPhase(func, ipt);\n cout << \"Range from bounding Phase for initial point :\" << ipt << endl;\n cout << range << endl;\n\n cout << \"Derivatives at \" << ipt << endl;\n cout << Derivative(func, ipt) << endl;\n\n cout << \"Finding optimal point using above range for Newton Rapshon Method.\" << endl;\n cout << \"Optimal Point is: \";\n cout << NewtonRapshon (func, range) << endl;;\n\n cout << \"Testing SVOptimize on (x + 10)^2 with initial point 5.4.\" << endl;\n cout << \"The Optimal Point obtained is: \";\n cout << SVOptimize(func, 5.4) << endl;\n\n cout << \"Testing Gradient function using func2 with 3 variables\" << endl;\n cout << Gradient(func2, Vector3d(3, 3, 4)) << endl;\n\n cout << \"Testing DFP on sum squared function with 3 variables and initial point (4, -3, 7).\" << endl;\n cout << \"The Optimal Point obtained is: \" << endl;\n Vector3d x(4, -3, 7);\n cout << DFP(func2, x) << endl;\n\n}\n", "meta": {"hexsha": "80d58d1571bdf36a993c55560b689ba2875d9d72", "size": 1353, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Tests/test.cpp", "max_stars_repo_name": "dhairyagada/Optimizer", "max_stars_repo_head_hexsha": "c5fcf13279ec6368c42038627ff6712eaa1870e5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tests/test.cpp", "max_issues_repo_name": "dhairyagada/Optimizer", "max_issues_repo_head_hexsha": "c5fcf13279ec6368c42038627ff6712eaa1870e5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tests/test.cpp", "max_forks_repo_name": "dhairyagada/Optimizer", "max_forks_repo_head_hexsha": "c5fcf13279ec6368c42038627ff6712eaa1870e5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4651162791, "max_line_length": 105, "alphanum_fraction": 0.6201034738, "num_tokens": 386, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.660487089791331}} {"text": "#include \n#include \n\n#include \n#include \n#include \n\n\nusing namespace Eigen;\nusing namespace tvmtl;\n\n\ntemplate \ndouble F(const MatrixBase& Y, const MatrixBase& A){\n return 0.5 * (Y.transpose() * A * Y).trace();\n}\n\ntemplate \nMatrixBase FY(const MatrixBase& Y, const MatrixBase& A){\n return A * Y;\n}\n\n\nint main(){\n\nsrand(42);\n\nconst int N=4;\nconst int P=3;\n\ntypedef Matrix ppmat;\ntypedef Matrix npmat;\ntypedef Matrix nnmat;\ntypedef Matrix np2mat;\ntypedef Manifold mf;\n\nnnmat R = nnmat::Random();\nnnmat A = 0.5 * (R + R.transpose());\n\nstd::cout << \"A:\\n\" << A << std::endl;\n\nnpmat Y;\nY = npmat::Random();\nHouseholderQR qr(Y);\nnpmat q = qr.householderQ() * npmat::Identity();\nY = q;\n\nstd::cout << \"Y:\\n\" << Y << std::endl;\n\nnnmat HYproj = nnmat::Identity() - Y * Y.transpose();\n\ndouble h = 1e-2;\nnpmat dY;\ndY = npmat::Random(); \nqr.compute(dY);\nq = qr.householderQ() * npmat::Identity();\ndY = h * HYproj * q;\n\nstd::cout << \"DY:\\n\" << dY << std::endl;\n\nVectorXd vecdY = Map(dY.data(), dY.size());\n\t\nnpmat FY = A * Y;\nstd::cout << \"\\nFY:\\n\" << FY << std::endl;\n\nnp2mat FYY = kroneckerProduct(ppmat::Identity(), A);\nstd::cout << \"FYY:\\n\" << FYY << std::endl;\n\nnpmat YpdY = Y + dY;\n//mf::exp(Y,dY,YpdY);\nmf::projector(YpdY);\n\ndouble exact = F(Y + dY, A);\ndouble exact2 = F(YpdY, A);\ndouble firstorder = F(Y,A) + FY.cwiseProduct(dY).sum();\ndouble secondorder_euc = firstorder + 0.5 * FYY.cwiseProduct(vecdY * vecdY.transpose()).sum() ;\n\nnpmat FYYdY_proj = HYproj * A * dY;\nnpmat FYY_corr_term = dY * Y.transpose() * FY;\ndouble secondorder_grass_nv = firstorder + 0.5 * (FYYdY_proj.cwiseProduct(dY).sum() - FYY_corr_term.cwiseProduct(dY).sum());\n\nnp2mat FYY_proj = kroneckerProduct(ppmat::Identity(), HYproj) * FYY ;\ndouble secondorder_grass_sv = firstorder + 0.5 * (FYY_proj.cwiseProduct(vecdY * vecdY.transpose()).sum() - FYY_corr_term.cwiseProduct(dY).sum());\n\nnp2mat FYY_grass = FYY_proj - kroneckerProduct(FY.transpose() * Y, nnmat::Identity());\ndouble secondorder_grass_fv = firstorder + 0.5 * (FYY_grass.cwiseProduct(vecdY * vecdY.transpose()).sum());\nstd::cout << \"FYY_Grass:\\n\" << FYY_grass << std::endl;\n\nstd::cout << \"\\n\\nFirst order approximation: \" << std::abs(exact-firstorder) << std::endl;\nstd::cout << \"Second order approximation (Euclidian): \" << std::abs(exact-secondorder_euc) << std::endl;\nstd::cout << \"Second order approximation (Grassmann non-vectorized): \" << std::abs(exact2-secondorder_grass_sv) << std::endl;\nstd::cout << \"Second order approximation (Grassmann semi-vectorized): \" << std::abs(exact2-secondorder_grass_sv) << std::endl;\nstd::cout << \"Second order approximation (Grassmann vectorized): \" << std::abs(exact2-secondorder_grass_fv) << std::endl;\n\n\n\nreturn 0;\n}\n", "meta": {"hexsha": "42b12a156f77f4d913436195ae6e344bff7aab2c", "size": 3002, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/grassmannDerTest.cpp", "max_stars_repo_name": "pdebus/MTVMTL", "max_stars_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-05-08T12:40:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-02T05:11:01.000Z", "max_issues_repo_path": "test/grassmannDerTest.cpp", "max_issues_repo_name": "pdebus/MTVMTL", "max_issues_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/grassmannDerTest.cpp", "max_forks_repo_name": "pdebus/MTVMTL", "max_forks_repo_head_hexsha": "65a7754b34d1f6a1e86d15e3c2d4346b9418414f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3232323232, "max_line_length": 145, "alphanum_fraction": 0.6798800799, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6604870882136259}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"../include/numerical_gradient.h\"\n#include \"../include/optimizer.h\"\n\nusing namespace Eigen;\nnamespace plt = matplotlibcpp;\n\ndouble sample_function(MatrixXd &);\nMatrixXd sample_function_gradient(MatrixXd &);\n\nint main()\n{\n using std::cout;\n using std::endl;\n using std::unordered_map;\n using std::vector;\n using namespace MyDL;\n\n vector> x, y, z;\n MatrixXd X = MatrixXd::Zero(1, 2);\n for (double i = -2; i <= 2; i += 0.1)\n {\n vector x_row, y_row, z_row;\n for (double j = -2; j <= 2; j += 0.1)\n {\n X(0) = i;\n X(1) = j;\n x_row.push_back(i);\n y_row.push_back(j);\n z_row.push_back(sample_function(X));\n }\n x.push_back(x_row);\n y.push_back(y_row);\n z.push_back(z_row);\n }\n\n plt::plot_surface(x, y, z);\n plt::save(\"suddle_function.png\");\n plt::clf();\n\n // x.clear();\n // y.clear();\n // vector ux, uy, vx, vy;\n // MatrixXd grad = MatrixXd::Zero(1, 2);\n // for (double i = -10; i <= 10; i++)\n // {\n // for (double j = -5; j <= 5; j++)\n // {\n // ux.push_back(i);\n // uy.push_back(j);\n // X(0) = i;\n // X(1) = j;\n // grad = sample_function_gradient(X);\n // vx.push_back((double)-grad(0));\n // vy.push_back((double)-grad(1));\n // }\n // }\n\n // Adam optimizer(0.3, 0.7, 0.9);\n // unordered_map params, grads;\n // int num_update = 30;\n // vector> param_history(2, vector(num_update, 0));\n // X(0) = -6;\n // X(1) = 2;\n // params[\"X\"] = X;\n // param_history[0][0] = X(0);\n // param_history[1][0] = X(1);\n\n // for (int i = 0; i < num_update; i++)\n // {\n // cout << \"iteration: \" << i << endl;\n // grads[\"X\"] = sample_function_gradient(params[\"X\"]);\n // optimizer.update(params, grads);\n\n // param_history[0][i + 1] = (double)params[\"X\"](0);\n // param_history[1][i + 1] = (double)params[\"X\"](1);\n // }\n\n // plt::quiver(ux, uy, vx, vy);\n // plt::save(\"SGD_function_gradient.png\");\n\n // plt::plot(param_history[0], param_history[1], {{\"color\", \"red\"}, {\"marker\", \"o\"}, {\"linestyle\", \"--\"}, {\"label\", \"$f(x, y) = \\\\frac{1}{20}x^{2} + y^{2}$\"}});\n // plt::plot(vector(1, 0), vector(1, 0), \"b+\");\n // plt::title(\"Adam: $f(x,y) = 0.05x^{2} + y^{2}$\");\n // plt::legend();\n // plt::save(\"Adam_function_gradient_descent.png\");\n // plt::cla();\n\n return 0;\n}\n\ndouble sample_function(MatrixXd &x)\n{\n return 0.25 * (- x(0) * x(0) + x(1) * x(1));\n}\n\n// MatrixXd sample_function_gradient(MatrixXd &x)\n// {\n// MatrixXd grad(1, 2);\n// grad(0) = 0.1 * x(0);\n// grad(1) = 2 * x(1);\n// return grad;\n// }", "meta": {"hexsha": "409167078b697c9071d12c9f72a8d7a8c1232b0c", "size": 2953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/suddle_point.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "test/suddle_point.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/suddle_point.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5981308411, "max_line_length": 164, "alphanum_fraction": 0.5096512022, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7826624738835051, "lm_q1q2_score": 0.6604850163724444}} {"text": "#ifndef DCS_TESTBED_DETAIL_VARIANCE_HPP\n#define DCS_TESTBED_DETAIL_VARIANCE_HPP\n\n\n#include \n#include \n#include \n#include \n\n\nnamespace dcs { namespace testbed { namespace detail {\n\n// See: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance\ntemplate \nValueT compensated_variance(IterT first, IterT last)\n{\n std::size_t n = 0;\n ValueT mean = 0;\n\n\tfor (IterT it = first; it != last; ++it)\n\t{\n\t\tconst ValueT x = *it;\n\t\t++n;\n\t\tmean += x;\n\t}\n\tmean /= n;\n\n ValueT sum1 = 0;\n ValueT sum2 = 0;\n\tfor (IterT it = first; it != last; ++it)\n\t{\n\t\tconst ValueT x = *it;\n\t\tconst ValueT dev = x-mean;\n\n sum1 += dev*dev;\n sum2 += dev;\n\t}\n\n return (n > 1) ? ((sum1 - sum2*sum2/n)/(n - 1)) : 0;\n}\n\ntemplate \nValueT boost_variance(IterT first, IterT last)\n{\n\tboost::accumulators::accumulator_set > acc;\n\tstd::size_t n = 0;\n\n\twhile (first != last)\n\t{\n\t\tacc(*first);\n\t\t++first;\n\t\t++n;\n\t}\n\n\treturn (n > 1) ? boost::accumulators::variance(acc)*n/static_cast(n-1) : 0;\n}\n\ntemplate \nValueT variance(IterT first, IterT last)\n{\n\treturn boost_variance(first, last);\n}\n\ntemplate \nValueT stdev(IterT first, IterT last)\n{\n\treturn std::sqrt(variance(first, last));\n}\n\n}}} // Namespace dcs::testbed::detail\n\n\n#endif // DCS_TESTBED_DETAIL_VARIANCE_HPP\n", "meta": {"hexsha": "d242bfa4b4e2b31a0138a8afada92dc865caa57c", "size": 1573, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/testbed/detail/variance.hpp", "max_stars_repo_name": "sguazt/dcsxx-testbed", "max_stars_repo_head_hexsha": "e7210f0c7f54256d5bf0c90297e0c4f9eaf82da0", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/testbed/detail/variance.hpp", "max_issues_repo_name": "sguazt/dcsxx-testbed", "max_issues_repo_head_hexsha": "e7210f0c7f54256d5bf0c90297e0c4f9eaf82da0", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/testbed/detail/variance.hpp", "max_forks_repo_name": "sguazt/dcsxx-testbed", "max_forks_repo_head_hexsha": "e7210f0c7f54256d5bf0c90297e0c4f9eaf82da0", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.2567567568, "max_line_length": 115, "alphanum_fraction": 0.6834075016, "num_tokens": 481, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950868503681, "lm_q2_score": 0.7826624688140726, "lm_q1q2_score": 0.6604850120943754}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\nusing namespace arma;\n\nvoid RHO_A_FILL(vec &rho, mat &A, int N,double rhoN); //rho, kind of like a linespace\n //A, Tridiagonal matrix\nvoid Maxoff(mat &A, int N,int &k, int &l, double &max); //Finds the max element of a matrix\n\nvoid Maxoff_test(double &max,int &k,int &l);\n\nvoid Ortho_test(mat &S,int N);\n\nint main(){\n int N = 400; //matrix size; N x N\n double rhoN = 60;\n double max;\n int k,l;\n Maxoff_test(max,k,l);\n\n mat A = mat(N,N,fill::zeros); //indexes go from (0) to (N-1)\n mat S = mat(N,N,fill::eye);\n vec rho = vec(N,fill::zeros);\n vec eigen = vec(N);\n\n RHO_A_FILL(rho,A,N,rhoN);\n Maxoff(A,N,k,l,max);\n int iterations = 0;\n\n double eps = 1E-10;\n\n double tau, t, s, c, il, ik, kk, ll, s_ik, s_il;\n double start, finish;\n\n start = clock(); //clock value before eigen solve\n while(max > eps){\n tau = (A(l,l)-A(k,k))/(double(2)*A(k,l));\n if(tau>0){\n t = (-tau - sqrt(1.0 + tau*tau));}\n else{t = ( -tau + sqrt(1.0 + tau*tau));}\n \n //cosine and sine\n c = double(1)/sqrt(1.+t*t);\n s = t*c;\n \n //Jacobi rotating A round theta in N-dim space\n for(int i = 0; i 0) rho(i) = i*h; \n A(i,i) = 2./(h*h)+ double(25)*rho(i)*rho(i)+(double(1)/rho(i));\n if(i max){\n max =A(i,j)*A(i,j);\n k = i; \n l = j;\n }\n }\n }\n \n }\n////////////Unit tests\nvoid Maxoff_test(double &max,int &k,int &l){\n mat matrix = mat(5,5,fill::zeros);\n matrix(0,3) = -9;\n matrix(3,0) = -9;\n matrix(4,4) = -3;\n matrix(3,4) = -1;\n matrix(4,3) = -1;\n Maxoff(matrix,5,k,l,max);\n if(abs(max-81) < 1E-13){cout << \"Maxoff function passes the test\"<\n#include \n\nnamespace sw {\nnamespace hprblas {\n\n// LEVEL 1 BLAS operators\n\n// 1-norm of a vector: sum of magnitudes of the vector elements, default increment stride is 1\ntemplate\ntypename Vector::value_type asum(size_t n, const Vector& x, size_t incx = 1) {\n\ttypename Vector::value_type sum = 0;\n\tsize_t ix;\n\tfor (ix = 0; ix < n; ix += incx) {\n\t\tsum += (x[ix] < 0 ? -x[ix] : x[ix]);\n\t}\n\treturn sum;\n}\n\n// sum of the vector elements, default increment stride is 1\ntemplate\ntypename Vector::value_type sum(size_t n, const Vector& x, size_t incx = 1) {\n\ttypename Vector::value_type sum = 0;\n\tsize_t ix;\n\tfor (ix = 0; ix < n; ix += incx) {\n\t\tsum += x[ix];\n\t}\n\treturn sum;\n}\n\n// a time x plus y\ntemplate\nvoid axpy(size_t n, Scalar a, const Vector& x, size_t incx, Vector& y, size_t incy) {\n\tusing namespace mtl;\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) {\n\t\ty[iy] += a * x[ix];\n\t}\n}\n\n// vector copy\ntemplate\nvoid copy(size_t n, const Vector& x, size_t incx, Vector& y, size_t incy) {\n\tusing namespace mtl;\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) {\n\t\ty[iy] = x[ix];\n\t}\n}\n\n// adapter for STL vectors\n//template auto size(const std::vector& v) { return v.size(); }\n\n// dot product: the operator vector::x[index] is limited to uint32_t, so the arguments are limited to uint32_t as well\n// The library does support arbitrary posit configuration conversions, but to simplify the \n// behavior of the dot product, the element type of the vectors x and y are declared to be the same.\n// TODO: investigate if the vector<> index is always a 32bit entity?\ntemplate\ntypename Vector::value_type dot(size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) {\n\tusing namespace mtl;\n\ttypename Vector::value_type product = 0;\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < n && ix < mtl::size(x) && iy < mtl::size(y); ++cnt, ix += incx, iy += incy) {\n\t\tproduct += x[ix] * y[iy];\n\t}\n\treturn product;\n}\n// specialized dot product\ntemplate\ntypename Vector::value_type dot(const Vector& x, const Vector& y) {\n\tusing namespace mtl;\n\ttypename Vector::value_type product = 0;\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < mtl::size(x); ++cnt, ++ix, ++iy) {\n\t\tproduct += x[ix] * y[iy];\n\t}\n\treturn product;\n}\n///\n/// fused dot product operators\n\n// Fused dot product with quire continuation\ntemplate\nvoid fdp_qr(Quire& sum_of_products, size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) {\n\tsize_t ix, iy;\n\tfor (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) {\n\t\tsum_of_products += sw::universal::quire_mul(x[ix], y[iy]);\n\t}\n}\n// Resolved fused dot product, with the option to control capacity bits in the quire\ntemplate\ntypename Vector::value_type fdp_stride(size_t n, const Vector& x, size_t incx, const Vector& y, size_t incy) {\n\tconstexpr size_t nbits = Vector::value_type::nbits;\n\tconstexpr size_t es = Vector::value_type::es;\n\tsw::universal::quire q(0);\n\tsize_t ix, iy;\n\tfor (ix = 0, iy = 0; ix < n && iy < n; ix = ix + incx, iy = iy + incy) {\n\t\tq += sw::universal::quire_mul(x[ix], y[iy]);\n\t\tif (sw::universal::_trace_quire_add) std::cout << q << '\\n';\n\t}\n\ttypename Vector::value_type sum;\n\tsw::universal::convert(q.to_value(), sum); // one and only rounding step of the fused-dot product\n\treturn sum;\n}\n// Specialized resolved fused dot product that assumes unit stride and a standard vector,\n// with the option to control capacity bits in the quire\ntemplate\ntypename Vector::value_type fdp(const Vector& x, const Vector& y) {\n\tusing namespace mtl;\n\tconstexpr size_t nbits = Vector::value_type::nbits;\n\tconstexpr size_t es = Vector::value_type::es;\n\tsw::universal::quire q(0);\n\tsize_t ix, iy, n = mtl::size(x);\n\tfor (ix = 0, iy = 0; ix < n && iy < n; ++ix, ++iy) {\n\t\tq += sw::universal::quire_mul(x[ix], y[iy]);\n\t}\n\ttypename Vector::value_type sum;\n\tsw::universal::convert(q.to_value(), sum); // one and only rounding step of the fused-dot product\n\treturn sum;\n}\n\n// rotation of points in the plane\ntemplate\nvoid rot(size_t n, Vector& x, size_t incx, Vector& y, size_t incy, Rotation c, Rotation s) {\n\tusing namespace mtl;\n\t// x_i = c*x_i + s*y_i\n\t// y_i = c*y_i - s*x_i\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) {\n\t\tRotation x_i = c*x[ix] + s*y[iy];\n\t\tRotation y_i = c*y[iy] - s*x[ix];\n\t\ty[iy] = y_i;\n\t\tx[ix] = x_i;\n\t}\n}\n\n// compute parameters for a Givens rotation\ntemplate\nvoid rotg(T& a, T& b, T& c, T&s) {\n\t// Given Cartesian coordinates (a,b) of a point, return parameters c,s,r, and z associated with the Givens rotation.\n}\n\n// scale a vector\ntemplate\nvoid scale(size_t n, Scalar a, Vector& x, size_t incx) {\n\tusing namespace mtl;\n\tsize_t cnt, ix;\n\tfor (cnt = 0, ix = 0; cnt < n && ix < size(x); ix += incx) {\n\t\tx[ix] *= a;\n\t}\n}\n\n// swap two vectors\ntemplate\nvoid swap(size_t n, Vector& x, size_t incx, Vector& y, size_t incy) {\n\tusing namespace mtl;\n\tsize_t cnt, ix, iy;\n\tfor (cnt = 0, ix = 0, iy = 0; cnt < n && ix < size(x) && iy < size(y); ++cnt, ix += incx, iy += incy) {\n\t\ttypename Vector::value_type tmp = x[ix];\n\t\tx[ix] = y[iy];\n\t\ty[iy] = tmp;\n\t}\n}\n\n// find the index of the element with maximum absolute value\ntemplate\nsize_t amax(size_t n, const Vector& x, size_t incx) {\n\tusing namespace mtl;\n\ttypename Vector::value_type running_max = -INFINITY;\n\tsize_t ix, index;\n\tfor (ix = 0; ix < size(x); ix += incx) {\n\t\tif (x[ix] > running_max) {\n\t\t\tindex = ix;\n\t\t\trunning_max = x[ix];\n\t\t}\n\t}\n\treturn index;\n}\n\n// find the index of the element with minimum absolute value\ntemplate\nsize_t amin(size_t n, const Vector& x, size_t incx) {\n\tusing namespace mtl;\n\ttypename Vector::value_type running_min = INFINITY;\n\tsize_t ix, index;\n\tfor (ix = 0; ix < size(x); ix += incx) {\n\t\tif (x[ix] < running_min) {\n\t\t\tindex = ix;\n\t\t\trunning_min = x[ix];\n\t\t}\n\t}\n\treturn index;\n}\n\n// absolute value of a complex number\ntemplate\nT cabs(T z) {\n}\n\n// print a vector\ntemplate\nvoid strided_print(std::ostream& ostr, size_t n, Vector& x, size_t incx = 1) {\n\tusing namespace mtl;\n\tsize_t cnt, ix;\n\tfor (cnt = 0, ix = 0; cnt < n && ix < size(x); ++cnt, ix += incx) {\n\t\tcnt == 0 ? ostr << \"[\" << x[ix] : ostr << \", \" << x[ix];\n\t}\n\tostr << \"]\";\n}\n\n\n// LEVEL 2 BLAS operators\n\n// Matrix-vector product: b = A * x\ntemplate\nvoid matvec(Vector& b, const Matrix& A, const Vector& x) {\n\tb = A * x;\n}\n\n// Matrix-vector product: b = A * x, posit specialized\ntemplate\nvoid matvec(mtl::vec::dense_vector< sw::universal::posit >& b, const mtl::mat::dense2D< sw::universal::posit >& A, const mtl::vec::dense_vector< sw::universal::posit >& x) {\n\tusing namespace mtl;\n\t// preconditions\n\tassert(A.num_cols() == size(x));\n\tassert(size(b) == size(x));\n\n#if HPRBLAS_TRACE_ROUNDING_EVENTS\n\tunsigned errors = 0;\n#endif\n\tsize_t nr = size(b);\n\tsize_t nc = size(x);\n\tfor (size_t i = 0; i < nr; ++i) {\n\t\tsw::universal::quire q(0);\n\t\tfor (size_t j = 0; j < nc; ++j) {\n\t\t\tq += sw::universal::quire_mul(A[i][j], x[j]);\n\t\t}\n\t\tsw::universal::convert(q.to_value(), b[i]); // one and only rounding step of the fused-dot product\n#if HPRBLAS_TRACE_ROUNDING_EVENTS\n\t\tsw::universal::quire qdiff = q;\n\t\tsw::universal::quire qsum = b[i];\n\t\tqdiff -= qsum;\n\t\tif (!qdiff.iszero()) {\n\t\t\t++errors;\n\t\t\tstd::cout << \"q : \" << q << std::endl;\n\t\t\tstd::cout << \"qsum : \" << qsum << std::endl;\n\t\t\tstd::cout << \"qdiff: \" << qdiff << std::endl;\n\t\t\tsw::universal::posit roundingError;\n\t\t\tconvert(qdiff.to_value(), roundingError);\n\t\t\tstd::cout << \"matvec b[\" << i << \"] = \" << posit_format(b[i]) << \" rounding error: \" << posit_format(roundingError) << \" \" << roundingError << std::endl;\n\t\t}\n#endif\n\t}\n#if HPRBLAS_TRACE_ROUNDING_EVENTS\n\tif (errors) {\n\t\tstd::cout << \"HPR-BLAS: tracing found \" << errors << \" rounding errors in matvec operation\\n\";\n\t}\n#endif\n}\n\n// A times x = b fused matrix-vector product\ntemplate\nmtl::vec::dense_vector< sw::universal::posit > fmv(const mtl::mat::dense2D< sw::universal::posit >& A, const mtl::vec::dense_vector< sw::universal::posit >& x) {\n\tusing namespace mtl;\n\t// preconditions\n\tassert(A.num_cols() == size(x));\n\tmtl::vec::dense_vector< sw::universal::posit > b(size(x));\n\n#if HPRBLAS_TRACE_ROUNDING_EVENTS\n\tunsigned errors = 0;\n#endif\n\tsize_t nr = size(b);\n\tsize_t nc = size(x);\n\tfor (size_t i = 0; i < nr; ++i) {\n\t\tsw::universal::quire q(0);\n\t\tfor (size_t j = 0; j < nc; ++j) {\n\t\t\tq += sw::universal::quire_mul(A[i][j], x[j]);\n\t\t}\n\t\tsw::universal::convert(q.to_value(), b[i]); // one and only rounding step of the fused-dot product\n#if HPRBLAS_TRACE_ROUNDING_EVENTS\n\t\tsw::universal::quire qdiff = q;\n\t\tsw::universal::quire qsum = b[i];\n\t\tqdiff -= qsum;\n\t\tif (!qdiff.iszero()) {\n\t\t\t++errors;\n\t\t\tstd::cout << \"q : \" << q << std::endl;\n\t\t\tstd::cout << \"qsum : \" << qsum << std::endl;\n\t\t\tstd::cout << \"qdiff: \" << qdiff << std::endl;\n\t\t\tsw::universal::posit roundingError;\n\t\t\tconvert(qdiff.to_value(), roundingError);\n\t\t\tstd::cout << \"matvec b[\" << i << \"] = \" << posit_format(b[i]) << \" rounding error: \" << posit_format(roundingError) << \" \" << roundingError << std::endl;\n\t\t}\n#endif\n\t}\n#if HPRBLAS_TRACE_ROUNDING_EVENTS\n\tif (errors) {\n\t\tstd::cout << \"HPR-BLAS: tracing found \" << errors << \" rounding errors in matvec operation\\n\";\n\t}\n#endif\n\treturn b;\n}\n\n// LEVEL 3 BLAS operators\n\ntemplate\nvoid matmul(Matrix& C, const Matrix& A, const Matrix& B) {\n\tC = A * B;\n}\n\n// C = A * B fused matrix-matrix product when posits are used\ntemplate\nvoid matmul(mtl::mat::dense2D< sw::universal::posit >& C, const mtl::mat::dense2D< sw::universal::posit >& A, const mtl::mat::dense2D< sw::universal::posit >& B) {\n\t// precondition\n\tassert(A.num_cols() == B.num_rows());\n\tsize_t nr = A.num_rows();\n\tsize_t nc = B.num_cols();\n\tsize_t nk = A.num_cols();\n\t// TODO: add asserts to make certain that C is the right size\n\n\tfor (size_t i = 0; i < nr; ++i) {\n\t\tfor (size_t j = 0; j < nc; ++j) {\n\t\t\tsw::universal::quire q(0);\n\t\t\tfor (size_t k = 0; k < nk; ++k) {\n\t\t\t\tq += sw::universal::quire_mul(A[i][k], B[k][j]);\n\t\t\t}\n\t\t\tsw::universal::convert(q.to_value(), C[i][j]); // one and only rounding step of the fused-dot product\n\t\t}\n\t}\n}\n\n// C = A * B fused matrix-matrix product when posits are used\ntemplate\nmtl::mat::dense2D< sw::universal::posit > fmm(const mtl::mat::dense2D< sw::universal::posit >& A, const mtl::mat::dense2D< sw::universal::posit >& B) {\n\t// precondition\n\tassert(A.num_cols() == B.num_rows());\n\tsize_t nr = A.num_rows();\n\tsize_t nc = B.num_cols();\n\tsize_t nk = A.num_cols();\n\tmtl::mat::dense2D< sw::universal::posit > C(nr, nc);\n\n\tfor (size_t i = 0; i < nr; ++i) {\n\t\tfor (size_t j = 0; j < nc; ++j) {\n\t\t\tsw::universal::quire q(0);\n\t\t\tfor (size_t k = 0; k < nk; ++k) {\n\t\t\t\tq += sw::universal::quire_mul(A[i][k], B[k][j]);\n\t\t\t}\n\t\t\tsw::universal::convert(q.to_value(), C[i][j]); // one and only rounding step of the fused-dot product\n\t\t}\n\t}\n\treturn C;\n}\n\ntemplate\ninline Scalar minimum(const Scalar& a, const Scalar& b) {\n\treturn (a < b ? a : b);\n}\n\n// if you only specify one set of block parameters in the specification then by \n// the virtue of doing block matrix multiplication you generate the invariant : blockHeight == blockWidth\n// Thus, no need to specify blockHeight and blockWidth: we can simplify to blockSize\n// blockHeight = blockWidth = blockSize\n\n// subBlockMM generates the partial sums of a sub-block matrix multiply\n// the QuireMatrix is [blockHeight][blockWidth] submatrix\n// A and B matrices are full [n][m] and [m][n] matrices\ntemplate\nvoid subBlockMM(Matrix& C_partial, const Matrix& A, unsigned Ai, unsigned Aj, const Matrix& B, unsigned Bi, unsigned Bj) {\n\tassert(mtl::mat::num_rows(C_partial) == mtl::mat::num_cols(C_partial));\n\tusing Scalar = typename Matrix::value_type;\n//\tconstexpr size_t nbits = Scalar::nbits;\n//\tconstexpr size_t es = Scalar::es;\n\n\tunsigned aRows = unsigned(mtl::mat::num_rows(A));\n\tunsigned aCols = unsigned(mtl::mat::num_cols(A));\n\tunsigned bRows = unsigned(mtl::mat::num_rows(B));\n\tunsigned bCols = unsigned(mtl::mat::num_cols(B));\n\n\tunsigned blockSize = unsigned(mtl::mat::num_rows(C_partial));\n\n\tunsigned aRow = Ai * blockSize;\n\tunsigned aCol = Aj * blockSize;\n\tunsigned bRow = Bi * blockSize;\n\tunsigned bCol = Bj * blockSize;\n\n\t// calculate the shape of submatrix A\n\tunsigned ar = (aRow + blockSize < aRows) ? blockSize : aRows - aRow;\n\tunsigned ac = (aCol + blockSize < aCols) ? blockSize : aCols - aCol;\n\tunsigned br = (bRow + blockSize < bRows) ? blockSize : bRows - bRow;\n\tunsigned bc = (bCol + blockSize < bCols) ? blockSize : bCols - bCol;\n\t\n//\tstd::cout << \"A=\" << ar << \"x\" << ac << \" B=\" << br << \"x\" << bc << std::endl;\n\tassert(ac == br);\n\t// A(ar,ac) x B(br,bc) = C(ar,bc) if ac == br\n\tfor (unsigned i = 0; i < ar; ++i) {\n\t\tfor (unsigned j = 0; j < bc; ++j) {\n\t\t\tfor (unsigned k = 0; k < ac; ++k) {\n\t\t\t\tC_partial[i][j] += A[aRow + i][aCol + k] * B[bRow + k][bCol + j];\n\t\t\t}\n//\t\t\tstd::cout << \"A(\" << Ai << \",\" << Aj << \") B(\" << Bi << \",\" << Bj << \") C(\" << i << \",\" << j << \")\\n\";\n//\t\t\tprintMatrix(std::cout, \"partial\", C_partial);\n\t\t}\n\t}\n}\n\n// copySubBlockInto copies a subblock matrix into of the mother matrix\ntemplate\nvoid copySubBlockInto(Matrix& A, unsigned ai, unsigned aj, const Matrix& SubBlock) {\n\tunsigned blockHeight = unsigned(mtl::mat::num_rows(SubBlock));\n\tunsigned blockWidth = unsigned(mtl::mat::num_cols(SubBlock));\n\n\tunsigned aRows = unsigned(mtl::mat::num_rows(A));\n\tunsigned aCols = unsigned(mtl::mat::num_cols(A));\n\n\tunsigned aRow = ai * blockHeight;\n\tunsigned aCol = aj * blockWidth;\n\n\tunsigned maxRow = (aRow + blockHeight < aRows) ? blockHeight : aRows - aRow;\n\tunsigned maxCol = (aCol + blockWidth < aCols) ? blockWidth : aCols - aCol;\n\n\tfor (unsigned i = 0; i < maxRow; ++i) {\n\t\tfor (unsigned j = 0; j < maxCol; ++j) {\n\t\t\tA[aRow + i][aCol + j] = SubBlock[i][j];\n\t\t}\n\t}\n}\n\n// bmm is a blocked matrix multply: C = A * B\ntemplate\nMatrix bmm(const Matrix& A, const Matrix& B, unsigned blockSize) {\n\t// precondition\n\tassert(A.num_cols() == B.num_rows());\n\tunsigned nr = unsigned(A.num_rows());\n\tunsigned nc = unsigned(B.num_cols());\n\tunsigned nk = unsigned(A.num_cols());\n\tMatrix C(nr, nc);\n\n\tusing Scalar = typename Matrix::value_type;\n\tMatrix C_partial(blockSize, blockSize);\n\n\tunsigned nrRowBlocks = nr % blockSize ? nr / blockSize + 1 : nr / blockSize;\n\tunsigned nrColBlocks = nc % blockSize ? nr / blockSize + 1 : nc / blockSize;\n\tfor (unsigned bi = 0; bi < nrRowBlocks; ++bi) {\t\t\t// row block index\n\t\tfor (unsigned bj = 0; bj < nrColBlocks; ++bj) {\t\t// col block index\n\t\t\tC_partial = Scalar(0);\n\t\t\tfor (unsigned bk = 0; bk < nrRowBlocks; ++bk) { // block iterator\n\t\t\t\tsubBlockMM(C_partial, A, bi, bk, B, bk, bj);\n\t\t\t}\n\t\t\tcopySubBlockInto(C, bi, bj, C_partial);\n\t\t}\n\t}\n\treturn C;\n}\n\n// subBlockMM generates the partial sums of a sub-block matrix multiply\n// the QuireMatrix is a square matrix\n// A and B matrices are full [n][m] and [m][n] matrices\ntemplate\nvoid subBlockMM(QuireMatrix& C, const Matrix& A, unsigned Ai, unsigned Aj, const Matrix& B, unsigned Bi, unsigned Bj) {\n\tassert(mtl::mat::num_rows(C) == mtl::mat::num_cols(C));\n\tusing Scalar = typename Matrix::value_type;\n\tconstexpr size_t nbits = Scalar::nbits;\n\tconstexpr size_t es = Scalar::es;\n\n\tunsigned aRows = unsigned(mtl::mat::num_rows(A));\n\tunsigned aCols = unsigned(mtl::mat::num_cols(A));\n\tunsigned bRows = unsigned(mtl::mat::num_rows(B));\n\tunsigned bCols = unsigned(mtl::mat::num_cols(B));\n\n\tunsigned blockSize = unsigned(mtl::mat::num_rows(C));\n\n\tunsigned aRow = Ai * blockSize;\n\tunsigned aCol = Aj * blockSize;\n\tunsigned bRow = Bi * blockSize;\n\tunsigned bCol = Bj * blockSize;\n\n\t// calculate the shape of submatrix A\n\tunsigned ar = (aRow + blockSize < aRows) ? blockSize : aRows - aRow;\n\tunsigned ac = (aCol + blockSize < aCols) ? blockSize : aCols - aCol;\n\tunsigned br = (bRow + blockSize < bRows) ? blockSize : bRows - bRow;\n\tunsigned bc = (bCol + blockSize < bCols) ? blockSize : bCols - bCol;\n\n\t//\tstd::cout << \"A=\" << ar << \"x\" << ac << \" B=\" << br << \"x\" << bc << std::endl;\n\tassert(ac == br);\n\t// A(ar,ac) x B(br,bc) = C(ar,bc) if ac == br\n\tfor (unsigned i = 0; i < ar; ++i) {\n\t\tfor (unsigned j = 0; j < bc; ++j) {\n\t\t\tfor (unsigned k = 0; k < ac; ++k) {\n\t\t\t\tC[i][j] += sw::universal::quire_mul(A[aRow+i][aCol+k], B[bRow+k][bCol+j]);\n\t\t\t}\n\t\t}\n\t}\n}\n\n// subBlockRound takes a sub-block address and a QuireMatrix and rounds the partial sums\n\ntemplate\nvoid subBlockRound(Matrix& C, unsigned ci, unsigned cj, const QuireMatrix& C_partial) {\n\tunsigned blockHeight = unsigned(mtl::mat::num_rows(C_partial));\n\tunsigned blockWidth = unsigned(mtl::mat::num_cols(C_partial));\n\n\tunsigned cRows = unsigned(mtl::mat::num_rows(C));\n\tunsigned cCols = unsigned(mtl::mat::num_cols(C));\n\n\tunsigned cRow = ci * blockHeight;\n\tunsigned cCol = cj * blockWidth;\n\n\tunsigned maxRow = (cRow + blockHeight < cRows) ? blockHeight : cRows - cRow;\n\tunsigned maxCol = (cCol + blockWidth < cCols) ? blockWidth : cCols - cCol;\n\n\tfor (unsigned i = 0; i < maxRow; ++i) {\n\t\tfor (unsigned j = 0; j < maxCol; ++j) {\n\t\t\tsw::universal::convert(C_partial[i][j].to_value(), C[cRow + i][cCol + j]);\n\t\t}\n\t}\n}\n\n// copySubBlock copies a subblock matrix out of the mother matrix\n// This function is more generic than used in block matmul, as this can take non-square matrices\ntemplate\nvoid copySubBlock(Matrix& SubBlock, const Matrix& M, unsigned bi, unsigned bj) {\n\tunsigned blockHeight = unsigned(mtl::mat::num_rows(SubBlock));\n\tunsigned blockWidth = unsigned(mtl::mat::num_cols(SubBlock));\n\tfor (unsigned i = 0; i < blockHeight; ++i) {\n\t\tfor (unsigned j = 0; j < blockWidth; ++j) {\n\t\t\tSubBlock[i][j] = M[bi*blockHeight + i][bj*blockWidth + j];\n\t\t}\n\t}\n}\n\n// bfmm is a blocked fused matrix multply: C = A * B\ntemplate\nMatrix bfmm(const Matrix& A, const Matrix& B, unsigned blockSize) {\n\t// precondition\n\tassert(A.num_cols() == B.num_rows());\n\tunsigned nr = unsigned(A.num_rows());\n\tunsigned nc = unsigned(B.num_cols());\n\tunsigned nk = unsigned(A.num_cols());\n\tMatrix C(nr, nc);\n\n\tusing Scalar = typename Matrix::value_type;\n\tconstexpr size_t nbits = Scalar::nbits;\n\tconstexpr size_t es = Scalar::es;\n\tusing Quire = typename sw::universal::quire;\n\tusing QuireMatrix = typename mtl::mat::dense2D;\n\tQuireMatrix C_partial(blockSize, blockSize);\n\n\tunsigned nrRowBlocks = nr % blockSize ? nr / blockSize + 1 : nr / blockSize;\n\tunsigned nrColBlocks = nc % blockSize ? nr / blockSize + 1 : nc / blockSize;\n\tfor (unsigned bi = 0; bi < nrRowBlocks; ++bi) {\t\t\t// row block index\n\t\tfor (unsigned bj = 0; bj < nrColBlocks; ++bj) {\t\t// col block index\n\t\t\tC_partial = Scalar(0);\n\t\t\tfor (unsigned bk = 0; bk < nrRowBlocks; ++bk) { // block iterator\n\t\t\t\tsubBlockMM(C_partial, A, bi, bk, B, bk, bj);\n\t\t\t}\n\t\t\tsubBlockRound(C, bi, bj, C_partial); // C_sub(i,j) = round(QuireMatrix)\n\t\t}\n\t}\n\treturn C;\n}\n\n}} // namespace sw::hprblas\n", "meta": {"hexsha": "4b449a238e2aac08c2fda0e081cfb72ffc2ca8d5", "size": 20270, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/hprblas.hpp", "max_stars_repo_name": "shikharvashistha/hpr-blas", "max_stars_repo_head_hexsha": "73f109d45701fc3816af0a1ecd42f11d494a6f97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-07T11:30:17.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-07T11:30:17.000Z", "max_issues_repo_path": "include/hprblas.hpp", "max_issues_repo_name": "jamesquinlan/hpr-blas", "max_issues_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/hprblas.hpp", "max_forks_repo_name": "jamesquinlan/hpr-blas", "max_forks_repo_head_hexsha": "2975b4378b36a0bdc55d0dbd4f979163f7009678", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.6866197183, "max_line_length": 206, "alphanum_fraction": 0.6525900345, "num_tokens": 6221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891218080991, "lm_q2_score": 0.8031737940012418, "lm_q1q2_score": 0.66036075634916}} {"text": "/**\n * \\file\n * \\copyright\n * Copyright (c) 2012-2019, OpenGeoSys Community (http://www.opengeosys.org)\n * Distributed under a Modified BSD License.\n * See accompanying file LICENSE.txt or\n * http://www.opengeosys.org/project/license\n */\n\n#include \n\n#include \n\n#include \"Point3d.h\"\n#include \"Vector3.h\"\n\n#include \"GeometricBasics.h\"\n\nnamespace MathLib\n{\ndouble orientation3d(MathLib::Point3d const& p,\n MathLib::Point3d const& a,\n MathLib::Point3d const& b,\n MathLib::Point3d const& c)\n{\n MathLib::Vector3 const ap (a, p);\n MathLib::Vector3 const bp (b, p);\n MathLib::Vector3 const cp (c, p);\n return MathLib::scalarTriple(bp,cp,ap);\n}\n\ndouble calcTetrahedronVolume(MathLib::Point3d const& a,\n MathLib::Point3d const& b,\n MathLib::Point3d const& c,\n MathLib::Point3d const& d)\n{\n const MathLib::Vector3 ab(a, b);\n const MathLib::Vector3 ac(a, c);\n const MathLib::Vector3 ad(a, d);\n return std::abs(MathLib::scalarTriple(ac, ad, ab)) / 6.0;\n}\n\ndouble calcTriangleArea(MathLib::Point3d const& a, MathLib::Point3d const& b,\n MathLib::Point3d const& c)\n{\n MathLib::Vector3 const u(a, c);\n MathLib::Vector3 const v(a, b);\n MathLib::Vector3 const w(MathLib::crossProduct(u, v));\n return 0.5 * w.getLength();\n}\n\nbool isPointInTetrahedron(MathLib::Point3d const& p, MathLib::Point3d const& a,\n MathLib::Point3d const& b, MathLib::Point3d const& c,\n MathLib::Point3d const& d, double eps)\n{\n double const d0 (MathLib::orientation3d(d,a,b,c));\n // if tetrahedron is not coplanar\n if (std::abs(d0) > std::numeric_limits::epsilon())\n {\n bool const d0_sign (d0>0);\n // if p is on the same side of bcd as a\n double const d1 (MathLib::orientation3d(d, p, b, c));\n if (!(d0_sign == (d1 >= 0) || std::abs(d1) < eps))\n {\n return false;\n }\n // if p is on the same side of acd as b\n double const d2 (MathLib::orientation3d(d, a, p, c));\n if (!(d0_sign == (d2 >= 0) || std::abs(d2) < eps))\n {\n return false;\n }\n // if p is on the same side of abd as c\n double const d3 (MathLib::orientation3d(d, a, b, p));\n if (!(d0_sign == (d3 >= 0) || std::abs(d3) < eps))\n {\n return false;\n }\n // if p is on the same side of abc as d\n double const d4 (MathLib::orientation3d(p, a, b, c));\n return d0_sign == (d4 >= 0) || std::abs(d4) < eps;\n }\n return false;\n}\n\nbool isPointInTriangle(MathLib::Point3d const& p,\n MathLib::Point3d const& a,\n MathLib::Point3d const& b,\n MathLib::Point3d const& c,\n double eps_pnt_out_of_plane,\n double eps_pnt_out_of_tri,\n MathLib::TriangleTest algorithm)\n{\n switch (algorithm)\n {\n case MathLib::GAUSS:\n return gaussPointInTriangle(p, a, b, c, eps_pnt_out_of_plane,\n eps_pnt_out_of_tri);\n case MathLib::BARYCENTRIC:\n return barycentricPointInTriangle(p, a, b, c, eps_pnt_out_of_plane,\n eps_pnt_out_of_tri);\n default:\n ERR(\"Selected algorithm for point in triangle testing not found, \"\n \"falling back on default.\");\n }\n return gaussPointInTriangle(p, a, b, c, eps_pnt_out_of_plane,\n eps_pnt_out_of_tri);\n}\n\nbool gaussPointInTriangle(MathLib::Point3d const& q,\n MathLib::Point3d const& a,\n MathLib::Point3d const& b,\n MathLib::Point3d const& c,\n double eps_pnt_out_of_plane,\n double eps_pnt_out_of_tri)\n{\n MathLib::Vector3 const v(a, b);\n MathLib::Vector3 const w(a, c);\n\n Eigen::Matrix2d mat;\n mat(0, 0) = v.getSqrLength();\n mat(0, 1) = v[0] * w[0] + v[1] * w[1] + v[2] * w[2];\n mat(1, 0) = mat(0, 1);\n mat(1, 1) = w.getSqrLength();\n Eigen::Vector2d y;\n y << v[0] * (q[0] - a[0]) + v[1] * (q[1] - a[1]) + v[2] * (q[2] - a[2]),\n w[0] * (q[0] - a[0]) + w[1] * (q[1] - a[1]) + w[2] * (q[2] - a[2]);\n\n y = mat.partialPivLu().solve(y);\n\n const double lower(eps_pnt_out_of_tri);\n const double upper(1 + lower);\n\n if (-lower <= y[0] && y[0] <= upper && -lower <= y[1] && y[1] <= upper &&\n y[0] + y[1] <= upper)\n {\n MathLib::Point3d const q_projected(std::array{\n {a[0] + y[0] * v[0] + y[1] * w[0], a[1] + y[0] * v[1] + y[1] * w[1],\n a[2] + y[0] * v[2] + y[1] * w[2]}});\n if (MathLib::sqrDist(q, q_projected) <= eps_pnt_out_of_plane)\n {\n return true;\n }\n }\n\n return false;\n}\n\nbool barycentricPointInTriangle(MathLib::Point3d const& p,\n MathLib::Point3d const& a,\n MathLib::Point3d const& b,\n MathLib::Point3d const& c,\n double eps_pnt_out_of_plane,\n double eps_pnt_out_of_tri)\n{\n if (std::abs(MathLib::orientation3d(p, a, b, c)) > eps_pnt_out_of_plane)\n {\n return false;\n }\n\n MathLib::Vector3 const pa(p, a);\n MathLib::Vector3 const pb(p, b);\n MathLib::Vector3 const pc(p, c);\n double const area_x_2(calcTriangleArea(a, b, c) * 2);\n\n double const alpha((MathLib::crossProduct(pb, pc).getLength()) / area_x_2);\n if (alpha < -eps_pnt_out_of_tri || alpha > 1 + eps_pnt_out_of_tri)\n {\n return false;\n }\n double const beta((MathLib::crossProduct(pc, pa).getLength()) / area_x_2);\n if (beta < -eps_pnt_out_of_tri || beta > 1 + eps_pnt_out_of_tri)\n {\n return false;\n }\n double const gamma(1 - alpha - beta);\n return !(gamma < -eps_pnt_out_of_tri || gamma > 1 + eps_pnt_out_of_tri);\n}\n\nbool isPointInTriangleXY(MathLib::Point3d const& p,\n MathLib::Point3d const& a,\n MathLib::Point3d const& b,\n MathLib::Point3d const& c)\n{\n // criterion: p-a = u0 * (b-a) + u1 * (c-a); 0 <= u0, u1 <= 1, u0+u1 <= 1\n Eigen::Matrix2d mat;\n mat(0, 0) = b[0] - a[0];\n mat(0, 1) = c[0] - a[0];\n mat(1, 0) = b[1] - a[1];\n mat(1, 1) = c[1] - a[1];\n Eigen::Vector2d y;\n y << p[0] - a[0], p[1] - a[1];\n\n y = mat.partialPivLu().solve(y);\n\n // check if u0 and u1 fulfills the condition\n return 0 <= y[0] && y[0] <= 1 && 0 <= y[1] && y[1] <= 1 && y[0] + y[1] <= 1;\n}\n\nbool dividedByPlane(const MathLib::Point3d& a, const MathLib::Point3d& b,\n const MathLib::Point3d& c, const MathLib::Point3d& d)\n{\n for (unsigned x = 0; x < 3; ++x)\n {\n const unsigned y = (x + 1) % 3;\n const double abc =\n (b[x] - a[x]) * (c[y] - a[y]) - (b[y] - a[y]) * (c[x] - a[x]);\n const double abd =\n (b[x] - a[x]) * (d[y] - a[y]) - (b[y] - a[y]) * (d[x] - a[x]);\n\n if ((abc > 0 && abd < 0) || (abc < 0 && abd > 0))\n {\n return true;\n }\n }\n return false;\n}\n\nbool isCoplanar(const MathLib::Point3d& a, const MathLib::Point3d& b,\n const MathLib::Point3d& c, const MathLib::Point3d& d)\n{\n const MathLib::Vector3 ab(a, b);\n const MathLib::Vector3 ac(a, c);\n const MathLib::Vector3 ad(a, d);\n\n if (ab.getSqrLength() < pow(std::numeric_limits::epsilon(), 2) ||\n ac.getSqrLength() < pow(std::numeric_limits::epsilon(), 2) ||\n ad.getSqrLength() < pow(std::numeric_limits::epsilon(), 2))\n {\n return true;\n }\n\n // In exact arithmetic should be zero\n // if all four points are coplanar.\n const double sqr_scalar_triple(\n pow(MathLib::scalarProduct(MathLib::crossProduct(ac, ad), ab), 2));\n // Due to evaluating the above numerically some cancellation or rounding\n // can occur. For this reason a normalisation factor is introduced.\n const double normalisation_factor =\n (ab.getSqrLength() * ac.getSqrLength() * ad.getSqrLength());\n\n // tolerance 1e-11 is choosen such that\n // a = (0,0,0), b=(1,0,0), c=(0,1,0) and d=(1,1,1e-6) are considered as\n // coplanar\n // a = (0,0,0), b=(1,0,0), c=(0,1,0) and d=(1,1,1e-5) are considered as not\n // coplanar\n return (sqr_scalar_triple / normalisation_factor < 1e-11);\n}\n\n} // end namespace MathLib\n", "meta": {"hexsha": "4fc03379471b68cfd9d78aa5334c6cc2e3f00221", "size": 8742, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MathLib/GeometricBasics.cpp", "max_stars_repo_name": "Bernie2019/ogs", "max_stars_repo_head_hexsha": "80b66724d72d8ce01e02ddcd1fb6866c90b41c1d", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-25T13:43:06.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-25T13:43:06.000Z", "max_issues_repo_path": "MathLib/GeometricBasics.cpp", "max_issues_repo_name": "Bernie2019/ogs", "max_issues_repo_head_hexsha": "80b66724d72d8ce01e02ddcd1fb6866c90b41c1d", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-08-09T12:13:22.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-09T12:13:22.000Z", "max_forks_repo_path": "MathLib/GeometricBasics.cpp", "max_forks_repo_name": "Bernie2019/ogs", "max_forks_repo_head_hexsha": "80b66724d72d8ce01e02ddcd1fb6866c90b41c1d", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-03-01T13:07:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T13:16:22.000Z", "avg_line_length": 34.828685259, "max_line_length": 80, "alphanum_fraction": 0.5292839167, "num_tokens": 2716, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009619539554, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6603235482495401}} {"text": "#include \"stdafx.h\"\n#include \"EigenParameterEstimator.h\"\n\n#include \n#include \nusing namespace std;\nusing namespace Eigen;\n\nEigenParameterEstimator::EigenParameterEstimator()\n{\n}\n\nEigenParameterEstimator::EigenParameterEstimator(MeasurementDB * mdb) : _mdb(mdb)\n{\n}\n\nEigenParameterEstimator::~EigenParameterEstimator()\n{\n}\n\nvoid EigenParameterEstimator::estimateParameters(AbstractSolution * sol, double newrelerr)\n{\n\tint m = _mdb->get_size();\n\tint n = 2;\n\n\tMatrixXd A = MatrixXd(m, n);\n\tVectorXd b = VectorXd(m);\n\tVectorXd x = VectorXd(n);\n\n\t// Fill values in vector of right-hand side b\n\tfor (int i = 0; i < m; i++)\n\t\tb[i] = _mdb->getPairAt(i).second;\n\n\t// Zero the solution vector x\n\tfor (int i = 0; i < n; i++)\n\t\tx[i] = 0.0;\n\n\t// Fill the coefficient matrix\n\tfor (int row = 0; row < m; row++) {\n\t\tA(row, 0) = 1.0;\n\t\tA(row, 1) = sol->evaluateConstantTermAt(_mdb->getPairAt(row).first);\n\t}\n\n\tx = A.jacobiSvd(ComputeThinU | ComputeThinV).solve(b);\n\n\t// Update Solution\n\tfor (int i = 1; i <= n; ++i) {\n\t\tsol->updateAt(i - 1, x[i - 1]);\n\t}\n}\n", "meta": {"hexsha": "bd239d084a7feb8965a2594fef995b679fd04c0f", "size": 1063, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SimulatedAnnealingExtraP/EigenParameterEstimator.cpp", "max_stars_repo_name": "MiBu84/SMP-Simulated-Annealing", "max_stars_repo_head_hexsha": "e70ce403012ffc285e5053afd87e5e78a0d5fefa", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "SimulatedAnnealingExtraP/EigenParameterEstimator.cpp", "max_issues_repo_name": "MiBu84/SMP-Simulated-Annealing", "max_issues_repo_head_hexsha": "e70ce403012ffc285e5053afd87e5e78a0d5fefa", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SimulatedAnnealingExtraP/EigenParameterEstimator.cpp", "max_forks_repo_name": "MiBu84/SMP-Simulated-Annealing", "max_forks_repo_head_hexsha": "e70ce403012ffc285e5053afd87e5e78a0d5fefa", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.8431372549, "max_line_length": 90, "alphanum_fraction": 0.6716839135, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009457116781, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6603235474785153}} {"text": "#ifndef NONLINEAR_BASIS_HPP\n#define NONLINEAR_BASIS_HPP\n\n#include \n#include \n\n\nclass NonLinearBasisFunction : public Basis {\n\npublic:\n\n int _nX;\n int _nK;\n int _nU;\n int _nM;\n int _nKU;\n\n NonLinearBasisFunction(int _nX = 7, int _nK = 25, int _nU = 2 , int _nM = 6, int _nKU = 18) : Basis(_nX,_nK,_nU,_nM,_nKU) {\n this->_nX = _nX;\n this->_nK = _nK;\n this->_nU = _nU;\n this->_nM = _nM;\n this->_nKU = _nKU;\n }\n\n arma::vec fk(const arma::vec & x, const arma::vec & u ) {\n return arma::join_cols( fkx(x), fku(x, u) );\n }\n\n arma::vec fkx( const arma::vec& x ) {\n return arma::vec({\n x[0],\n x[1],\n x[2],\n x[3],\n x[4],\n x[5],\n 1\n });\n }\n\n arma::vec fku( const arma::vec & x, const arma::vec& u ) {\n\n return arma::vec({\n u[0],\n u[1],\n u[0]*x[0],\n u[0]*x[1],\n u[0]*x[2],\n u[0]*x[3],\n u[0]*x[4],\n u[0]*x[5],\n u[1]*x[0],\n u[1]*x[1],\n u[1]*x[2],\n u[1]*x[3],\n u[1]*x[4],\n u[1]*x[5],\n u[0]*cos(x[2]),\n u[0]*sin(x[2]),\n u[1]*cos(x[2]),\n u[1]*sin(x[2])\n });\n\n }\n\n arma::mat fkudu( const arma::vec & x, const arma::vec & u) {\n return arma::mat({\n {1,0},\n {0,1},\n {x[0],0},\n {x[1],0},\n {x[2],0},\n {x[3],0},\n {x[4],0},\n {x[5],0},\n {0,x[0]},\n {0,x[1]},\n {0,x[2]},\n {0,x[3]},\n {0,x[4]},\n {0,x[5]},\n {cos(x[2]), 0},\n {sin(x[2]), 0},\n {0, cos(x[2])},\n {0, sin(x[2])}\n });\n }\n\n};\n\n#endif\n", "meta": {"hexsha": "1ef1de4ab112c1c9e610d543f5314514a9d5f47e", "size": 1872, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/model_based_shared_control/src/robotlib/dynamicalSystems/koopman/basis_functions/nonlinear_basis.hpp", "max_stars_repo_name": "argallab/model_based_shared_control", "max_stars_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2019-05-08T19:47:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T06:43:31.000Z", "max_issues_repo_path": "src/model_based_shared_control/src/robotlib/dynamicalSystems/koopman/basis_functions/nonlinear_basis.hpp", "max_issues_repo_name": "argallab/model_based_shared_control", "max_issues_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/model_based_shared_control/src/robotlib/dynamicalSystems/koopman/basis_functions/nonlinear_basis.hpp", "max_forks_repo_name": "argallab/model_based_shared_control", "max_forks_repo_head_hexsha": "ff42226b6345266f35a32021c7d0b44cc5948ec1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2019-05-08T19:47:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-07T10:10:17.000Z", "avg_line_length": 20.1290322581, "max_line_length": 127, "alphanum_fraction": 0.3456196581, "num_tokens": 659, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6600956707616472}} {"text": "#include \"utils.h\"\n\n#include \n#include \n\n#include \n#include \n\n#include \n\nnamespace masterthesis {\n double expit(double x) {\n return x > 0 ? 1 / (1 + std::exp(-x)) : 1 - 1 / (1 + std::exp(x));\n }\n\n double log1exp(double x) {\n return x > 0 ? x + log1p(exp(-x)) : log1p(exp(x));\n }\n\n void readFeatureFile(std::string path,\n size_t* const nItems, size_t* const mFeatures,\n std::vector* const features) {\n std::fstream features_file_input;\n features_file_input.open(path, std::ios::in);\n\n std::string line;\n std::vector tokens;\n getline(features_file_input, line);\n boost::split(tokens, line, boost::is_any_of(\",\"));\n *nItems = stoul(tokens[0]);\n *mFeatures = stoul(tokens[1]);\n\n features->reserve(*nItems * *mFeatures);\n for (size_t i = 0; i < *nItems; ++i) {\n getline(features_file_input, line);\n boost::split(tokens, line, boost::is_any_of(\",\"));\n for (size_t j = 0; j < *mFeatures; ++j) {\n (*features)[(i * *mFeatures) + j] = stod(tokens[j]);\n }\n }\n }\n\n void readFeatureFileBoost(std::string path,\n size_t &nItems, size_t &mFeatures,\n Eigen::Matrix &features) {\n std::fstream features_file_input;\n features_file_input.open(path, std::ios::in);\n\n std::string line;\n std::vector tokens;\n getline(features_file_input, line);\n boost::split(tokens, line, boost::is_any_of(\",\"));\n nItems = stoul(tokens[0]);\n mFeatures = stoul(tokens[1]);\n\n features.resize(nItems, mFeatures);\n for (size_t i = 0; i < nItems; ++i) {\n getline(features_file_input, line);\n boost::split(tokens, line, boost::is_any_of(\",\"));\n for (size_t j = 0; j < mFeatures; ++j) {\n features(i, j) = stod(tokens[j]);\n }\n }\n }\n}", "meta": {"hexsha": "3862bd4be0be6984c561fcb3b6b96a465ca63b7f", "size": 2167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cppsrc/utils.cpp", "max_stars_repo_name": "dballesteros7/master-thesis-2015", "max_stars_repo_head_hexsha": "8c0bf9a6eef172fc8167a30780ae0666f8ea2d88", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cppsrc/utils.cpp", "max_issues_repo_name": "dballesteros7/master-thesis-2015", "max_issues_repo_head_hexsha": "8c0bf9a6eef172fc8167a30780ae0666f8ea2d88", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cppsrc/utils.cpp", "max_forks_repo_name": "dballesteros7/master-thesis-2015", "max_forks_repo_head_hexsha": "8c0bf9a6eef172fc8167a30780ae0666f8ea2d88", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3384615385, "max_line_length": 113, "alphanum_fraction": 0.5403784033, "num_tokens": 549, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.89181104831338, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6600956686333126}} {"text": "#include \n#include \n#include \n#include \n#include \n\n\nusing namespace dlib;\nusing namespace std;\n\ndouble nonlin(double x, bool deriv)\n{\n if (deriv)\n return x * (1 - x);\n else\n return 1/(1+exp(-x));\n}\n/*\ntemplate T nonlinT(T x, bool deriv)\n{\n if (deriv)\n return x * (1 - x);\n else\n return 1/(1+exp(-x));\n}\n\n\nvoid foo(std::vector x);\n\nfoo({1,2,3,4});\n*/\n\nint main()\n{\n std::default_random_engine generator;\n std::uniform_real_distribution distribution(-1.0,1.0);\n\n matrix X, l0;\n matrix y, l1, l1_error, l1_delta, l1_tmp;\n matrix syn;\n \n y.set_size(4);\n l1.set_size(4);\n l1_error.set_size(4);\n l1_delta.set_size(4);\n l1_tmp.set_size(4);\n \n X = 0, 0, 1,\n 0, 1, 1,\n 1, 0, 1,\n 1, 1, 1;\n\n y = 0,\n 0, \n 1,\n 1;\n \n chrono::steady_clock::time_point begin = chrono::steady_clock::now();\n\n for (int i=0; i<3; i++)\n syn(i,1) = distribution(generator);\n \n cout << syn;\n \n\n for (int i=0; i<60000; i++)\n {\n l0 = X;\n l1 = l0 * syn;\n \n for (int i=0; i<4; i++)\n l1(i) = nonlin(l1(i), false); \n\n l1_error = y - l1;\n\n for (int i=0; i<4; i++)\n l1_tmp(i) = nonlin(l1(i), true); \n\n l1_delta = pointwise_multiply(l1_error, l1_tmp);\n\n syn += trans(l0) * l1_delta;\n }\n \n chrono::steady_clock::time_point end = chrono::steady_clock::now();\n cout << \"Exec: \" << chrono::duration_cast (end - begin).count() << endl;\n \n cout << \"syn: \\n\" << syn << endl;\n cout << \"l1: \\n\" << l1 << endl;\n\n}\n\n", "meta": {"hexsha": "6eabe07cdf4a398f064f53c07ca616627d429e56", "size": 1747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/dlib_examples/small_neural_network.cpp", "max_stars_repo_name": "ALojdl/HastenedARMDeepLearning", "max_stars_repo_head_hexsha": "68279af342fc742ed72f3e05d22e332eae6e60c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/dlib_examples/small_neural_network.cpp", "max_issues_repo_name": "ALojdl/HastenedARMDeepLearning", "max_issues_repo_head_hexsha": "68279af342fc742ed72f3e05d22e332eae6e60c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/dlib_examples/small_neural_network.cpp", "max_forks_repo_name": "ALojdl/HastenedARMDeepLearning", "max_forks_repo_head_hexsha": "68279af342fc742ed72f3e05d22e332eae6e60c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-02-18T13:16:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-18T13:16:37.000Z", "avg_line_length": 18.9891304348, "max_line_length": 98, "alphanum_fraction": 0.5163136806, "num_tokens": 579, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213853793453, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.6600625660605222}} {"text": "/**\n * ravg.cpp\n *\n * 2021 Gabriel Moreira\n *\n * https://github.com/gabmoreira/maks\n *\n * This software and the related documents are provided as is, with no express\n * or implied warranties, other than those that are expressly stated in the\n * License.\n *\n * Copyright © 2021 Gabriel Moreira. All rights reserved.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"linalg.hpp\"\n#include \"err.hpp\"\n#include \"ravg.hpp\"\n\nusing std::vector;\nusing std::string;\n\nusing Eigen::MatrixXd;\nusing Eigen::Matrix3d;\nusing Eigen::VectorXd;\nusing Eigen::Ref;\n\nusing namespace std::chrono;\n\ntypedef Eigen::Triplet Triplet;\ntypedef Eigen::SparseMatrix Sparse;\ntypedef Eigen::PardisoLDLT PardisoLDLT;\n\n\n/**\n * Cycle graph solver in SO(3).\n *\n * Closed-form cycle graph rotation averaging solver in SO(3).\n *\n * @param edge_r (input) Eigen::MatrixXd - 3 x 3n Eigen matrix with SO(3) blocks. Assumes blocks are stacked as [ R_{1,2} R_{2,3} ... R_{n,1} ]\n * @param num_nodes (input) int - number of variables.\n * @param R (output) Eigen::MatrixXd - 3n x 3 Eigen matrix containing optimal solution.\n */\nvoid cycleSolverSO3(const Ref edge_r, int num_nodes, Ref R) {\n auto start = high_resolution_clock::now();\n \n // Cycle error E = R_12 * R_23 * R_n-1,n * R_n,1\n MatrixXd E = Matrix3d::Identity();\n \n for (int i = 0; i < num_nodes; ++i)\n E = E * edge_r.block<3,3>(0, i*3);\n \n // Diagonal blocks of change-of-basis matrix U\n vector U(num_nodes);\n \n // Build first block\n Eigen::SelfAdjointEigenSolver eig(E + E.transpose());\n U[0] = eig.eigenvectors();\n \n // Build other blocks\n for (int i = 1; i < num_nodes; ++i)\n U[i] = edge_r.block<3,3>(0, (i-1)*4).transpose() * U[i-1];\n \n /* Change basis according to U^\\top * Rtilde * U\n * We need only compute the corner block U_n * Rtilde_n1 * U_1 */\n MatrixXd one_param_edge_r = MatrixXd::Zero(3,3);\n one_param_edge_r += U[num_nodes-1].transpose() * edge_r.block<3,3>(0, (num_nodes-1)*3) * U[0];\n \n // Gamma is the angular cycle error\n double gamma_cos = 0.5 * (one_param_edge_r(0,0) + one_param_edge_r(1,1));\n double sine_sign = (double) ((one_param_edge_r(1,0) > 0) - (one_param_edge_r(1,0) < 0));\n double gamma = sine_sign * acos(gamma_cos);\n \n double gamma_mean = gamma / num_nodes;\n double theoretical_min = - ((double) num_nodes) * (5.0f + 4.0f * cos(gamma_mean));\n \n // Build solution in SO(2) and change basis to produce solution in SO(3)\n R.block<3,3>(0,0) += U[0];\n VectorXd theta = VectorXd::Zero(num_nodes,1);\n \n for (int i = 1; i < num_nodes; ++i) {\n theta(i) += theta(i-1) + gamma_mean;\n double c = cos(theta(i));\n double s = sin(theta(i));\n \n R(i*3,0) += c;\n R(i*3,1) -= s;\n R(i*3+1,0) += s;\n R(i*3+1,1) += c;\n R(i*3+2,2) += 1;\n \n // Revert the basis-change\n R.block<3,3>(i*3,0) = U[i] * R.block<3,3>(i*3,0);\n };\n \n // Fix gauge freedom by setting R_1 = I_3\n R = R * R.block<3,3>(0,0).transpose();\n\n auto stop = high_resolution_clock::now();\n auto duration = duration_cast(stop - start);\n \n // Verbose\n printf(\"Cycle error (mean): %1.8f\\n\", gamma_mean);\n printf(\"Theoretical minimum: %1.8f\\n\", theoretical_min);\n printf(\"CPU time: %.6f\\n\", static_cast(duration.count())*1e-6);\n};\n\n\n/**\n * Primal-Dual in SO(3)\n *\n * Primal-dual update method for averaging rotations in SO(3).\n * Finds R in SO(3)^n that minimizes the trace of R^\\top Rtilde R\n *\n * @param Rtilde (input) Eigen::SparseMatrix - 3n x 3n sparse rotation adjacency matrix.\n * @param A (input/output) Eigen::SparseMatrix - n x n symmetric graph adjacency matrix.\n * @param R (output) Eigen::MatrixXd - 3n x 3 solution.\n * @param num_nodes (input) int - number of variables.\n * @param maxiter (input) int - maxiter.\n * @param dual (output) double - value of the dual problem.\n * @param eta (input) double - minimum eigenvalue stopping criterion.\n * @param sigma (input) double - spectral shift.\n */\nvoid primalDualSO3(const Sparse& Rtilde,\n const Sparse& A,\n Ref R,\n int num_nodes,\n int maxiter,\n double& dual,\n double eta,\n double sigma) {\n \n printf(\"\\n%*s SO(3) Primal-dual\\n\", 20, \" \");\n \n auto start = high_resolution_clock::now();\n \n // Graph degree vector\n VectorXd D = A * VectorXd::Ones(num_nodes);\n \n /* Initialize symmetric block diagonal Lagrange multiplier.\n * Should initialize all 3x3 blocks instead of just the main\n * diagonal to ensure the correct NNZ pattern. */\n vector lambda_buffer(num_nodes * 9);\n \n unsigned int k = 0;\n unsigned int j = 0;\n for (unsigned int i = 0; i < num_nodes; ++i) {\n lambda_buffer[j] = Triplet( k, k, D(i) );\n lambda_buffer[j+1] = Triplet( k+1, k+1, D(i) );\n lambda_buffer[j+2] = Triplet( k+2, k+2, D(i) );\n lambda_buffer[j+3] = Triplet( k, k+1, 1e-15 );\n lambda_buffer[j+4] = Triplet( k, k+2, 1e-15 );\n lambda_buffer[j+5] = Triplet( k+1, k, 1e-15 );\n lambda_buffer[j+6] = Triplet( k+1, k+2, 1e-15 );\n lambda_buffer[j+7] = Triplet( k+2, k, 1e-15 );\n lambda_buffer[j+8] = Triplet( k+2, k+1, 1e-15 );\n j += 9;\n k += 3;\n };\n \n Sparse Lambda(num_nodes * 3, num_nodes * 3);\n Lambda.setFromTriplets(lambda_buffer.begin(), lambda_buffer.end());\n \n Sparse L = Lambda - Rtilde;\n L.makeCompressed();\n \n // LDLt solver used in the shift-and-invert spectral transform\n PardisoLDLT ldlt_solver;\n \n // Analyze the NNZ pattern\n ldlt_solver.analyzePattern(L);\n\n // Store eigenvalues\n VectorXd evals = VectorXd::Zero(3, 1);\n \n // Main primal-dual loop\n for (unsigned int i = 0; i < maxiter; ++i) {\n /* Call symmetric Krylov-Schur LDLt eigensolver on the matrix\n * Lambda - Rtilde. The three eigenvectors will be stored in R. */\n alg::symKrylovSchurLDL(&ldlt_solver, L, evals, R, 3, sigma);\n \n // Correct gauge freedom\n Matrix3d gauge = R.block<3,3>(0,0);\n R = R * gauge.inverse();\n \n // SO(3) projection\n for (unsigned int j = 0; j < 3*num_nodes; j += 3)\n alg::orthoProcrustesSO3(R.block<3,3>(j, 0));\n \n // Build Lambda from triplets for the next iteration\n MatrixXd RtildeR = Rtilde * R;\n dual = 3 * num_nodes;\n for (unsigned int k = 0; k < num_nodes*3; k+=3) {\n Matrix3d Rk = R.block<3,3>(k,0);\n Rk.transposeInPlace();\n MatrixXd block = RtildeR.block<3,3>(k,0) * Rk;\n \n // Dual <- + trace(Lambda_i)\n dual += block(0,0) + block(1,1) + block(2,2);\n \n L.coeffRef(k,k) = block(0,0);\n L.coeffRef(k+1,k+1) = block(1,1);\n L.coeffRef(k+2,k+2) = block(2,2);\n L.coeffRef(k,k+1) = 0.5 * (block(0,1) + block(1,0));\n L.coeffRef(k+1,k) = L.coeffRef(k,k+1);\n L.coeffRef(k,k+2) = 0.5 * (block(0,2) + block(2,0));\n L.coeffRef(k+2,k) = L.coeffRef(k,k+2);\n L.coeffRef(k+1,k+2) = 0.5 * (block(1,2) + block(2,1));\n L.coeffRef(k+2,k+1) = L.coeffRef(k+1,k+2);\n };\n \n // Verbose\n printf(\"Iteration %d Dual %.9f Min eigenvalue %1.3e\\n\", i, dual, abs(evals.minCoeff()));\n\n // Stopping criterion\n if (abs(evals.minCoeff()) < eta)\n break;\n };\n \n auto stop = high_resolution_clock::now();\n auto duration = duration_cast(stop - start);\n printf(\"\\nCPU time : %.6f\\n\", static_cast(duration.count())*1e-6);\n};\n", "meta": {"hexsha": "0529547ee16f95609054b02551b77fe75c7c2120", "size": 8017, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ravg.cpp", "max_stars_repo_name": "rjanvier/maks", "max_stars_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2020-12-15T10:15:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:19:07.000Z", "max_issues_repo_path": "src/ravg.cpp", "max_issues_repo_name": "rjanvier/maks", "max_issues_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T12:24:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:47:43.000Z", "max_forks_repo_path": "src/ravg.cpp", "max_forks_repo_name": "rjanvier/maks", "max_forks_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-06T07:22:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T09:31:30.000Z", "avg_line_length": 34.7056277056, "max_line_length": 143, "alphanum_fraction": 0.5805164026, "num_tokens": 2471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881363, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6600147507154207}} {"text": "// standard library\n#include \n#include \n#include \n// boost\n#include \n#include // is_any_of\n#include \n#include \n#include \n#include \n// Eigen\n#include \n//\n#include \"gradient_descent_solver.h\"\n\ndouble fn( Eigen::VectorXd x, Eigen::MatrixXd A, Eigen::VectorXd b, double lambda )\n{\n Eigen::VectorXd t = ( b - A * x );\n return t.dot( t ) + lambda * x.dot( x );\n}\n\nEigen::VectorXd dfn( Eigen::VectorXd x, Eigen::MatrixXd A, Eigen::VectorXd b, double lambda )\n{\n return 2 * A.transpose() * ( A * x - b ) + 2 * lambda * x;\n}\n\ndouble errorn( Eigen::VectorXd x, Eigen::VectorXd x_star, Eigen::MatrixXd A, Eigen::VectorXd b, double lambda )\n{\n return std::abs( fn( x, A, b, lambda ) - fn( x_star, A, b, lambda ) );\n}\n\nbool loadParam( std::string filename, int& degree, Eigen::MatrixXd& A, Eigen::VectorXd& b, double& lambda, Eigen::VectorXd& x_start )\n{\n std::ifstream ifs( filename );\n std::string str;\n\n if ( ifs.fail() ) {\n return false;\n } else {\n std::getline( ifs, str ); //\n std::getline( ifs, str ); //\n degree = std::stoi( str );\n\n A = Eigen::MatrixXd::Identity(degree,degree);\n b = Eigen::VectorXd::Ones(degree);\n lambda = 0.0;\n x_start = b;\n\n std::getline( ifs, str ); //\n for ( int i=0; i result;\n boost::algorithm::split( result, str, boost::is_any_of(\" \") );\n for ( int j=0; j()->default_value(0), \"acceleration method\" )\n (\"debug\", boost::program_options::value()->default_value(0), \"debug mode\" )\n (\"degree,d\", boost::program_options::value(), \"size of problem\")\n (\"error,e\", boost::program_options::value(), \"threshold of error\")\n (\"lambda,l\", boost::program_options::value(), \"lambda\")\n (\"printparam\", boost::program_options::value()->default_value(false), \"print parameter\" )\n (\"loadparamfile\", boost::program_options::value(), \"\" );\n boost::program_options::variables_map vm;\n try {\n boost::program_options::store( boost::program_options::parse_command_line( argc, argv, opt ), vm );\n } catch ( const boost::program_options::error_with_option_name& e ) {\n std::cout << e.what() << std::endl;\n return 0;\n }\n boost::program_options::notify( vm );\n\n srand((unsigned int) time(0));\n\n int accel;\n int debug;\n int degree;\n double error;\n bool printparam;\n Eigen::MatrixXd A;\n Eigen::VectorXd b, x_start;\n double lambda;\n if ( vm.count(\"help\")\n || ( !vm.count(\"loadparamfile\") and !vm.count(\"degree\") )\n || !vm.count(\"error\")\n || ( !vm.count(\"loadparamfile\") and !vm.count(\"lambda\") ) ) {\n std::cout << opt << std::endl;\n return 0;\n } else if ( vm.count(\"loadparamfile\") ) {\n std::string filename;\n try {\n accel = vm[\"accel\"].as();\n debug = vm[\"debug\"].as();\n error = vm[\"error\"].as();\n printparam = vm[\"printparam\"].as();\n filename = vm[\"loadparamfile\"].as();\n } catch ( const boost::bad_any_cast& e ) {\n std::cout << e.what() << std::endl;\n return 0;\n }\n if ( not loadParam( filename, degree, A, b, lambda, x_start ) ) {\n std::cout << opt << std::endl;\n return 0;\n }\n } else {\n try {\n accel = vm[\"accel\"].as();\n debug = vm[\"debug\"].as();\n degree = vm[\"degree\"].as();\n error = vm[\"error\"].as();\n lambda = vm[\"lambda\"].as();\n printparam = vm[\"printparam\"].as();\n } catch ( const boost::bad_any_cast& e ) {\n std::cout << e.what() << std::endl;\n return 0;\n }\n double coef = 4.0 / degree;\n A = Eigen::MatrixXd::Random(degree,degree) * 3 * coef;\n A = A.transpose() * A;\n Eigen::VectorXd omega_hat = Eigen::VectorXd::Ones(degree);\n Eigen::VectorXd eps = Eigen::VectorXd::Random(degree) * coef;\n b = A * omega_hat + eps;\n x_start = Eigen::VectorXd::Random(degree) * 10;\n }\n\n Eigen::VectorXd x_star = 2 * ( 2 * A.transpose() * A + lambda * Eigen::MatrixXd::Identity( A.rows(), A.cols() ) ).inverse() * A.transpose() * b;\n\n std::cout << std::fixed;\n\n if ( printparam ) {\n std::cout << \"degree:\" << std::endl;\n std::cout << degree << std::endl;\n std::cout << \"A:\" << std::endl;\n std::cout << A << std::endl;\n std::cout << \"b:\" << std::endl;\n std::cout << b << std::endl;\n std::cout << \"lambda:\" << std::endl;\n std::cout << lambda << std::endl;\n std::cout << \"x_start:\" << std::endl;\n std::cout << x_start << std::endl;\n }\n\n GradientDescentSolver solver( debug );\n solver.setf( boost::bind( fn, _1, A, b, lambda ) );\n solver.setdf( boost::bind( dfn, _1, A, b, lambda ) );\n solver.seterror( boost::bind( errorn, _1, x_star, A, b, lambda ) );\n std::vector trajectory;\n Eigen::VectorXd x_target = solver.solve( x_start, trajectory, error, accel );\n\n if ( isnan( x_target.norm() ) ) {\n std::cout << \"diverged.\" << std::endl;\n }\n\n return 0;\n}\n", "meta": {"hexsha": "44825b692bb8c4b180c7630321a142918d3615bf", "size": 6579, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/03_strongconvex.cpp", "max_stars_repo_name": "sktometometo/GradientDescentSolver", "max_stars_repo_head_hexsha": "4a5286f22b5c0223132ca7b2ec0e828e06278514", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/03_strongconvex.cpp", "max_issues_repo_name": "sktometometo/GradientDescentSolver", "max_issues_repo_head_hexsha": "4a5286f22b5c0223132ca7b2ec0e828e06278514", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/03_strongconvex.cpp", "max_forks_repo_name": "sktometometo/GradientDescentSolver", "max_forks_repo_head_hexsha": "4a5286f22b5c0223132ca7b2ec0e828e06278514", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.9946808511, "max_line_length": 148, "alphanum_fraction": 0.537619699, "num_tokens": 1742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.7879311956428947, "lm_q1q2_score": 0.6599868992035561}} {"text": "#include \"splines.h\"\n#include \n#include \n#include \n\nstd::vector CalculateCoeffFromPoints(const std::vector& points, bool is3D = true)\n{\n\tstd::vector coeff;\n\tif (points.size() < 4 || points.size() % 4)\n\t\treturn coeff;\n\n\tdouble Ax = 0.0, Bx = 0.0, Cx = 0.0, Dx = 0.0;\n\tdouble Ay = 0.0, By = 0.0, Cy = 0.0, Dy = 0.0;\n\tdouble Az = 0.0, Bz = 0.0, Cz = 0.0, Dz = 0.0;\n\t\n\tEigen::Vector3d cp[4];\n\tfor (size_t i = 0; i < points.size(); i += 4)\n\t{\n\t\tfor (size_t j = 0; j < 4; ++j)\n\t\t{\n\t\t\tcp[j] = points[i + j];\n\t\t}\n\n\t\tAx = cp[3].x() - 3.0 * cp[2].x() + 3.0 * cp[1].x() - cp[0].x();\n\t\tAy = cp[3].y() - 3.0 * cp[2].y() + 3.0 * cp[1].y() - cp[0].y();\n\t\tAz = cp[3].z() - 3.0 * cp[2].z() + 3.0 * cp[1].z() - cp[0].z();\n\n\t\tBx = 3.0 * cp[2].x() - 6.0 * cp[1].x() + 3.0 * cp[0].x();\n\t\tBy = 3.0 * cp[2].y() - 6.0 * cp[1].y() + 3.0 * cp[0].y();\n\t\tBz = 3.0 * cp[2].z() - 6.0 * cp[1].z() + 3.0 * cp[0].z();\n\n\t\tCx = 3.0 * (cp[1].x() - cp[0].x());\n\t\tCy = 3.0 * (cp[1].y() - cp[0].y());\n\t\tCz = 3.0 * (cp[1].z() - cp[0].z());\n\n\t\tDx = cp[0].x();\n\t\tDy = cp[0].y();\n\t\tDz = cp[0].z();\n\n\t\tcoeff.push_back(Ax);\n\t\tcoeff.push_back(Bx);\n\t\tcoeff.push_back(Cx);\n\t\tcoeff.push_back(Dx);\n\n\t\tcoeff.push_back(Ay);\n\t\tcoeff.push_back(By);\n\t\tcoeff.push_back(Cy);\n\t\tcoeff.push_back(Dy);\n\n\t\tif (is3D)\n\t\t{\n\t\t\tcoeff.push_back(Az);\n\t\t\tcoeff.push_back(Bz);\n\t\t\tcoeff.push_back(Cz);\n\t\t\tcoeff.push_back(Dz);\n\t\t}\n\t}\n\treturn coeff;\n}\n\n", "meta": {"hexsha": "d66dcf1f7613bcac4b3dc04b3b50f06c0834ca32", "size": 1451, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "splines/splines.cpp", "max_stars_repo_name": "hpmachining/splines", "max_stars_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-07-22T15:29:18.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-04T21:31:33.000Z", "max_issues_repo_path": "splines/splines.cpp", "max_issues_repo_name": "hpmachining/splines", "max_issues_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "splines/splines.cpp", "max_forks_repo_name": "hpmachining/splines", "max_forks_repo_head_hexsha": "9df0e51eac3169f0f518159752719f3b0fbfdb9c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7868852459, "max_line_length": 106, "alphanum_fraction": 0.4996554101, "num_tokens": 692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619947119304, "lm_q2_score": 0.7879312056025699, "lm_q1q2_score": 0.659986894770474}} {"text": "/*\nA class to represent a prime field \n*/\n\n\n#ifndef PRIME_FIELD\n#define PRIME_FIELD\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\n\n//! for debugging purpose only\n//! print the boost map of the cyclic group structure\ntemplate< class MapType >\nvoid print_map(const MapType & map,\n const std::string & separator,\n std::ostream & os )\n{\n typedef typename MapType::const_iterator const_iterator;\n\n for( const_iterator i = map.begin(), iend = map.end(); i != iend; ++i )\n {\n os << i->first << separator << i->second << std::endl;\n }\n}\n\n\n\n// prime field element (PFE)\n// class template el_t should be interger type\ntemplate class PFE:\n\tboost::field_operators< PFE,\n\tboost::equality_comparable< PFE\n\t> >\n{\npublic: \n\tel_t element;\n\tstatic el_t prime;\n\n\ttypedef boost::bimap< el_t, el_t> bim; \n\t//! maps exponents to elements \n\tstatic bim exp_el;\n\t\n\t//!Constructs a prime f\n\tPFE(el_t el): element(el % prime) {};\n\tPFE(){element = 0;};\n\n\t\n\n\n\n\tstatic void set_prime(const el_t& a){prime = a;}\n\n\t//! for initializying the map exponent to element; \n\t//! takes as parameter a primitive element of GF(prime)\n\t\n\tstatic void initialize_exp_el(el_t priel){\n\t\t\n\t\tel_t el = 1;\n\t\tfor(unsigned i = 0; i < prime-1; ++i){\n\t\t\t// insert (exponent, corresponding element)\n\t\t\t\n\t\t\texp_el.insert(typename bim::value_type(i,el ));\n\t\t\tel = (el*priel) % prime;\n\t\t//cout << i << \" \" << ((int) pow((double) priel,(int) i)) % prime << endl;\n\t\t}\n\t\t\n\t}\n\t\n\tbool isempty() const {return (element==prime);}\n\tvoid setempty() {element = prime;};\n\n\n\n\tPFE& operator += (const PFE& x){\n\t\telement = (element+x.element) % prime;\n\t\treturn *this;\n\t}\n\t\n\tPFE& operator -= (const PFE& x){\n\t\telement = (element-x.element) % prime;\n\t\tif(element < 0) element += prime;\n\t\treturn *this;\n\t}\n\n\tPFE& operator *= (const PFE& x){\n\t\t\n\t\telement = element*x.element % prime;\n\t\treturn *this;\n\t}\n\n\n\t\n\tPFE& operator /= (const PFE& x){\n\t\t//print_map(exp_el.left , \" \" , cout);\n\t\tel_t ea = exp_el.right.at(element);\t\n\t\tel_t eb = exp_el.right.at(x.element);\n\t\tel_t eres = (prime - 1 - eb + ea) % (prime-1);\n\t\telement = exp_el.left.at(eres);\n\t\treturn *this;\n\t}\n\n\t//operator const el_t (){\n\t//\treturn element;\n\t//}\n\t//operator el_t (){return element;}\n\toperator int (){return (int) element;};\n\n\n\tPFE inverse() const {\n\t\treturn pow(*this, -1);\n\t}\n\n\tbool operator ==(const PFE& x) const {\n\t\treturn (x.element == element);\n\t}\n\tbool operator < (const PFE& x) const {\n\t\treturn (element < x.element);\t\n\t}\n\t\n\tbool iszero() const { return (element == 0); };\n\t//! get the multiplication order of the element\n\tunsigned order() const {\n\t\t// additive zero has no order\n\t\tif(element == 0){ return -1;}\n\t\tel_t tmp = element;\n\t\tunsigned ord = 1;\n\t\twhile(!(tmp == 1)){\n\t\t\tord++;\n\t\t\ttmp = (tmp * element) % prime;\n\t\t\t//cout << tmp << endl;\n\t\t}\n\t\treturn ord;\n\t}\n};\t\n\n template\n ostream &operator<<(ostream &stream, PFE x)\n {\n stream << x.element;\n return stream; // must return stream\n };\n\n\n template\n PFE pow(PFE a, int exp){\n\t\tif( a.iszero() ) return a;\n\t\tif( exp == 0 ) return PFE(1);\n\t\tel_t ea = a.exp_el.right.at(a.element);\t\n\t\tint nexp = exp*ea;\n\t\twhile( nexp < 0) {\n\t\t\t\n\t\t\tnexp += a.prime-1;\n\t\t}\n\t\tnexp = nexp % (a.prime-1) ; \n\t\treturn PFE( a.exp_el.left.at(nexp ) );\n\t};\t\n\n#endif\n", "meta": {"hexsha": "cda4e7acdb37b12f8abb20ea3b50be5c213d18f0", "size": 3427, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/PFE.hpp", "max_stars_repo_name": "zhaofeng-shu33/dna_data_storage", "max_stars_repo_head_hexsha": "87ae439c6a5d90701a9c26060776fa364dac5582", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/PFE.hpp", "max_issues_repo_name": "zhaofeng-shu33/dna_data_storage", "max_issues_repo_head_hexsha": "87ae439c6a5d90701a9c26060776fa364dac5582", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/PFE.hpp", "max_forks_repo_name": "zhaofeng-shu33/dna_data_storage", "max_forks_repo_head_hexsha": "87ae439c6a5d90701a9c26060776fa364dac5582", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.6445783133, "max_line_length": 78, "alphanum_fraction": 0.6139480595, "num_tokens": 1027, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767874818408, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6598735871224225}} {"text": "#include \"pauli_product.hpp\"\n#include \n#include \n#include \n\n\nusing namespace std;\nusing namespace arma;\n\n// Applies a Pauli operator i^{xz} X^xZ^z to the k'th qubit to the state psi.\n// This algorithm takes at most 2^n complex number multiplications.\nvoid apply_pauli_fast(int k, bool x, bool z, cx_dvec &psi)\n{\n int d;\n d = psi.size();\n if (pow(2,k) >= d)\n {\n throw \"Qubit index out of range.\";\n }\n if (z)\n {\n if (x)\n\t{\n\t for (int i=0; i> k == 0)\n\t\t{\n\t\t cx_double temp1, temp2;\n\t\t temp1 = psi(i) * cx_double(0.0, 1.0);\n\t\t temp2 = psi((1<> k == 1)\n\t\t{\n\t\t psi(i) *= -1.0;\n\t\t}\n\t }\n\t}\n }\n else\n {\n if (x)\n\t{\n\t for (int i=0; i> k == 0)\n\t\t{\n\t\t cx_double temp1, temp2;\n\t\t temp1 = psi(i);\n\t\t temp2 = psi((1<>= 1;\n unsigned int n_q = bits - 1;\n \n cx_double c, s;\n c = cos(theta);\n s = sin(theta);\n\n cx_dmat PX(2,2, fill::zeros), PY(2,2, fill::zeros), PZ(2,2, fill::zeros), PI(2,2, fill::zeros), P, PString(1,1, fill::ones);\n PX(0, 1) = 1.0; PX(1, 0) = 1.0;\n PZ(0, 0) = 1.0; PZ(1, 1) = -1.0;\n PY(1, 0) = cx_double(0.0, 1.0); PY(0, 1) = cx_double(0.0, -1.0);\n PI(0, 0) = 1.0; PI(1, 1) = 1.0;\n\t\t \n for (int i=0; i>= 1;\n unsigned int n_q = bits - 1;\n\n cx_double mysum = 0.0;\n for (int y=0; y>= 1;\n unsigned int n_q = bits - 1;\n\n cx_dmat PX(2,2, fill::zeros), PY(2,2, fill::zeros), PZ(2,2, fill::zeros), PI(2,2, fill::zeros), P, PString(1,1, fill::ones);\n PX(0, 1) = 1.0; PX(1, 0) = 1.0;\n PZ(0, 0) = 1.0; PZ(1, 1) = -1.0;\n PY(1, 0) = cx_double(0.0, 1.0); PY(0, 1) = cx_double(0.0, -1.0);\n PI(0, 0) = 1.0; PI(1, 1) = 1.0;\n \n for (int i=0; i\n\n#include \n#include \n#include \n#include \n\n#include \nnamespace fs = std::filesystem;\n#include \nusing namespace Eigen;\n\n\nstruct Point {\n\tuint32 x;\n\tuint32 y;\n};\n\nstruct ellipseABCDEF {\n\tdouble A;\n\tdouble B;\n\tdouble C;\n\tdouble D;\n\tdouble E;\n\tdouble F;\n};\n\nstruct ellipseABCDEF fitEllipse(struct Point p1, struct Point p2, struct Point p3, struct Point p4, struct Point p5) {\n\tMatrix mat56(5, 6);\n\tmat56 << \n\t\t(double)p1.x * (double)p1.x, (double)p1.x * -(double)p1.y, (double)p1.y * (double)p1.y, (double)p1.x, -(double)p1.y, 1,\n\t\t(double)p2.x * (double)p2.x, (double)p2.x * -(double)p2.y, (double)p2.y * (double)p2.y, (double)p2.x, -(double)p2.y, 1,\n\t\t(double)p3.x * (double)p3.x, (double)p3.x * -(double)p3.y, (double)p3.y * (double)p3.y, (double)p3.x, -(double)p3.y, 1,\n\t\t(double)p4.x * (double)p4.x, (double)p4.x * -(double)p4.y, (double)p4.y * (double)p4.y, (double)p4.x, -(double)p4.y, 1,\n\t\t(double)p5.x * (double)p5.x, (double)p5.x * -(double)p5.y, (double)p5.y * (double)p5.y, (double)p5.x, -(double)p5.y, 1;\n\t\n\tCompleteOrthogonalDecomposition > cod;\n\tcod.compute(mat56);\n\n\t// Find URV^T\n\tMatrixXd V = cod.matrixZ().transpose();\n\tMatrixXd Null_space = V.block(0, cod.rank(), V.rows(), V.cols() - cod.rank());\n\tMatrixXd P = cod.colsPermutation();\n\tNull_space = P * Null_space; // Unpermute the columns\n\n\n\treturn {\n\t\tNull_space(0) / Null_space(5),\n\t\tNull_space(1) / Null_space(5),\n\t\tNull_space(2) / Null_space(5),\n\t\tNull_space(3) / Null_space(5),\n\t\tNull_space(4) / Null_space(5),\n\t\t1\n\t};\n}\n\n\nstatic uint16 finalAverage;\nstatic std::ofstream outStream(\"out.csv\");\n\ntypedef unsigned long long uint64;\n\n\n\nstruct followReturn {\n\tbool success;\n\tstruct Point point;\n};\n\nbool validateEdge(bool* considered, struct Point point, uint32 width, uint32 height) {\n\tstruct Point nearby[4] = {\n\t\t{point.x + 0, point.y - 1},\n\t\t{point.x - 1, point.y + 0},\n\t\t{point.x + 1, point.y + 0},\n\t\t{point.x + 0, point.y + 1}\n\t};\n\n\tfor (uint32 i = 0; i < 4; i++) {\n\t\tstruct Point tested = nearby[i];\n\n\t\tif (tested.x != 0xFFFFFFFF && tested.y != 0xFFFFFFFF && tested.x != width && tested.y != height) {\n\t\t\tuint32 index = tested.y * width + tested.x;\n\n\t\t\tif (!considered[index]) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false;\n}\n\nstruct EllipseParams {\n\tdouble fCenterX, fCenterY;\n\tdouble fLongLength, fShortLength;\n\tdouble fAngle;\n};\n\nEllipseParams toEllipseParams(ellipseABCDEF a) {\n\n\tEllipseParams eOutParams;\n\n\teOutParams.fCenterX = ((2 * a.C * a.D) - (a.B * a.E)) / ((a.B * a.B) - (4 * a.A * a.C));\n\teOutParams.fCenterY = ((2 * a.A * a.E) - (a.B * a.D)) / ((a.B * a.B) - (4 * a.A * a.C));\n\n\teOutParams.fLongLength = -sqrt(2 * (a.A * pow(a.E, 2) + a.C * pow(a.D, 2) - a.B * a.D * a.E + (pow(a.B, 2) - 4 * a.A * a.C) * a.F) * ((a.A + a.C) + sqrt(pow((a.A - a.C), 2) + pow(a.B, 2)))) /\n\t\t\t\t\t\t\t ((a.B * a.B) - (4 * a.A * a.C));\n\n\teOutParams.fShortLength = -sqrt(2 * (a.A * pow(a.E, 2) + a.C * pow(a.D, 2) - a.B * a.D * a.E + (pow(a.B, 2) - 4 * a.A * a.C) * a.F) * ((a.A + a.C) - sqrt(pow((a.A - a.C), 2) + pow(a.B, 2)))) /\n\t\t\t\t\t\t\t ((a.B * a.B) - (4 * a.A * a.C));\n\n\tif (a.B != 0)\n\t\teOutParams.fAngle = atan((a.C - a.A - sqrt(pow((a.A - a.C), 2) + pow(a.B, 2))) / a.B);\n\telse if\n\t\t(a.A <= a.C) eOutParams.fAngle = 0;\n\telse\n\t\teOutParams.fAngle = M_PI / 2;\n\n\treturn eOutParams;\n}\n\ndouble rad2Deg(double rad) {\n\treturn (rad * 180) / M_PI;\n}\n\n//filename, ellipse_center_x, ellipse_center_y, ellipse_majoraxis, ellipse_minoraxis, ellipse_angle, elapsed_time\n\nvoid saveEllipse(bool empty, EllipseParams params, float elapsedTime, char* fileName){\n\t\n\tif (empty) {\n\n\t\toutStream << fileName << \",\";\n\t\toutStream << \",\";\n\t\toutStream << \",\";\n\t\toutStream << \",\";\n\t\toutStream << \",\";\n\t\toutStream << \",\";\n\t\toutStream << (int)(elapsedTime * 1000) << std::endl;\n\t\treturn;\n\t}\n\n\toutStream << fileName << \",\";\n\toutStream << params.fCenterX << \",\";\n\toutStream << -params.fCenterY << \",\";\n\toutStream << params.fLongLength << \",\";\n\toutStream << params.fShortLength << \",\";\n\toutStream << fmod(180 - rad2Deg(params.fAngle), 360) << \",\";\n\toutStream << (int)(elapsedTime * 1000) << std::endl;\n\n}\n\n\ndouble ratePoint(struct Point point, struct EllipseParams ellipse) {\n\tdouble xi = (double)point.x;\n\tdouble yi = (double)point.y;\n\n\txi = xi - ellipse.fCenterX;\n\tyi = yi + ellipse.fCenterY;\n\n\tdouble x = xi * cos(ellipse.fAngle) + yi * sin(ellipse.fAngle);\n\tdouble y = xi * -sin(ellipse.fAngle) + yi * cos(ellipse.fAngle);\n\n\tdouble angle = atan(y / x);\n\n\tdouble distanceFromCenter = hypot(x, y);\n\n\tdouble distanceFromCenterToEdge = ellipse.fLongLength * ellipse.fShortLength / (sqrt(pow(ellipse.fShortLength * cos(angle), 2) + pow(ellipse.fLongLength * sin(angle), 2)));\n\n\tdouble finalDistance = abs(distanceFromCenter - distanceFromCenterToEdge);\n\n\t//some gaussian trickery right here\n\tdouble rating = exp(-(finalDistance * finalDistance) / 8);\n\treturn rating;\n}\n\n\nvoid ParseEllipse(std::string path) { \n\tTIFF* tif = TIFFOpen(path.c_str(), \"r\");\n\n\tif (tif == nullptr) {\n\t\tstd::cout << path << \" is not a valid TIFF image!\" << std::endl << std::endl;\n\t\treturn;\n\t}\n\n\tuint32 width, height;\n\n\tTIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &width); // uint32 width;\n\tTIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height); // uint32 height;\n\n\tstd::cout << std::endl << \"Image: \" << path << std::endl;\n\tprintf(\"Width: %d\\nHeight: %d\\n\", width, height);\n\n\tuint16* raster = (uint16*)_TIFFmalloc(width * height * sizeof(uint16));\n\n\tfor (uint32 row = 0; row < height; row++) {\n\t\tTIFFReadScanline(tif, raster + width * row, row, 0);\n\t}\n\n\t//Time Taken\n\tauto timeStart = std::chrono::system_clock::now();\n\n\tuint64 average = 0;\n\tfor (uint32 i = 0; i < width * height; i++) {\n\t\taverage += uint64(raster[i]);\n\t}\n\n\tfinalAverage = average / (uint64(width) * uint64(height)) * 1;\n\n\t/*uint32 maxLuminance = 0;\n\n\tfor (uint32 i = 0; i < width * height; i++) {\n\t\tif (raster[i] > maxLuminance) {\n\t\t\tmaxLuminance = raster[i];\n\t\t}\n\t}\n\n\tdouble fmaxLuminance = (double)maxLuminance;\n\n\tdouble average = 0;\n\n\tfor (uint32 i = 0; i < width * height; i++) {\n\t\taverage += (1 - pow(exp(-(pow((double)raster[i] / fmaxLuminance, 2) / 0.5)), 64)) * fmaxLuminance;\n\t}\n\n\taverage /= width * height;\n\n\n\tfinalAverage = (uint16)average;*/\n\n\tbool* considered = (bool*)malloc(width * height * sizeof(bool));\n\tbool* alreadyTaken = (bool*)calloc(width * height, sizeof(bool));\n\n\tfor (uint32 y = 0; y < height; y++) {\n\t\tfor (uint32 x = 0; x < width; x++) {\n\t\t\tconst uint32 index = y * width + x;\n\n\t\t\t//considered[index] = bool(raster[index] < fmaxLuminance * 0.45);\n\t\t\tconsidered[index] = bool(raster[index] < finalAverage);\n\t\t}\n\t}\n\n\n\tstd::vector> sequences;\n\n\tstd::vector paths[2] = {\n\t\tstd::vector(),\n\t\tstd::vector()\n\t};\n\n\n\n\tfor (uint32 y = 0; y < height; y++) {\n\t\tfor (uint32 x = 0; x < width; x++) {\n\t\t\tuint32 indexInitial = y * width + x;\n\n\t\t\tif (alreadyTaken[indexInitial] || !considered[indexInitial]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!validateEdge(considered, { x, y }, width, height)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tuint32 newX = x, newY = y;\n\n\t\t\tstruct Point nearbyInitial[8] = {\n\t\t\t\t{newX - 1, newY - 1},\n\t\t\t\t{newX + 0, newY - 1},\n\t\t\t\t{newX + 1, newY - 1},\n\t\t\t\t{newX - 1, newY + 0},\n\t\t\t\t{newX + 1, newY + 0},\n\t\t\t\t{newX - 1, newY + 1},\n\t\t\t\t{newX + 0, newY + 1},\n\t\t\t\t{newX + 1, newY + 1}\n\t\t\t};\n\n\t\t\tuint32 part = 0;\n\t\t\tuint32 firstPointIndex = 0;\n\n\n\n\t\t\twhile (part < 2 && firstPointIndex < 8) {\n\t\t\t\tnewX = nearbyInitial[firstPointIndex].x;\n\t\t\t\tnewY = nearbyInitial[firstPointIndex].y;\n\t\t\t\tfirstPointIndex++;\n\n\t\t\t\tif (newX == 0xFFFFFFFF || newY == 0xFFFFFFFF || newX == width || newY == height) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!validateEdge(considered, { newX, newY }, width, height)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tbool endPath = false;\n\t\t\t\tdo {\n\t\t\t\t\tuint32 indexThis = newY * width + newX;\n\n\n\t\t\t\t\tstruct Point nearby[8] = {\n\t\t\t\t\t\t{newX - 1, newY - 1},\n\t\t\t\t\t\t{newX + 0, newY - 1},\n\t\t\t\t\t\t{newX + 1, newY - 1},\n\t\t\t\t\t\t{newX - 1, newY + 0},\n\t\t\t\t\t\t{newX + 1, newY + 0},\n\t\t\t\t\t\t{newX - 1, newY + 1},\n\t\t\t\t\t\t{newX + 0, newY + 1},\n\t\t\t\t\t\t{newX + 1, newY + 1}\n\t\t\t\t\t};\n\n\t\t\t\t\tendPath = true;\n\n\t\t\t\t\tfor (uint32 i = 0; i < 8; i++) {\n\t\t\t\t\t\tstruct Point tested = nearby[i];\n\n\t\t\t\t\t\tif (tested.x != 0xFFFFFFFF && tested.y != 0xFFFFFFFF && tested.x != width && tested.y != height) {\n\t\t\t\t\t\t\tif (!validateEdge(considered, tested, width, height)) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tuint32 testedIndex = tested.y * width + tested.x;\n\n\t\t\t\t\t\t\tif (alreadyTaken[testedIndex] || !considered[testedIndex]) {\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\t\tpaths[part].push_back({ newX, newY });\n\n\n\t\t\t\t\t\t\tnewX = tested.x;\n\t\t\t\t\t\t\tnewY = tested.y;\n\n\t\t\t\t\t\t\tendPath = false;\n\n\t\t\t\t\t\t\talreadyTaken[testedIndex] = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\t\n\n\t\t\t\t} while (!endPath);\n\n\t\t\t\tpart++;\n\t\t\t}\n\n\t\t\tuint32 sizePart1 = paths[0].size();\n\t\t\tuint32 sizePart2 = paths[1].size();\n\n\t\t\tif (sizePart1 + sizePart2 >= 10) {\n\t\t\t\tstd::vector finalPath = std::vector();\n\n\t\t\t\tfinalPath.reserve(sizePart1 + sizePart2);\n\n\t\t\t\tfor (int i = sizePart1 - 1; i >= 0; i--) {\n\t\t\t\t\tfinalPath.push_back(paths[0][i]);\n\n\t\t\t\t}\n\n\t\t\t\tint a = 0;\n\n\t\t\t\tfor (int i = 0; i < sizePart2; i++) {\n\t\t\t\t\tfinalPath.push_back(paths[1][i]);\n\t\t\t\t}\n\n\t\t\t\tpaths[0] = std::vector();\n\t\t\t\tpaths[1] = std::vector();\n\n\t\t\t\tsequences.push_back(finalPath);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tpaths[0].clear();\n\t\t\t\tpaths[1].clear();\n\t\t\t}\n\t\t}\n\t}\n\n\tif (sequences.size() == 0) {\n\n\t\tauto timeEnd = std::chrono::system_clock::now();\n\n\t\tstd::chrono::duration elapsedTime = timeEnd - timeStart;\n\t\tstd::cout << \"No ellipse found!\" << std::endl;\n\n\t\tsaveEllipse(true, {}, elapsedTime.count(), (char*)fs::path(path).filename().string().c_str());\n\t\treturn;\n\t}\n\n\tuint32 maxLength = 0;\n\tuint32 longestIndex = 0;\n\tfor (uint32 i = 0; i < sequences.size(); i++) {\n\t\tif (sequences[i].size() > maxLength) {\n\t\t\tmaxLength = sequences[i].size();\n\t\t\tlongestIndex = i;\n\t\t}\n\t}\n\n\tstd::vector longest = sequences[longestIndex];\n\n\n\n\t//Sampling\n\tPoint pSamples[5];\n\tconst int nMaxSampleItterations = 4; //Linear addition\n\n\tstruct EllipseParams bestFit;\n\tdouble bestFitRating = 0;\n\n\t//Iterate through\n\tfor (int nCurrItteration = 0; nCurrItteration < nMaxSampleItterations; nCurrItteration++) {\n\n\t\t//Populate samples \n\t\tint nPointDistance = longest.size() / (5 + 2 * nCurrItteration);\n\n\t\tif (nPointDistance == 0) {\n\t\t\tbreak;\n\t\t}\n\n\t\tfor (int i = 0; i < 5; i++) {\n\t\t\tpSamples[i] = longest[i * nPointDistance];\n\t\t}\n\n\n\t\tint nCurrOffset = 0;\n\t\t//Go through the path\n\n\t\twhile ((4 * nPointDistance + nCurrOffset) < longest.size()) {\n\n\t\t\tfor (int i = 0; i < 5; i++) {\n\t\t\t\tpSamples[i] = longest[i * nPointDistance + nCurrOffset];\n\t\t\t}\n\n\t\t\tEllipseParams eFitEllipse = toEllipseParams(fitEllipse(pSamples[0], pSamples[1], pSamples[2], pSamples[3], pSamples[4]));\n\t\t\t\n\n\n\t\t\tdouble rating = 0;\n\t\t\tfor (int i = 0; i < longest.size(); i++) {\n\t\t\t\trating += ratePoint(longest[i], eFitEllipse);\n\t\t\t}\n\n\t\t\tif (rating > bestFitRating) {\n\t\t\t\tbestFitRating = rating;\n\t\t\t\tbestFit = eFitEllipse;\n\t\t\t}\n\n\t\t\t//Update offset for next iteration\n\t\t\tnCurrOffset++;\n\t\t}\n\t}\n\n\tstd::cout << \"Best fit got rated: \" << bestFitRating << \" (out of \" << longest.size() << \")\" << std::endl;\n\n\tauto timeEnd = std::chrono::system_clock::now();\n\n\tstd::chrono::duration elapsedTime = timeEnd - timeStart;\n\tstd::cout << \"Finding the best ellipse took: \" << elapsedTime.count() << \" s\" << std::endl;\n\n\tsaveEllipse(false, bestFit, elapsedTime.count(), (char*)fs::path(path).filename().string().c_str());\n\n\tTIFFClose(tif);\n\t//free mallocs\n\n\t_TIFFfree(raster);\n\tfree(considered);\n\tfree(alreadyTaken);\n}\n\nint main(int argc, char** argv) {\n\n\toutStream << \"filename,ellipse_center_x,ellipse_center_y,ellipse_majoraxis,ellipse_minoraxis,ellipse_angle,elapsed_time\" << std::endl; //write the header\n\n\tif (argc == 1) {\n\t\tstd::cout << \"No input directory provided! Exiting...\" << std::endl;\n\t\treturn 0;\n\t}\n\n\tstd::string path(argv[1]);\n\ttry {\n\t\tfor (const auto& entry : fs::recursive_directory_iterator(path))\n\t\t\tParseEllipse(entry.path().string());\n\t}\n\tcatch (std::exception e) {\n\t\tstd::cout << argv[1] << \" is not a valid folder!\" << std::endl;\n\t}\n\n\toutStream.close();\n\n\treturn 0;\n}", "meta": {"hexsha": "302f8f0c53a78e16c97a6b268a76b016bf0a271c", "size": 12273, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EllipseParser/Main.cpp", "max_stars_repo_name": "NeverGonnaGiveYouUpHK/EllipseParser", "max_stars_repo_head_hexsha": "a1b429d50b4d342cac06b21fd0253c22afc9087c", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EllipseParser/Main.cpp", "max_issues_repo_name": "NeverGonnaGiveYouUpHK/EllipseParser", "max_issues_repo_head_hexsha": "a1b429d50b4d342cac06b21fd0253c22afc9087c", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EllipseParser/Main.cpp", "max_forks_repo_name": "NeverGonnaGiveYouUpHK/EllipseParser", "max_forks_repo_head_hexsha": "a1b429d50b4d342cac06b21fd0253c22afc9087c", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.0469387755, "max_line_length": 193, "alphanum_fraction": 0.6072679866, "num_tokens": 3951, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.926303724190573, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6597433190908656}} {"text": "#include \"function.h\"\n#include \n#include \n#include \n\nvoid Function::IndefCoeff()\n{\n\tarma::mat::fixed<5, 5> A;\n\tdouble h = 0;\n\tstd::vector coeff;\n\tfor (int i = 0; i < 5; ++i)\n\t{\n\t\tcoeff.push_back(f[i].first - x);\n\t}\n\tfor (int j = 0; j < 5; j++)\n\t{\n\t\tfor (int i = 0; i < 5; i++)\n\t\t{\n\t\t\tA(j, i) = pow(coeff[i], j);\n\t\t}\n\t}\n\tarma::vec B(5, arma::fill::zeros);\n\tB(1) = 1;\n\tarma::vec X = arma::solve(A, B);\n\tfor (int i = 0; i < 5; i++)\n\t{\n\t\tIndefResult += X(i) * f[i].second;\n\t}\n}\n\nvoid Function::FindDerivative()\n{\n\tdouble eps_1 = (e[0].first + e[1].first);\n\tdouble eps_2 = (e[0].first * (e[1].first + e[2].first) + e[1].first * e[2].first);\n\tdouble eps_3 = (e[0].first * e[2].first * (e[1].first + e[3].first) + e[1].first * e[3].first *\n\t\t(e[0].first + e[2].first));\n\tNewtonResult = FindDivDiff(1) + FindDivDiff(2) * eps_1 + FindDivDiff(3) * eps_2 + FindDivDiff(4) * eps_3;\n\n}\n\ndouble Function::FindDivDiff(int IterationNum)\n{\n\tdouble temp = 1;\n\tdouble sum = 0;\n\tfor (int p = 0; p <= IterationNum; ++p)\n\t{\n\t\tfor (int i = 0; i <= IterationNum; ++i)\n\t\t{\n\t\t\tif (i != p)\n\t\t\t\ttemp *= 1 / (f[p].first - f[i].first);\n\t\t}\n\t\tsum += f[p].second * temp;\n\t\ttemp = 1;\n\t}\n\treturn sum;\n}\n\nFunction::Function(std::vector> f_, double x_)\n{\n\tf = f_;\n\tx = x_;\n\tstd::pair temp;\n\tfor (auto it : f)\n\t{\n\t\ttemp.first = x - it.first;\n\t\ttemp.second = it.second;\n\t\te.push_back(temp);\n\t}\n\tIndefCoeff();\n\tFindDerivative();\n}\n\nvoid Function::Print()\n{\n\tstd::cout << \"Newton method result: \" << NewtonResult << std::endl;\n\tstd::cout << \"Indef coeff method result: \" << IndefResult << std::endl << std::endl;\n}\n\nFunction::~Function()\n{}\n", "meta": {"hexsha": "787c865dbbfe284b30a882db16a451cc53a7483d", "size": 1680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lab2/src/function.cpp", "max_stars_repo_name": "KorovinVA/CompMath", "max_stars_repo_head_hexsha": "f6e2d87effd42956f9f06331a2652777a1d2f4d5", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "lab2/src/function.cpp", "max_issues_repo_name": "KorovinVA/CompMath", "max_issues_repo_head_hexsha": "f6e2d87effd42956f9f06331a2652777a1d2f4d5", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab2/src/function.cpp", "max_forks_repo_name": "KorovinVA/CompMath", "max_forks_repo_head_hexsha": "f6e2d87effd42956f9f06331a2652777a1d2f4d5", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-24T19:39:05.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-24T19:39:05.000Z", "avg_line_length": 20.7407407407, "max_line_length": 107, "alphanum_fraction": 0.5720238095, "num_tokens": 626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6597337045584045}} {"text": "#pragma once\n#include \n#include \n\nnamespace ppl {\nnamespace math {\n\n/**\n * Estimates sample variance for n-dimensional data using\n * Welford's online algorithm\n */\nstruct WelfordVar\n{\n WelfordVar(size_t n_params)\n : m_{n_params, 2}\n , mean_{m_.col(0)}\n , m2n_{m_.col(1)}\n { m_.setZero(); }\n\n /*\n * Update sample mean and sample variance with new sample x.\n */\n template \n void update(const MatType& x)\n {\n ++n_;\n auto delta = x - mean_;\n mean_ += (1./static_cast(n_)) * delta;\n m2n_ += (delta.array() * (x - mean_).array()).matrix();\n }\n\n const auto& get_variance() const { return m2n_; }\n size_t get_n_samples() const { return n_; }\n\n /**\n * Resets sample mean, sample variance, and number of samples to 0\n * Equivalent to constructing a new object of this type.\n */\n void reset()\n {\n m_.setZero();\n n_ = 0;\n }\n\nprivate:\n Eigen::MatrixXd m_; \n\n using col_t = std::decay_t;\n col_t mean_;\n col_t m2n_;\n\n size_t n_ = 0; // number of samples\n};\n\n} // namespace math\n} // namespace ppl\n", "meta": {"hexsha": "098cf6a073a897919888b87ebf753dee2b3a853f", "size": 1190, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/autoppl/math/welford.hpp", "max_stars_repo_name": "JamesYang007/autoppl", "max_stars_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-04-12T19:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T19:05:38.000Z", "max_issues_repo_path": "include/autoppl/math/welford.hpp", "max_issues_repo_name": "JamesYang007/autoppl", "max_issues_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-04-26T14:55:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T19:21:50.000Z", "max_forks_repo_path": "include/autoppl/math/welford.hpp", "max_forks_repo_name": "JamesYang007/autoppl", "max_forks_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T04:45:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:28:42.000Z", "avg_line_length": 20.8771929825, "max_line_length": 70, "alphanum_fraction": 0.5857142857, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392848011833, "lm_q2_score": 0.7461389873857264, "lm_q1q2_score": 0.6596161767707567}} {"text": "#include \n#include \n#include \n#include \"CommonFunctions.h\"\n#include \"MeshGeometry.h\"\n#include \"IntrinsicGeometry.h\"\n#include \"MeshConnectivity.h\"\n\nEigen::MatrixXd lowRankApprox(Eigen::MatrixXd A)\n{\n Eigen::MatrixXd posHess = A;\n Eigen::SelfAdjointEigenSolver es;\n es.compute(posHess);\n Eigen::VectorXd evals = es.eigenvalues();\n\n for (int i = 0; i < evals.size(); i++)\n {\n if (evals(i) < 0)\n evals(i) = 0;\n }\n Eigen::MatrixXd D = evals.asDiagonal();\n Eigen::MatrixXd V = es.eigenvectors();\n posHess = V * D * V.inverse();\n\n return posHess;\n}\n\nEigen::MatrixXd nullspaceExtraction(const Eigen::SparseMatrix A)\n{\n\tEigen::SPQR> solver_SPQR(A.transpose());\n\tint r = solver_SPQR.rank();\n\n\tEigen::MatrixXd N(A.cols(), A.cols() - r);\n\tfor (int i = 0; i < A.cols() - r; i++)\n\t{\n\t\tEigen::VectorXd ei(A.cols());\n\t\tei.setZero();\n\t\tei(i + r) = 1;\n\t\tN.col(i) = solver_SPQR.matrixQ() * ei;\n\t}\n\tstd::cout << \"rank of A = \" << r << std::endl;\n\treturn N;\n}\n\ndouble cotan(const Eigen::Vector3d v0, const Eigen::Vector3d v1, const Eigen::Vector3d v2)\n{\n double e0 = (v2 - v1).norm();\n double e1 = (v2 - v0).norm();\n double e2 = (v0 - v1).norm();\n double angle0 = acos((e1 * e1 + e2 * e2 - e0 * e0) / (2 * e1 * e2));\n double cot = 1.0 / tan(angle0);\n\n return cot;\n}\n\n\nvoid locatePotentialPureTensionFaces(const std::vector& abars, const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, std::set& potentialPureTensionFaces)\n{\n\tMeshConnectivity mesh(F);\n\tMeshGeometry curGeo(V, mesh);\n\tIntrinsicGeometry restGeo(mesh, abars);\n\tassert(abars.size() == F.rows());\n\tint nfaces = F.rows();\n\tint nverts = V.rows();\n\n\tEigen::VectorXd smallestEvals(nfaces);\n\n\tstd::vector isPureFaces(nfaces, false);\n\tstd::vector isPureVerts(nverts, false);\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tEigen::Matrix2d abar = abars[i];\n\t\tEigen::Matrix2d a = curGeo.Bs[i].transpose() * curGeo.Bs[i];\n\t\tEigen::Matrix2d diff = a - abar;\n\t\tEigen::GeneralizedSelfAdjointEigenSolver solver(diff, abar);\n\n\t\tsmallestEvals(i) = std::min(solver.eigenvalues()[0], solver.eigenvalues()[1]);\n\t}\n\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tif (smallestEvals(i) >= 0)\n\t\t{\n\t\t\tisPureFaces[i] = true;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tif (isPureFaces[i])\n\t\t{\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tisPureVerts[mesh.faceVertex(i, j)] = true;\n\t\t\t}\n\t\t}\n\t}\n\n\t//// if a face is not pure tension, but all its vertices are on the other pure faces, we think it is pure tension\n\t//// this is used to fill the mixed state \"holes\" in the pure tension region\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tif (!isPureFaces[i])\n\t\t{\n\t\t\tbool isAllPureVerts = true;\n\t\t\tfor (int j = 0; j < 3; j++)\n\t\t\t{\n\t\t\t\tint vid = mesh.faceVertex(i, j);\n\t\t\t\tif (isPureVerts[vid] == false)\n\t\t\t\t\tisAllPureVerts = false;\n\t\t\t}\n\t\t\tisPureFaces[i] = isAllPureVerts;\n\t\t}\n\t}\n\n\tfor (int i = 0; i < nfaces; i++)\n\t{\n\t\tif (isPureFaces[i])\n\t\t\tpotentialPureTensionFaces.insert(i);\n\t}\n\t// set this to empty means we never relax the integrability constriant.\n\t// potentialPureTensionFaces.clear();\n}\n\nvoid getPureTensionVertsEdges(const std::set& potentialPureTensionFaces, const Eigen::MatrixXi& F, std::set* pureTensionEdges, std::set* pureTensionVerts)\n{\n\tMeshConnectivity mesh(F);\n\n\tstd::set tmpPureTensionEdges, tmpPureTensionVerts;\n\t\n\tstd::set mixedStateEdges;\n\t// locate the mixed edges: \n\tfor (int i = 0; i < mesh.nEdges(); i++)\n\t{\n\t\tEigen::Vector2i faceFlags;\n\t\tfaceFlags << 0, 0;\n\t\tfor (int j = 0; j < 2; j++)\n\t\t{\n\t\t\tint fid = mesh.edgeFace(i, j);\n\t\t\tif (potentialPureTensionFaces.find(fid) != potentialPureTensionFaces.end())\n\t\t\t{\n\t\t\t\tfaceFlags(j) = 1;\n\t\t\t}\n\t\t}\n\t\tif (faceFlags(0) + faceFlags(1) == 1)\n\t\t{\n\t\t\tif (mixedStateEdges.find(i) == mixedStateEdges.end())\n\t\t\t{\n\t\t\t\tmixedStateEdges.insert(i);\n\t\t\t}\n\t\t}\n\n\t\telse if (faceFlags(0) + faceFlags(1) == 2)\n\t\t{\n\t\t\tif (tmpPureTensionEdges.find(i) == tmpPureTensionEdges.end())\n\t\t\t{\n\t\t\t\ttmpPureTensionEdges.insert(i);\n\t\t\t}\n\t\t}\n\t}\n\t// mixedStateEdges.clear();\n\t// tmpPureTensionEdges.clear();\n\tstd::cout << mixedStateEdges.size() << \" edges between compressed and pure tension faces. \" << tmpPureTensionEdges.size() << \" edges are inside the pure tension region\" << std::endl;\n\n\tfor (auto& fid : potentialPureTensionFaces)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tint vid = mesh.faceVertex(fid, j);\n\t\t\tif (tmpPureTensionVerts.find(vid) == tmpPureTensionVerts.end())\n\t\t\t{\n\t\t\t\ttmpPureTensionVerts.insert(vid);\n\t\t\t}\n\t\t}\n\t}\n\t// tmpPureTensionVerts.clear();\n\tstd::cout << tmpPureTensionVerts.size() << \" vertices are inside the pure tension region (including the boundary)\" << std::endl;\n\n\tif (pureTensionEdges)\n\t{\n\t\t*pureTensionEdges = tmpPureTensionEdges;\n\t}\n\tif (pureTensionVerts)\n\t{\n\t\t*pureTensionVerts = tmpPureTensionVerts;\n\t}\n}\n\n\nvoid trivialOffset(const Eigen::MatrixXd& V, const Eigen::MatrixXi& F, Eigen::MatrixXd &offsettedV, double d)\n{\n\tEigen::MatrixXd VN;\n\tigl::per_vertex_normals(V, F, VN);\n\toffsettedV = V + d * VN;\n}\n\nvoid rigidBodyAlignment(const Eigen::MatrixXd& tarPos, const MeshConnectivity& mesh, const Eigen::MatrixXd &pos, Eigen::Matrix3d &R, Eigen::Vector3d &t)\n{\n\tint nverts = tarPos.rows();\n int nfaces = mesh.nFaces();\n Eigen::VectorXd massVec;\n massVec.resize(nverts);\n massVec.setZero();\n \n Eigen::VectorXd areaList;\n igl::doublearea(tarPos, mesh.faces(), areaList);\n areaList = areaList / 2;\n \n for(int i=0; i < nfaces; i++)\n {\n double faceArea = areaList(i);\n for(int j=0; j<3; j++)\n {\n int vertIdx = mesh.faceVertex(i, j);\n massVec(vertIdx) += faceArea / 3;\n }\n }\n \n massVec = massVec / 3;\n massVec = massVec / massVec.maxCoeff();\n \n Eigen::MatrixXd W = Eigen::MatrixXd::Zero(nverts, nverts);\n W.diagonal() = massVec;\n \n Eigen::Vector3d avePos, aveTarPos;\n avePos.setZero();\n aveTarPos.setZero();\n \n for(int i = 0; i < nverts; i++)\n {\n avePos += massVec(i) * pos.row(i);\n aveTarPos += massVec(i) * tarPos.row(i);\n }\n \n avePos = avePos / massVec.sum();\n aveTarPos = aveTarPos / massVec.sum();\n \n Eigen::MatrixXd onesMat(nverts,1);\n onesMat.setOnes();\n \n Eigen::MatrixXd shiftedPos = pos - onesMat * avePos.transpose();\n Eigen::MatrixXd shiftedTarPos = tarPos - onesMat * aveTarPos.transpose();\n \n Eigen::MatrixXd S = shiftedPos.transpose() * W * shiftedTarPos;\n Eigen::VectorXd b = Eigen::VectorXd::Zero(3);\n \n \n Eigen::BDCSVD solver(S);\n solver.compute(S, Eigen::ComputeFullU | Eigen::ComputeFullV);\n Eigen::MatrixXd U = solver.matrixU();\n Eigen::MatrixXd V = solver.matrixV();\n \n Eigen::MatrixXd middleMat(S.rows(), S.cols());\n middleMat.setIdentity();\n middleMat(S.rows()-1,S.cols()-1) = (V*U.transpose()).determinant();\n \n R = V * middleMat * U.transpose();\n t = aveTarPos - R*avePos;\n}\n\nbool parse(bool& b, const Json::Value& json) {\n\tif (!json.isBool())\n\t\treturn false;\n\tb = json.asBool();\n\treturn true;\n}\nbool parse(int& n, const Json::Value& json) {\n\tif (!json.isIntegral())\n\t\treturn false;\n\tn = json.asInt();\n\treturn true;\n}\nbool parse(double& x, const Json::Value& json) {\n\tif (!json.isNumeric())\n\t\treturn false;\n\tx = json.asDouble();\n\treturn true;\n}\nbool parse(std::string& s, const Json::Value& json)\n{\n\tif (!json.isString())\n\t\treturn false;\n\ts = json.asString();\n\treturn true;\n}\n\nvoid generateWTFJson(std::string prefix)\n{\n\tstd::string matName = prefix + std::string(\"_material.dat\");\n\tstd::ifstream mfs(matName);\n\tif (!mfs)\n\t{\n\t\tstd::cout << \"Missing \" << matName << std::endl;\n\t\treturn;\n\t}\n\tdouble thickness, youngs, poisson, density, penaltyK, pressure, sphereR;\n\tEigen::Vector3d gravity, sphereCenter;\n\tbool isTFT;\n\tint framefreq, numInterp, bendingType;\n\tJson::Value json;\n\n\tmfs >> thickness;\n\tmfs >> youngs;\n\tmfs >> poisson;\n\tmfs >> density;\n\tmfs >> penaltyK;\n\tmfs >> gravity[0] >> gravity[1] >> gravity[2];\n\tmfs >> isTFT;\n\tmfs >> framefreq;\n\tmfs >> sphereCenter[0] >> sphereCenter[1] >> sphereCenter[2];\n\tmfs >> sphereR;\n\tmfs >> numInterp;\n\tmfs >> bendingType;\n\tmfs >> pressure;\n\n\tjson[\"poisson_ratio\"] = poisson;\n\tjson[\"thickness\"] = thickness;\n\tjson[\"youngs_modulus\"] = youngs;\n\n\tjson[\"nasoq_eps\"] = 1e-6;\n\tjson[\"quadpoints\"] = 3;\n\tjson[\"rest_flat\"] = true;\n\tjson[\"clamp\"] = true;\n\tjson[\"sff_type\"] = \"midedgeTan\";\n\n\tstd::string filePrefix = prefix;\n\tstd::replace(filePrefix.begin(), filePrefix.end(), '\\\\', '/'); // handle the backslash issue for windows\n\n\tint index = filePrefix.rfind(\"/\");\n\tstd::string modelName = filePrefix.substr(index + 1, filePrefix.length() - 1);\n\n\n\tjson[\"rest_mesh\"] = modelName + \".obj\";\n\tjson[\"base_mesh\"] = modelName + \"_simulated.obj\";\n\tjson[\"obs_mesh\"] = modelName + \"_obstacle.obj\";\n\n\tjson[\"clamped_DOFs\"] = modelName + \"_clamped_vertices.dat\";\n\n\tjson[\"dphi_path\"] = modelName + \"_dphi_simulated.txt\";\n\tjson[\"amp_path\"] = modelName + \"_amplitude_simulated.txt\";\n\tjson[\"phi_path\"] = modelName + \"_phi_simulated.txt\";\n\n\tstd::ofstream file((prefix + \"_WTF.json\").c_str());\n\tif (!file)\n\t{\n\t\tstd::cout << \"output path doesn't exist.\" << std::endl;\n\t\treturn;\n\t}\n\tJson::StyledStreamWriter writer;\n\twriter.write(file, json);\n\tfile.close();\n}\n\nvoid generateElasticJson(std::string prefix)\n{\n\tstd::string matName = prefix + std::string(\"_material.dat\");\n\tstd::ifstream mfs(matName);\n\tif (!mfs)\n\t{\n\t\tstd::cout << \"Missing \" << matName << std::endl;\n\t\treturn;\n\t}\n\tdouble thickness, youngs, poisson, density, penaltyK, pressure,sphereR;\n\tEigen::Vector3d gravity, sphereCenter;\n\tbool isTFT;\n\tint framefreq, numInterp, bendingType;\n\tJson::Value json;\n\n\tmfs >> thickness;\n\tmfs >> youngs;\n\tmfs >> poisson;\n\tmfs >> density;\n\tmfs >> penaltyK;\n\tmfs >> gravity[0] >> gravity[1] >> gravity[2];\n\tmfs >> isTFT;\n\tmfs >> framefreq;\n\tmfs >> sphereCenter[0] >> sphereCenter[1] >> sphereCenter[2];\n\tmfs >> sphereR;\n\tmfs >> numInterp;\n\tmfs >> bendingType;\n\tmfs >> pressure;\n\n\tjson[\"poisson_ratio\"] = poisson;\n\tjson[\"thickness\"] = thickness;\n\tjson[\"youngs_modulus\"] = youngs;\n\tjson[\"density\"] = density;\n\tjson[\"collision_penalty\"] = penaltyK;\n\tjson[\"perturb\"] = 0;\n\tjson[\"pressure\"] = pressure;\n\tjson[\"collision_eta\"] = 0.5 * thickness;\n\tjson[\"rest_flat\"] = true;\n\tjson[\"isNeoHookean\"] = false;\n\tjson[\"isTFT\"] = isTFT;\n\tjson[\"bending_type\"] = bendingType == 0 ? \"elastic\" : \"quadratic\";\n\tif (bendingType == 2)\n\t\tjson[\"bending_type\"] = \"None\";\n\n\tjson[\"sff_type\"] = \"midedgeTan\";\n\tjson[\"max_stepsize\"] = 1.0;\n\tjson[\"gravity\"].resize(3);\n\tfor (int i = 0; i < 3; i++)\n\t\tjson[\"gravity\"][i] = gravity(i);\n\n\tjson[\"frame_frequency\"] = framefreq;\n\tjson[\"num_interpolation\"] = numInterp;\n\n\tstd::string filePrefix = prefix;\n\tstd::replace(filePrefix.begin(), filePrefix.end(), '\\\\', '/'); // handle the backslash issue for windows\n\n\tint index = filePrefix.rfind(\"/\");\n\tstd::string modelName = filePrefix.substr(index + 1, filePrefix.length() - 1);\n\n\tjson[\"rest_mesh\"] = modelName + \".obj\";\n\tjson[\"init_mesh\"] = modelName + \"_guess.obj\";\n\tjson[\"cur_mesh\"] = modelName + \"_simulated.obj\";\n\tjson[\"obs_mesh\"] = modelName + \"_obstacle.obj\";\n\n\tjson[\"curedge_DOFs\"] = modelName + \"_edgedofs_simulated.txt\";\n\tjson[\"clamped_DOFs\"] = modelName + \"_clamped_vertices.dat\";\n\n\tstd::ofstream file((prefix + \"_Elastic.json\").c_str());\n\tif (!file)\n\t{\n\t\tstd::cout << \"output path doesn't exist.\" << std::endl;\n\t\treturn;\n\t}\n\tJson::StyledStreamWriter writer;\n\twriter.write(file, json);\n\tfile.close();\n}", "meta": {"hexsha": "d50a7dff910ada517521c00e73089709a00e49c7", "size": 11545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CommonFunctions.cpp", "max_stars_repo_name": "csyzzkdcz/effective-garbanzo", "max_stars_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CommonFunctions.cpp", "max_issues_repo_name": "csyzzkdcz/effective-garbanzo", "max_issues_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CommonFunctions.cpp", "max_forks_repo_name": "csyzzkdcz/effective-garbanzo", "max_forks_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.724537037, "max_line_length": 183, "alphanum_fraction": 0.6431355565, "num_tokens": 3487, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894717137996, "lm_q2_score": 0.7371581626286834, "lm_q1q2_score": 0.6596013629080348}} {"text": "// -*- mode: c++; fill-column: 80; indent-tabs-mode: nil; -*-\n#ifndef MXPFIT_JACOBI_SVD_HPP\n#define MXPFIT_JACOBI_SVD_HPP\n\n#include \n#ifdef DEBUG\n#include \n#include \n#endif /* DEBUG */\n\n#include \n\nnamespace mxpfit\n{\nnamespace detail\n{\n//\n// Make Jacobi rotation matrix \\c J of the form\n//\n// J = [ cs conj(sn)]\n// [-sn conj(cs)]\n//\n// that diagonalize the 2x2 matirix\n//\n// B = [ a c]\n// [conj(c) b]\n//\n// as D = J.t() * B * J\n//\n// J.t() = [ conj(cs) -conj(sn)] = J.inv()\n// [ sn cs ]\n//\n// J * [a11 a12] = [ cs*a11 + conj(sn)*a21 cs*a12 + conj(sn)*a22]\n// [a21 a22] [-sn*a11 + conj(cs)*a21 -sn*a12 + conj(cs)*a22]\n//\n// [a11 a12] * J = [ cs *a11 - sn *a12 cs *a21 - sn *a22]\n// [a21 a22] [conj(sn)*a11 +E conj(cs)*a12 -conj(sn)*a21 + conj(cs)*a22]\n//\ntemplate \nbool make_jacobi_rotation(RealT a, RealT b, ScalarT c, RealT& cs, ScalarT& sn)\n{\n using Eigen::numext::abs;\n using Eigen::numext::abs2;\n using Eigen::numext::conj;\n using Eigen::numext::sqrt;\n\n constexpr const RealT one = RealT(1);\n\n if (c == ScalarT())\n {\n cs = one;\n sn = ScalarT();\n return false;\n }\n\n auto zeta = (a - b) / (RealT(2) * abs(c));\n auto w = sqrt(abs2(zeta) + one);\n auto t = (zeta > RealT() ? one / (zeta + w) : one / (zeta - w));\n\n cs = one / sqrt(abs2(t) + one);\n sn = -t * cs * (conj(c) / abs(c));\n\n return true;\n}\n\ntemplate \nstruct one_sided_jacobi_helper\n{\n using Index = Eigen::Index;\n using Scalar = T;\n using RealScalar = typename Eigen::NumTraits::Real;\n //\n // Sum of the square of the absolute value of the elments in the i-th column\n // of the matrix G, i.e. \\f$ \\sum_{k=0}^{n-1} |G_{ki}|^{2}. \\f$\n //\n template \n static RealScalar submat_diag(const Eigen::MatrixBase& G, Index i)\n {\n return G.col(i).squaredNorm();\n }\n\n template \n static Scalar submat_offdiag(const Eigen::MatrixBase& G, Index i,\n Index j)\n {\n return G.col(i).dot(G.col(j));\n }\n\n template \n static void update_vecs(Eigen::MatrixBase& U, Index i, Index j,\n RealScalar cs, const Scalar& sn)\n {\n using Eigen::numext::conj;\n for (Index k = 0; k < U.rows(); ++k)\n {\n const auto t1 = U(k, i);\n const auto t2 = U(k, j);\n // Apply Jacobi rotation matrix on the right\n U(k, i) = cs * t1 - sn * t2;\n U(k, j) = conj(sn) * t1 + cs * t2;\n }\n }\n};\n\n} // namespace: detail\n\n///\n/// Compute the singular value decomposition (SVD) by one-sided Jacobi\n/// algorithm.\n///\n/// This function compute the singular value decomposition (SVD) using modified\n/// one-sided Jacobi algorithm.\n///\n/// #### References\n/// - James Demmel and Kresimir Veselic, \"Jacobi's method is more accurate than\n/// QR\", LAPACK working note 15 (lawn15) (1989), Algorithm 4.1.\n///\n/// \\param[in,out] A On entry, an \\f$m \\times n\\f$ matrix to be decomposed. On\n/// exit, columns of `A` holds left singular vectors.\n/// \\param[out] sigma singular values of matrix `A`.\n/// \\param[out] V right singular vectors.\n/// \\param[in] small positive real number that determines stopping criterion\n/// of Jacobi algorithm.\n///\ntemplate \nvoid one_sided_jacobi_svd(Eigen::MatrixBase& A,\n Eigen::MatrixBase& sigma,\n Eigen::MatrixBase& V, RealT tol)\n{\n using Index = Eigen::Index;\n using Scalar = typename MatA::Scalar;\n using RealScalar = typename Eigen::NumTraits::Real;\n using jacobi_aux = detail::one_sided_jacobi_helper;\n\n using Eigen::numext::abs;\n using Eigen::numext::sqrt;\n // constexpr const Index max_sweep = 50;\n\n auto n = A.cols();\n const Index max_sweep = n * (n - 1) / 2;\n assert(V.rows() == A.cols());\n //\n // Initialize right singular vectors\n //\n V.setIdentity();\n\n Scalar sn;\n RealScalar cs;\n RealScalar max_resid = tol + RealScalar(1);\n Index nsweep = max_sweep + 1;\n while (--nsweep && max_resid > tol)\n {\n max_resid = RealScalar();\n for (Index j = 1; j < n; ++j)\n {\n auto b = jacobi_aux::submat_diag(A, j);\n for (Index i = 0; i < j; ++i)\n {\n //\n // For all pairs i < j, compute the 2x2 submatrix of A.t() * A\n // constructed from i-th and j-th columns, such as\n //\n // M = [ a c]\n // [conj(c) b]\n //\n // where\n //\n // a = \\sum_{k=0}^{n-1} |A(k,i)|^{2} (computed in outer loop)\n // b = \\sum_{k=0}^{n-1} |A(k,j)|^{2}\n // c = \\sum_{k=0}^{n-1} conj(A(k,i)) * A(k,j)\n //\n auto a = jacobi_aux::submat_diag(A, i);\n auto c = jacobi_aux::submat_offdiag(A, i, j);\n max_resid = std::max(max_resid, abs(c) / sqrt(a * b));\n //\n // Compute the Jacobi rotation matrix which diagonalize M.\n //\n if (detail::make_jacobi_rotation(a, b, c, cs, sn))\n {\n // If the return vlaue of make_jacobi_rotation is false, no\n // rotation is made.\n //\n // Update columns i and j of A\n //\n jacobi_aux::update_vecs(A, i, j, cs, sn);\n //\n // Update right singular vector V\n //\n jacobi_aux::update_vecs(V, i, j, cs, sn);\n }\n }\n }\n#ifdef DEBUG\n std::cout << \"(one_sided_jacobi_svd) iter \" << std::setw(8)\n << max_sweep - nsweep << \": max residual = \" << max_resid\n << '\\n';\n#endif /* DEBUG */\n }\n //\n // Set singular values and left singular vectors.\n //\n for (Index j = 0; j < A.cols(); ++j)\n {\n // Singular values are the norms of the columns of the final A\n sigma(j) = A.col(j).norm();\n // Left singular vectors are the normalized columns of the final A\n A.col(j) /= sigma(j);\n }\n //\n // Sort singular values in descending order. The corresponding singular\n // vectors are also rearranged.\n //\n for (Index i = 0; i < n - 1; ++i)\n {\n //\n // Find the index of the maximum value of a sub-array, sigma(i:n-1).\n //\n Index imax = i;\n for (Index k = i + 1; k < n; ++k)\n {\n if (sigma(k) > sigma(imax))\n {\n imax = k;\n }\n }\n\n if (imax != i)\n {\n // Move the largest singular value to the beggining of the\n // sub-array, and corresponsing singular vectors by swapping columns\n // of A and V.\n std::swap(sigma(i), sigma(imax));\n A.col(i).swap(A.col(imax));\n V.col(i).swap(V.col(imax));\n }\n }\n}\n\n///\n/// Compute the singular value decomposition (SVD) by one-sided Jacobi\n/// algorithm.\n///\n/// This function only computes the singular values and left singular vectors.\n///\n/// \\param[in,out] A On entry, an \\f$m \\times n\\f$ matrix to be decomposed. On\n/// exit, columns of `A` holds left singular vectors.\n/// \\param[out] sigma singular values of matrix `A`.\n/// \\param[in] small positive real number that determines stopping criterion\n/// of Jacobi algorithm.\n///\ntemplate \nvoid one_sided_jacobi_svd(Eigen::MatrixBase& A,\n Eigen::MatrixBase& sigma, RealT tol)\n{\n using Index = Eigen::Index;\n using Scalar = typename MatA::Scalar;\n using RealScalar = typename Eigen::NumTraits::Real;\n using jacobi_aux = detail::one_sided_jacobi_helper;\n\n using Eigen::numext::abs;\n using Eigen::numext::sqrt;\n // constexpr const Index max_sweep = 50;\n\n auto n = A.cols();\n const Index max_sweep = n * (n - 1) / 2;\n\n Scalar sn;\n RealScalar cs;\n RealScalar max_resid = tol + RealScalar(1);\n Index nsweep = max_sweep + 1;\n while (--nsweep && max_resid > tol)\n {\n max_resid = RealScalar();\n for (Index j = 1; j < n; ++j)\n {\n auto b = jacobi_aux::submat_diag(A, j);\n for (Index i = 0; i < j; ++i)\n {\n //\n // For all pairs i < j, compute the 2x2 submatrix of A.t() * A\n // constructed from i-th and j-th columns, such as\n //\n // M = [ a c]\n // [conj(c) b]\n //\n // where\n //\n // a = \\sum_{k=0}^{n-1} |A(k,i)|^{2} (computed in outer loop)\n // b = \\sum_{k=0}^{n-1} |A(k,j)|^{2}\n // c = \\sum_{k=0}^{n-1} conj(A(k,i)) * A(k,j)\n //\n auto a = jacobi_aux::submat_diag(A, i);\n auto c = jacobi_aux::submat_offdiag(A, i, j);\n max_resid = std::max(max_resid, abs(c) / sqrt(a * b));\n //\n // Compute the Jacobi rotation matrix which diagonalize M.\n //\n if (detail::make_jacobi_rotation(a, b, c, cs, sn))\n {\n // If the return vlaue of make_jacobi_rotation is false, no\n // rotation is made.\n //\n // Update columns i and j of A\n //\n jacobi_aux::update_vecs(A, i, j, cs, sn);\n }\n }\n }\n#ifdef DEBUG\n std::cout << \"(one_sided_jacobi_svd) iter \" << std::setw(8)\n << max_sweep - nsweep << \": max residual = \" << max_resid\n << '\\n';\n#endif /* DEBUG */\n }\n //\n // Set singular values and left singular vectors.\n //\n for (Index j = 0; j < A.cols(); ++j)\n {\n // Singular values are the norms of the columns of the final A\n sigma(j) = A.col(j).norm();\n // Left singular vectors are the normalized columns of the final A\n A.col(j) /= sigma(j);\n }\n //\n // Sort singular values in descending order. The corresponding singular\n // vectors are also rearranged.\n //\n for (Index i = 0; i < n - 1; ++i)\n {\n //\n // Find the index of the maximum value of a sub-array, sigma(i:n-1).\n //\n Index imax = i;\n for (Index k = i + 1; k < n; ++k)\n {\n if (sigma(k) > sigma(imax))\n {\n imax = k;\n }\n }\n\n if (imax != i)\n {\n // Move the largest singular value to the beggining of the\n // sub-array, and corresponsing singular vectors by swapping columns\n // of A and V.\n std::swap(sigma(i), sigma(imax));\n A.col(i).swap(A.col(imax));\n }\n }\n}\n\n} // namespace: mxpfit\n\n#endif /* MXPFIT_JACOBI_SVD_HPP */\n", "meta": {"hexsha": "37172a02b7be86a7b598cf153bdd0edaee8dcb96", "size": 11417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mxpfit/jacobi_svd.hpp", "max_stars_repo_name": "hydeik/mxpfit", "max_stars_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2018-04-25T07:07:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T09:13:11.000Z", "max_issues_repo_path": "include/mxpfit/jacobi_svd.hpp", "max_issues_repo_name": "hydeik/mxpfit", "max_issues_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2018-07-04T08:42:03.000Z", "max_issues_repo_issues_event_max_datetime": "2019-08-15T02:57:05.000Z", "max_forks_repo_path": "include/mxpfit/jacobi_svd.hpp", "max_forks_repo_name": "hydeik/mxpfit", "max_forks_repo_head_hexsha": "a18621b191e426f549374cff0af3374861e9f065", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9803921569, "max_line_length": 80, "alphanum_fraction": 0.498467198, "num_tokens": 3104, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969137, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6596013567034585}} {"text": "// RMRayTracer.cpp : Defines the entry point for the console application.\n//\n\n#include \"stdafx.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nusing Ray = ParametrizedLine;\nusing Colori = Vector3i;\nusing Colorf = Vector3f;\n\nnamespace rm\n{\n\tclass HitResult\n\t{\n\tpublic:\n\t\tHitResult()\n\t\t\t: t(0.0f)\n\t\t\t, hitPostion(Vector3f::Zero())\n\t\t\t, isHit(false)\n\t\t{}\n\n\t\tvoid Reset()\n\t\t{\n\t\t\tt = 0.0f;\n\t\t\thitPostion = Vector3f::Zero();\n\t\t\tisHit = false;\n\t\t}\n\n\t\tfloat t;\n\t\tVector3f hitPostion;\n\t\tbool isHit;\n\t};\n\n\tclass Camera\n\t{\n\tpublic:\n\t\tCamera(const Vector2i& lScreenSize, const Vector2f& lScreenVirtualSize, const Vector3f& lCameraPosition, const Vector3f& lLeftRightCorner, int lSampleCount)\n\t\t\t: screenSize(lScreenSize)\n\t\t\t, screenVirtualSize(lScreenVirtualSize)\n\t\t\t, screenVirtualHalfSize(lScreenVirtualSize / 2.0f)\n\t\t\t, cameraPosition(lCameraPosition)\n\t\t\t, leftRightCorner(lLeftRightCorner)\n\t\t\t, sampleCount(lSampleCount)\n\t\t{\n\n\t\t}\n\n\t\tconst Vector2i& GetScreenSize() const { return screenSize; }\n\t\tconst Vector2f& GetScreenVirtualSize() const { return screenVirtualSize; }\n\t\tconst Vector2f& GetScreenVirtualHalfSize() const { return screenVirtualHalfSize; }\n\t\tconst Vector3f& GetCameraPosition() const { return cameraPosition; }\n\t\tconst Vector3f& GetLeftRightCorner() const { return leftRightCorner; }\n\t\tint GetSampleCount() const { return sampleCount; }\n\n\tprivate:\n\t\tVector2i screenSize;\n\t\tVector2f screenVirtualSize;\n\t\tVector2f screenVirtualHalfSize;\n\t\tVector3f cameraPosition;\n\t\tVector3f leftRightCorner;\n\t\tint sampleCount;\n\t};\n\n\tclass IHitableObject\n\t{\n\tpublic:\n\t\tvirtual bool\t\tIsHit(const Ray& ray, float minT, float maxT, HitResult& hitResult) const = 0;\n\t\tvirtual Vector3f\tGetNormal(const Vector3f& surfacePosition) const = 0;\n\t\tvirtual Colorf\t\tGetColor() const = 0;\n\t};\n\n\tclass Sphere : public IHitableObject\n\t{\n\tpublic:\n\t\tSphere(const Vector3f& lCenter, float lRadius, const Colorf lColor)\n\t\t\t: center(lCenter)\n\t\t\t, radius(lRadius)\n\t\t\t, color(lColor)\n\t\t{}\n\n\t\tvirtual bool IsHit(const Ray& ray, float minT, float maxT, HitResult& hitResult) const\n\t\t{\n\t\t\thitResult.Reset();\n\n\t\t\tconst Vector3f& vectorA = ray.origin();\n\t\t\tconst Vector3f& vectorB = ray.direction();\n\t\t\tconst Vector3f& vectorC = center;\n\n\t\t\tfloat a = vectorB.dot(vectorB);\n\t\t\tVector3f vectorAC = vectorA - vectorC;\n\t\t\tfloat b = 2 * vectorB.dot(vectorAC);\n\t\t\tfloat c = vectorAC.dot(vectorAC) - radius * radius;\n\n\t\t\tfloat discriminant = b * b - 4 * a * c;\n\n\t\t\tif (discriminant > 0.0f)\n\t\t\t{\n\t\t\t\tfloat t1 = (-b + std::sqrt(discriminant)) / (2.0f * a);\n\t\t\t\tfloat t2 = (-b - std::sqrt(discriminant)) / (2.0f * a);\n\t\t\t\t\n\t\t\t\tfloat t = std::min(t1, t2);\n\n\t\t\t\tif (t >= minT && t < maxT)\n\t\t\t\t{\n\t\t\t\t\thitResult.t = t;\n\t\t\t\t\thitResult.hitPostion = ray.pointAt(t);\n\t\t\t\t\thitResult.isHit = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn hitResult.isHit;\n\t\t}\n\n\t\tvirtual Vector3f GetNormal(const Vector3f& surfacePosition) const\n\t\t{\n\t\t\tVector3f normal = surfacePosition - center;\n\t\t\tnormal.normalize();\n\t\t\treturn normal;\n\t\t}\n\n\t\tvirtual Colorf GetColor() const\n\t\t{\n\t\t\treturn color;\n\t\t}\n\n\tprivate:\n\t\tVector3f center;\n\t\tfloat radius;\n\t\tColorf color;\n\t};\n\n\tclass Scene\n\t{\n\tpublic:\n\t\tScene()\n\t\t{\n\t\t\tInitScene();\n\t\t}\n\n\t\t~Scene()\n\t\t{\n\t\t\tDestoryScene();\n\t\t}\n\n\t\tvoid AddHitableObject(IHitableObject* obj)\n\t\t{\n\t\t\tobjectList.push_back(obj);\n\t\t}\n\n\t\tvoid RayTrace(ofstream& fileHandle, const Camera& cam);\n\n\tprotected:\n\t\tvoid InitScene()\n\t\t{\n\n\t\t}\n\n\t\tvoid DestoryScene()\n\t\t{\n\t\t\tfor each (auto obj in objectList)\n\t\t\t{\n\t\t\t\tdelete obj;\n\t\t\t}\n\n\t\t\tobjectList.clear();\n\t\t}\n\n\tprivate:\n\t\tColori GetBackgroundColor(Ray& ray)\n\t\t{\n\t\t\tfloat sqrt = std::sqrt(ray.direction().x() * ray.direction().x() + ray.direction().y() * ray.direction().y());\n\t\t\tfloat lerpValue = std::min(1.0f, sqrt);\n\t\t\tint value = (int)(255.0f * (1.0f - lerpValue));\n\t\t\treturn Colori(value, value, 255);\n\t\t}\n\n\t\tusing HitableObjectList = std::vector;\n\n\t\tHitableObjectList objectList;\n\t};\n\n\tvoid Scene::RayTrace(ofstream& fileHandle, const Camera& cam)\n\t{\n\t\tstd::random_device rd; \n\t\tstd::mt19937 gen(rd());\n\t\tstd::uniform_real_distribution dis(0.0f, 1.0f);\n\n\t\tfor (int y = cam.GetScreenSize().y(); y >= 0; --y)\n\t\t{\n\t\t\tfor (int x = 0; x < cam.GetScreenSize().x(); ++x)\n\t\t\t{\n\t\t\t\tColori color(0, 0, 0);\n\n\t\t\t\tfor (int index = 0; index < cam.GetSampleCount(); ++index)\n\t\t\t\t{\n\t\t\t\t\tfloat sampleX = float(x) + dis(gen);\n\t\t\t\t\tfloat sampleY = float(y) + dis(gen);\n\t\t\t\t\t\n\t\t\t\t\tVector3f offset(sampleX / (float)cam.GetScreenSize().x() * cam.GetScreenVirtualSize().x(),\n\t\t\t\t\t\tsampleY / (float)cam.GetScreenSize().y() * cam.GetScreenVirtualSize().y(), 0.0f);\n\t\t\t\t\toffset = offset + cam.GetLeftRightCorner();\n\t\t\t\t\toffset.normalize();\n\n\t\t\t\t\tRay ray(cam.GetCameraPosition(), offset);\n\n\t\t\t\t\tHitResult hitResult;\n\t\t\t\t\tfloat minT = 0.0f;\n\t\t\t\t\tfloat maxT = FLT_MAX;\n\t\t\t\t\tbool atLeastHitOnce = false;\n\n\t\t\t\t\tfor each (auto obj in objectList)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (obj->IsHit(ray, minT, maxT, hitResult))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tatLeastHitOnce = true;\n\t\t\t\t\t\t\tmaxT = hitResult.t;\n\t\t\t\t\t\t\tVector3f normal = obj->GetNormal(hitResult.hitPostion);\n\t\t\t\t\t\t\tfloat blend = 1.0f - (1.0f + ray.direction().dot(normal)) / 2.0f;\n\t\t\t\t\t\t\tColorf objColor = blend * 256.0f * obj->GetColor();\n\t\t\t\t\t\t\tcolor += Colori((int)objColor.x(), (int)objColor.y(), (int)objColor.z());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!atLeastHitOnce)\n\t\t\t\t\t{\n\t\t\t\t\t\tcolor += GetBackgroundColor(ray);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tcolor /= cam.GetSampleCount();\n\n\t\t\t\tfileHandle << color.x() << \" \" << color.y() << \" \" << color.z() << \"\\n\";\n\t\t\t}\n\t\t}\n\t} // end of Scene::RayTrace\n\n} // end of namespace\n\nint main()\n{\n\tofstream ppmFile;\n\tppmFile.open(\"buffer.ppm\");\n\n\tVector2i screenSize(200, 200);\n\tVector2f screenVirtualSize(2, 2);\n\tVector2f screenVirtualHalfSize(screenVirtualSize / 2.0f);\n\tVector3f cameraPosition(0.0f, 0.0f, 1.0f);\n\tVector3f leftRightCorner(-screenVirtualHalfSize.x(), -screenVirtualHalfSize.y(), -1.0f);\n\n\trm::Camera cam(screenSize, screenVirtualSize, cameraPosition, leftRightCorner, 8);\n\n\tppmFile << \"P3\\n\" << screenSize.x() << \" \" << screenSize.y() << \"\\n255\\n\";\n\n\trm::Sphere* sphere1 = new rm::Sphere { Vector3f(0.0f, 0.0f, -1.0f), 0.8f, Colorf(1.0f, 0.0f, 0.0f) };\n\trm::Sphere* sphere2 = new rm::Sphere { Vector3f(0.0f, 0.0f, -2.5f), 1.8f, Colorf(0.0f, 0.0f, 1.0f) };\n\n\trm::Scene scene;\n\tscene.AddHitableObject(sphere1);\n\tscene.AddHitableObject(sphere2);\n\tscene.RayTrace(ppmFile, cam);\n\n\tppmFile.close();\n\n return 0;\n}\n\n", "meta": {"hexsha": "de16a5ed155000d7eecad3cfa6225b8103f3a682", "size": 6491, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "RMRayTracer.cpp", "max_stars_repo_name": "cherlix/rmraytracer", "max_stars_repo_head_hexsha": "c11980438b4531e42e0115e1589f1affd6af2841", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RMRayTracer.cpp", "max_issues_repo_name": "cherlix/rmraytracer", "max_issues_repo_head_hexsha": "c11980438b4531e42e0115e1589f1affd6af2841", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RMRayTracer.cpp", "max_forks_repo_name": "cherlix/rmraytracer", "max_forks_repo_head_hexsha": "c11980438b4531e42e0115e1589f1affd6af2841", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.518115942, "max_line_length": 158, "alphanum_fraction": 0.6535202588, "num_tokens": 2033, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9099069962657175, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6595645302702531}} {"text": "/* 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 \n#include \n\nnamespace {\n\naf::array savitzkyGolay(af::array &y, int window_size, int order, unsigned int deriv, double rate=1.0) {\n\n // window_size has to be greater than three\n if (window_size < 3) {\n throw std::invalid_argument(\"Window size must be greater or equal to three\");\n }\n\n // window_size has to be an odd number\n if (window_size % 2 == 0) {\n throw std::invalid_argument(\"Window size must be an odd number.\");\n }\n\n if (window_size < (order + 2)) {\n throw std::invalid_argument(\"Window size is too small for polynomials order\");\n }\n\n if (deriv > order) {\n throw std::invalid_argument(\"Deriv parameter has to be less than order\");\n }\n\n auto const half_window = (window_size - 1) / 2;\n auto const order_range = order + 1;\n\n // Create a matrix with as many rows as window_size and as many columns as order + 1\n // The contents of each column is going to be a consecutive range\n // from -half_window to half_window.\n // example:\n // -half_window + 0, ..., -half_window + 0 (as many columns as order range)\n // -half_window + 1, ..., -half_window + 1\n // .... \n // -1, ..., -1\n // 0, ..., 0\n // 1, ..., 1\n // ....\n // half_window - 1, ..., half_window - 1\n // half_window - 0, ..., half_window - 0\n auto const b1 = af::iota(af::dim4(window_size), af::dim4(1, order_range), y.type()) - half_window;\n \n // This will generate the exponent to each value on b1\n // example:\n // 0, 1, 2, 3, 4, ..., order\n // 0, 1, 2, 3, 4, ..., order\n // ...\n // 0, 1, 2, 3, 4, ..., order\n //\n // note the explicit usage of tiling on the first dimension.\n auto const bExp = af::range(af::dim4(window_size, order_range), 1, y.type());\n \n // we have finally the Vandermonde matrix built.\n auto const b = af::pow(b1, bExp);\n\n // b could be also be constructed by the following iterative logic\n // but, if an accelerated device is present, the above code would work better, \n // as it doesn't imply an interation with sequential state.\n // b1(af::span, 0) = 1.0;\n // b1(af::span, 2) = b1(af::span, 1) * b1(af::span, 1);\n // b1(af::span, 3) = b1(af::span, 1) * b1(af::span, 2);\n // b1(af::span, 4) = b1(af::span, 1) * b1(af::span, 3);\n // etc...\n\n // now we need to compute the inverse of b\n auto const bInv = af::pinverse(b);\n\n // if b is (window_size x order+1), bInv is (order+1 x window_size)\n // we should select the row corresponding to the required derivative \n auto const m = bInv(deriv, af::span);\n\n // scale it\n auto const mAdj = m * pow(rate, deriv) * boost::math::factorial(deriv);\n \n // finally, we need to flip the row before applying the conv operator.\n auto const mAdjFlip = af::flip(mAdj, 1);\n return af::convolve(y, mAdjFlip, af::convMode::AF_CONV_DEFAULT);\n}\n\n}", "meta": {"hexsha": "f1537c60f383b88ca41c32bc21d79fe70e4f4988", "size": 3275, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/gauss/src/filters.cpp", "max_stars_repo_name": "shapelets/shapelets-compute", "max_stars_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T09:43:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:44:55.000Z", "max_issues_repo_path": "modules/gauss/src/filters.cpp", "max_issues_repo_name": "shapelets/shapelets-compute", "max_issues_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T11:48:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:30:34.000Z", "max_forks_repo_path": "modules/gauss/src/filters.cpp", "max_forks_repo_name": "shapelets/shapelets-compute", "max_forks_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.2159090909, "max_line_length": 104, "alphanum_fraction": 0.5905343511, "num_tokens": 977, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357735451835, "lm_q2_score": 0.7606506472514405, "lm_q1q2_score": 0.6595113223372971}} {"text": "//-----------------------------------------------------------------------------\n// Copyright (c) 2015-2018 Benjamin Buch\n//\n// https://github.com/bebuch/mitrax\n//\n// Distributed under the Boost Software License, Version 1.0. (See accompanying\n// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)\n//-----------------------------------------------------------------------------\n#ifndef _mitrax__gauss_newton_algorithm__hpp_INCLUDED_\n#define _mitrax__gauss_newton_algorithm__hpp_INCLUDED_\n\n#include \"make_matrix.hpp\"\n#include \"gaussian_elimination.hpp\"\n#include \"operator.hpp\"\n#include \"norm.hpp\"\n\n#include \"io/matrix.hpp\"\n\n#include \n\n#include \n\n\nnamespace mitrax{\n\n\n\ttemplate < typename F, typename M, row_t R, typename T, typename ... V >\n\tauto gauss_newton_algorithm(\n\t\tF&& f,\n\t\tcol_vector< M, R > const& start_value,\n\t\tT const& threshold,\n\t\tboost::container::vector< std::tuple< V ... > > const& data\n\t){\n\t\tusing std::abs;\n\n\t\tauto arg = start_value;\n\n\t\tfor(;;){\n\t\t\tstd::cout << arg << std::endl;\n\n\t\t\tauto r = make_vector_fn(rows(data.size()),\n\t\t\t\t[&data, &arg, &f](r_t r){\n\t\t\t\t\treturn f(arg, data[r]);\n\t\t\t\t});\n\n\t\t\tauto d = make_matrix_fn(dim_pair(arg.rows().as_col(), data.size()),\n\t\t\t\t[&data, &arg, &f, &threshold](c_t c, r_t r){\n\t\t\t\t\tauto arg1 = arg;\n\t\t\t\t\targ1[c] += threshold / 128;\n\t\t\t\t\treturn (\n\t\t\t\t\t\tf(arg1, data[r]) - f(arg, data[r])\n\t\t\t\t\t) / (threshold / 128);\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tauto trans_d = transpose(d);\n// \t\t\tstd::cout << d << std::endl;\n// \t\t\tstd::cout << trans_d << std::endl;\n// \t\t\tstd::cout << trans_d * d << std::endl;\n// \t\t\tstd::cout << trans_d * r << std::endl;\n\t\t\tauto s = gaussian_elimination(trans_d * d, -trans_d * r);\n\t\t\tauto arg_new = arg + s;\n\n\t\t\tauto diff = arg_new - arg;\n\n\t\t\targ = arg_new;\n\n\t\t\tif(vector_norm_2sqr(diff) < threshold) break;\n\t\t}\n\n\t\treturn arg;\n\t}\n\n\n\ttemplate < typename F, typename M, row_t R, typename T, typename ... V >\n\tauto levenberg_marquardt_algorithm(\n\t\tF&& f,\n\t\tcol_vector< M, R > const& start_value,\n\t\tT const& threshold,\n\t\tT mu,\n\t\tT const& beta0,\n\t\tT const& beta1,\n\t\tboost::container::vector< std::tuple< V ... > > const& data\n\t){\n\t\tusing std::abs;\n\n\t\tauto arg = start_value;\n\n\t\tauto r = make_vector_fn(rows(data.size()),\n\t\t\t[&data, &arg, &f](r_t r){\n\t\t\t\treturn f(arg, data[r]);\n\t\t\t});\n\n\t\tfor(;;){\n// \t\t\tstd::cout << arg << std::endl;\n\n\t\t\tauto d = make_matrix_fn(dim_pair(arg.rows().as_col(), data.size()),\n\t\t\t\t[&data, &arg, &f, &threshold](c_t c, r_t r){\n\t\t\t\t\tauto arg1 = arg;\n\t\t\t\t\targ1[c] += threshold / 128;\n\t\t\t\t\treturn (\n\t\t\t\t\t\tf(arg1, data[r]) - f(arg, data[r])\n\t\t\t\t\t) / (threshold / 128);\n\t\t\t\t}\n\t\t\t);\n\n\t\t\tauto s = [&data, &arg, &r, &d, &f, &mu, beta0, beta1]{ for(;;){\n\t\t\t\tauto const mu2_matrix = make_diag_matrix_v< T >(\n\t\t\t\t\targ.rows().as_dim(), mu * mu\n\t\t\t\t);\n\n\t\t\t\tauto trans_d = transpose(d);\n\t\t\t\tauto s = gaussian_elimination(\n\t\t\t\t\ttrans_d * d + mu2_matrix,\n\t\t\t\t\t-trans_d * r\n\t\t\t\t);\n\n\t\t\t\tauto r_new = make_vector_fn(rows(data.size()),\n\t\t\t\t\t[&data, &arg, &s, &f](r_t r){\n\t\t\t\t\t\treturn f(arg + s, data[r]);\n\t\t\t\t\t});\n\n\t\t\t\tauto r_norm = vector_norm_2sqr(r);\n\t\t\t\tauto numerator = (r_norm - vector_norm_2sqr(r_new));\n\t\t\t\tauto denominator = (r_norm - vector_norm_2sqr(r + d * s));\n\t\t\t\tauto eps = numerator / denominator;\n\n\t\t\t\tif(denominator == 0){\n\t\t\t\t\tthrow std::runtime_error(\"eps is infinite\");\n\t\t\t\t}\n\n// \t\t\t\tstd::cout << \"eps: \" << eps << std::endl;\n\t\t\t\tif(eps <= beta0){\n\t\t\t\t\tmu *= 2;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tr = r_new;\n\n\t\t\t\tif(eps < beta1){\n\t\t\t\t\treturn s;\n\t\t\t\t}\n\n\t\t\t\tmu /= 2;\n\t\t\t\treturn s;\n\t\t\t} }();\n\n// \t\t\tstd::cout << \"s: \" << s << std::endl;\n\t\t\tauto arg_new = arg + s;\n\n\t\t\targ = arg_new;\n\n\t\t\tif(vector_norm_2sqr(s) < threshold) break;\n\t\t}\n\n\t\treturn arg;\n\t}\n\n\n}\n\n\n#endif\n", "meta": {"hexsha": "f8ae2b303d728588ee827001d220ba8c8acc01d9", "size": 3697, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/mitrax/gauss_newton_algorithm.hpp", "max_stars_repo_name": "bebuch/Mitrax", "max_stars_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/mitrax/gauss_newton_algorithm.hpp", "max_issues_repo_name": "bebuch/Mitrax", "max_issues_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/mitrax/gauss_newton_algorithm.hpp", "max_forks_repo_name": "bebuch/Mitrax", "max_forks_repo_head_hexsha": "bc33a1b93058886daab3e4ef736ef9b519111454", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.5426829268, "max_line_length": 79, "alphanum_fraction": 0.5612658913, "num_tokens": 1110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951625409307, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6594821100221893}} {"text": "#ifndef NN_3_LAYER_H\n#define NN_3_LAYER_H\n\n#include \n\nusing namespace arma;\n\nclass NN3Layer {\n private:\n mat w;\n mat v;\n double learningRate;\n double sigmoid(double x){\n return 1 / (1 + exp(-x));\n }\n double sigmoid_de(double y){//Differential equation\n return y * ( 1 - y );\n }\n mat mat_to_sigmoid(mat x){\n x.for_each( [&](mat::elem_type& val) { val=sigmoid(val); } );\n return x;\n }\n mat mat_to_sigmoid_de(mat x){\n x.for_each( [&](mat::elem_type& val) { val=sigmoid_de(val); } );\n return x;\n }\n mat mat_to_learning_rate(mat x){\n x.for_each( [&](mat::elem_type& val) { val=val*this->learningRate; } );\n return x;\n }\n public:\n NN3Layer(int inputLayer,int hiddenLayer,int outputLayer,double learningRate){\n this->learningRate = learningRate;\n this->w =mat(hiddenLayer,inputLayer+1,fill::randu);\n this->v =mat(outputLayer,hiddenLayer+1,fill::randu);\n };\n mat forward_input_to_hidden(mat x){\n mat h;\n //set bias\n mat set_bias(1, 1, fill::ones);\n x = join_rows(x,set_bias);\n //h=sigmoid(wx+bias)\n h=this->mat_to_sigmoid(this->w*x.t());\n return h;\n }\n mat forward_hidden_to_output(mat h){\n mat o;\n //set bias\n mat set_bias(1, 1, fill::ones);\n h = join_cols(h,set_bias);\n //o=sigmoid(vh+bias)\n o=this->mat_to_sigmoid(this->v*h);\n return o;\n }\n //dO\n mat backward_output_to_hidden(mat o,mat d){\n mat error = d-o;\n square(error).print(\"error:\");\n //-1*(d-o)\n mat dError =error;\n dError.for_each( [&](mat::elem_type& val) { val=val*-1; } );\n //sigmoid_de\n return this->mat_to_sigmoid_de(o)%dError;\n }\n //dH\n mat backward_hidden_to_input(mat dO,mat h){\n mat dnet =this->mat_to_sigmoid_de(h);\n mat dH = this->v;\n //remove bias\n dH.reshape(this->v.n_rows,this->v.n_cols-1);\n return (dH.t()*dO) %dnet;\n }\n void backward_update(mat dO,mat h,mat dH,mat x){\n //set bias\n mat set_bias(1, 1, fill::ones);\n //calculate weight update value\n mat dV = dO * join_cols(h,set_bias).t();\n mat dW = dH * join_rows(x,set_bias);\n //update weight\n this->v = this->v - this->mat_to_learning_rate(dV);\n this->w = this->w - this->mat_to_learning_rate(dW);\n }\n void train_step_sgd(mat x,mat d){\n //forward\n mat h = this->forward_input_to_hidden(x);\n mat o = this->forward_hidden_to_output(h);\n //backward\n //calculate gradient\n mat dO = this->backward_output_to_hidden(o,d);\n mat dH = this->backward_hidden_to_input(dO,h);\n //update weight\n this->backward_update(dO,h,dH,x);\n }\n mat only_forward(mat x){\n //forward\n mat h = this->forward_input_to_hidden(x);\n return this->forward_hidden_to_output(h);\n }\n\n\n\n};\n\n#endif", "meta": {"hexsha": "fc7a420e026e8f9b11c4f40e36eb8406261b057b", "size": 2916, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NN3Layer.hpp", "max_stars_repo_name": "ShangHong-CAI/NN3Layer", "max_stars_repo_head_hexsha": "61b75f44d65b7036e2689567b261fd668a4166ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-26T06:50:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T10:42:13.000Z", "max_issues_repo_path": "NN3Layer.hpp", "max_issues_repo_name": "ShangHong-CAI/NN3Layer", "max_issues_repo_head_hexsha": "61b75f44d65b7036e2689567b261fd668a4166ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NN3Layer.hpp", "max_forks_repo_name": "ShangHong-CAI/NN3Layer", "max_forks_repo_head_hexsha": "61b75f44d65b7036e2689567b261fd668a4166ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-25T16:13:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-27T07:37:19.000Z", "avg_line_length": 28.0384615385, "max_line_length": 81, "alphanum_fraction": 0.585733882, "num_tokens": 829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6593568386813116}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing real_t = boost::multiprecision::number>;\n\nreal_t operator\"\" _R( long double d ) {\n\treturn real_t{ d };\n}\n\nreal_t get_fibonacci( uintmax_t const n ) {\n\t// Use Binet's formula, limited n to decimal for perf increase\n\tif( n < 1 ) {\n\t\treturn 0.0_R;\n\t}\n\tstatic real_t const sqrt_five = sqrt( 5.0_R );\n\tstatic real_t const a_part = (1.0_R + sqrt_five) / 2.0_R;\n\tstatic real_t const b_part = (1.0_R - sqrt_five) / 2.0_R;\n\t\n\treal_t const a = pow( a_part, n );\n\treal_t const b = pow( b_part, n );\n\treturn round( (a - b)/sqrt_five );\n}\n\nint main( int argc, char **argv ) { \n//\tassert( argc == 2 );\n//\n//\tauto n = strtoull( argv[1], 0, 10 );\n\tuint64_t n = 1234567;\n\tstd::cout << n << \": \" << std::setprecision(std::numeric_limits::max_digits10) << get_fibonacci( n ) << '\\n';\n\treturn EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "b49834d7b1b656d3f07b90ef2695c505a0620a15", "size": 1012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fibonacci.cpp", "max_stars_repo_name": "beached/fibonacci", "max_stars_repo_head_hexsha": "89555c95c9408f7304ab7ea1832e9a48bb604106", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fibonacci.cpp", "max_issues_repo_name": "beached/fibonacci", "max_issues_repo_head_hexsha": "89555c95c9408f7304ab7ea1832e9a48bb604106", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fibonacci.cpp", "max_forks_repo_name": "beached/fibonacci", "max_forks_repo_head_hexsha": "89555c95c9408f7304ab7ea1832e9a48bb604106", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6315789474, "max_line_length": 118, "alphanum_fraction": 0.6669960474, "num_tokens": 314, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9473810496235895, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6593377284644676}} {"text": "// Copyright (C) 2016 Daniele Panozzo \n//\n// This Source Code Form is subject to the terms of the Mozilla Public License\n// v. 2.0. If a copy of the MPL was not distributed with this file, You can\n// obtain one at http://mozilla.org/MPL/2.0/.\n#include \"tutorial_nrosy.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nstd::complex find_root(std::complex c0, int n)\n{\n // Find the roots of p(t) = (t - c0)^n using\n // https://en.wikipedia.org/wiki/Companion_matrix\n Eigen::MatrixXcd M = Eigen::MatrixXcd::Zero(n,n);\n for (int i=1;i(1,0);\n M(0,n-1) = c0;\n return M.eigenvalues()(0);\n}\n\nMatrixXd tutorial_nrosy\n (\n const MatrixXd& V, // Vertices of the mesh\n const MatrixXi& F, // Faces\n const MatrixXi& TT, // Adjacency triangle-triangle\n const VectorXi& soft_id, // Soft constraints face ids\n const MatrixXd& soft_value, // Soft constraints 3d vectors\n const int n // Degree of the n-rosy field\n )\n{\n assert(soft_id.size() > 0); // One constraint is necessary to make the solution unique\n\n Matrix T1(F.rows(),3), T2(F.rows(),3);\n\n // Compute the local reference systems for each face\n for (unsigned i=0;i > > t;\n std::vector< Triplet > > tb;\n\n unsigned count = 0;\n for (unsigned f=0;f g) continue;\n\n // Compute the complex representation of the common edge\n Vector3d e = (V.row(F(f,(ei+1)%3)) - V.row(F(f,ei)));\n Vector2d vef = Vector2d(e.dot(T1.row(f)),e.dot(T2.row(f))).normalized();\n std::complex ef(vef(0),vef(1));\n Vector2d veg = Vector2d(e.dot(T1.row(g)),e.dot(T2.row(g))).normalized();\n std::complex eg(veg(0),veg(1));\n\n // Add the term conj(f)^n*ui - conj(g)^n*uj to the energy matrix\n t.push_back(Triplet >(count,f, std::pow(std::conj(ef),n)));\n t.push_back(Triplet >(count,g,-1.*std::pow(std::conj(eg),n)));\n\n ++count;\n }\n }\n\n // Convert the constraints into the complex polynomial coefficients and add them as soft constraints\n double lambda = 10e6;\n for (unsigned r=0; r c(v.dot(T1.row(f)),v.dot(T2.row(f)));\n t.push_back(Triplet >(count,f, sqrt(lambda)));\n tb.push_back(Triplet >(count,0, std::pow(c,n) * std::complex(sqrt(lambda),0)));\n ++count;\n }\n\n // Solve the linear system\n typedef SparseMatrix> SparseMatrixXcd;\n SparseMatrixXcd A(count,F.rows());\n A.setFromTriplets(t.begin(), t.end());\n SparseMatrixXcd b(count,1);\n b.setFromTriplets(tb.begin(), tb.end());\n SimplicialLDLT< SparseMatrixXcd > solver;\n solver.compute(A.adjoint()*A);\n assert(solver.info()==Success);\n MatrixXcd u = solver.solve(A.adjoint()*MatrixXcd(b));\n assert(solver.info()==Success);\n\n // Convert the interpolated polyvector into Euclidean vectors\n MatrixXd R(F.rows(),3);\n for (int f=0; f root = find_root(u(f),n);\n R.row(f) = T1.row(f) * root.real() + T2.row(f) * root.imag();\n }\n\n return R;\n}\n", "meta": {"hexsha": "0f72be97fbe5fcf79bd0b8069f735a1f0e49ac5c", "size": 4045, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lab4/src/tutorial_nrosy_complete.cpp", "max_stars_repo_name": "bambrow/geometric-modeling", "max_stars_repo_head_hexsha": "10c30f4254928d94f057f18e7542cccfa98ddb3c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-11T05:20:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-11T05:20:52.000Z", "max_issues_repo_path": "lab4/src/tutorial_nrosy_complete.cpp", "max_issues_repo_name": "bambrow/geometric-modeling", "max_issues_repo_head_hexsha": "10c30f4254928d94f057f18e7542cccfa98ddb3c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lab4/src/tutorial_nrosy_complete.cpp", "max_forks_repo_name": "bambrow/geometric-modeling", "max_forks_repo_head_hexsha": "10c30f4254928d94f057f18e7542cccfa98ddb3c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5726495726, "max_line_length": 112, "alphanum_fraction": 0.626946848, "num_tokens": 1213, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026618464796, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6591685380369127}} {"text": "// Gao Wang and Kushal K. Dey (c) 2016\n// code format configuration: clang-format -style=Google -dump-config >\n// ~/.clang-format\n#ifndef _PFA_HPP\n#define _PFA_HPP\n\n#include \n#include \n#include \n#include \n\nstatic const double INV_SQRT_2PI = 0.3989422804014327;\nstatic const double INV_SQRT_2PI_LOG = -0.91893853320467267;\n\ninline double normal_pdf(double x, double m, double sd) {\n double a = (x - m) / sd;\n return INV_SQRT_2PI / sd * std::exp(-0.5 * a * a);\n};\n\ninline double normal_pdf_log(double x, double m, double sd) {\n double a = (x - m) / sd;\n return INV_SQRT_2PI_LOG - std::log(sd) - 0.5 * a * a;\n};\n\n/* The digamma function is the derivative of gammaln.\n Reference:\n J Bernardo,\n Psi ( Digamma ) Function,\n Algorithm AS 103,\n Applied Statistics,\n Volume 25, Number 3, pages 315-317, 1976.\n From http://www.psc.edu/~burkardt/src/dirichlet/dirichlet.f\n (with modifications for negative numbers and extra precision)\n*/\ninline double digamma(double x) {\n double neginf = -INFINITY;\n static const double c = 12, digamma1 = -0.57721566490153286,\n trigamma1 = 1.6449340668482264365, /* pi^2/6 */\n s = 1e-6, s3 = 1. / 12, s4 = 1. / 120, s5 = 1. / 252, s6 = 1. / 240,\n s7 = 1. / 132, s8 = 691. / 32760, s9 = 1. / 12,\n s10 = 3617. / 8160;\n double result;\n /* Illegal arguments */\n if ((x == neginf) || std::isnan(x)) {\n return NAN;\n }\n /* Singularities */\n if ((x <= 0) && (floor(x) == x)) {\n return neginf;\n }\n /* Negative values */\n /* Use the reflection formula (Jeffrey 11.1.6):\n * digamma(-x) = digamma(x+1) + pi*cot(pi*x)\n *\n * This is related to the identity\n * digamma(-x) = digamma(x+1) - digamma(z) + digamma(1-z)\n * where z is the fractional part of x\n * For example:\n * digamma(-3.1) = 1/3.1 + 1/2.1 + 1/1.1 + 1/0.1 + digamma(1-0.1)\n * = digamma(4.1) - digamma(0.1) + digamma(1-0.1)\n * Then we use\n * digamma(1-z) - digamma(z) = pi*cot(pi*z)\n */\n if (x < 0) {\n return digamma(1 - x) + M_PI / tan(-M_PI * x);\n }\n /* Use Taylor series if argument <= S */\n if (x <= s) return digamma1 - 1 / x + trigamma1 * x;\n /* Reduce to digamma(X + N) where (X + N) >= C */\n result = 0;\n while (x < c) {\n result -= 1 / x;\n x++;\n }\n /* Use de Moivre's expansion if argument >= C */\n /* This expansion can be computed in Maple via asympt(Psi(x),x) */\n if (x >= c) {\n double r = 1 / x, t;\n result += log(x) - 0.5 * r;\n r *= r;\n#if 1\n result -= r * (s3 - r * (s4 - r * (s5 - r * (s6 - r * s7))));\n#else\n /* this version for lame compilers */\n t = (s5 - r * (s6 - r * s7));\n result -= r * (s3 - r * (s4 - r * t));\n#endif\n }\n return result;\n}\n\ntemplate \nvoid print(const T &e) {\n std::cout << e << std::endl;\n}\n\nclass Exception {\n public:\n /// constructor\n /// \\param msg error message\n Exception(const std::string &msg) : m_msg(msg) {}\n\n /// return error message\n const char *message() { return m_msg.c_str(); }\n\n virtual ~Exception(){};\n\n private:\n /// error message\n std::string m_msg;\n};\n\n/// exception, thrown if out of memory\nclass StopIteration : public Exception {\n public:\n StopIteration(const std::string msg) : Exception(msg){};\n};\n\n/// exception, thrown if index out of range\nclass IndexError : public Exception {\n public:\n IndexError(const std::string msg) : Exception(msg){};\n};\n\n/// exception, thrown if value of range etc\nclass ValueError : public Exception {\n public:\n ValueError(const std::string msg) : Exception(msg){};\n};\n\n/// exception, thrown if system error occurs\nclass SystemError : public Exception {\n public:\n SystemError(const std::string msg) : Exception(msg){};\n};\n\n/// exception, thrown if a runtime error occurs\nclass RuntimeError : public Exception {\n public:\n RuntimeError(const std::string msg) : Exception(msg){};\n};\n\nextern \"C\" int pfa_em(double *, double *, double *, double *, int *, int *,\n int *, int *, double *, int *, double *, int *, int *,\n double *, double *, double *, double *, int *, int *,\n int *, int *, int *, int *);\nextern \"C\" int pfa_model_loglik(double *, double *, double *, double *, int *,\n int *, int *, double *);\n\nclass PFA {\n public:\n PFA(double *cX, double *cF, double *cP, double *cQ, double *cLout, int N,\n int J, int K, int C)\n : // mat(aux_mem*, n_rows, n_cols, copy_aux_mem = true, strict = true)\n D(cX, N, J, false, true),\n F(cF, K, J, false, true),\n P(cP, K, K, false, true),\n q(cQ, C, false, true),\n L(cLout, N, K, false, true) {\n // initialize residual sd with sample sd\n s = arma::vectorise(arma::stddev(D));\n W.set_size(F.n_rows, F.n_rows);\n delta.set_size(int((F.n_rows + 1) * F.n_rows / 2), q.n_elem, D.n_rows);\n delta.fill(0);\n n_threads = omp_get_max_threads();\n n_updates = 0;\n for (size_t k1 = 0; k1 < F.n_rows; k1++) {\n for (size_t k2 = 0; k2 <= k1; k2++) {\n // set factor pair coordinates to avoid\n // having to compute it at each iteration\n // (b + 1) * b / 2 - (b - a)\n size_t k1k2 = size_t(k1 * (k1 + 1) / 2 + k2);\n F_pair_coord[std::make_pair(k1, k2)] = k1k2;\n F_pair_coord[std::make_pair(k2, k1)] = k1k2;\n }\n }\n }\n virtual ~PFA() {}\n\n virtual PFA *clone() const { return new PFA(*this); }\n\n virtual void write(std::ostream &out, int info) {\n throw RuntimeError(\"The base write() function should not be called\");\n }\n virtual int E_step() {\n throw RuntimeError(\"The base E_step() function should not be called\");\n }\n\n virtual int M_step() {\n throw RuntimeError(\"The base M_step() function should not be called\");\n }\n\n void update_model_loglik(arma::vec &true_s, arma::mat &true_q);\n void set_threads(int n) { n_threads = n; }\n void update_ldelta(int core = 0);\n void update_loglik_and_delta();\n void update_factor_model();\n void update_residual_error();\n double get_loglik() { return loglik; }\n double get_bic() {\n // BIC = -2 * loglik + d * log(N)\n // number of parameters:\n // P: (K + 1) * K / 2\n // L: N * K\n // F: K * J\n return -2 * loglik +\n ((P.n_rows + 1) * P.n_rows / 2 + D.n_rows * P.n_rows +\n P.n_rows * D.n_cols) *\n std::log(D.n_rows);\n }\n\n protected:\n // N by J matrix of data\n arma::mat D;\n // K by K matrix of factor pair frequencies\n arma::mat P;\n // K by J matrix of factors\n arma::mat F;\n // Q by 1 vector of membership grids\n arma::vec q;\n // J by 1 vector of residual standard error\n arma::vec s;\n // K1K2 by Q by N tensor\n arma::cube delta;\n arma::cube ldelta;\n std::map, size_t> F_pair_coord;\n // N by K matrix of loadings\n arma::mat L;\n // W = L'L is K X K matrix\n arma::mat W;\n // loglik\n double loglik;\n // number of threads\n int n_threads;\n // updates on the model\n int n_updates;\n};\n\nclass PFA_EM : public PFA {\n public:\n PFA_EM(double *cX, double *cF, double *cP, double *cQ, double *cLout, int N,\n int J, int K, int C)\n : PFA(cX, cF, cP, cQ, cLout, N, J, K, C) {}\n\n PFA *clone() const { return new PFA_EM(*this); }\n\n void update_paired_factor_weights();\n int E_step() {\n update_ldelta();\n update_loglik_and_delta();\n update_paired_factor_weights();\n return 0;\n }\n\n int M_step() {\n update_factor_model();\n update_residual_error();\n n_updates += 1;\n return 0;\n }\n\n void write(std::ostream &out, int info) {\n if (info == 0) {\n // D.print(out, \"Data Matrix:\");\n q.print(out, \"Membership grids:\");\n }\n if (info == 1) {\n F.print(out, \"Factor matrix:\");\n P.print(out, \"Factor frequency matrix:\");\n if (n_updates > 0)\n L.print(out, \"Loading matrix:\");\n else\n out << \"Loading matrix:\" << std::endl;\n }\n if (info == 2) {\n // W.print(out, \"E[L'L] matrix:\");\n s.print(out, \"Residual standard deviation of data columns:\");\n if (n_updates > 0) {\n ldelta.print(out, \"log delta tensor\");\n delta.print(out, \"delta tensor\");\n }\n }\n }\n};\n\nclass PFA_VEM : public PFA {\n public:\n PFA_VEM(double *cX, double *cF, double *cP, double *cQ, double *cLout,\n double *calphaout, int N, int J, int K, int C, double alpha0)\n : PFA(cX, cF, cP, cQ, cLout, N, J, K, C),\n alpha(calphaout, K, K, false, true),\n alpha0(alpha0) {\n alpha.zeros();\n digamma_alpha.set_size(P.n_rows, P.n_rows);\n digamma_alpha.fill(digamma(alpha0));\n digamma_sum_alpha = 0;\n maxiter = 1000;\n tol = 1E-3;\n }\n\n PFA *clone() const { return new PFA_VEM(*this); }\n\n void update_variational_ldelta();\n double get_variational_lowerbound();\n void update_variational_parameters();\n void update_paired_factor_weights();\n\n int E_step() {\n int status = 0;\n update_ldelta(1);\n size_t niter = 0;\n lowerbound.resize(0);\n while (niter <= maxiter) {\n update_variational_ldelta();\n update_loglik_and_delta();\n update_variational_parameters();\n update_paired_factor_weights();\n lowerbound.push_back(get_variational_lowerbound());\n if (lowerbound.back() != lowerbound.back()) {\n std::cerr\n << \"[ERROR] lower bound nan produced in variational approximation!\"\n << std::endl;\n status = 1;\n break;\n }\n niter++;\n if (niter > 1) {\n double diff = lowerbound[niter - 1] - lowerbound[niter - 2];\n if (diff < 0.0) {\n std::cerr << \"[ERROR] lower bound decreased in variational \"\n \"approximation: \\n\\tfrom \"\n << lowerbound[niter - 2] << \" to \" << lowerbound[niter - 1]\n << \"!\" << std::endl;\n status = 1;\n break;\n }\n if (diff < tol) break;\n }\n if (niter == maxiter) {\n std::cerr << \"[WARNIKNG] variational approximation procedure failed to \"\n \"converge at tolerance level \"\n << tol << \", after \" << maxiter\n << \" iterations: \\n\\tlog lower bound starts \"\n << lowerbound.front() << \", ends \" << lowerbound.back() << \"!\"\n << std::endl;\n status = 1;\n break;\n }\n }\n return status;\n }\n\n int M_step() {\n update_factor_model();\n update_residual_error();\n n_updates += 1;\n return 0;\n }\n\n void write(std::ostream &out, int info) {\n if (info == 0) {\n // D.print(out, \"Data Matrix:\");\n q.print(out, \"Membership grids:\");\n }\n if (info == 1) {\n F.print(out, \"Factor matrix:\");\n P.print(out, \"Factor frequency matrix:\");\n if (n_updates > 0)\n L.print(out, \"Loading matrix:\");\n else\n out << \"Loading matrix:\" << std::endl;\n }\n if (info == 2) {\n // W.print(out, \"E[L'L] matrix:\");\n s.print(out, \"Residual standard deviation of data columns:\");\n if (n_updates > 0) {\n alpha.print(out, \"Dirichlet parameter for factor pairs:\");\n out << \"log lower bound:\" << std::endl;\n for (size_t i = 0; i < lowerbound.size(); ++i) {\n out << lowerbound[i] << \", \";\n }\n out << std::endl;\n }\n }\n }\n\n private:\n // Dirichlet priors for factors and grids\n double alpha0;\n // K by K matrix of digamma of variational parameter for factor pair\n // frequencies\n arma::mat digamma_alpha;\n arma::mat alpha;\n double digamma_sum_alpha;\n size_t maxiter;\n double tol;\n std::vector lowerbound;\n};\n#endif\n", "meta": {"hexsha": "11086ca2444623d0688dd840b0b4fbc55482f9b7", "size": 11549, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pfa.hpp", "max_stars_repo_name": "gaow/pfar", "max_stars_repo_head_hexsha": "d027916721337b98ef296e45763d4301ccbbe248", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2016-07-20T20:16:08.000Z", "max_stars_repo_stars_event_max_datetime": "2016-09-14T19:16:25.000Z", "max_issues_repo_path": "src/pfa.hpp", "max_issues_repo_name": "gaow/pfar", "max_issues_repo_head_hexsha": "d027916721337b98ef296e45763d4301ccbbe248", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2016-08-15T03:02:03.000Z", "max_issues_repo_issues_event_max_datetime": "2017-05-12T21:59:19.000Z", "max_forks_repo_path": "src/pfa.hpp", "max_forks_repo_name": "gaow/pfar", "max_forks_repo_head_hexsha": "d027916721337b98ef296e45763d4301ccbbe248", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.8725, "max_line_length": 80, "alphanum_fraction": 0.572517101, "num_tokens": 3476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677583778257, "lm_q2_score": 0.7772998508568417, "lm_q1q2_score": 0.6591252121184943}} {"text": "#include \n#include \n#include \n#include \n#include \"boost/program_options.hpp\"\n\nusing namespace std;\nusing namespace arma;\nnamespace po = boost::program_options;\n\n// m: numRows, n: numCols\ninline double simpleDenseTest_Arma(int m, int n, int num_trials) {\n\n mat A = randu(m, n);\n mat B = randu(m, n);\n mat C = randu(m, n);\n mat D = randu(m, n);\n mat E = randu(m, n);\n\n clock_t start;\n start = clock();\n for (unsigned i = 0; i < num_trials; i++) {\n\n mat res = ((A + B) / C - D) % E;\n\n }\n double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n return duration / num_trials;\n\n}\n\n// m: numRows of A, n: numCols of A, and numRows of B, k: numCols of B\ninline double gemmSanityTest_Arma(int m, int n, int k, int num_trials) {\n\n mat A = randu(m, n);\n mat C = randu(n, k);\n mat E = randu(m, k);\n\n clock_t start;\n start = clock();\n for (unsigned i = 0; i < num_trials; i++) {\n\n E += A * C;\n\n }\n double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n\n return duration / num_trials;\n\n}\n\n// m: numRows of A, n: numCols of A, and numRows of B, k: numCols of B\ninline double gemmDenseTest_Arma(int m, int n, int k, int num_trials) {\n\n mat A = randu(m, n);\n mat B = randu(m, n);\n mat C = randu(n, k);\n mat D = randu(n, k);\n mat E = randu(m, k);\n\n clock_t start;\n start = clock();\n for (unsigned i = 0; i < num_trials; i++) {\n\n E += (A + B) * (C - D);\n\n }\n double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n \n return duration / num_trials;\n\n}\n\ninline double mulDenseTest_Arma(int a, int b, int c, int d, int num_trials) {\n\n mat A = randu(a, a);\n mat B = randu(a, b);\n mat C = randu(b, c);\n mat D = randu(c, d);\n\n clock_t start;\n start = clock();\n for (unsigned i = 0; i < num_trials; i++) {\n\n mat res = A * B * C * D;\n\n }\n double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n return duration / num_trials;\n}\n\n// m: numRows of A, n: numCols of A, and numRows of B, k: numCols of B\ninline double denseVectorTest_Arma(int l, int num_trials) {\n\n vec a = randu(l);\n vec b = randu(l);\n vec c = randu(l);\n vec d = randu(l);\n vec e = randu(l);\n\n clock_t start;\n start = clock();\n for (unsigned i = 0; i < num_trials; i++) {\n e = a + b + c + d;\n }\n double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;\n\n return duration / num_trials;\n}\n\nvoid runArmaTests(int num_trials, int l, int m, int n, int k, int a, int b, int c, int d, \n bool skip_vec, bool skip_simple, bool skip_gemm, bool skip_mult) {\n\n if (!skip_vec)\n cout << \"Armadillo Vectors Test:\\t\" << denseVectorTest_Arma(l, num_trials) << endl;\n if (!skip_simple)\n cout << \"Armadillo Simple Test:\\t\" << simpleDenseTest_Arma(m, n, num_trials) << endl;\n if (!skip_gemm) {\n cout << \"Armadillo gemmSanity Test:\\t\" << gemmDenseTest_Arma(m, n, k, num_trials) << endl;\n cout << \"Armadillo gemm Test:\\t\" << gemmDenseTest_Arma(m, n, k, num_trials) << endl;\n }\n if (!skip_mult)\n cout << \"Armadillo mulDense Test:\\t\" << mulDenseTest_Arma(a, b, c, d, num_trials) << endl;\n\n}\n\nint main(int argc, char *argv[]) {\n\n int l, m, n, k, a, b, c, d, trials;\n bool skip_vec, skip_simple, skip_gemm, skip_mult;\n \n po::options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help\", \"produce help message\")\n (\"l\", po::value(&l)->default_value(1048576),\n \"length of vectors in vector addition test\")\n (\"m\", po::value(&m)->default_value(1024),\n \"numRows of matrices in Simple Test, and gemm Test\")\n (\"n\", po::value(&n)->default_value(1024),\n \"numCols of matrices in Simple Test, and gemm Test\")\n (\"k\", po::value(&k)->default_value(1024),\n \"numCols of B in gemm Test\")\n (\"trials\", po::value(&trials)->default_value(10), \"number of trials\")\n (\"a\", po::value(&a)->default_value(1024),\n \"size matrix A in mulDense Test\")\n (\"b\", po::value(&b)->default_value(512),\n \"size matrix B in mulDense Test\")\n (\"c\", po::value(&c)->default_value(256),\n \"size matrix C in mulDense Test\")\n (\"d\", po::value(&d)->default_value(128),\n \"size matrix D in mulDense Test\")\n (\"skip-vec\", po::value(&skip_vec)->default_value(false),\n \"skip vectors Test\")\n (\"skip-simple\", po::value(&skip_simple)->default_value(false),\n \"skip simple Test\")\n (\"skip-gemm\", po::value(&skip_gemm)->default_value(false),\n \"skip gemm Tests\")\n (\"skip-mult\", po::value(&skip_mult)->default_value(false),\n \"skip mulDense Test\")\n ;\n \n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n po::notify(vm);\n\n runArmaTests(trials, l, m, n, k, a, b, c, d, skip_vec, skip_simple, skip_gemm, skip_mult);\n\n return 0;\n}\n", "meta": {"hexsha": "cdf3a1a3cfbdb08f4311752724cd14fd59f760ff", "size": 5064, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main/cpp/arma.cpp", "max_stars_repo_name": "brkyvz/linalg-benchmarks", "max_stars_repo_head_hexsha": "64b2414bf8cf75089853021ca02ccd2078e938ca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main/cpp/arma.cpp", "max_issues_repo_name": "brkyvz/linalg-benchmarks", "max_issues_repo_head_hexsha": "64b2414bf8cf75089853021ca02ccd2078e938ca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main/cpp/arma.cpp", "max_forks_repo_name": "brkyvz/linalg-benchmarks", "max_forks_repo_head_hexsha": "64b2414bf8cf75089853021ca02ccd2078e938ca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7882352941, "max_line_length": 94, "alphanum_fraction": 0.5963665087, "num_tokens": 1610, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677430095496, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6591252045473374}} {"text": "#include \n#include \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 triOfA(A);\nMatrix4d pm = triOfA.packedMatrix();\ncout << \"The packed matrix M is:\" << endl << pm << endl;\ncout << \"The diagonal and subdiagonal corresponds to the matrix T, which is:\" \n << endl << triOfA.matrixT() << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "86e5a8913a23c2ee5510ac75e26e5e5ad676bcdc", "size": 545, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_packedMatrix.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_packedMatrix.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_packedMatrix.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.9523809524, "max_line_length": 78, "alphanum_fraction": 0.6697247706, "num_tokens": 159, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6590870220471323}} {"text": "#include \"include/MMVII_all.h\"\n#include \n\nnamespace MMVII\n{\n\n// return the variance of exponential distribution of parameter \"a\" ( i.e proportiona to \"a^|x|\")\ndouble Sigma2FromFactExp(double a)\n{\n return (2*a) / Square(1-a);\n}\n\n// return the value of \"a\" such that exponential distribution of parameter \"a\" has variance S2\n// i.e. this the \"inverse\" function of Sigma2FromFactExp\n\ndouble FactExpFromSigma2(double aS2)\n{\n return (aS2+1 - sqrt(Square(aS2+1)-Square(aS2)) ) / aS2 ;\n}\n\n\n/* *********************************************** */\n/* */\n/* cComputeStdDev */\n/* */\n/* *********************************************** */\n\n#if (0)\n/// Class to compute non biased variance from a statisic \n\n/** Class to compute non biased variance from a statisic\n This generalise the standard formula\n EstimVar = N/(N-1) EmpirVar\n To the case where there is a weighting.\n\n It can be uses with N variable to factorize the computation on Weight\n */\n\ntemplate class cComputeStdDev\n{\n public :\n typedef double tTab[Dim];\n\n cComputeStdDev();\n\n void Add(const double * aVal,const double & aPds);\n const double * ComputeUnBiasedVar() ;\n const double * ComputeBiasedVar() ;\n double DeBiasFactor() const;\n\n private :\n double mSomW; ///< Sum of Weight\n double mSomWW; ///< Sum of Weight ^2\n tTab mSomWV; ///< Weighted som of vals\n tTab mSomWVV; ///< Weighted som of vals ^2\n tTab mVar; ///< Buffer to compute the unbiased variance\n tTab mBVar; ///< Buffer to compute the empirical variance\n};\n#endif\n\ntemplate cComputeStdDev::cComputeStdDev() :\n mSomW (0.0),\n mSomWW (0.0)\n{\n for (int aD=0 ; aD void cComputeStdDev::Add(const double * aVal,const double & aPds)\n{\n mSomW += aPds;\n mSomWW += Square(aPds);\n for (int aD=0 ; aD double cComputeStdDev::DeBiasFactor() const\n{\n MMVII_INTERNAL_ASSERT_strong(mSomW>0,\"No value in DeBiasFactor\");\n return 1 - mSomWW/Square(mSomW);\n}\n\ntemplate bool cComputeStdDev::OkForUnBiasedVar() const\n{\n return (mSomW>0) && (DeBiasFactor()!=0);\n}\n\ntemplate const double * cComputeStdDev::ComputeUnBiasedVar()\n{\n /* At least, this formula is correct :\n - when all weight are equal => 1-1/N\n - when all but one weight are 0 => 0 \n - and finally if all are equal or 0\n */\n double aDebias = DeBiasFactor();\n MMVII_INTERNAL_ASSERT_strong(aDebias>0,\"No var can be computed in ComputeVar\");\n\n for (int aD=0 ; aD const double * cComputeStdDev::ComputeBiasedVar()\n{\n for (int aD=0 ; aD;\n\nvoid BenchUnbiasedStdDev()\n{\n for (int aNbTest = 0 ; aNbTest<1000 ; aNbTest++)\n {\n int aNbVar = 1 + RandUnif_N(3);\n int aNbTir = aNbVar;\n int aNbComb = pow(aNbVar,aNbTir);\n std::vector aVecVals = VRandUnif_0_1(aNbVar);\n std::vector aVecWeight = VRandUnif_0_1(aNbVar);\n// aVecWeight = std::vector (aNbVar,1.0);\n\n // compute the average of all empirical variance\n double aMoyVar=0;\n for (int aFlag=0 ; aFlag < aNbComb ; aFlag++) // Explore all combinaison\n {\n cComputeStdDev<1> aUBS;\n for (int aVar=0 ; aVar < aNbVar ; aVar++) // All Variable of this realization\n {\n int aNumVar = (aFlag / round_ni(pow(aNbVar,aVar))) % aNbVar; // \"Majic\" formula to exdtrac p-adic decomp\n aUBS.Add(&(aVecVals.at(aNumVar)),aVecWeight.at(aNumVar));\n }\n aMoyVar += aUBS.ComputeBiasedVar()[0];\n }\n aMoyVar /= aNbComb;\n\n cComputeStdDev<1> aUBS;\nStdOut() << \"WWW=\" ;\n for (int aK=0 ; aK void TestVarFilterExp(cPt2di aP0,cPt2di aP1,const Type & aV0,double aFx,double aFy,int aNbIt)\n{\n cPt2di aPMil = (aP0+aP1) / 2;\n cRect2 aRect2(aP0,aP1);\n\n cIm2D aIm(aP0,aP1,nullptr,eModeInitImage::eMIA_Null);\n cDataIm2D & aDIm = aIm.DIm();\n\n // 1- Make 1 iteration of expon filter on a Direc, check variance and aver\n aDIm.InitDirac(aPMil,aV0);\n\n ExponentialFilter(true,aDIm,aNbIt,aRect2,aFx,aFy);\n cMatIner2Var aMat = StatFromImageDist(aDIm);\n\n MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S1() - aPMil.x()) < 1e-5 ,\"Average Exp\")\n MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S2() - aPMil.y()) < 1e-5 ,\"Average Exp\")\n\n MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S11()-Sigma2FromFactExp(aFx) * aNbIt)<1e-5,\"Var Exp\");\n MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S22()-Sigma2FromFactExp(aFy) * aNbIt)<1e-5,\"Var Exp\");\n}\n\n\n\ntemplate void TestVarFilterExp(cPt2di aSz,double aStdDev,int aNbIter,double aEps)\n{\n cIm2D aIm(cPt2di(0,0),aSz,nullptr,eModeInitImage::eMIA_Null);\n cDataIm2D & aDIm = aIm.DIm();\n cPt2di aPMil = aSz / 2;\n double aV0 = 2.0;\n\n // 1- Make 1 iteration of expon filter on a Direc, check variance and aver\n aDIm.InitDirac(aPMil,aV0);\n\n ExpFilterOfStdDev(aDIm,aNbIter,aStdDev);\n cMatIner2Var aMat = StatFromImageDist(aDIm);\n\n MMVII_INTERNAL_ASSERT_bench(std::abs(aMat.S11()-Square(aStdDev))(cPt2di(-2,2),cPt2di(400,375),2.0,0.6,0.67,1);\n TestVarFilterExp(cPt2di(-2,2),cPt2di(400,375),2.0,0.6,0.67,3);\n\n // Test Sigma2FromFactExp\n for (int aK=1 ; aK<100 ; aK++)\n {\n double aS2 = aK / 5.0;\n double aF = FactExpFromSigma2(aS2);\n {\n // Check both formula are inverse of each others\n double aCheckS2 = Sigma2FromFactExp(aF);\n MMVII_INTERNAL_ASSERT_bench(std::abs( aS2 - aCheckS2 ) < 1e-5 ,\"Sigma2FromFactExp\")\n \n }\n {\n // Check formula Sigma2FromFactExp on exponential filters\n TestVarFilterExp(cPt2di(0,0),cPt2di(4000,3),2.0,aF,0,1);\n }\n }\n\n TestVarFilterExp(cPt2di(300,300),2.0,2,1e-6);\n TestVarFilterExp(cPt2di(300,300),5.0,3,1e-3);\n}\n\n\n\n};\n\n", "meta": {"hexsha": "adc3d8908d740a266eda2424b0ec1d97ae721e70", "size": 7722, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "MMVII/src/UtiMaths/uti_stat.cpp", "max_stars_repo_name": "nguyenign/micmac4wasm", "max_stars_repo_head_hexsha": "adbd3be3858279cb9004942ddd35c38a5d38c03c", "max_stars_repo_licenses": ["CECILL-B"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-31T06:20:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T06:20:23.000Z", "max_issues_repo_path": "MMVII/src/UtiMaths/uti_stat.cpp", "max_issues_repo_name": "nguyenign/micmac4wasm", "max_issues_repo_head_hexsha": "adbd3be3858279cb9004942ddd35c38a5d38c03c", "max_issues_repo_licenses": ["CECILL-B"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MMVII/src/UtiMaths/uti_stat.cpp", "max_forks_repo_name": "nguyenign/micmac4wasm", "max_forks_repo_head_hexsha": "adbd3be3858279cb9004942ddd35c38a5d38c03c", "max_forks_repo_licenses": ["CECILL-B"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-02-07T08:29:49.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-07T08:29:49.000Z", "avg_line_length": 31.0120481928, "max_line_length": 121, "alphanum_fraction": 0.5788655789, "num_tokens": 2477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127417985636, "lm_q2_score": 0.7718434978390747, "lm_q1q2_score": 0.659086997479158}} {"text": "\n#define _wassert wassert_awf\n#include \n#define _USE_MATH_DEFINES \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \"eigen_extras.h\"\n\n#include \n#include \n#include \"unsupported/Eigen/src/SparseExtra/BlockSparseQR.h\"\n#include \"unsupported/Eigen/src/SparseExtra/BlockDiagonalSparseQR.h\"\n\n#include \"MeshTopology.h\"\n#include \"SubdivEvaluator.h\"\n#include \"log3d.h\"\n\nusing namespace Eigen;\n\nstruct Subdiv3D_Functor : Eigen::SparseFunctor\n{\n typedef Eigen::SparseFunctor Base;\n typedef typename Base::JacobianType JacobianType;\n\n // Input data\n Matrix3X data_points;\n\n // Topology (faces as vertex indices, fixed during shape optimization)\n MeshTopology mesh;\n\n SubdivEvaluator evaluator;\n\n // Functor constructor\n Subdiv3D_Functor(const Matrix3X& data_points, const MeshTopology& mesh) :\n Base(mesh.num_vertices*3 + data_points.cols()*2, /* number of parameters */\n data_points.cols()*3), /* number of residuals */\n data_points(data_points), \n mesh(mesh),\n evaluator(mesh)\n {\n initWorkspace();\n }\n\n // Variables for optimization live in InputType\n struct InputType {\n Matrix3X control_vertices;\n std::vector us;\n\n Index nVertices() const { return control_vertices.cols(); }\n };\n\n // And the optimization steps are computed using VectorType.\n // For subdivs (see xx), the correspondences are of type (int, Vec2) while the updates are of type (Vec2).\n // The iteractions between InputType and VectorType are restricted to:\n // The Jacobian computation takeas an InputType, and its worows must easily convert to VectorType\n // The increment_in_place operation takes InputType and StepType. \n typedef VectorX VectorType;\n\n // Workspace variables for evaluation\n Matrix3X S;\n Matrix3X dSdu;\n Matrix3X dSdv;\n SubdivEvaluator::triplets_t dSdX, dSudX, dSvdX;\n void initWorkspace()\n {\n Index nPoints = data_points.cols();\n S.resize(3, nPoints);\n dSdu.resize(3, nPoints);\n dSdv.resize(3, nPoints);\n }\n\n // Functor functions\n // 1. Evaluate the residuals at x\n int operator()(const InputType& x, ValueType& fvec) {\n evaluator.evaluateSubdivSurface(x.control_vertices, x.us, &S);\n\n // Fill residuals\n for (int i = 0; i < data_points.cols(); i++)\n fvec.segment(i * 3, 3) = S.col(i) - data_points.col(i);\n\n return 0;\n }\n\n // 2. Evaluate jacobian at x\n int df(const InputType& x, JacobianType& fjac) \n {\n // Evaluate surface at x\n evaluator.evaluateSubdivSurface(x.control_vertices, x.us, &S, &dSdX, &dSudX, &dSvdX, &dSdu, &dSdv);\n\n Index nPoints = data_points.cols();\n Index X_base = nPoints * 2;\n Index ubase = 0;\n\n // Fill Jacobian columns. \n // 1. Derivatives wrt control vertices.\n Eigen::TripletArray jvals(nPoints * 3 * 3);\n for (int i = 0; i < dSdX.size(); ++i) {\n auto const& triplet = dSdX[i];\n assert(0 <= triplet.row() && triplet.row() < nPoints);\n assert(0 <= triplet.col() && triplet.col() < x.nVertices());\n jvals.add(triplet.row() * 3 + 0, X_base + triplet.col() * 3 + 0, triplet.value());\n jvals.add(triplet.row() * 3 + 1, X_base + triplet.col() * 3 + 1, triplet.value());\n jvals.add(triplet.row() * 3 + 2, X_base + triplet.col() * 3 + 2, triplet.value());\n }\n\n // 2. Derivatives wrt correspondences\n for (int i = 0; i < nPoints; i++) {\n jvals.add(3 * i + 0, ubase + 2 * i + 0, dSdu(0, i));\n jvals.add(3 * i + 1, ubase + 2 * i + 0, dSdu(1, i));\n jvals.add(3 * i + 2, ubase + 2 * i + 0, dSdu(2, i));\n\n jvals.add(3 * i + 0, ubase + 2 * i + 1, dSdv(0, i));\n jvals.add(3 * i + 1, ubase + 2 * i + 1, dSdv(1, i));\n jvals.add(3 * i + 2, ubase + 2 * i + 1, dSdv(2, i));\n }\n\n fjac.resize(3 * nPoints, 2 * nPoints + 3 * x.nVertices());\n fjac.setFromTriplets(jvals.begin(), jvals.end());\n fjac.makeCompressed();\n\n return 0;\n }\n\n void increment_in_place(InputType* x, StepType const& p)\n {\n Index nPoints = data_points.cols();\n Index X_base = nPoints * 2;\n Index ubase = 0;\n\n // Increment control vertices\n Index nVertices = x->nVertices();\n\n assert(p.size() == nVertices * 3 + nPoints * 2);\n assert(x->us.size() == nPoints);\n\n Map(x->control_vertices.data(), nVertices * 3) += p.tail(nVertices * 3);\n \n // Increment surface correspondences\n int loopers = 0;\n int totalhops = 0;\n for (int i = 0; i < nPoints; ++i) {\n Vector2 du = p.segment<2>(ubase + 2 * i);\n int nhops = increment_u_crossing_edges(x->control_vertices, x->us[i].face, x->us[i].u, du, &x->us[i].face, &x->us[i].u);\n if (nhops < 0)\n ++loopers;\n totalhops += std::abs(nhops);\n }\n if (loopers > 0)\n std::cerr << \"[\" << totalhops / Scalar(nPoints) << \" hops, \" << loopers << \" points looped]\";\n else if (totalhops > 0)\n std::cerr << \"[\" << totalhops << \"/\" << Scalar(nPoints) << \" hops]\";\n }\n\n // \"Mesh walking\" to update correspondences, as in Fig 3, Taylor et al, CVPR 2014, \"Hand shape..\"\n int increment_u_crossing_edges(Matrix3X const& X, int face, const Vector2& u, const Vector2& du, int* new_face_out, Vector2* new_u_out)\n {\n const int MAX_HOPS = 7;\n\n Scalar u1_old = u[0];\n Scalar u2_old = u[1];\n Scalar du1 = du[0];\n Scalar du2 = du[1];\n Scalar u1_new = u1_old + du1;\n Scalar u2_new = u2_old + du2;\n\n for (int count = 0; ; ++count) {\n bool crossing = (u1_new < 0.f) || (u1_new > 1.f) || (u2_new < 0.f) || (u2_new > 1.f);\n\n if (!crossing) {\n *new_face_out = face;\n *new_u_out << u1_new, u2_new;\n return count;\n }\n\n //Find the new face\tand the coordinates of the crossing point within the old face and the new face\n int face_new;\n\n bool face_found = false;\n\n Scalar dif, aux, u1_cross, u2_cross;\n\n if (u1_new < 0.f)\n {\n dif = u1_old;\n const Scalar u2t = u2_old - du2*dif / du1;\n if ((u2t >= 0.f) && (u2t <= 1.f))\n {\n face_new = mesh.face_adj(3, face); aux = u2t; face_found = true;\n u1_cross = 0.f; u2_cross = u2t;\n }\n }\n if ((u1_new > 1.f) && (!face_found))\n {\n dif = 1.f - u1_old;\n const Scalar u2t = u2_old + du2*dif / du1;\n if ((u2t >= 0.f) && (u2t <= 1.f))\n {\n face_new = mesh.face_adj(1, face); aux = 1.f - u2t; face_found = true;\n u1_cross = 1.f; u2_cross = u2t;\n }\n }\n if ((u2_new < 0.f) && (!face_found))\n {\n dif = u2_old;\n const Scalar u1t = u1_old - du1*dif / du2;\n if ((u1t >= 0.f) && (u1t <= 1.f))\n {\n face_new = mesh.face_adj(0, face); aux = 1.f - u1t; face_found = true;\n u1_cross = u1t; u2_cross = 0.f;\n }\n }\n if ((u2_new > 1.f) && (!face_found))\n {\n dif = 1.f - u2_old;\n const Scalar u1t = u1_old + du1*dif / du2;\n if ((u1t >= 0.f) && (u1t <= 1.f))\n {\n face_new = mesh.face_adj(2, face); aux = u1t; face_found = true;\n u1_cross = u1t; u2_cross = 1.f;\n }\n }\n assert(face_found);\n\n // Find the coordinates of the crossing point as part of the new face, and update u_old (as that will be new u in next iter).\n unsigned int conf;\n for (unsigned int f = 0; f < 4; f++)\n if (mesh.face_adj(f, face_new) == face) { conf = f; }\n\n switch (conf)\n {\n case 0: u1_old = aux; u2_old = 0.f; break;\n case 1: u1_old = 1.f; u2_old = aux; break;\n case 2:\tu1_old = 1.f - aux; u2_old = 1.f; break;\n case 3:\tu1_old = 0.f; u2_old = 1.f - aux; break;\n }\n\n // Evaluate the subdivision surface at the edge (with respect to the original face)\n std::vector pts;\n pts.push_back({ face,{ u1_cross, u2_cross } });\n pts.push_back({ face_new, { u1_old, u2_old } });\n Matrix3X S(3, 2);\n Matrix3X Su(3, 2);\n Matrix3X Sv(3, 2);\n evaluator.evaluateSubdivSurface(X, pts, &S, 0, 0, 0, &Su, &Sv);\n\n Matrix J_Sa;\n J_Sa.col(0) = Su.col(0);\n J_Sa.col(1) = Sv.col(0);\n\n Matrix J_Sb;\n J_Sb.col(0) = Su.col(1);\n J_Sb.col(1) = Sv.col(1);\n\n //Compute the new u increments\n Vector2 du_remaining; \n du_remaining << u1_new - u1_cross, u2_new - u2_cross;\n Vector3 prod = J_Sa*du_remaining;\n Matrix22 AtA = J_Sb.transpose()*J_Sb;\n Vector2 AtB = J_Sb.transpose()*prod;\n\n //Vector2 du_new = AtA.ldlt().solve(AtB);\n Vector2 u_incr = AtA.inverse()*AtB;\n\n du1 = u_incr[0];\n du2 = u_incr[1];\n\n if (count == MAX_HOPS) {\n //std::cerr << \"Problem!!! Many jumps between the mesh faces for the update of one correspondence. I remove the remaining u_increment!\\n\";\n auto dmax = std::max(du1, du2);\n Scalar scale = Scalar(0.5 / dmax);\n *new_face_out = face;\n //*new_u_out << u1_old + du1 * scale, u2_old + du2 * scale;\n *new_u_out << 0.5, 0.5;\n\n assert((*new_u_out)[0] >= 0 && (*new_u_out)[1] <= 1.0 && (*new_u_out)[1] >= 0 && (*new_u_out)[1] <= 1.0);\n return -count;\n }\n\n u1_new = u1_old + du1;\n u2_new = u2_old + du2;\n face = face_new;\n }\n }\n\n Scalar estimateNorm(InputType const& x, StepType const& diag)\n {\n Index nVertices = x.nVertices();\n Map xtop{ (Scalar*)x.control_vertices.data(), nVertices * 3 };\n double total = xtop.cwiseProduct(diag.tail(nVertices*3)).stableNorm();\n total = total*total;\n for (int i = 0; i < x.us.size(); ++i) {\n Vector2 const& u = x.us[i].u;\n Vector2 di = diag.segment<2>(2 * i);\n total += u.cwiseProduct(di).squaredNorm();\n }\n return Scalar(sqrt(total));\n }\n\n // 5. Describe the QR solvers\n // For generic Jacobian, one might use this Dense QR solver.\n typedef SparseQR > GeneralQRSolver;\n\n // But for optimal performance, declare QRSolver that understands the sparsity structure.\n // Here it's block-diagonal LHS with dense RHS\n //\n // J1 = [J11 0 0 ... 0\n // 0 J12 0 ... 0\n // ...\n // 0 0 0 ... J1N];\n // And \n // J = [J1 J2];\n\n // QR for J1 subblocks is 2x1\n typedef ColPivHouseholderQR > DenseQRSolver3x2;\n\n // QR for J1 is block diagonal\n typedef BlockDiagonalSparseQR LeftSuperBlockSolver;\n\n // QR for J1'J2 is general dense (faster than general sparse by about 1.5x for n=500K)\n typedef ColPivHouseholderQR > RightSuperBlockSolver;\n\n // QR for J is concatenation of the above.\n typedef BlockSparseQR SchurlikeQRSolver;\n\n typedef SchurlikeQRSolver QRSolver;\n\n // And tell the algorithm how to set the QR parameters.\n void initQRSolver(SchurlikeQRSolver &qr) {\n // set block size\n qr.setBlockParams(data_points.cols() * 2);\n qr.getLeftSolver().setSparseBlockParams(3, 2);\n }\n};\n\nvoid logmesh(log3d& log, MeshTopology const& mesh, Matrix3X const& vertices)\n{\n Matrix3Xi tris(3, mesh.quads.cols() * 2);\n tris.block(0, 0, 1, mesh.quads.cols()) = mesh.quads.row(0);\n tris.block(1, 0, 1, mesh.quads.cols()) = mesh.quads.row(2);\n tris.block(2, 0, 1, mesh.quads.cols()) = mesh.quads.row(1);\n tris.block(0, mesh.quads.cols(), 1, mesh.quads.cols()) = mesh.quads.row(0);\n tris.block(1, mesh.quads.cols(), 1, mesh.quads.cols()) = mesh.quads.row(3);\n tris.block(2, mesh.quads.cols(), 1, mesh.quads.cols()) = mesh.quads.row(2);\n log.mesh(tris, vertices);\n}\n\nvoid logsubdivmesh(log3d& log, MeshTopology const& mesh, Matrix3X const& vertices)\n{\n log.wiremesh(mesh.quads, vertices);\n SubdivEvaluator evaluator(mesh);\n MeshTopology refined_mesh;\n Matrix3X refined_verts;\n evaluator.generate_refined_mesh(vertices, 3, &refined_mesh, &refined_verts);\n logmesh(log, refined_mesh, refined_verts);\n}\n\nint main()\n{\n std::cout << \"Go\\n\";\n log3d log(\"log3d.html\", \"fit-subdiv-to-3d-points\");\n log.ArcRotateCamera();\n log.axes();\n\n // CREATE DATA SAMPLES\n int nDataPoints = 200;\n Matrix3X data(3, nDataPoints);\n for (int i = 0; i < nDataPoints; i++) {\n if (0) {\n float t = float(i) / float(nDataPoints);\n data(0, i) = 0.1f + 1.3f*cos(80*t);\n data(1, i) = -0.2f + 0.7f*sin(80*t);\n data(2, i) = t;\n }\n else {\n Scalar t = rand() / Scalar(RAND_MAX);\n Scalar s = rand() / Scalar(RAND_MAX);\n\n auto u = Scalar(2 * EIGEN_PI * t);\n auto v = Scalar(EIGEN_PI * (s - 0.5));\n data(0, i) = 0.1f + 1.3f*cos(u)*cos(v);\n data(1, i) = -0.2f + 0.7f*sin(u)*cos(v);\n data(2, i) = sin(v);\n }\n if (1)\n log.position(log.CreateSphere(0, 0.02), data(0, i), data(1, i), data(2, i));\n else\n log.star(data.col(i));\n }\n \n\n MeshTopology mesh;\n Matrix3X control_vertices_gt;\n makeCube(&mesh, &control_vertices_gt);\n int nFaces = int(mesh.quads.cols());\n\n // INITIAL PARAMS\n typedef Subdiv3D_Functor Functor;\n \n Functor::InputType params;\n params.control_vertices = control_vertices_gt + 0.1 * MatrixXX::Random(3, control_vertices_gt.cols());\n params.us.resize(nDataPoints);\n\n // Initialize uvs.\n {\n // 1. Make a list of test points, e.g. centre point of each face\n Matrix3X test_points(3, nFaces);\n std::vector uvs{ size_t(nFaces),{ 0,{ 0.5, 0.5 } } };\n for (int i = 0; i < nFaces; ++i)\n uvs[i].face = i;\n\n SubdivEvaluator evaluator(mesh);\n evaluator.evaluateSubdivSurface(params.control_vertices, uvs, &test_points);\n\n for (int i = 0; i < nDataPoints; i++) {\n // Closest test point\n Eigen::Index test_pt_index;\n (test_points.colwise() - data.col(i)).colwise().squaredNorm().minCoeff(&test_pt_index);\n params.us[i] = uvs[test_pt_index];\n }\n }\n\n logsubdivmesh(log, mesh, params.control_vertices);\n\n Functor functor(data, mesh);\n\n // Check Jacobian\n if (0)\n for (float eps = 1e-8f; eps < 1.1e-3f; eps*=10.f) {\n NumericalDiff fd{ functor, Functor::Scalar(eps) };\n Functor::JacobianType J;\n Functor::JacobianType J_fd;\n functor.df(params, J);\n fd.df(params, J_fd);\n double diff = (J - J_fd).norm();\n if (diff > 0) {\n std::cerr << \"Jacobian diff(eps=\" << eps <<\"), = \" << diff << std::endl;\n write(J, \"c:\\\\tmp\\\\J.txt\");\n write(J_fd, \"c:\\\\tmp\\\\J_fd.txt\");\n }\n }\n\n Eigen::LevenbergMarquardt< Functor > lm(functor);\n lm.setVerbose(true);\n lm.setMaxfev(10);\n\n Eigen::LevenbergMarquardtSpace::Status info = lm.minimize(params);\n log.color(0, 1, 0);\n logsubdivmesh(log, mesh, params.control_vertices);\n\n std::cerr << \"Done: err = \"<< lm.fnorm() <<\"\\n\";\n\n // Now, on a refined mesh.\n if (1) {\n log.color(.5, .8, 0);\n\n MeshTopology mesh1;\n Matrix3X verts1;\n SubdivEvaluator evaluator(mesh);\n evaluator.generate_refined_mesh(params.control_vertices, 1, &mesh1, &verts1);\n \n {\n log3d log2(\"log2.html\");\n log2.ArcRotateCamera();\n log2.axes();\n log2.wiremesh(mesh1.quads, verts1);\n }\n\n params.control_vertices = verts1;\n\n // Initialize uvs.\n {\n // 1. Make a list of test points, e.g. centre point of each face\n int nFaces = mesh1.num_faces();\n Matrix3X test_points(3, nFaces);\n std::vector uvs{ size_t(nFaces),{ 0,{ 0.5, 0.5 } } };\n for (int i = 0; i < nFaces; ++i)\n uvs[i].face = i;\n\n SubdivEvaluator evaluator(mesh1);\n evaluator.evaluateSubdivSurface(params.control_vertices, uvs, &test_points);\n\n for (int i = 0; i < nDataPoints; i++) {\n // Closest test point\n Eigen::Index test_pt_index;\n (test_points.colwise() - data.col(i)).colwise().squaredNorm().minCoeff(&test_pt_index);\n params.us[i] = uvs[test_pt_index];\n }\n }\n\n\n Functor functor1(data, mesh1);\n\n Eigen::LevenbergMarquardt< Functor > lm(functor1);\n lm.setVerbose(true);\n lm.setMaxfev(40);\n\n Eigen::LevenbergMarquardtSpace::Status info = lm.minimize(params);\n logsubdivmesh(log, mesh1, params.control_vertices);\n\n std::cerr << \"Done: err = \" << lm.fnorm() << \"\\n\";\n }\n}\n\n// Override system assert so one can set a breakpoint in it rather than clicking \"Retry\" and \"Break\"\nvoid __cdecl _wassert(_In_z_ wchar_t const* _Message,_In_z_ wchar_t const* _File, _In_ unsigned _Line)\n{\n std::wcerr << _File << \"(\" << _Line << \"): ASSERT FAILED [\" << _Message << \"]\\n\";\n\n abort();\n}\n", "meta": {"hexsha": "a751adf0a6254460a70f41dbe65643d5d3a5e597", "size": 16540, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/fit-subdiv-to-3d-points.cpp", "max_stars_repo_name": "awf/OpenSubdiv-Model-Fitting", "max_stars_repo_head_hexsha": "4ef5ea0e712cecd19ae9f0465d8cc64d4d80e963", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 27.0, "max_stars_repo_stars_event_min_datetime": "2016-09-08T09:37:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T05:59:12.000Z", "max_issues_repo_path": "src/fit-subdiv-to-3d-points.cpp", "max_issues_repo_name": "awf/OpenSubdiv-Model-Fitting", "max_issues_repo_head_hexsha": "4ef5ea0e712cecd19ae9f0465d8cc64d4d80e963", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-01-23T16:25:31.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-24T09:53:35.000Z", "max_forks_repo_path": "src/fit-subdiv-to-3d-points.cpp", "max_forks_repo_name": "awf/OpenSubdiv-Model-Fitting", "max_forks_repo_head_hexsha": "4ef5ea0e712cecd19ae9f0465d8cc64d4d80e963", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-09-08T17:40:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-21T17:23:12.000Z", "avg_line_length": 31.9922630561, "max_line_length": 146, "alphanum_fraction": 0.6085852479, "num_tokens": 5293, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240125464114, "lm_q2_score": 0.7025300573952054, "lm_q1q2_score": 0.6590603163780507}} {"text": "/*\n * This example was gathered from Stack Overflow. Only small modification were introduced.\n *\n * Check here: https://stackoverflow.com/questions/35656237/dynamic-eigen-vectors-in-boostodeint\n *\n * Credit: Sjonnie (user nickname)\n */\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace boost::numeric::odeint;\n\ntypedef Eigen::VectorXd state_type;\n\nEigen::MatrixXd A;\n\nvoid ODE_function (const state_type &x, state_type &dxdt, const double &t)\n{\n dxdt = A * x;\n}\n\nvoid write_states(const state_type &x, const double &t)\n{\n std::cout << t << \"\\t\";\n for (int i = 0; i < x.size(); i++)\n {\n std::cout << *(x.data()+i) << \"\\t\";\n }\n std::cout << std::endl;\n}\n\nint main()\n{\n int nr_of_states = 10;\n state_type x;\n\n std::cout << \"Simulation with \" << nr_of_states << \" states\\n\";\n\n x = state_type(nr_of_states);\n A = Eigen::MatrixXd(nr_of_states, nr_of_states);\n\n srand(365);\n\n for (int i = 0; i < A.size(); i++)\n {\n *(A.data()+i) = ((double)rand()/(double)RAND_MAX);\n }\n\n for (int i = 0; i < x.size(); i++)\n {\n *(x.data()+i) = i;\n }\n\n typedef runge_kutta_dopri5 stepper;\n integrate_adaptive(stepper(), ODE_function, x, 0.0, 25.0, 0.1, write_states);\n\n std::cout <\n#include \n#include \n#include \"Adam.hpp\"\n\n#define EIGEN_MPL2_ONLY\nusing namespace Eigen;\nusing namespace std;\n\nAdam::Adam(int _N,int _d,MatrixXd _x,VectorXd _label,double _C,double _alpha,double _beta1,double _beta2,double _epsilon,double _lambda,int iter):\n N(_N),\n d(_d),\n alpha(_alpha),\n beta1(_beta1),\n beta2(_beta2),\n epsilon(_epsilon),\n lambda(_lambda),\n C(_C),\n X(_x),\n m(VectorXd::Zero(d)),\n v(VectorXd::Zero(d)),\n label(_label),\n iteration(iter),\n w(VectorXd::Zero(d))\n{}\n\ndouble Adam::Acc(vector& pred,VectorXd &l){\n int t =0;\n double loss =0;\n for(int i = 0; i< pred.size();i++){\n loss += (l(i) - pred[i]) * (l(i) - pred[i]);\n int s = pred[i] > 0.5 ? 1 : 0;\n if(s == l(i)){\n t++;\n }\n }\n return (double)t/pred.size();\n}\n\nvoid Adam::train(){\n for(int iter = 0; iter< iteration; iter++){\n for(int i = 0; i < N; i++){\n double pred = sigma(X,i);\n for(int idx = 0; idx < d; idx++){\n if(X(i,idx) != 0){\n double tbeta = 1-(1-beta1) * pow(lambda,iter);\n double grad = (pred - label(i)) * X(i,idx)+ C * w(idx);\n m[idx] = tbeta * grad + (1-tbeta) * m[idx];\n v[idx] = beta2*pow(grad,2) + (1-beta2) * v[idx];\n double hat_m = m[idx]/(1-pow((1-beta1),iter+1));\n double hat_v = v[idx]/(1-pow((1-beta2),iter+1));\n w(idx) -= alpha*hat_m/(sqrt(hat_v) + epsilon);\n }\n }\n }\n vector ret;\n predict(X,label,ret);\n iterscores.push_back(Acc(ret,label));\n }\n}\n\ndouble Adam::sigma(const MatrixXd& _x, int i){\n return sigmoid(_x.row(i).dot(w));\n}\n\ndouble Adam::sigmoid(double z){\n return 1.0 / (1.0 + exp(-z));\n}\n\nvoid Adam::predict(MatrixXd& _x,VectorXd& _l,vector& ret){\n for(int i = 0; i < _x.rows(); i++){\n ret.push_back(sigma(_x,i));\n }\n}\n\n", "meta": {"hexsha": "20f253feb4c92757115340b85937ad909fb48127", "size": 1840, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Adam.cpp", "max_stars_repo_name": "saiias/Adadelta", "max_stars_repo_head_hexsha": "2a8d94ec32b887d078409b5252170d4e9ffeb402", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2015-08-27T10:49:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-01T07:42:49.000Z", "max_issues_repo_path": "Adam.cpp", "max_issues_repo_name": "huangpingchun/Adadelta", "max_issues_repo_head_hexsha": "2a8d94ec32b887d078409b5252170d4e9ffeb402", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-02-20T12:33:39.000Z", "max_issues_repo_issues_event_max_datetime": "2017-06-23T08:12:09.000Z", "max_forks_repo_path": "Adam.cpp", "max_forks_repo_name": "huangpingchun/Adadelta", "max_forks_repo_head_hexsha": "2a8d94ec32b887d078409b5252170d4e9ffeb402", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-08-27T10:49:48.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-08T08:36:07.000Z", "avg_line_length": 24.2105263158, "max_line_length": 146, "alphanum_fraction": 0.564673913, "num_tokens": 596, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.6590156407356154}} {"text": "#include \n#include \n\nint main()\n{\n Eigen::MatrixXd xn;\n Eigen::MatrixXd mu;\n Eigen::VectorXi gk;\n Eigen::VectorXi numk;\n Eigen::MatrixXd::Index minIndex;\n int ni;\n int nn;\n int kk;\n int i;\n int j;\n int l;\n int sum_gk;\n int bef_sum_gk;\n\n // after :: from file input\n ni = 10;\n kk = 3;\n\n nn = ni*kk;\n std::cout << \"nn \" << nn << std::endl;\n\n xn = Eigen::MatrixXd::Random(2, nn);\n gk = Eigen::VectorXi(nn);\n numk = Eigen::VectorXi::Zero(kk);\n std::cout << \"xn =\" << std::endl << xn << std::endl;\n\n xn.block(0, nn/kk, 1, nn/kk).array() += 2.0;\n xn.block(0, 2*nn/kk, 1, nn/kk).array() += 4.0;\n\n mu = xn.block(0, 0, 2, kk);\n\n std::cout << \"mu =\" << std::endl << mu << std::endl;\n\n bef_sum_gk = 0;\n for(i = 0; i < 100; i++){\n std::cout << \"loop =\" << i << std::endl;\n for(j = 0; j < nn; j++){\n\n// Is which better?\n (mu.colwise() - xn.col(j)).colwise().squaredNorm().minCoeff(&minIndex);\n// (xn.col(j).replicate(1, 3) - mu).colwise().squaredNorm().minCoeff(&minIndex);\n\n gk(j) = minIndex;\n }\n numk.array() = 0;\n for(l = 0; l < kk; l++){\n mu.col(l).array() = 0.0;\n for(j = 0; j < nn; j++){\n\tif(gk(j) == l){\n\t numk(l) += 1;\n\t mu.col(l) += xn.col(j);\n\t}\n }\n// Is which better?\n mu.col(l).array() /= static_cast (numk(l));\n// mu.col(l) /= static_cast (numk(l));\n }\n sum_gk = gk.sum();\n if(bef_sum_gk == sum_gk) break;\n bef_sum_gk = sum_gk;\n }\n\n std::cout << \"numk =\" << std::endl << numk << std::endl;\n std::cout << \"gk =\" << std::endl << gk << std::endl;\n std::cout << \"mu =\" << std::endl << mu << std::endl;\n}\n", "meta": {"hexsha": "e222b4c3ceef982bda556a1b1e6970b19fc54223", "size": 1641, "ext": "cc", "lang": "C++", "max_stars_repo_path": "main.cc", "max_stars_repo_name": "ya-mat/k_means_cc", "max_stars_repo_head_hexsha": "651d147ae4e66f7e66bbeb65fc954effcb153425", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cc", "max_issues_repo_name": "ya-mat/k_means_cc", "max_issues_repo_head_hexsha": "651d147ae4e66f7e66bbeb65fc954effcb153425", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cc", "max_forks_repo_name": "ya-mat/k_means_cc", "max_forks_repo_head_hexsha": "651d147ae4e66f7e66bbeb65fc954effcb153425", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7916666667, "max_line_length": 85, "alphanum_fraction": 0.5149299208, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.897695292107347, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6590156326984775}} {"text": "\n#include \n#include \n\n#include \n#include \n\nnamespace sphericalsfm {\n void make_spherical_essential_matrix( const Eigen::Matrix3d &R, bool inward, Eigen::Matrix3d &E )\n {\n Eigen::Vector3d t( R(0,2), R(1,2), R(2,2)-1 );\n if ( inward ) t = -t;\n E = skew3(t)*R;\n }\n\n void decompose_spherical_essential_matrix( const Eigen::Matrix3d &E, bool inward, Eigen::Vector3d &r, Eigen::Vector3d &t )\n {\n Eigen::JacobiSVD svdE(E,Eigen::ComputeFullU|Eigen::ComputeFullV);\n \n Eigen::Matrix3d U = svdE.matrixU();\n Eigen::Matrix3d V = svdE.matrixV();\n \n // from theia sfm\n if (U.determinant() < 0) {\n U.col(2) *= -1.0;\n }\n \n if (V.determinant() < 0) {\n V.col(2) *= -1.0;\n }\n \n Eigen::Matrix3d D;\n D <<\n 0,1,0,\n -1,0,0,\n 0,0,1;\n \n Eigen::Matrix3d DT;\n DT <<\n 0,-1,0,\n 1,0,0,\n 0,0,1;\n \n Eigen::Matrix3d VT = V.transpose().eval();\n \n Eigen::Vector3d tu = U.col(2);\n \n Eigen::Matrix3d R1 = U*D*VT;\n Eigen::Matrix3d R2 = U*DT*VT;\n \n Eigen::Vector3d t1( R1(0,2), R1(1,2), R1(2,2)-1 );\n Eigen::Vector3d t2( R2(0,2), R2(1,2), R2(2,2)-1 );\n \n if ( inward ) { t1 = -t1; t2 = -t2; }\n \n Eigen::Vector3d myt1 = t1/t1.norm();\n Eigen::Vector3d myt2 = t2/t2.norm();\n \n Eigen::Vector3d r1 = so3ln(R1);\n Eigen::Vector3d r2 = so3ln(R2);\n \n double score1 = fabs(myt1.dot(tu));\n double score2 = fabs(myt2.dot(tu));\n \n if ( score1 > score2 ) { r = r1; t = t1; }\n else { r = r2; t = t2; }\n }\n\n static Eigen::Vector3d triangulateMidpoint( const Eigen::Matrix4d &rel_pose, const Eigen::Vector3d &u, const Eigen::Vector3d &v )\n {\n Eigen::Vector3d cu( 0, 0, 0 );\n Eigen::Vector3d cv( -rel_pose.block<3,3>(0,0).transpose() * rel_pose.block<3,1>(0,3) );\n \n Eigen::Matrix3d A;\n A <<\n u(0), -v(0), cu(0) - cv(0),\n u(1), -v(1), cu(1) - cv(1),\n u(2), -v(2), cu(2) - cv(2);\n \n const Eigen::Vector3d soln = A.jacobiSvd( Eigen::ComputeFullV ).matrixV().col(2);\n const double du = soln(0)/soln(2);\n const double dv = soln(1)/soln(2);\n \n const Eigen::Vector3d Xu = cu + u*du;\n const Eigen::Vector3d Xv = cv + v*dv;\n \n return (Xu+Xv)*0.5;\n }\n\n void decompose_spherical_essential_matrix( const Eigen::Matrix3d &E, bool inward,\n RayPairList::iterator begin, RayPairList::iterator end, const std::vector &inliers,\n Eigen::Vector3d &r, Eigen::Vector3d &t )\n {\n Eigen::JacobiSVD svdE(E,Eigen::ComputeFullU|Eigen::ComputeFullV);\n \n Eigen::Matrix3d U = svdE.matrixU();\n Eigen::Matrix3d V = svdE.matrixV();\n \n // from theia sfm\n if (U.determinant() < 0) {\n U.col(2) *= -1.0;\n }\n \n if (V.determinant() < 0) {\n V.col(2) *= -1.0;\n }\n\n Eigen::Matrix3d D;\n D <<\n 0,1,0,\n -1,0,0,\n 0,0,1;\n\n Eigen::Matrix3d DT;\n DT <<\n 0,-1,0,\n 1,0,0,\n 0,0,1;\n\n Eigen::Matrix3d VT = V.transpose().eval();\n \n Eigen::Matrix3d R1 = U*D*VT;\n Eigen::Matrix3d R2 = U*DT*VT;\n \n Eigen::Vector3d t1( R1(0,2), R1(1,2), (inward) ? R1(2,2)+1 : R1(2,2)-1 );\n Eigen::Vector3d t2( R2(0,2), R2(1,2), (inward) ? R2(2,2)+1 : R2(2,2)-1 );\n \n Eigen::Vector3d r1 = so3ln(R1);\n Eigen::Vector3d r2 = so3ln(R2);\n\n double r1test = r1.norm();\n double r2test = r2.norm();\n \n if ( r2test > M_PI/2 && r1test < M_PI/2 ) { r = r1; t = t1; return; }\n if ( r1test > M_PI/2 && r2test < M_PI/2 ) { r = r2; t = t2; return; }\n\n Eigen::Matrix4d P1( Eigen::Matrix4d::Identity() );\n Eigen::Matrix4d P2( Eigen::Matrix4d::Identity() );\n \n P1.block(0,0,3,3) = R1;\n P1.block(0,3,3,1) = t1;\n\n P2.block(0,0,3,3) = R2;\n P2.block(0,3,3,1) = t2;\n \n int ninfront1 = 0;\n int ninfront2 = 0;\n \n int i = 0;\n for ( RayPairList::iterator it = begin; it != end; it++,i++ )\n {\n if ( !inliers[i] ) continue;\n \n Eigen::Vector3d u = it->first.head(3);\n Eigen::Vector3d v = it->second.head(3);\n \n Eigen::Vector3d X1 = triangulateMidpoint(P1, u, v);\n Eigen::Vector3d X2 = triangulateMidpoint(P2, u, v);\n\n if ( X1(2) > 0 ) ninfront1++;\n if ( X2(2) > 0 ) ninfront2++;\n }\n \n if ( ninfront1 > ninfront2 )\n {\n r = so3ln(R1);\n t = t1;\n }\n else\n {\n r = so3ln(R2);\n t = t2;\n }\n }\n}\n", "meta": {"hexsha": "3cf22f136bf311853994119df149b6fd7e1aa971", "size": 5076, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/spherical_utils.cpp", "max_stars_repo_name": "jonathanventura/spherical-sfm", "max_stars_repo_head_hexsha": "0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2020-03-26T15:07:14.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-04T06:27:32.000Z", "max_issues_repo_path": "src/spherical_utils.cpp", "max_issues_repo_name": "jonathanventura/spherical-sfm", "max_issues_repo_head_hexsha": "0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-07-09T06:32:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-09T07:26:47.000Z", "max_forks_repo_path": "src/spherical_utils.cpp", "max_forks_repo_name": "jonathanventura/spherical-sfm", "max_forks_repo_head_hexsha": "0f0dafdd66641cebcb57cdb8a87b9ce466ab36eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T20:30:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T20:30:46.000Z", "avg_line_length": 28.8409090909, "max_line_length": 133, "alphanum_fraction": 0.4686761229, "num_tokens": 1751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9252299591537478, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.6589785547313854}} {"text": "/*\n * polynomial_splines.hpp\n *\n * Created on: Mar 7, 2017\n * Author: Dario Bellicoso\n */\n\n#pragma once\n\n// stl\n#include \n#include \n\n// eigen\n#include \n#include \n\n// boost\n#include \n\nnamespace curves {\n\nstruct SplineOptions {\n\n SplineOptions()\n : tf_(0.0),\n pos0_(0.0), posT_(0.0),\n vel0_(0.0), velT_(0.0),\n acc0_(0.0), accT_(0.0)\n {\n\n }\n\n constexpr SplineOptions(double tf, double pos0, double posT, double vel0,\n double velT, double acc0, double accT)\n : tf_(tf),\n pos0_(pos0), posT_(posT),\n vel0_(vel0), velT_(velT),\n acc0_(acc0), accT_(accT)\n {\n\n }\n\n //! The total duration of the spline in seconds.\n double tf_;\n\n //! The scalar position at time 0.\n double pos0_;\n\n //! The scalar position at time tf.\n double posT_;\n\n //! The scalar velocity at time 0.\n double vel0_;\n\n //! The scalar velocity at time tf.\n double velT_;\n\n //! The scalar acceleration at time 0.\n double acc0_;\n\n //! The scalar acceleration at time tf.\n double accT_;\n};\n\nnamespace spline_traits {\n\n// Main struct template.\ntemplate\nstruct spline_rep {\n\n static constexpr unsigned int splineOrder = SplineOrder_;\n static constexpr unsigned int numCoefficients = SplineOrder_+1;\n\n using TimeVectorType = std::array;\n using SplineCoefficients = std::array;\n\n static inline TimeVectorType tau(Core_ tk) noexcept;\n static inline TimeVectorType dtau(Core_ tk) noexcept;\n static inline TimeVectorType ddtau(Core_ tk) noexcept;\n\n static bool compute(const SplineOptions& opts, SplineCoefficients& coefficients);\n};\n\n// Specialization for third order splines.\ntemplate<>\nstruct spline_rep {\n\n static constexpr unsigned int splineOrder = 3;\n static constexpr unsigned int numCoefficients = splineOrder+1;\n\n using TimeVectorType = std::array;\n using SplineCoefficients = std::array;\n\n static inline TimeVectorType tau(double tk) noexcept {\n return { boost::math::pow<3>(tk), boost::math::pow<2>(tk), tk, 1.0 };\n }\n\n static inline TimeVectorType dtau(double tk) noexcept {\n return { 3.0*boost::math::pow<2>(tk), 2.0*tk, 1.0, 0.0 };\n }\n\n static inline TimeVectorType ddtau(double tk) noexcept {\n return { 6.0*tk, 2.0, 0.0, 0.0 };\n }\n\n static constexpr TimeVectorType tauZero{{ 0.0, 0.0, 0.0, 1.0 }};\n static constexpr TimeVectorType dtauZero{{ 0.0, 0.0, 1.0, 0.0 }};\n static constexpr TimeVectorType ddtauZero{{ 0.0, 2.0, 0.0, 0.0 }};\n\n static bool compute(const SplineOptions& opts, SplineCoefficients& coefficients) {\n\n Eigen::Matrix b;\n b << opts.pos0_, opts.vel0_, opts.posT_, opts.velT_;\n\n Eigen::Matrix A;\n A << Eigen::Map>(tauZero.data()),\n Eigen::Map>(dtauZero.data()),\n Eigen::Map>((tau(opts.tf_)).data()),\n Eigen::Map>((dtau(opts.tf_)).data());\n\n Eigen::Map(coefficients.data(), numCoefficients, 1) = A.colPivHouseholderQr().solve(b);\n\n return true;\n }\n};\n\n\n// Specialization for fifth order splines.\ntemplate<>\nstruct spline_rep {\n\n static constexpr unsigned int splineOrder = 5;\n static constexpr unsigned int numCoefficients = splineOrder+1;\n\n using TimeVectorType = std::array;\n using SplineCoefficients = std::array;\n\n static inline TimeVectorType tau(double tk) noexcept {\n return { boost::math::pow<5>(tk), boost::math::pow<4>(tk), boost::math::pow<3>(tk),\n boost::math::pow<2>(tk), tk, 1.0};\n }\n\n static inline TimeVectorType dtau(double tk) noexcept {\n return { 5.0*boost::math::pow<4>(tk), 4.0*boost::math::pow<3>(tk), 3.0*boost::math::pow<2>(tk),\n 2.0*tk, 1.0, 0.0};\n }\n\n static inline TimeVectorType ddtau(double tk) noexcept {\n return { 20.0*boost::math::pow<3>(tk), 12.0*boost::math::pow<2>(tk), 6.0*tk,\n 2.0, 0.0, 0.0};\n }\n\n static constexpr TimeVectorType tauZero{{ 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }};\n static constexpr TimeVectorType dtauZero{{ 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }};\n static constexpr TimeVectorType ddtauZero{{ 0.0, 0.0, 0.0, 2.0, 0.0, 0.0 }};\n\n static bool compute(const SplineOptions& opts, SplineCoefficients& coefficients) {\n Eigen::Matrix b;\n b << opts.pos0_, opts.vel0_, opts.acc0_, opts.posT_, opts.velT_, opts.accT_;\n\n Eigen::Matrix A;\n A << Eigen::Map>(tauZero.data()),\n Eigen::Map>(dtauZero.data()),\n Eigen::Map>(ddtauZero.data()),\n Eigen::Map>((tau(opts.tf_)).data()),\n Eigen::Map>((dtau(opts.tf_)).data()),\n Eigen::Map>((ddtau(opts.tf_)).data());\n\n Eigen::Map(coefficients.data(), numCoefficients, 1) = A.colPivHouseholderQr().solve(b);\n\n return true;\n }\n\n};\n\n}\n\n}\n", "meta": {"hexsha": "8b2941466475822bfbf7300e1da4afb102d5148e", "size": 5481, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "curves/include/curves/polynomial_splines_traits.hpp", "max_stars_repo_name": "frontw/curves", "max_stars_repo_head_hexsha": "b442b753922ec270c46096d169a8042e0ef9a5f3", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2019-08-21T08:58:09.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-02T16:17:52.000Z", "max_issues_repo_path": "curves/include/curves/polynomial_splines_traits.hpp", "max_issues_repo_name": "copark86/curves", "max_issues_repo_head_hexsha": "b442b753922ec270c46096d169a8042e0ef9a5f3", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "curves/include/curves/polynomial_splines_traits.hpp", "max_forks_repo_name": "copark86/curves", "max_forks_repo_head_hexsha": "b442b753922ec270c46096d169a8042e0ef9a5f3", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.45, "max_line_length": 108, "alphanum_fraction": 0.669585842, "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6589729702585957}} {"text": "#pragma once\n#include \n#include \n\nnamespace ppl {\nnamespace math {\nnamespace details {\n\ntemplate \nusing vec_cref_t = std::vector<\n std::reference_wrapper> >;\n\n} // namespace details\n\n/**\n * Computes the effective sample size (ESS) for a given vector of samples (matrices).\n * Every element of the vector is a matrix of samples for each chain.\n * Every matrix contains the samples as rows, i.e.\n * every row is a sample of an p-dimensional vector, where p\n * is the number of columns of the matrix (number of parameters).\n *\n * The algorithm assumes that every sample matrix has the same dimensions.\n *\n * @tparam T underlying Eigen expression type\n * @param samples vector of samples\n *\n * @return a vector of ESS for each component\n * If number of samples is 1 or less, or there are 0 components,\n * or number of chains is 0, return an empty vector.\n * In either case, the dimension of the return vector is same\n * as the number of components.\n */\ntemplate \ninline auto ess(const details::vec_cref_t& samples)\n{\n using value_t = T;\n using vec_t = Eigen::Matrix;\n using mat_t = Eigen::Matrix;\n\n vec_t tau_hat;\n\n size_t M = samples.size(); // number of chains\n\n if (M == 0) return tau_hat;\n\n size_t dim = samples[0].get().cols(); // sample dimension\n size_t N = samples[0].get().rows(); // number of samples\n\n if (N <= 1 || dim == 0) return tau_hat;\n\n tau_hat = vec_t::Zero(dim);\n\n auto var = [N](const auto& mat) {\n return (mat.rowwise() - \n mat.colwise().mean()).colwise()\n .squaredNorm() / (N-1);\n };\n\n // use N-1 scaling to compute variance\n // each col is the sample variance per chain\n mat_t sample_vars(dim, M);\n for (size_t i = 0; i < M; ++i) {\n sample_vars.col(i) = var(samples[i].get());\n }\n\n // column vector of average of sample variances\n vec_t W = sample_vars.rowwise().mean();\n\n // compute variance estimator\n vec_t var_est = static_cast(N-1) / N * W;\n\n // if there is more than 1 chain, then update by N * B\n // where B is the between-chain variance\n if (M > 1) {\n mat_t sample_mean(dim, M);\n for (size_t i = 0; i < M; ++i) {\n sample_mean.col(i) = samples[i].get().colwise().mean();\n }\n var_est += var(sample_mean.transpose());\n }\n\n // compute autocorrelation vector for each component\n // every column vector (every component) is average AC over chains\n mat_t acov_mean(N, dim);\n acov_mean.setZero();\n\n for (size_t m = 1; m <= M; ++m) {\n mat_t next_acov = autocorrelation(samples[m-1].get());\n for (int j = 0; j < next_acov.cols(); ++j) {\n next_acov.col(j) *= sample_vars(j,m-1);\n }\n value_t m_inv = 1./m;\n acov_mean = m_inv * next_acov + (m-1) * m_inv * acov_mean;\n }\n \n // compute rho-hat at lag t for dimension d\n auto rho_hat = [&](size_t t, size_t d) {\n return 1. - (W(d) - acov_mean(t,d))/var_est(d);\n };\n\n // compute tau-hat directly to save memory\n for (size_t d = 0; d < dim; ++d) {\n \n // first two should not be corrected for positive and monotoneness\n value_t curr_rho_hat_even = rho_hat(0,d);\n value_t curr_p_hat = curr_rho_hat_even + rho_hat(1,d); // current P_hat(t)\n value_t curr_min = curr_p_hat; // current min of P_hat(t)\n tau_hat(d) = curr_min; // update with P_hat(0)\n\n // only estimate up to 3 samples before the end\n // and Geyer's positive condition holds\n size_t t = 2;\n for (; t < (N-3) && curr_p_hat > 0; t += 2) {\n curr_rho_hat_even = rho_hat(t,d);\n curr_p_hat = curr_rho_hat_even + rho_hat(t+1,d);\n\n // if positive condition holds, take the min \n // of current P_hat(t) with the min of previous P_hat's\n // to create a monotone sequence and accumulate to tau_hat\n if (curr_p_hat >= 0) {\n curr_min = std::min(curr_min, curr_p_hat);\n tau_hat(d) += curr_min;\n }\n }\n\n // correct to improve estimate (see STAN's implementation)\n value_t correction = (curr_rho_hat_even > 0) ? \n curr_rho_hat_even : rho_hat(t,d);\n\n tau_hat(d) *= 2.; // 2 * sum of adjusted P_hat(t)\n tau_hat(d) -= 1.; // -1 + 2 * sum of adjusted P_hat(t) \n tau_hat(d) += correction; \n }\n\n vec_t n_eff = N*M*(1./tau_hat.array()).min(std::log10(N)).matrix();\n\n return n_eff;\n}\n\n/**\n * Computes the effective sample size (ESS) for a given sample matrix.\n * This is an overload for when there is only chain and can supply\n * a single matrix instead.\n * See above overload for more details.\n *\n * @tparam T underlying Eigen expression type\n * @param samples sample matrix (1 chain)\n *\n * @return a vector of ESS for each component\n */\ntemplate \ninline auto ess(const Eigen::Matrix& samples)\n{\n details::vec_cref_t v;\n v.emplace_back(samples);\n return ess(v);\n}\n \n\n} // namespace math\n} // namespace ppl\n", "meta": {"hexsha": "e37298482ba30b4c43d749f7df81ce5e7068ef0d", "size": 5416, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/autoppl/math/ess.hpp", "max_stars_repo_name": "JamesYang007/autoppl", "max_stars_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37.0, "max_stars_repo_stars_event_min_datetime": "2020-04-12T19:45:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T19:05:38.000Z", "max_issues_repo_path": "include/autoppl/math/ess.hpp", "max_issues_repo_name": "JamesYang007/autoppl", "max_issues_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 11.0, "max_issues_repo_issues_event_min_datetime": "2020-04-26T14:55:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-13T19:21:50.000Z", "max_forks_repo_path": "include/autoppl/math/ess.hpp", "max_forks_repo_name": "JamesYang007/autoppl", "max_forks_repo_head_hexsha": "e78f8d229d2e399f86f338e473da5ddc7dbed053", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2020-04-15T04:45:22.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-25T17:28:42.000Z", "avg_line_length": 33.4320987654, "max_line_length": 90, "alphanum_fraction": 0.5961964549, "num_tokens": 1426, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942232112239, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6589729586923893}} {"text": "// Software License for MTL\n// \n// Copyright (c) 2007 The Trustees of Indiana University.\n// 2008 Dresden University of Technology and the Trustees of Indiana University.\n// 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.\n// All rights reserved.\n// Authors: Peter Gottschling and Andrew Lumsdaine\n// \n// This file is part of the Matrix Template Library\n// \n// See also license.mtl.txt in the distribution.\n\n#ifndef META_MATH_IS_PRIME_INCLUDE\n#define META_MATH_IS_PRIME_INCLUDE\n\n#include \n#include \n// #include \n#ifdef __GXX_CONCEPTS__\n# include \n#endif\n\n\nnamespace meta_math {\n\nnamespace mpl = boost::mpl;\n\nnamespace impl {\n\n // Checks if 'x' is divisible by some odd number >= max_odd, checking decreasingly\n template \n struct is_prime_to_max_odd\n {\n\tstatic bool const value = x % max_odd != 0\n && is_prime_to_max_odd::value;\n };\n\n // Once we reach 1, it's prime\n template struct is_prime_to_max_odd : mpl::true_ {};\n\n\n // Returns the largest number that x is tried to divided by.\n // This is a odd number slightly larger than the approximated square root.\n template \n struct max_prime_compare\n {\n\tstatic long int const tmp = sqrt::value,\n value = tmp % 2 == 0 ? tmp + 1 : tmp + 2;\n };\n\n\n // Checks if there is an odd number between 3 and sqrt(x)+1 that divides x\n // if there is no divisor found then x is prime (otherwise not)\n // must be disabled when x is even\n template \n struct check_odd\n {\n\tstatic bool const value = is_prime_to_max_odd::value>::value;\n };\n\n // Intended for even numbers (> 2) which are always prime\n template \n struct check_odd\n {\n\tstatic bool const value = false;\n };\n\n}\n\ntemplate \nstruct is_prime\n{\n static bool const value = impl::check_odd::value;\n};\n\ntemplate <> struct is_prime<0> : mpl::false_ {};\ntemplate <> struct is_prime<1> : mpl::false_ {};\ntemplate <> struct is_prime<2> : mpl::true_ {};\ntemplate <> struct is_prime<3> : mpl::true_ {};\ntemplate <> struct is_prime<5> : mpl::true_ {};\n\n\n#ifdef __GXX_CONCEPTS__\n concept Prime {}\n\n template \n where std::True::value> \n concept_map Prime {}\n#endif\n\n\n\n} // namespace meta_math\n\n#endif // META_MATH_IS_PRIME_INCLUDE\n", "meta": {"hexsha": "e6aa21de3e5a55bf7fe37ab9164f1f774c934617", "size": 2606, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/meta_math/is_prime.hpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "lib/mtl4/boost/numeric/meta_math/is_prime.hpp", "max_issues_repo_name": "spraetor/amdis2", "max_issues_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "lib/mtl4/boost/numeric/meta_math/is_prime.hpp", "max_forks_repo_name": "spraetor/amdis2", "max_forks_repo_head_hexsha": "53c45c81a65752a8fafbb54f9ae6724a86639dcd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 27.1458333333, "max_line_length": 94, "alphanum_fraction": 0.6623177283, "num_tokens": 671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178919837706, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6586301077019208}} {"text": "#pragma once\n#include \"PolynomialRootSolver.h\"\n#include \n#include \n#include \n\n\nPolynomialRootSolver::PolynomialRootSolver()\n{\n\n}\n\nPolynomialRootSolver::~PolynomialRootSolver()\n{\n\n}\n\nEigen::MatrixXd computeCompanionMatrix(const cv::Mat rowOfCoefficientsInAscendingDegreeOrder)\n{\n int numberOfColumns = rowOfCoefficientsInAscendingDegreeOrder.size().width -1 ;\n Eigen::MatrixXd eigenCoefficients(1,numberOfColumns+1);\n Eigen::MatrixXd companionMatrix(numberOfColumns,numberOfColumns);\n companionMatrix.setZero();\n Eigen::MatrixXd identitySubmatrix = Eigen::MatrixXd::Identity(numberOfColumns-1,numberOfColumns-1);\n cv::cv2eigen(rowOfCoefficientsInAscendingDegreeOrder, eigenCoefficients);\n eigenCoefficients /= eigenCoefficients(numberOfColumns);\n\n companionMatrix.block(0,1,numberOfColumns-1,numberOfColumns-1) = identitySubmatrix;\n companionMatrix.block(numberOfColumns-1,0,1,numberOfColumns) -= eigenCoefficients.block(0,0,1,numberOfColumns);\n return companionMatrix;\n}\n\ncv::Mat PolynomialRootSolver::computeRoots(const cv::Mat& rowOfCoefficientsInAscendingDegreeOrder)\n{\n Eigen::MatrixXd eigenCompanionMatrix = computeCompanionMatrix(rowOfCoefficientsInAscendingDegreeOrder);\n Eigen::EigenSolver eigenSolver(eigenCompanionMatrix);\n Eigen::MatrixXd realEigenvalues = eigenSolver.eigenvalues().real();\n realEigenvalues.transposeInPlace();\n cv::Mat roots;\n cv::eigen2cv(realEigenvalues, roots);\n return roots;\n}\n", "meta": {"hexsha": "23004f8eccfc5f1351b383e2ff2ec19824737397", "size": 1541, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sw/polynomialRootSolver/PolynomialRootSolver.cpp", "max_stars_repo_name": "galpHub/PolynomialRootSolverForOpenCV", "max_stars_repo_head_hexsha": "28683fe03d77efc77f277e9a93eeb474ba582298", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sw/polynomialRootSolver/PolynomialRootSolver.cpp", "max_issues_repo_name": "galpHub/PolynomialRootSolverForOpenCV", "max_issues_repo_head_hexsha": "28683fe03d77efc77f277e9a93eeb474ba582298", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sw/polynomialRootSolver/PolynomialRootSolver.cpp", "max_forks_repo_name": "galpHub/PolynomialRootSolverForOpenCV", "max_forks_repo_head_hexsha": "28683fe03d77efc77f277e9a93eeb474ba582298", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.8372093023, "max_line_length": 115, "alphanum_fraction": 0.7942894225, "num_tokens": 364, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467738423874, "lm_q2_score": 0.7490872075132153, "lm_q1q2_score": 0.6585576018118462}} {"text": "// (C) Copyright Andrew Sutton 2007\n//\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0 (See accompanying file\n// LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\n\n//[mean_geodesic_example\n#include \n#include \n\n#include \n#include \n#include \n#include \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 Graph;\ntypedef graph_traits::vertex_descriptor Vertex;\ntypedef graph_traits::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::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 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 WeightMap;\n\n// Declare a container and its corresponding property map that\n// will contain the resulting mean geodesic distances of each\n// vertex in the graph.\ntypedef exterior_vertex_property GeodesicProperty;\ntypedef GeodesicProperty::container_type GeodesicContainer;\ntypedef GeodesicProperty::map_type GeodesicMap;\n\nint\nmain(int argc, char *argv[])\n{\n // Create the graph and a property map that provides access\n // to the actor names.\n Graph g;\n NameMap nm(get(&Actor::name, g));\n\n // Read the graph from standad input.\n read_graph(g, nm, cin);\n\n // Compute the distances between all pairs of vertices using\n // the Floyd-Warshall algorithm. Note that the weight map is\n // created so that every edge has a weight of 1.\n DistanceMatrix distances(num_vertices(g));\n DistanceMatrixMap dm(distances, g);\n WeightMap wm(1);\n floyd_warshall_all_pairs_shortest_paths(g, dm, weight_map(wm));\n\n // Compute the mean geodesic distances for each vertex in\n // the graph and get the average mean geodesic distace (the\n // so-called small-world distance) as a result.\n GeodesicContainer geodesics(num_vertices(g));\n GeodesicMap gm(geodesics, g);\n float sw = all_mean_geodesics(g, dm, gm);\n\n // Print the mean geodesic distance of each vertex and finally,\n // the graph itself.\n graph_traits::vertex_iterator i, end;\n for(tie(i, end) = vertices(g); i != end; ++i) {\n cout << setw(12) << setiosflags(ios::left)\n << g[*i].name << get(gm, *i) << endl;\n }\n cout << \"small world distance: \" << sw << endl;\n\n\n return 0;\n}\n//]\n", "meta": {"hexsha": "f6b6892c06147751a2025ef2e8ccc78eaebb0126", "size": 3058, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/graph/example/mean_geodesic.cpp", "max_stars_repo_name": "oudream/boost_1_42_0", "max_stars_repo_head_hexsha": "e92227bf374e478030e89876ec353de6eecaeac0", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-06-25T23:20:19.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-14T19:38:34.000Z", "max_issues_repo_path": "libs/graph/example/mean_geodesic.cpp", "max_issues_repo_name": "boost-cmake/vintage", "max_issues_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "libs/graph/example/mean_geodesic.cpp", "max_forks_repo_name": "boost-cmake/vintage", "max_forks_repo_head_hexsha": "dcfb7da3177134eddaee6789d6f582259cb0d6ee", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-07-26T08:07:09.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-25T23:20:21.000Z", "avg_line_length": 33.9777777778, "max_line_length": 67, "alphanum_fraction": 0.7361020275, "num_tokens": 725, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473846343394, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6585481096051392}} {"text": "// This file is part of PoseEstimation.\n// Copyright (c) 2021, Eijiro Shibusawa \n// All rights reserved.\n\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n\n// 1. Redistributions of source code must retain the above copyright notice, this\n// list of conditions and the following disclaimer.\n// 2. Redistributions in binary form must reproduce the above copyright notice,\n// this list of conditions and the following disclaimer in the documentation\n// and/or other materials provided with the distribution.\n\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#ifndef THREE_POINT_HPP_\n#define THREE_POINT_HPP_\n\n#include \n\nclass ThreePointTest;\n\nnamespace ThreePoint\n{\ntemplate \nclass ThreePoint\n{\n\tfriend ::ThreePointTest;\n\nprivate:\n\ttypedef Eigen::Matrix Matrix_Dx1;\n\ttypedef Eigen::Matrix Matrix_3x1;\n\ttypedef Eigen::Matrix Matrix_3x3;\n\ttypedef Eigen::Matrix Matrix_3x3R;\n\ttypedef Eigen::Matrix Matrix_3xD;\n\ttypedef Eigen::Matrix Matrix_4x4;\n\ttypedef Eigen::Matrix Matrix_4x1;\n\npublic:\n\t// q = [x, y, z, w] = w + x*i + y*j + z*k\n\tstatic inline void getRotation(const FloatType *q, FloatType *R)\n\t{\n\t\tconst FloatType q0_2 = 2 * q[0], q1_2 = 2 * q[1], q2_2 = 2 * q[2];\n\t\tconst FloatType q03_2 = q0_2 * q[3], q13_2 = q1_2 * q[3], q23_2 = q2_2 * q[3];\n\t\tconst FloatType q00_2 = q0_2 * q[0], q01_2 = q0_2 * q[1], q02_2 = q0_2 * q[2];\n\t\tconst FloatType q11_2 = q1_2 * q[1], q12_2 = q1_2 * q[2], q22_2 = q2_2 * q[2];\n\t\tR[0] = 1 - (q11_2 + q22_2);\n\t\tR[1] = q01_2 - q23_2;\n\t\tR[2] = q02_2 + q13_2;\n\t\tR[3] = q01_2 + q23_2;\n\t\tR[4] = 1 - (q00_2 + q22_2);\n\t\tR[5] = q12_2 - q03_2;\n\t\tR[6] = q02_2 - q13_2;\n\t\tR[7] = q12_2 + q03_2;\n\t\tR[8] = 1 - (q00_2 + q11_2);\n\t}\n\n\tstatic inline void transformPoints(int n, FloatType s, const FloatType *R, const FloatType *t, const FloatType *X1, FloatType *X2)\n\t{\n\t\tEigen::Map mR(R);\n\t\tEigen::Map mt(t);\n\t\tEigen::Map mX1(X1, 3, n);\n\t\tEigen::Map mX2(X2, 3, n);\n\t\tmX2 = (s * mR * mX1).colwise() + mt;\n\t}\n\n\t// X1 = [X11 Y11 Z11 X12 Y12 ... X1n Y1n Z1n]\n\t// X2 = [X21 Y21 Z21 X22 Y22 ... X2n Y2n Z2n]\n\t// X2 = s*R*X1 + t\n\tstatic void getRT(int n, const FloatType *X1, const FloatType *X2, FloatType *R, FloatType *t, FloatType &s)\n\t{\n\t\tEigen::Map mX1(X1, 3, n);\n\t\tEigen::Map mX2(X2, 3, n);\n\t\t// centroid\n\t\tMatrix_3x1 mc1 = mX1.rowwise().sum() / mX1.cols();\n\t\tMatrix_3x1 mc2 = mX2.rowwise().sum() / mX2.cols();\n\t\t// translate origin to centroid\n\t\tMatrix_3xD mX1c = mX1.colwise() - mc1;\n\t\tMatrix_3xD mX2c = mX2.colwise() - mc2;\n\n\t\t// estimate scale\n\t\tMatrix_Dx1 mX1n = mX1c.colwise().norm();\n\t\tMatrix_Dx1 mX2n = mX2c.colwise().norm();\n\t\ts = (mX1n.array() * mX2n.array()).sum() / (mX1n.array() * mX1n.array()).sum();\n\t\tmX2c *= s;\n\n\t\t// corrrelation matrix\n\t\tMatrix_3x3 mC = mX1c * mX2c.transpose();\n\t\t// system matrix\n\t\tMatrix_4x4 A;\n\t\tA(3, 3) = mC(0, 0) + mC(1, 1) + mC(2, 2);\n\t\tA(3, 0) = A(0, 3) = mC(1, 2) - mC(2, 1);\n\t\tA(3, 1) = A(1, 3) = mC(2, 0) - mC(0, 2);\n\t\tA(3, 2) = A(2, 3) = mC(0, 1) - mC(1, 0);\n\t\tA(0, 0) = mC(0, 0) - mC(1, 1) - mC(2, 2);\n\t\tA(0, 1) = A(1, 0) = mC(0, 1) + mC(1, 0);\n\t\tA(0, 2) = A(2, 0) = mC(2, 0) + mC(0, 2);\n\t\tA(1, 1) = -mC(0, 0) + mC(1, 1) - mC(2, 2);\n\t\tA(1, 2) = A(2, 1) = mC(1, 2) + mC(2, 1);\n\t\tA(2, 2) = -mC(0, 0) - mC(1, 1) + mC(2, 2);\n\n\t\t// estimate quaternion from eiven vector\n\t\tEigen::SelfAdjointEigenSolver eig(A, Eigen::ComputeEigenvectors);\n\t\tgetRotation(eig.eigenvectors().col(3).data(), R);\n\t\tEigen::Map mR(R);\n\t\tEigen::Map mt(t);\n\t\tmt = -mR * mc1 * s + mc2;\n\t}\n};\n\n}\n\n#endif // THREE_POINT_HPP_", "meta": {"hexsha": "68af23f1882a04193ea7179a0fce29d8eda4e603", "size": 4656, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ThreePoint.hpp", "max_stars_repo_name": "eshibusawa/PoseEstimation", "max_stars_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/ThreePoint.hpp", "max_issues_repo_name": "eshibusawa/PoseEstimation", "max_issues_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ThreePoint.hpp", "max_forks_repo_name": "eshibusawa/PoseEstimation", "max_forks_repo_head_hexsha": "7eca2b21673b2cd42f40c1f05d4f67ee89bdc279", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.1639344262, "max_line_length": 131, "alphanum_fraction": 0.6580756014, "num_tokens": 1833, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278633625322, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.658413847354251}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n\ndouble am(double x, double m) {\n\tif (m == 0) {\n\t\treturn x;\n\t} else if (x == 0) {\n\t\treturn 0;\n\t} else {\n\t\t// function to calculate jacobi amplitude for real input\n\t\t// \"borrowed\" from sagemath\n\t\tdouble sn, cn, dn;\n\t\tif (fabs(m) == 1) {\n\t\t\tdouble tanhx = tanh(x);\n\t\t\treturn asin(tanhx);\n\t\t} else if (fabs(m) > 1){\n\t\t\tgsl_sf_elljac_e(x, m, &sn, &cn, &dn);\n\t\t\treturn atan2(sn, cn);\n\t\t}\n\t\telse{\n\t\t\tdouble K = gsl_sf_ellint_Kcomp(sqrt(m), GSL_PREC_DOUBLE);\n\t\t\tif (fabs(x) <= K) {\n\t\t\t\tgsl_sf_elljac_e(x, m, &sn, &cn, &dn);\n\t\t\t\treturn atan2(sn, cn);\n\t\t\t} else {\n\t\t\t\t// Do argument reduction on x to end up with z = x - 2nK, with\n\t\t\t\t// abs(z) <= K\n\t\t\t\tdouble tK = 2 * K;\n\t\t\t\tint n = floor(x / tK);\n\t\t\t\tdouble tnK = n * tK;\n\t\t\t\tdouble npi = n * M_PI;\n\t\t\t\tdouble z = x - tnK;\n\n\t\t\t\tgsl_sf_elljac_e(z, m, &sn, &cn, &dn);\n\t\t\t\treturn atan2(sn, cn) + npi;\n\t\t\t}\n\t\t}\n\t}\n}\n\n\ndouble calc_radius(double psi, double slr, double ecc) {\n\tdouble r = slr / (1 + ecc * cos(psi));\n\t// printf(\"slr = %.17g \\n\", slr);\n\t// printf(\"ecc = %.17g \\n\", ecc);\n\t// printf(\"psi = %.17g \\n\", psi);\n\treturn r;\n}\n\n\ndouble calc_lambda_r(double r, double r1, double r2, double r3,\n\tdouble r4, double En) {\n\n\t// compute function to change from t[lambda] -> t[psi] with psi an angle\n\t// associated with radial motion. \n\n\tdouble yr, F_asin, kr;\n\tkr = ((r1 - r2)*(r3 - r4))/((r1 - r3)*(r2 - r4));\n\t// there is some problem here because of the high precision part of the\n\t// code. r can be less than r2 (peribothron).\n\t// TODO: fix the code, but for now a temporary fix:\n\tif (r < r2) {\n\t\tr = r2;\n\t\tyr = sqrt(((r - r2)*(r1 - r3))/((r1 - r2)*(r - r3)));\n\t}\n\telse {\n\t\tyr = sqrt(((r - r2)*(r1 - r3))/((r1 - r2)*(r - r3)));\n\t}\n\t// printf(\"r = %.17g \\n\", r);\n\t// printf(\"r2 = %.17g \\n\", r2);\n\tF_asin = gsl_sf_ellint_F(asin(yr), sqrt(kr), GSL_PREC_DOUBLE);\n\treturn (2*F_asin)/(sqrt(1 - En * En)*sqrt((r1 - r3)*(r2 - r4)));\n}\n\n\ndouble calc_lambda_psi(double psi, double ups_r, double r1,\n\tdouble r2, double r3, double r4, double En, double slr, double ecc) {\n\n\tdouble lam_r, lam_r1, r, turns, res, kr;\n\tkr = ((r1 - r2)*(r3 - r4))/((r1 - r3)*(r2 - r4));\n\tr = calc_radius(psi, slr, ecc);\n\tlam_r = 2 * M_PI / ups_r; // radial period\n\tlam_r1 = calc_lambda_r(r2, r1, r2, r3, r4, En);\n\tturns = floor(psi / (2 * M_PI));\n\tif (fmod(psi, 2 * M_PI) <= M_PI) {\n\t\t// printf(\"psi = %.17g\\n\", psi);\n\t\tres = calc_lambda_r(r, r1, r2, r3, r4, En) - lam_r1;\n\t\t// printf(\"res = %.17g\\n\", res);\n\t} else {\n\t\tres = lam_r1 - calc_lambda_r(r, r1, r2, r3, r4, En);\n\t}\n\t// printf(\"two\\n\");\n\n\treturn lam_r * turns + res;\n}\n\n\ndouble calc_lambda_chi(double chi, double zp, double zm, double En, double aa) {\n\t// compute function to change from t[lambda] -> t[chi] with chi an angle\n\t// associated with polar motion. \n\tdouble beta, k, k2, prefactor, ellipticK_k, ellipticF;\n\tbeta = aa * aa * (1 - En * En);\n\tk = sqrt(zm / zp);\n\tk2 = k * k;\n\tprefactor = 1 / sqrt(beta * zp);\n\tellipticK_k = gsl_sf_ellint_Kcomp(sqrt(k2), GSL_PREC_DOUBLE);\n\tellipticF = gsl_sf_ellint_F(M_PI / 2 - chi, sqrt(k2), GSL_PREC_DOUBLE);\n\n\treturn prefactor * (ellipticK_k - ellipticF);\n}\n\n// routines used to find t, r, theta, phi\n\n\ndouble calc_theta_chi(double chi, double zm) {\n\treturn acos(zm * cos(chi));\n}\n\n\ndouble calc_rq(double qr, double r1, double r2,\n\tdouble r3, double r4) {\n\n\tdouble arg, sn2, sn, cn, dn, kr;\n\n\tkr = ((r1 - r2)*(r3 - r4))/((r1 - r3)*(r2 - r4));\n\n\targ = (qr*gsl_sf_ellint_Kcomp(sqrt(kr), GSL_PREC_DOUBLE))/M_PI;\n\tgsl_sf_elljac_e(arg, kr, &sn, &cn, &dn);\n\tsn2 = sn * sn;\n\n\treturn ((-(r2*(r1 - r3)) + (r1 - r2)*r3*sn2)/ (-r1 + r3 + (r1 - r2)*sn2));\n}\n\n\ndouble calc_zq(double qz, double zp, double zm, double En, double aa) {\n\tdouble ktheta, sn, dn, cn, ellipticK_k, arg1, arg2;\n\tktheta = (aa*aa *(1 - En*En)*zm*zm)/zp*zp;\n\tellipticK_k = gsl_sf_ellint_Kcomp(sqrt(ktheta), GSL_PREC_DOUBLE);\n\targ1 = (2*(M_PI/2. + qz)*ellipticK_k)/M_PI;\n\targ2 = ktheta;\n\tgsl_sf_elljac_e(arg1, arg2, &sn, &cn, &dn);\n\n\treturn zm * sn;\n}\n\n\ndouble calc_psi_r(double qr, double r1, double r2, double r3, double r4) {\n\tdouble kr, amplitude;\n\tkr = ((r1 - r2)*(r3 - r4))/((r1 - r3)*(r2 - r4));\n\tamplitude = am((qr * gsl_sf_ellint_Kcomp(sqrt(kr), GSL_PREC_DOUBLE))/M_PI,\n\t\t\t\t kr);\n\treturn amplitude;\n}\n\n\ndouble calc_t_r(double qr, double r1, double r2, double r3, double r4,\n\tdouble En, double Lz, double aa, double M=1) {\n\tdouble psi_r, kr, rp, rm, hr, hp, hm, aa2, En2, sin_psi_r, ellipe_k, ince_k;\n\tdouble ellippi_hm, ellippi_hr, ellippi_hp, inc_pi_hm, inc_pi_hr, inc_pi_hp;\n\taa2 = aa * aa;\n\tEn2 = En * En;\n\tpsi_r = calc_psi_r(qr, r1, r2, r3, r4);\n\n\tkr = ((r1 - r2)*(r3 - r4))/((r1 - r3)*(r2 - r4));\n\n\trp = M + sqrt(-aa*aa + M*M);\n\trm = M - sqrt(-aa*aa + M*M);\n\n\thr = (r1 - r2)/(r1 - r3);\n\thp = ((r1 - r2)*(r3 - rp))/((r1 - r3)*(r2 - rp));\n\thm = ((r1 - r2)*(r3 - rm))/((r1 - r3)*(r2 - rm));\n\n\tsin_psi_r = pow(sin(psi_r), 2);\n\tince_k = gsl_sf_ellint_E(psi_r, sqrt(kr), GSL_PREC_DOUBLE);\n\tellipe_k = gsl_sf_ellint_Ecomp(sqrt(kr), GSL_PREC_DOUBLE);\n\tellippi_hm = gsl_sf_ellint_Pcomp(sqrt(kr), -hm, GSL_PREC_DOUBLE);\n\tellippi_hp = gsl_sf_ellint_Pcomp(sqrt(kr), -hp, GSL_PREC_DOUBLE);\n\tellippi_hr = gsl_sf_ellint_Pcomp(sqrt(kr), -hr, GSL_PREC_DOUBLE);\n\n\t// printf(\"ellippi_hm = %.17g \\n\", ellippi_hm);\n\n\tinc_pi_hm = gsl_sf_ellint_P(psi_r, sqrt(kr), -hm, GSL_PREC_DOUBLE);\n\tinc_pi_hp = gsl_sf_ellint_P(psi_r, sqrt(kr), -hp, GSL_PREC_DOUBLE);\n\tinc_pi_hr = gsl_sf_ellint_P(psi_r, sqrt(kr), -hr, GSL_PREC_DOUBLE);\n\n\n\treturn (-((En * ((-4*(r2 - r3)*(-(((-2*aa2 + (4 - (aa*Lz)/En)*rm)*\n\t\t\t((qr*ellippi_hm)/M_PI - inc_pi_hm))/\n\t\t\t((r2 - rm)*(r3 - rm))) + \n\t\t\t((-2*aa2 + (4 - (aa*Lz)/En)*rp)*\n\t\t\t((qr*ellippi_hp)/M_PI - inc_pi_hp))/\n\t\t\t((r2 - rp)*(r3 - rp))))/(-rm + rp) + \n\t\t\t4*(r2 - r3)*((qr*ellippi_hr)/M_PI - inc_pi_hr) + \n\t\t\t(r2 - r3)*(r1 + r2 + r3 + r4)*\n\t\t\t((qr*ellippi_hr)/M_PI - inc_pi_hr) + \n\t\t\t(r1 - r3)*(r2 - r4)*((qr*ellipe_k)/M_PI - ince_k + \n\t\t\t(hr*cos(psi_r)*sin(psi_r)*sqrt(1 - kr*sin_psi_r))/\n\t\t\t(1 - hr*sin_psi_r))))/sqrt((1 - En2)*(r1 - r3)*(r2 - r4))));\n\n}\n\n\ndouble calc_phi_r(double qr, double r1, double r2, double r3, double r4,\n\tdouble En, double Lz, double aa, double M=1){\n\n\tdouble psi_r, kr, rp, rm, hp, hm, aa2, En2;\n\tdouble ellpi_hp, ellpi_hm, incpi_hp, incpi_hm;\n\taa2 = aa * aa;\n\tEn2 = En * En;\n\tpsi_r = calc_psi_r(qr, r1, r2, r3, r4);\n\tkr = ((r1 - r2)*(r3 - r4))/((r1 - r3)*(r2 - r4));\n\trp = M + sqrt(-aa2 + M*M);\n\trm = M - sqrt(-aa2 + M*M);\n\n\thp = ((r1 - r2)*(r3 - rp))/((r1 - r3)*(r2 - rp));\n\thm = ((r1 - r2)*(r3 - rm))/((r1 - r3)*(r2 - rm));\n\n\tellpi_hp = gsl_sf_ellint_Pcomp(sqrt(kr), -hp, GSL_PREC_DOUBLE);\n\tellpi_hm = gsl_sf_ellint_Pcomp(sqrt(kr), -hm, GSL_PREC_DOUBLE);\n\tincpi_hp = gsl_sf_ellint_P(psi_r, sqrt(kr), -hp, GSL_PREC_DOUBLE);\n\tincpi_hm = gsl_sf_ellint_P(psi_r, sqrt(kr), -hm, GSL_PREC_DOUBLE);\n\n\treturn ((2*aa*En*(-(((r2 - r3)*(-((aa*Lz)/En) + 2*rm)*\n\t\t\t((qr*ellpi_hm)/M_PI - incpi_hm))/\n\t\t\t((r2 - rm)*(r3 - rm))) + \n\t\t\t((r2 - r3)*(-((aa*Lz)/En) + 2*rp)*\n\t\t\t((qr*ellpi_hp)/M_PI - incpi_hp))/\n\t\t\t((r2 - rp)*(r3 - rp))))/\n\t\t\t(sqrt((1 - En2)*(r1 - r3)*(r2 - r4))*(-rm + rp)));\n\n}\n\n\ndouble calc_psi_z(double qz, double zp, double zm, double En, double aa){\n\tdouble ktheta, ellK_k;\n\tktheta = (aa*aa *(1 - En*En)*zm*zm)/zp*zp;\n\tellK_k = gsl_sf_ellint_Kcomp(sqrt(ktheta), GSL_PREC_DOUBLE);\n\treturn am((2*(M_PI/2. + qz) * ellK_k)/M_PI, ktheta);\n}\n\n\ndouble calc_t_z(double qz, double zp, double zm, double En, double aa){\n\tdouble psi_z, ktheta, elle_k, ince_k;\n\tpsi_z = calc_psi_z(qz, zp, zm, En, aa);\n\tktheta = (aa*aa *(1 - En*En)*zm*zm)/zp*zp;\n\telle_k = gsl_sf_ellint_Ecomp(sqrt(ktheta), GSL_PREC_DOUBLE);\n\tince_k = gsl_sf_ellint_E(psi_z, sqrt(ktheta), GSL_PREC_DOUBLE);\n\treturn ((En*zp*((2*(M_PI/2. + qz)*elle_k)/M_PI - ince_k))/\n\t\t\t(1 - En*En));\n}\n\n\ndouble calc_phi_z(double qz, double zp, double zm, double En, double Lz,\n\tdouble aa){\n\n\tdouble psi_z, ktheta, ellpi_k, incpi_k;\n\tpsi_z = calc_psi_z(qz, zp, zm, En, aa);\n\tktheta = (aa*aa * (1 - En*En)*zm*zm)/zp*zp;\n\tellpi_k = gsl_sf_ellint_Pcomp(sqrt(ktheta), -zm*zm, GSL_PREC_DOUBLE);\n\tincpi_k = gsl_sf_ellint_P(psi_z, sqrt(ktheta), -zm*zm, GSL_PREC_DOUBLE);\n\treturn (-((Lz*((2*(M_PI/2. + qz)*ellpi_k)/M_PI - \n\t\t\tincpi_k))/zp));\n}\n\n\ndouble calc_Ct(double qr0, double qz0, double r1, double r2, double r3,\n\tdouble r4, double zp, double zm, double En, double Lz, double aa) {\n\n\tdouble t_r, t_z;\n\tt_r = calc_t_r(qr0, r1, r2, r3, r4, En, Lz, aa);\n\tt_z = calc_t_z(qz0, zp, zm, En, aa);\n\treturn t_r + t_z;\n}\n\n\ndouble calc_Cz(double qr0, double qz0, double r1, double r2, double r3, double r4,\n\tdouble zp, double zm, double En, double Lz, double aa) {\n\n\tdouble phi_r, phi_z;\n\tphi_r = calc_phi_r(qr0, r1, r2, r3, r4, En, Lz, aa);\n\tphi_z = calc_phi_z(qz0, zp, zm, En, Lz, aa);\n\treturn phi_r + phi_z;\n}\n\n\ndouble calc_t(double mino_t, double ups_r, double ups_theta, double gamma,\n\tdouble qt0, double qr0, double qz0, double r1, double r2, double r3,\n\tdouble r4, double zp, double zm, double En, double Lz, double aa){\n\n\tdouble eta_t, eta_r, eta_z, t_r, t_z, Ct;\n\teta_t = qt0 + gamma * mino_t;\n\teta_r = qr0 + ups_r * mino_t;\n\teta_z = qz0 + ups_theta * mino_t;\n\tif (r1 == r2) {\n\t\tt_r = 0;\n\t} else {\n\t\tt_r = calc_t_r(eta_r, r1, r2, r3, r4, En, Lz, aa);\n\t\t// printf(\"t_r = %.17g \\n\", t_r);\n\t}\n\tif (zm == 0){\n\t\tt_z = 0;\n\t} else {\n\t\tt_z = calc_t_z(eta_z, zp, zm, En, aa);\n\t}\n\tif (qr0 == 0 && qz0 == 0) {\n\t\tCt = 0;\n\t} else {\n\t\tCt = calc_Ct(qr0, qz0, r1, r2, r3, r4, zp, zm, En, Lz, aa);\n\t}\n\treturn eta_t + t_r + t_z - Ct;\n}\n\n\ndouble calc_r(double mino_t, double ups_r, double qr0, double r1, double r2,\n\tdouble r3, double r4){\n\n\tdouble eta;\n\teta = ups_r * mino_t + qr0;\n\treturn calc_rq(eta, r1, r2, r3, r4);\n}\n\n\ndouble calc_theta(double mino_t, double ups_theta, double qz0, double zp,\n\tdouble zm, double En, double aa){\n\n\tdouble eta;\n\teta = ups_theta * mino_t + qz0;\n\treturn acos(calc_zq(eta, zp, zm, En, aa));\n}\n\n\ndouble calc_phi(double mino_t, double ups_r, double ups_theta, double ups_phi,\n\tdouble qphi0, double qr0, double qz0, double r1, double r2, double r3,\n\tdouble r4, double zp, double zm, double En, double Lz, double aa){\n\n\tdouble eta_phi, eta_r, eta_theta, phi_r, phi_z, Cz;\n\teta_phi = ups_phi * mino_t + qphi0;\n\teta_r = ups_r * mino_t + qr0;\n\teta_theta = ups_theta * mino_t + qz0;\n\tif (r1 == r2) {\n\t\tphi_r = 0;\n\t} else {\n\t\tphi_r = calc_phi_r(eta_r, r1, r2, r3, r4, En, Lz, aa);\n\t}\n\n\tif (zm == 0) {\n\t\tphi_z = 0;\n\t}\n\telse {\n\t\tphi_z = calc_phi_z(eta_theta, zp, zm, En, Lz, aa);\n\t}\n\n\tif (qr0 == 0 && qz0 == 0){\n\t\tCz = 0;\n\t} else {\n\t\tCz = calc_Cz(qr0, qz0, r1, r2, r3, r4, zp, zm, En, Lz, aa);\n\t}\n\treturn eta_phi + phi_r + phi_z - Cz;\n}\n\n\ndouble calc_J(double chi, double En, double Lz, double Q, double aa, double slr, double ecc) {\n // \"\"\"\n // Schmidt's J function.\n\n // Parameters:\n // chi (float): radial angle\n // En (float): energy\n // Lz (float): angular momentum\n // Q (float): Carter constant\n // aa (float): spin\n // slr (float): semi-latus rectum\n // ecc (float): eccentricity\n\n // Returns:\n // J (float)\n // \"\"\"\n double En2 = En * En;\n double ecc2 = ecc * ecc;\n double aa2 = aa * aa;\n double Lz2 = Lz * Lz;\n double slr2 = slr * slr;\n\n double eta = 1 + ecc * cos(chi);\n double eta2 = eta * eta;\n\n double J = (\n (1 - ecc2) * (1 - En2)\n + 2 * (1 - En2 - (1 - ecc2) / slr) * eta\n + (\n ((3 + ecc2) * (1 - En2)) / (1 - ecc2)\n + ((1 - ecc2) * (aa2 * (1 - En2) + Lz2 + Q)) / slr2\n - 4 / slr\n )\n * eta2\n );\n\n return J;\n}\n\n\n// double calc_wr(double psi, double ups_r, double En, double Lz,\n// \t\t\t double Q, double aa, double slr, double ecc, double x) {\n// \t// note that this has only been checked for psi in [0, pi]\n// \tdouble aa2 = aa * aa;\n// \tdouble slr2 = slr * slr;\n// \tdouble ecc2 = ecc * ecc;\n// \tdouble En2 = En * En;\n// \tdouble Lz2 = Lz * Lz;\n// \tdouble a1 = (1 - ecc2) * (1 - En2);\n// double b1 = 2 * (1 - En2 - (1 - ecc2) / slr);\n// double c1 = (((3 + ecc2)*(1 - En2))/(1 - ecc2) - 4/slr + \n// \t\t ((1 - ecc2) * (aa2*(1 - En2) + Lz2 + Q)) / slr2);\n\n// \tdouble b12 = b1 * b1;\n// \tif (psi == M_PI) {\n// \t\treturn M_PI;\n// \t} else {\n// \t\tcomplex phi {0, asinh(sqrt((a1 - (-1 + ecc)*(b1 + c1 - c1*ecc))/\n// \t\t\t\t\t\t (a1 + b1 + c1 - c1*ecc2 + sqrt(b12 - 4*a1*c1)*ecc2)))* tan(psi/2.))};\n\n// \t \tdouble m = ((a1 + b1 + c1 - c1*ecc2 + sqrt((b12 - 4*a1*c1)*ecc2))/\n// \t\t\t\t (a1 + b1 + c1 - c1*ecc2 - sqrt((b12 - 4*a1*c1)*ecc2)));\n// \t\tdouble k = sqrt(m);\n// \t\tcomplex ellint_f = ellint_1(k, phi);\n// \t\tcomplex res {0, ((-2*(1 - ecc2) * ellint_f * ups_r * power(cos(psi/2.),2)*\n// \t\t\t\tsqrt(2 + (2*(a1 - (-1 + ecc)*(b1 + c1 - c1*ecc))*power(tan(psi/2.),2))/\n// \t\t\t\t\t(a1 + b1 + c1 - c1*ecc2 - sqrt(b12 - 4*a1*c1)*ecc2)))*\n// \t\t\t\tsqrt(1 + ((a1 - (-1 + ecc)*(b1 + c1 - c1*ecc))*power(tan(psi/2.),2))/\n// \t\t\t\t\t(a1 + b1 + c1 - c1*ecc2 + sqrt((b12 - 4*a1*c1)*ecc2))))/\n// \t\t\t(sqrt((a1 - (-1 + ecc)*(b1 + c1 - c1*ecc))/\n// \t\t\t\t(a1 + b1 + c1 - c1*ecc2 + sqrt((b12 - 4*a1*c1)*ecc2)))*\n// \t\t\t\tslr*sqrt(2*a1 + 2*b1 + 2*c1 + c1*ecc2 + 2*(b1 + 2*c1)*ecc*cos(psi) + \n// \t\t\t\tc1*ecc2*cos(2*psi))))};\n// \t\tdouble re_res = real(res);\n\t\t\n// \t\treturn re_res;\n// \t}\n// }\n\n\ndouble calc_dwr_dpsi(double psi, double ups_r, double En, double Lz,\n\t\t\t\t\t double Q, double aa, double slr, double ecc) {\n double J = calc_J(psi, En, Lz, Q, aa, slr, ecc);\n\tdouble ecc2 = ecc * ecc;\n return (1 - ecc2) / slr * ups_r / sqrt(J);\n}\n\n\n// double calc_wtheta(double chi, double ups_theta, double zp, double zm,\n// \t\t\t\t double En, double Lz, double aa, double slr, double x) {\n// // \"\"\"\n// // w_theta = ups_theta * lambda as a function of polar angle chi\n\n// // Parameters:\n// // chi (float): polar angle\n// // ups_theta (float): theta mino frequency\n// // En (float): energy\n// // Lz (float): angular momentum\n// // aa (float): spin\n// // slr (float): semi-latus rectum\n// // x (float): inclination\n\n// // Returns:\n// // w_theta (float)\n// // \"\"\"\n// double pi = M_PI;\n// if (chi >= 0 && chi <= pi / 2) {\n// return ups_theta * calc_lambda_chi(chi, zp, zm, En, Lz, aa, slr, x);\n// \t} else if (chi > pi / 2 && chi <= pi) {\n// return pi - ups_theta * calc_lambda_chi(pi - chi, zp, zm, En, Lz, aa, slr, x);\n// \t} else if (chi > pi && chi <= 3 * pi / 2) {\n// return pi + ups_theta * calc_lambda_chi(chi - pi, zp, zm, En, Lz, aa, slr, x);\n// \t} else if (chi > 3 * pi / 2 && chi <= 2 * pi) {\n// return 2 * pi - ups_theta * calc_lambda_chi(2 * pi - chi, zp, zm, En, Lz, aa, slr, x);\n// \t} else {\n// // print(\"Something went wrong in calc_wtheta!\")\n// return 0.0; // this case should not occur, but is required by C++\n// \t}\n// }\n\n\ndouble calc_dwtheta_dchi(double chi, double zp, double zm) {\n // \"\"\"\n // derivative of w_theta\n\n // Parameters:\n // chi (float): polar angle\n // zp (float): polar root\n // zm (float): polar root\n\n // Returns:\n // dw_dtheta (float)\n // \"\"\"\n double k = sqrt(zm / zp);\n double ellipticK_k = gsl_sf_ellint_Kcomp(k, GSL_PREC_DOUBLE);\n return M_PI / (2 * ellipticK_k) * (1 / (1 - k * k * pow(cos(chi),2)));\n}\n\n\nvoid calc_circular_eq_coords(double &t, double &r, double &theta, double &phi,\n\t\t\t\t\t\t\t double psi, double En, double Lz, double aa, double slr, double M) {\n // lam_psi is used to cross check with circular orbits in BHPTK\n // lam_psi = (psi / (sqrt(1 - En**2 + 3*(1 - En**2) + 2*(1 - En**2 - 1/slr) + \n // (aa**2*(1 - En**2) + Lz**2)/slr**2 - 4/slr)*slr))\n // print(lam_psi)\n\n\tdouble x, Vr, Vphi, Vt, J, denom;\n\tdouble aa2 = aa * aa;\n\tdouble slr2 = slr * slr;\n\tx = Lz - aa * En;\n\tdouble x2 = x * x;\n\n Vr = aa2 + x2 + 2 * aa * x * En - 6 * M * x2 / slr;\n Vphi = x + aa * En - 2 * M * x / slr;\n Vt = aa2 * En - 2 * aa * M * x / slr + En * slr2;\n J = 1 - 2 * M / slr + aa2 / slr2;\n denom = J * sqrt(Vr);\n\tt = Vt / denom * psi;\n phi = Vphi / denom * psi;\n r = slr;\n\ttheta = M_PI / 2;\n}\n\n\nvoid calc_equatorial_coords(double &t, double &r, double &theta, double &phi,\n\tdouble psi, double ups_r, double ups_theta,\n\tdouble ups_phi, double gamma, double r1, double r2, double r3,\n\tdouble r4, double zp, double zm, double En, double Lz, double aa,\n\tdouble slr, double ecc, double qt0, double qr0, double qz0,\n\tdouble qphi0) {\n\n\tdouble lam_psi;\n\tif (zm != 0){\n\t\tprintf(\"The orbit specified is not equatorial.\\n\");\n\t}\n\tr = calc_radius(psi, slr, ecc);\n\tlam_psi = calc_lambda_psi(psi, ups_r, r1, r2, r3, r4, En, slr, ecc);\n\tt = calc_t(lam_psi, ups_r, ups_theta, gamma, qt0, qr0, qz0, r1, r2, r3, r4,\n\t\t\t zp, zm, En, Lz, aa);\n\ttheta = M_PI / 2; // TODO(aaron): check generic theta\n\tphi = calc_phi(lam_psi, ups_r, ups_theta, ups_phi, qphi0, qr0, qz0, r1, r2,\n\t\t\t\t r3, r4, zp, zm, En, Lz, aa);\n\n}\n\n\nvoid calc_gen_coords_mino(double &t, double &r, double &theta, double &phi,\n\tdouble mino_t, double ups_r, double ups_theta, double ups_phi, double gamma,\n double r1, double r2, double r3, double r4, double zp, double zm, double En,\n double Lz, double aa, double qphi0, double qr0, double qz0, double qt0) {\n\n\tt = calc_t(mino_t, ups_r, ups_theta, gamma, qt0, qr0, qz0, r1, r2, r3, r4, zp, zm, En, Lz, aa);\n\tr = calc_r(mino_t, ups_r, qr0, r1, r2, r3, r4);\n\ttheta = calc_theta(mino_t, ups_theta, qz0, zp, zm, En, aa);\n\tphi = calc_phi(mino_t, ups_r, ups_theta, ups_phi, qphi0, qr0, qz0, r1, r2, r3, r4, zp, zm, En, Lz, aa);\n}\n\n\n// void calc_gen_coords_psi(double &t, double &r, double &theta, double &phi,\n// \tdouble psi, double ups_r, double ups_theta, double ups_phi, double gamma,\n// double r1, double r2, double r3, double r4, double zp, double zm, double En,\n// \tdouble Lz, double Q, double aa, double slr, double ecc, double x,\n// \tdouble qphi0, double qr0, double qz0, double qt0) {\n\n// \tdouble wr = calc_wr(psi, ups_r, En, Lz, Q, aa, slr, ecc, x);\n// \tdouble mino_t = wr / ups_r;\n// \tt = calc_t(mino_t, ups_r, ups_theta, gamma, qt0, qr0, qz0, r1, r2, r3, r4, zp, zm, En, Lz, aa);\n// \tr = calc_r(mino_t, ups_r, qr0, r1, r2, r3, r4);\n// \ttheta = calc_theta(mino_t, ups_theta, qz0, zp, zm, En, aa);\n// \tphi = calc_phi(mino_t, ups_r, ups_theta, ups_phi, qphi0, qr0, qz0, r1, r2, r3, r4, zp, zm, En, Lz, aa);\n// }\n\n\n", "meta": {"hexsha": "40cf51612f45bd324d669560aa635fb5f9bbca6f", "size": 18431, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "geodesic/coordsc.cpp", "max_stars_repo_name": "AaronDJohnson/fbtpoint", "max_stars_repo_head_hexsha": "d5f84006b7b5a53cbf92a9e763f8a6913b86233e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-19T19:14:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T19:14:03.000Z", "max_issues_repo_path": "geodesic/coordsc.cpp", "max_issues_repo_name": "AaronDJohnson/fbtpoint", "max_issues_repo_head_hexsha": "d5f84006b7b5a53cbf92a9e763f8a6913b86233e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geodesic/coordsc.cpp", "max_forks_repo_name": "AaronDJohnson/fbtpoint", "max_forks_repo_head_hexsha": "d5f84006b7b5a53cbf92a9e763f8a6913b86233e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7775862069, "max_line_length": 107, "alphanum_fraction": 0.582985188, "num_tokens": 7272, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9161096067182449, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6583112318889769}} {"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 2006 - 2016 by the deal.II authors\n *\n * This file is part of the deal.II library.\n *\n * The deal.II library is free software; you can use it, redistribute\n * it, and/or modify it under the terms of the GNU Lesser General\n * Public License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * The full text of the license can be found in the file LICENSE.md at\n * the top level directory of deal.II.\n *\n * ---------------------------------------------------------------------\n *\n * Author: Ivan Christov, Wolfgang Bangerth, Texas A&M University, 2006\n */\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nnamespace Step25\n{\n using namespace dealii;\n template \n class SineGordonProblem\n {\n public:\n SineGordonProblem();\n void run();\n private:\n void make_grid_and_dofs();\n void assemble_system();\n void compute_nl_term(const Vector &old_data,\n const Vector &new_data,\n Vector & nl_term) const;\n void compute_nl_matrix(const Vector &old_data,\n const Vector &new_data,\n SparseMatrix &nl_matrix) const;\n unsigned int solve();\n void output_results(const unsigned int timestep_number) const;\n Triangulation triangulation;\n FE_Q fe;\n DoFHandler dof_handler;\n SparsityPattern sparsity_pattern;\n SparseMatrix system_matrix;\n SparseMatrix mass_matrix;\n SparseMatrix laplace_matrix;\n const unsigned int n_global_refinements;\n double time;\n const double final_time, time_step;\n const double theta;\n Vector solution, solution_update, old_solution;\n Vector M_x_velocity;\n Vector system_rhs;\n const unsigned int output_timestep_skip;\n };\n template \n class ExactSolution : public Function\n {\n public:\n ExactSolution(const unsigned int n_components = 1, const double time = 0.)\n : Function(n_components, time)\n {}\n virtual double value(const Point & p,\n const unsigned int component = 0) const override;\n };\n template \n double ExactSolution::value(const Point &p,\n const unsigned int /*component*/) const\n {\n double t = this->get_time();\n switch (dim)\n {\n case 1:\n {\n const double m = 0.5;\n const double c1 = 0.;\n const double c2 = 0.;\n return -4. * std::atan(m / std::sqrt(1. - m * m) *\n std::sin(std::sqrt(1. - m * m) * t + c2) /\n std::cosh(m * p[0] + c1));\n }\n case 2:\n {\n const double theta = numbers::PI / 4.;\n const double lambda = 1.;\n const double a0 = 1.;\n const double s = 1.;\n const double arg = p[0] * std::cos(theta) +\n std::sin(theta) * (p[1] * std::cosh(lambda) +\n t * std::sinh(lambda));\n return 4. * std::atan(a0 * std::exp(s * arg));\n }\n case 3:\n {\n const double theta = numbers::PI / 4;\n const double phi = numbers::PI / 4;\n const double tau = 1.;\n const double c0 = 1.;\n const double s = 1.;\n const double arg = p[0] * std::cos(theta) +\n p[1] * std::sin(theta) * std::cos(phi) +\n std::sin(theta) * std::sin(phi) *\n (p[2] * std::cosh(tau) + t * std::sinh(tau));\n return 4. * std::atan(c0 * std::exp(s * arg));\n }\n default:\n Assert(false, ExcNotImplemented());\n return -1e8;\n }\n }\n template \n class InitialValues : public Function\n {\n public:\n InitialValues(const unsigned int n_components = 1, const double time = 0.)\n : Function(n_components, time)\n {}\n virtual double value(const Point & p,\n const unsigned int component = 0) const override;\n };\n template \n double InitialValues::value(const Point & p,\n const unsigned int component) const\n {\n return ExactSolution(1, this->get_time()).value(p, component);\n }\n template \n SineGordonProblem::SineGordonProblem()\n : fe(1)\n , dof_handler(triangulation)\n , n_global_refinements(6)\n , time(-5.4414)\n , final_time(2.7207)\n , time_step(10 * 1. / std::pow(2., 1. * n_global_refinements))\n , theta(0.5)\n , output_timestep_skip(1)\n {}\n template \n void SineGordonProblem::make_grid_and_dofs()\n {\n GridGenerator::hyper_cube(triangulation, -10, 10);\n triangulation.refine_global(n_global_refinements);\n std::cout << \" Number of active cells: \" << triangulation.n_active_cells()\n << std::endl\n << \" Total number of cells: \" << triangulation.n_cells()\n << std::endl;\n dof_handler.distribute_dofs(fe);\n std::cout << \" Number of degrees of freedom: \" << dof_handler.n_dofs()\n << std::endl;\n DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs());\n DoFTools::make_sparsity_pattern(dof_handler, dsp);\n sparsity_pattern.copy_from(dsp);\n system_matrix.reinit(sparsity_pattern);\n mass_matrix.reinit(sparsity_pattern);\n laplace_matrix.reinit(sparsity_pattern);\n MatrixCreator::create_mass_matrix(dof_handler,\n QGauss(fe.degree + 1),\n mass_matrix);\n MatrixCreator::create_laplace_matrix(dof_handler,\n QGauss(fe.degree + 1),\n laplace_matrix);\n solution.reinit(dof_handler.n_dofs());\n solution_update.reinit(dof_handler.n_dofs());\n old_solution.reinit(dof_handler.n_dofs());\n M_x_velocity.reinit(dof_handler.n_dofs());\n system_rhs.reinit(dof_handler.n_dofs());\n }\n template \n void SineGordonProblem::assemble_system()\n {\n system_matrix.copy_from(mass_matrix);\n system_matrix.add(std::pow(time_step * theta, 2), laplace_matrix);\n SparseMatrix tmp_matrix(sparsity_pattern);\n compute_nl_matrix(old_solution, solution, tmp_matrix);\n system_matrix.add(std::pow(time_step * theta, 2), tmp_matrix);\n system_rhs = 0.;\n Vector tmp_vector(solution.size());\n mass_matrix.vmult(system_rhs, solution);\n laplace_matrix.vmult(tmp_vector, solution);\n system_rhs.add(std::pow(time_step * theta, 2), tmp_vector);\n mass_matrix.vmult(tmp_vector, old_solution);\n system_rhs.add(-1.0, tmp_vector);\n laplace_matrix.vmult(tmp_vector, old_solution);\n system_rhs.add(std::pow(time_step, 2) * theta * (1 - theta), tmp_vector);\n system_rhs.add(-time_step, M_x_velocity);\n compute_nl_term(old_solution, solution, tmp_vector);\n system_rhs.add(std::pow(time_step, 2) * theta, tmp_vector);\n system_rhs *= -1.;\n }\n template \n void SineGordonProblem::compute_nl_term(const Vector &old_data,\n const Vector &new_data,\n Vector &nl_term) const\n {\n nl_term = 0;\n const QGauss quadrature_formula(fe.degree + 1);\n FEValues fe_values(fe,\n quadrature_formula,\n update_values | update_JxW_values |\n update_quadrature_points);\n const unsigned int dofs_per_cell = fe.dofs_per_cell;\n const unsigned int n_q_points = quadrature_formula.size();\n Vector local_nl_term(dofs_per_cell);\n std::vector local_dof_indices(dofs_per_cell);\n std::vector old_data_values(n_q_points);\n std::vector new_data_values(n_q_points);\n typename DoFHandler::active_cell_iterator cell =\n dof_handler.begin_active(),\n endc = dof_handler.end();\n for (; cell != endc; ++cell)\n {\n local_nl_term = 0;\n fe_values.reinit(cell);\n fe_values.get_function_values(old_data, old_data_values);\n fe_values.get_function_values(new_data, new_data_values);\n for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n for (unsigned int i = 0; i < dofs_per_cell; ++i)\n local_nl_term(i) +=\n (std::sin(theta * new_data_values[q_point] +\n (1 - theta) * old_data_values[q_point]) *\n fe_values.shape_value(i, q_point) * fe_values.JxW(q_point));\n cell->get_dof_indices(local_dof_indices);\n for (unsigned int i = 0; i < dofs_per_cell; ++i)\n nl_term(local_dof_indices[i]) += local_nl_term(i);\n }\n }\n template \n void SineGordonProblem::compute_nl_matrix(\n const Vector &old_data,\n const Vector &new_data,\n SparseMatrix &nl_matrix) const\n {\n QGauss quadrature_formula(fe.degree + 1);\n FEValues fe_values(fe,\n quadrature_formula,\n update_values | update_JxW_values |\n update_quadrature_points);\n const unsigned int dofs_per_cell = fe.dofs_per_cell;\n const unsigned int n_q_points = quadrature_formula.size();\n FullMatrix local_nl_matrix(dofs_per_cell, dofs_per_cell);\n std::vector local_dof_indices(dofs_per_cell);\n std::vector old_data_values(n_q_points);\n std::vector new_data_values(n_q_points);\n typename DoFHandler::active_cell_iterator cell =\n dof_handler.begin_active(),\n endc = dof_handler.end();\n for (; cell != endc; ++cell)\n {\n local_nl_matrix = 0;\n fe_values.reinit(cell);\n fe_values.get_function_values(old_data, old_data_values);\n fe_values.get_function_values(new_data, new_data_values);\n for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n for (unsigned int i = 0; i < dofs_per_cell; ++i)\n for (unsigned int j = 0; j < dofs_per_cell; ++j)\n local_nl_matrix(i, j) +=\n (std::cos(theta * new_data_values[q_point] +\n (1 - theta) * old_data_values[q_point]) *\n fe_values.shape_value(i, q_point) *\n fe_values.shape_value(j, q_point) * fe_values.JxW(q_point));\n cell->get_dof_indices(local_dof_indices);\n for (unsigned int i = 0; i < dofs_per_cell; ++i)\n for (unsigned int j = 0; j < dofs_per_cell; ++j)\n nl_matrix.add(local_dof_indices[i],\n local_dof_indices[j],\n local_nl_matrix(i, j));\n }\n }\n template \n unsigned int SineGordonProblem::solve()\n {\n SolverControl solver_control(1000, 1e-12 * system_rhs.l2_norm());\n SolverCG<> cg(solver_control);\n PreconditionSSOR<> preconditioner;\n preconditioner.initialize(system_matrix, 1.2);\n cg.solve(system_matrix, solution_update, system_rhs, preconditioner);\n return solver_control.last_step();\n }\n template \n void SineGordonProblem::output_results(\n const unsigned int timestep_number) const\n {\n DataOut data_out;\n data_out.attach_dof_handler(dof_handler);\n data_out.add_data_vector(solution, \"u\");\n data_out.build_patches();\n const std::string filename =\n \"solution-\" + Utilities::int_to_string(timestep_number, 3) + \".vtk\";\n std::ofstream output(filename);\n data_out.write_vtk(output);\n }\n template \n void SineGordonProblem::run()\n {\n make_grid_and_dofs();\n {\n AffineConstraints constraints;\n constraints.close();\n VectorTools::project(dof_handler,\n constraints,\n QGauss(fe.degree + 1),\n InitialValues(1, time),\n solution);\n }\n output_results(0);\n unsigned int timestep_number = 1;\n for (time += time_step; time <= final_time;\n time += time_step, ++timestep_number)\n {\n old_solution = solution;\n std::cout << std::endl\n << \"Time step #\" << timestep_number << \"; \"\n << \"advancing to t = \" << time << \".\" << std::endl;\n double initial_rhs_norm = 0.;\n bool first_iteration = true;\n do\n {\n assemble_system();\n if (first_iteration == true)\n initial_rhs_norm = system_rhs.l2_norm();\n const unsigned int n_iterations = solve();\n solution += solution_update;\n if (first_iteration == true)\n std::cout << \" \" << n_iterations;\n else\n std::cout << '+' << n_iterations;\n first_iteration = false;\n }\n while (system_rhs.l2_norm() > 1e-6 * initial_rhs_norm);\n std::cout << \" CG iterations per nonlinear step.\" << std::endl;\n Vector tmp_vector(solution.size());\n laplace_matrix.vmult(tmp_vector, solution);\n M_x_velocity.add(-time_step * theta, tmp_vector);\n laplace_matrix.vmult(tmp_vector, old_solution);\n M_x_velocity.add(-time_step * (1 - theta), tmp_vector);\n compute_nl_term(old_solution, solution, tmp_vector);\n M_x_velocity.add(-time_step, tmp_vector);\n if (timestep_number % output_timestep_skip == 0)\n output_results(timestep_number);\n }\n }\n} // namespace Step25\nint main()\n{\n try\n {\n using namespace dealii;\n using namespace Step25;\n SineGordonProblem<1> sg_problem;\n sg_problem.run();\n }\n catch (std::exception &exc)\n {\n std::cerr << std::endl\n << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n std::cerr << \"Exception on processing: \" << std::endl\n << exc.what() << std::endl\n << \"Aborting!\" << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n return 1;\n }\n catch (...)\n {\n std::cerr << std::endl\n << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n std::cerr << \"Unknown exception!\" << std::endl\n << \"Aborting!\" << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n return 1;\n }\n return 0;\n}\n", "meta": {"hexsha": "3e2c6ef2d116ec92e7a57479956ab76cc485a5ba", "size": 16188, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/DEALII/sine-GordonEquation/main.cc", "max_stars_repo_name": "chtld/Finite_Element_Method", "max_stars_repo_head_hexsha": "f38fed7a3bf472a95acbb93d5546bf2a2e8b4438", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-09-03T14:09:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T14:12:55.000Z", "max_issues_repo_path": "src/DEALII/sine-GordonEquation/main.cc", "max_issues_repo_name": "chtld/Finite_Element_Method_for_1D_Possion_Equation", "max_issues_repo_head_hexsha": "f38fed7a3bf472a95acbb93d5546bf2a2e8b4438", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/DEALII/sine-GordonEquation/main.cc", "max_forks_repo_name": "chtld/Finite_Element_Method_for_1D_Possion_Equation", "max_forks_repo_head_hexsha": "f38fed7a3bf472a95acbb93d5546bf2a2e8b4438", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T07:15:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-26T09:04:07.000Z", "avg_line_length": 40.2686567164, "max_line_length": 80, "alphanum_fraction": 0.5690017297, "num_tokens": 3774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.91610961358942, "lm_q2_score": 0.7185943805178138, "lm_q1q2_score": 0.658311220263703}} {"text": "#include \r\n#include \r\n\r\nusing namespace margait_contrib;\r\n\r\nKalmanFilter::KalmanFilter()\r\n{\r\n\tlastX = 0;\r\n\tlastV = 0;\r\n\tsmoothing = 0.1;\r\n\ttimeStep = 0.010;\r\n\tx = 0;\r\n\tv = 0;\r\n\ta = 0;\r\n\tpx = 0;\r\n\tpv = 0;\r\n\tpa = 0;\r\n\r\n\t// When the gain is adaptive, the smoothing config parameters don't make any difference.\r\n\tadaptiveGain = true;\r\n\r\n\tinit();\r\n}\r\n\r\n// Prepares (resets) the noise matrices and the kalman gain, but preserves the current state.\r\n// This is good for changing the smoothing on the fly without messing with the state estimate.\r\nvoid KalmanFilter::init()\r\n{\r\n\t// Process noise.\r\n\tQ = Eigen::Matrix3d::Identity();\r\n\r\n\t// Measurement noise.\r\n\tR = (0.001 + smoothing*100.0) * Eigen::Matrix3d::Identity();\r\n\r\n\t// Passive linear system dynamics matrix A.\r\n\tA << 1.0, timeStep, 0.0 ,\r\n\t 0.0, 1.0 , timeStep,\r\n\t 0.0, 0.0 , 1.0 ;\r\n\r\n\t// State and measurement vectors.\r\n\tX << x, v, a;\r\n\tZ.setZero();\r\n\r\n\t// Other matrices\r\n\tH = I = K = Eigen::Matrix3d::Identity();\r\n\tP.setZero();\r\n}\r\n\r\n// Sets the smoothing parameter.\r\nvoid KalmanFilter::setSmoothing(double s)\r\n{\r\n\tsmoothing = s;\r\n\tinit();\r\n}\r\n\r\n// Sets the time interval between the updates. It's set to 10 milliseconds by default.\r\nvoid KalmanFilter::setTimeStep(double t)\r\n{\r\n\ttimeStep = t;\r\n\tinit();\r\n}\r\n\r\n// Resets the state to the provided parameters, but doesn't change the noise and the kalman gain.\r\n// This is good to set the state estimate on the fly without messing with the Kalman gain.\r\nvoid KalmanFilter::reset(double xx, double vv, double aa)\r\n{\r\n\tx = xx;\r\n\tv = vv;\r\n\ta = aa;\r\n\r\n\tX << x, v, a;\r\n\r\n\tlastX = x;\r\n\tlastV = v;\r\n}\r\n\r\n// Updates the process. Provide a position measurement z.\r\nvoid KalmanFilter::update(double z)\r\n{\r\n\tdouble Zv = (z - lastX)/timeStep;\r\n\tZ << z, Zv, (Zv - lastV)/timeStep;\r\n\tlastX = Z(0);\r\n\tlastV = Z(1);\r\n\r\n\tif (adaptiveGain)\r\n\t{\r\n\t\tX = A*X;\r\n\t\tP = A*P*A.transpose() + Q;\r\n\t\tK = P*H.transpose() * (H*P*H.transpose() + R).inverse();\r\n\t\tX = X + K*(Z - H*X);\r\n\t\tP = (I - K*H)*P;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tX = A*X;\r\n\t\tK = Q*H.transpose() * (H*Q*H.transpose() + R).inverse();\r\n\t\tX = X + K*(Z - H*X);\r\n\t}\r\n\r\n\tx = X(0);\r\n\tv = X(1);\r\n\ta = X(2);\r\n\r\n\tpx = P(0,0);\r\n\tpv = P(1,1);\r\n\tpa = P(2,2);\r\n}\r\n", "meta": {"hexsha": "200a6bf9f3ea53ecc200c046c949b388b3f6e99a", "size": 2243, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro/motion/gait_engines/cap_gait/src/contrib/KalmanFilter.cpp", "max_stars_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_stars_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 45.0, "max_stars_repo_stars_event_min_datetime": "2015-11-04T01:29:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T05:37:42.000Z", "max_issues_repo_path": "src/nimbro/motion/gait_engines/cap_gait/src/contrib/KalmanFilter.cpp", "max_issues_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_issues_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-22T08:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-22T08:34:34.000Z", "max_forks_repo_path": "src/nimbro/motion/gait_engines/cap_gait/src/contrib/KalmanFilter.cpp", "max_forks_repo_name": "hfarazi/humanoid_op_ros_kinetic", "max_forks_repo_head_hexsha": "84712bd541d0130b840ad1935d5bfe301814dbe6", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 20.0, "max_forks_repo_forks_event_min_datetime": "2016-03-05T14:28:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:50:47.000Z", "avg_line_length": 20.7685185185, "max_line_length": 98, "alphanum_fraction": 0.5898350424, "num_tokens": 700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9284088005554475, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6582596035682807}} {"text": "#include \n\n#include \"FactorBase.h\"\n\n#ifdef DEBUG\n#include\n#endif\n\nFactorBase::FactorBase(ZZ bound)\n{\n setBound(bound);\n}\n\nbool FactorBase::factor(std::vector& f, const ZZ& _n)const\n{\n /*\n * Factorization of a number over a rational factor base.\n */\n#ifdef DEBUG\n std::cerr<<\"Value of factored num is: \"<<_n<(r[r.size()-1]))))\n {\n ++smallInd;\n }\n#ifdef DEBUG\n std::cerr<<\"\\n\";\n#endif\n}\n\nunsigned long FactorBase::getSize() const\n{\n return r.size();\n}\n", "meta": {"hexsha": "638b12c9009e4e692b0db35174755cec433cbfb5", "size": 2443, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FactorBase.cpp", "max_stars_repo_name": "Saviero/discrete-log", "max_stars_repo_head_hexsha": "0cd3bc65275b4c48cc9c0120c58c1dc5c1c4117d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FactorBase.cpp", "max_issues_repo_name": "Saviero/discrete-log", "max_issues_repo_head_hexsha": "0cd3bc65275b4c48cc9c0120c58c1dc5c1c4117d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FactorBase.cpp", "max_forks_repo_name": "Saviero/discrete-log", "max_forks_repo_head_hexsha": "0cd3bc65275b4c48cc9c0120c58c1dc5c1c4117d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 17.3262411348, "max_line_length": 71, "alphanum_fraction": 0.3905034793, "num_tokens": 696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7799929104825006, "lm_q1q2_score": 0.658232197183446}} {"text": "/**\n * @file matode.cc\n * @brief NPDE homework MatODE code\n * @copyright Developed at ETH Zurich\n */\n\n#include \n\nnamespace MatODE {\n\n/* SAM_LISTING_BEGIN_3 */\nEigen::MatrixXd eeulstep(const Eigen::MatrixXd& A, const Eigen::MatrixXd& Y0,\n double h) {\n return Y0 + h * A * Y0;\n}\n/* SAM_LISTING_END_3 */\n\n/* SAM_LISTING_BEGIN_4 */\nEigen::MatrixXd ieulstep(const Eigen::MatrixXd& A, const Eigen::MatrixXd& Y0,\n double h) {\n int n = A.rows();\n return (Eigen::MatrixXd::Identity(n, n) - h * A).partialPivLu().solve(Y0);\n}\n/* SAM_LISTING_END_4 */\n\n/* SAM_LISTING_BEGIN_5 */\nEigen::MatrixXd impstep(const Eigen::MatrixXd& A, const Eigen::MatrixXd& Y0,\n double h) {\n int n = A.rows();\n return (Eigen::MatrixXd::Identity(n, n) - h * 0.5 * A)\n .partialPivLu()\n .solve(Y0 + h * 0.5 * A * Y0);\n}\n/* SAM_LISTING_END_5 */\n\n} // namespace MatODE\n", "meta": {"hexsha": "0fa8b2cc7da99cc5385ac2f0a36645ebbe1739ff", "size": 930, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MatODE/mastersolution/matode.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/MatODE/mastersolution/matode.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/MatODE/mastersolution/matode.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 25.1351351351, "max_line_length": 77, "alphanum_fraction": 0.6032258065, "num_tokens": 271, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7690802370707283, "lm_q2_score": 0.8558511524823263, "lm_q1q2_score": 0.6582182072483636}} {"text": "/*\n Copyright (C) 2015-2021 by Synge Todo \n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\n// Free energy, energy, and specific heat of triangular lattice Ising model\n\n#include \n#include \n#include \n#include \n#include \"ising/mp_wrapper.hpp\"\n#include \"triangular.hpp\"\n\nstruct options {\n unsigned int prec;\n std::string Ja, Jb, Jc, Tmin, Tmax, dT;\n bool valid;\n options(unsigned int argc, char *argv[]) :\n prec(15), Ja(\"1\"), Jb(\"1\"), Jc(\"1\"), valid(true) {\n if (argc == 1) { valid = false; return; }\n for (unsigned i = 1; i < argc; ++i) {\n switch (argv[i][0]) {\n case '-' :\n switch (argv[i][1]) {\n case 'p' :\n if (++i == argc) { valid = false; return; }\n prec = std::atoi(argv[i]); break;\n default :\n valid = false; return;\n }\n break;\n default :\n switch (argc - i) {\n case 1:\n Ja = Jb = Jc = \"1\";\n Tmin = Tmax = dT = argv[i];\n return;\n case 2:\n Ja = Jb = Jc = argv[i];\n Tmin = Tmax = dT = argv[i+1];\n return;\n case 4:\n Ja = argv[i];\n Jb = argv[i+1];\n Jc = argv[i+2];\n Tmin = Tmax = dT = argv[i+3];\n return;\n case 6:\n Ja = argv[i];\n Jb = argv[i+1];\n Jc = argv[i+2];\n Tmin = argv[i+3];\n Tmax = argv[i+4];\n dT = argv[i+5];\n return;\n default:\n valid = false; return;\n }\n }\n }\n }\n};\n\ntemplate\nvoid calc(const options& opt) {\n using namespace ising::free_energy;\n typedef T real_t;\n real_t Ja = convert(opt.Ja);\n real_t Jb = convert(opt.Jb);\n real_t Jc = convert(opt.Jc);\n real_t Tmin = convert(opt.Tmin);\n real_t Tmax = convert(opt.Tmax);\n real_t dT = convert(opt.dT);\n if (Tmin > Tmax) throw(std::invalid_argument(\"Tmax should be larger than Tmin\"));\n if (dT <= 0) throw(std::invalid_argument(\"dT should be positive\"));\n std::cout << std::scientific << std::setprecision(std::numeric_limits::digits10)\n << \"# lattice: triangular\\n\"\n << \"# precision: \" << std::numeric_limits::digits10 << std::endl\n << \"# Lx Ly Ja Jb Jc T 1/T F/N E/N C/N\\n\";\n for (auto t = Tmin; t < Tmax + 1e-4 * dT; t += dT) {\n auto beta = boost::math::differentiation::make_fvar(1 / t);\n auto f = triangular::infinite(Ja, Jb, Jc, beta);\n std::cout << \"inf inf \" << Ja << ' ' << Jb << ' ' << Jc << ' ' << t << ' ' << (1 / t) << ' '\n << free_energy(f, beta) << ' ' << energy(f, beta) << ' '\n << specific_heat(f, beta) << std::endl;\n }\n}\n\n\nint main(int argc, char **argv) {\n using namespace boost::multiprecision;\n options opt(argc, argv);\n if (!opt.valid) {\n std::cerr << \"Usage: \" << argv[0] << \" [-p prec] T\\n\"\n << \" \" << argv[0] << \" [-p prec] J T\\n\"\n << \" \" << argv[0] << \" [-p prec] Ja Jb Jc T\\n\"\n << \" \" << argv[0] << \" [-p prec] Ja Jb Jc Tmin Tmax dT\\n\"; return 127;\n }\n if (opt.prec <= std::numeric_limits::digits10) {\n calc(opt);\n } else if (opt.prec <= std::numeric_limits::digits10) {\n calc(opt);\n } else if (opt.prec <= std::numeric_limits>::digits10) {\n calc>(opt);\n } else if (opt.prec <= std::numeric_limits>::digits10) {\n calc>(opt);\n } else {\n std::cerr << \"Error: Required precision is too high\\n\"; return 127;\n }\n}\n", "meta": {"hexsha": "28952c1043775de32612f2340b0d373a8c8614be", "size": 4254, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ising/free_energy/triangular.cpp", "max_stars_repo_name": "todo-group/exact", "max_stars_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-27T14:45:49.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T14:45:49.000Z", "max_issues_repo_path": "ising/free_energy/triangular.cpp", "max_issues_repo_name": "todo-group/exact", "max_issues_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-30T14:48:41.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-30T14:48:41.000Z", "max_forks_repo_path": "ising/free_energy/triangular.cpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5853658537, "max_line_length": 96, "alphanum_fraction": 0.5620592384, "num_tokens": 1238, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6582182064111053}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\nstd::random_device rd;\nstd::mt19937 rng(rd());\t\n\nint reed_frost(int n, int s0, double Q, double beta, double alpha, double k)\n{\n\tstd::binomial_distribution outside(s0,1-Q);\n\n\tdouble gamma_mean = beta/pow(n,alpha);\n\tdouble gamma_shape = k;\n\tstd::gamma_distribution hazard(gamma_shape,\n\t\tgamma_mean/gamma_shape);\n\n\tint infected = outside(rd);\n\tint total_infected = infected;\n\tint susceptibles = s0-total_infected;\n\n\twhile(infected!=0)\n\t{\n\t\tdouble cum_hazard=0.;\n\t\tfor (int i = 0; i < infected; ++i)\n\t\t{\n\t\t\tdouble h = hazard(rd);\n\t\t\tcum_hazard += h;\n\t\t}\n\t\tdouble trans_prob = std::exp(-cum_hazard);\n\t\tstd::binomial_distribution next_gen(susceptibles,1-trans_prob);\n\t\tinfected = next_gen(rd);\n\t\ttotal_infected += infected;\n\t\tsusceptibles -= infected;\n\t}\n\treturn total_infected;\n}\n\nint single_household(int n,std::vector ¶ms)\n{\n\n\t/* Les paramètres sont dans l'ordre (cf Fraser et al. 2011) :\n\n\t- La proba d'échappement Q\n\t- La proba d'infection asymptomatique et infectieuse p_asx\n\t- La proba d'infection asymptomatique et non-infectieuse p_r\n\t- La proba d'échappement à une infection antérieure Q_prior\n\t- Hétérogénéité des infectivités k\n\t- Facteur de taille du domicile beta\n\t- Exposant de la taille du domicile alpha\n\n\t*/\n\n\tstd::binomial_distribution protection(n,params[2]);\n\n\tint prot = protection(rd);\n\tint susceptibles = n-prot;\n\n\tint prev_infected = reed_frost(n,susceptibles,params[3],params[5],params\n\t\t[6],params[4]);\n\n\tsusceptibles -= prev_infected;\n\n\tint new_infected = reed_frost(n,susceptibles,params[0],params[5],params\n\t\t[6],params[4]);\n\n\tstd::binomial_distribution asympt(new_infected,params[1]);\n\tint asymptomatics = asympt(rd);\n\tint symptomatics = new_infected - asymptomatics;\n\treturn symptomatics;\n}\n\n\nint main(int argc, char const *argv[])\n{\n\n\tstd::vector test_params { 0.8,0,0,0.88,0.94,0.37,0.35 } ;\n\tstd::vector params=test_params;\n\n\tstd::vector test_numbers {244,1126,1342,1378,1017,680,434,\n\t 284,117,74,25,23,5,3,0,0,1 };\n\n\tint max_n = test_numbers.size();\n\n\tEigen::MatrixXi table(max_n+1,max_n);\n\n\tfor (int n = 0; n < max_n; ++n)\n\t{\n\t\tstd::vector symptomatics;\n\t\tint num_households = test_numbers[n];\n\t\tfor (int i = 0; i < num_households; ++i)\n\t\t{\n\t\t\tint infected = single_household(n+1,params);\n\t\t\tsymptomatics.push_back(infected);\n\t\t}\n\n\t\tfor (int m = 0; m <= n+1; ++m)\n\t\t{\n\t\t\tint occurrences = std::count(symptomatics.begin(),\n\t\t\t\tsymptomatics.end(),m);\n\t\t\ttable(m,n) = occurrences;\n\t\t}\n\t}\n\n\tstd::cout << table << std::endl;\n\n\tstd::ofstream outfile(\"sim_matrix.txt\");\n\toutfile << table;\n\n\treturn 0;\n}", "meta": {"hexsha": "fe39a7c9628513ecb41de44998d7e65e2a7515ef", "size": 2711, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/fraser_model_optim/simulator.cpp", "max_stars_repo_name": "phoscheit/reed_frost", "max_stars_repo_head_hexsha": "17555bb1808c5068047f28f431882a389215517a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/fraser_model_optim/simulator.cpp", "max_issues_repo_name": "phoscheit/reed_frost", "max_issues_repo_head_hexsha": "17555bb1808c5068047f28f431882a389215517a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/fraser_model_optim/simulator.cpp", "max_forks_repo_name": "phoscheit/reed_frost", "max_forks_repo_head_hexsha": "17555bb1808c5068047f28f431882a389215517a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9911504425, "max_line_length": 76, "alphanum_fraction": 0.7001106603, "num_tokens": 841, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.658203561255796}} {"text": "#include \n#include \nusing namespace boost::multiprecision;\nusing namespace std;\ntypedef long long ll;\ntypedef vector vi;\n#define mod 10000000000000007\n\ncpp_int pow(ll b, ll p){\n cpp_int res = 1, a = b;\n while(p){\n if(p & 1){\n res = (res * a) % mod;\n }\n a = (a * a) % mod;\n a %= mod;\n p >>= 1;\n }\n return res;\n}\n\nint main(){\n ios_base::sync_with_stdio(false);\n cin.tie(nullptr);\n freopen(\"in.txt\", \"r\", stdin);\n freopen(\"out.txt\", \"w\", stdout);\n int tc; cin >> tc;\n ll n, m, p, q;\n while(tc--){\n cin >> p >> q;\n n = (p*q)/2;\n m = p*q - n;\n cout << (pow(n, m-1)*pow(m, n-1)) % mod << \"\\n\";\n }\n return 0;\n}", "meta": {"hexsha": "b9f9ae09d69e808380391ca8a4f26c5702fbcf13", "size": 772, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/Gridland Airports.cpp", "max_stars_repo_name": "satvik007/uva", "max_stars_repo_head_hexsha": "72a763f7ed46a34abfcf23891300d68581adeb44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2017-08-12T06:09:39.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-16T02:31:27.000Z", "max_issues_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/Gridland Airports.cpp", "max_issues_repo_name": "satvik007/uva", "max_issues_repo_head_hexsha": "72a763f7ed46a34abfcf23891300d68581adeb44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Rare Topics/Rare Algorithms/Formulas or Theorems/Gridland Airports.cpp", "max_forks_repo_name": "satvik007/uva", "max_forks_repo_head_hexsha": "72a763f7ed46a34abfcf23891300d68581adeb44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.4444444444, "max_line_length": 56, "alphanum_fraction": 0.4948186528, "num_tokens": 242, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418283357703, "lm_q2_score": 0.7122321781307374, "lm_q1q2_score": 0.6582035472973077}} {"text": "/**\n * @file\n * @copyright This code is licensed under the 3-clause BSD license.\\n\n * Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\\n\n * See LICENSE.txt for details.\n */\n#include \"Properties.h\"\n#include \"Utils/Geometry/AtomCollection.h\"\n#include \"Utils/Geometry/ElementInfo.h\"\n#include \n\nnamespace Scine {\nnamespace Utils {\nnamespace Geometry {\nnamespace Properties {\n\nstd::vector getMasses(const ElementTypeCollection& elements) {\n std::vector masses;\n masses.reserve(elements.size());\n std::transform(elements.begin(), elements.end(), std::back_inserter(masses), ElementInfo::mass);\n return masses;\n}\n\nPosition getCenterOfMass(const PositionCollection& positions, const std::vector& masses) {\n Position P;\n P.setZero();\n double totalMass = 0;\n for (int i = 0; i < positions.rows(); ++i) {\n P += masses[i] * positions.row(i);\n totalMass += masses[i];\n }\n P /= totalMass;\n return P;\n}\n\nPosition getCenterOfMass(const AtomCollection& structure) {\n auto masses = getMasses(structure.getElements());\n return getCenterOfMass(structure.getPositions(), masses);\n}\n\nPosition getAveragePosition(const PositionCollection& positions) {\n return positions.colwise().sum() / positions.rows();\n}\n\nEigen::Matrix3d calculateInertiaTensor(const PositionCollection& positions, const std::vector& masses,\n const Position& centerOfMass) {\n double Ixx = 0, Iyy = 0, Izz = 0, Ixy = 0, Ixz = 0, Iyz = 0;\n for (int i = 0; i < positions.rows(); ++i) {\n double m = masses[i];\n auto dp = positions.row(i) - centerOfMass;\n double x = dp.x();\n double y = dp.y();\n double z = dp.z();\n Ixx += m * (y * y + z * z);\n Iyy += m * (x * x + z * z);\n Izz += m * (x * x + y * y);\n Ixy -= m * x * y;\n Ixz -= m * x * z;\n Iyz -= m * y * z;\n }\n Eigen::Matrix3d In;\n In << Ixx, Ixy, Ixz, Ixy, Iyy, Iyz, Ixz, Iyz, Izz;\n return In;\n}\n\nPrincipalMomentsOfInertia calculatePrincipalMoments(const PositionCollection& positions,\n const std::vector& masses, const Position& centerOfMass) {\n auto In = calculateInertiaTensor(positions, masses, centerOfMass);\n\n Eigen::SelfAdjointEigenSolver es;\n es.compute(In);\n\n PrincipalMomentsOfInertia pmi;\n pmi.eigenvalues = es.eigenvalues();\n pmi.eigenvectors = es.eigenvectors();\n return pmi;\n}\n\nbool operator==(const PositionCollection& lhs, const PositionCollection& rhs) {\n return lhs.isApprox(rhs);\n}\n\nbool operator!=(const PositionCollection& lhs, const PositionCollection& rhs) {\n return !(lhs == rhs);\n}\n\n} /* namespace Properties */\n} /* namespace Geometry */\n} /* namespace Utils */\n} /* namespace Scine */\n", "meta": {"hexsha": "46e22a717a0ae39946de367a600085bd0d644892", "size": 2783, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Utils/Utils/Geometry/Utilities/Properties.cpp", "max_stars_repo_name": "qcscine/utilities", "max_stars_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Utils/Utils/Geometry/Utilities/Properties.cpp", "max_issues_repo_name": "qcscine/utilities", "max_issues_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-06-19T14:34:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T15:07:18.000Z", "max_forks_repo_path": "src/Utils/Utils/Geometry/Utilities/Properties.cpp", "max_forks_repo_name": "qcscine/utilities", "max_forks_repo_head_hexsha": "493b8db45772b231bc0296535a09905b8e292f77", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-06-14T16:44:19.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-19T20:48:19.000Z", "avg_line_length": 30.5824175824, "max_line_length": 118, "alphanum_fraction": 0.6550485088, "num_tokens": 730, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240756264638, "lm_q2_score": 0.7606506418255928, "lm_q1q2_score": 0.658133248448225}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace boost::numeric::ublas;\n\nint main()\n{\n\tstd::cout << \"\\nVector\" << std::endl;\n\t// basic Vector Usage\n\tvector v(3);\n\tfor (unsigned i = 0; i < v.size(); ++ i)\n\t{\n\t\tv(i) = i;\n\t}\n\tstd::cout << \"vector \\t\\t\" << v << std::endl;\n\n\t// unit_vector\n\tfor (int i = 0; i < 3; ++ i) \n\t{\n\t\tunit_vector v_unit(3, i);\n\t\tstd::cout << \"unit_vector \\t\" << v_unit << std::endl;\n\t}\n\n\t// zero_vector\n\tzero_vector v_zero(3);\n\tstd::cout << \"zero_vector \\t\" << v_zero << std::endl;\n\n\t// scalr_vector\n\tscalar_vector v_scalar(3,100);\n\tstd::cout << \"scalar_vector \\t\" << v_scalar << std::endl;\n\n\tstd::cout << \"\\nMatrix\" << std::endl;\n\t// basic matrix\n\tmatrix m(3, 3);\n\tfor (unsigned i = 0; i < m.size1 (); ++ i)\n\t{\n\t\tfor (unsigned j = 0; j < m.size2 (); ++ j)\n\t\t{\n\t\t\tm(i, j) = 3 * i + j;\n\t\t}\n\t}\n\tstd::cout << \"matrix \\t\\t\" << m << std::endl;\n\n\t// identity matrix\n\tidentity_matrix m_identity(3);\n std::cout << \"eye matrix\\t\" << m_identity << std::endl;\n\n // zero matrix\n zero_matrix m_zero(3, 3);\n std::cout << \"zero matrix\\t\" << m_zero << std::endl;\n\n // scalar matrix\n scalar_matrix m_scalar(3, 3, 100);\n std::cout << \"scalar matrix\\t\" << m_scalar << std::endl;\n\n // lower and upper triangular matrix\n triangular_matrix ml(3, 3);\n for (unsigned i = 0; i < ml.size1 (); ++ i)\n for (unsigned j = 0; j <= i; ++ j)\n ml(i, j) = 3 * i + j;\n std::cout << \"lower triangular matrix\\t\" << ml << std::endl;\n\n triangular_matrix mu(3, 3);\n for (unsigned i = 0; i < mu.size1 (); ++ i)\n for (unsigned j = i; j < mu.size2 (); ++ j)\n mu(i, j) = 3 * i + j;\n std::cout << \"upper triangular matrix\\t\" << mu << std::endl;\n\n // lower and upper symmetric matrix\n symmetric_matrix ml_symm(3, 3);\n for (unsigned i = 0; i < ml_symm.size1 (); ++ i)\n for (unsigned j = 0; j <= i; ++ j)\n ml_symm(i, j) = 3 * i + j;\n std::cout << \"lower symmetric matrix\\t\" << ml_symm << std::endl;\n\n symmetric_matrix mu_symm(3, 3);\n for (unsigned i = 0; i < mu_symm.size1 (); ++ i)\n for (unsigned j = i; j < mu_symm.size2 (); ++ j)\n mu_symm(i, j) = 3 * i + j;\n std::cout << \"upper symmetric matrix\\t\" << mu_symm << std::endl;\n\n // banded matrix\n banded_matrix m_banded (3, 3, 1, 1);\n for (signed i = 0; i < signed (m_banded.size1 ()); ++ i)\n for (signed j = std::max (i - 1, 0); j < std::min (i + 2, signed (m_banded.size2 ())); ++ j)\n m_banded (i, j) = 3 * i + j;\n std::cout << \"banded matrix\\t\" << m_banded << std::endl;\n\treturn 0;\n}", "meta": {"hexsha": "8905f7750eb12b6bdcba75bae87187110c1815ad", "size": 2928, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "yoon-gu/la-table", "max_stars_repo_head_hexsha": "fa4a783b87a6486c26f4867a39e6f7400e5d9443", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "yoon-gu/la-table", "max_issues_repo_head_hexsha": "fa4a783b87a6486c26f4867a39e6f7400e5d9443", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "yoon-gu/la-table", "max_forks_repo_head_hexsha": "fa4a783b87a6486c26f4867a39e6f7400e5d9443", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4838709677, "max_line_length": 100, "alphanum_fraction": 0.5642076503, "num_tokens": 981, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513759047848, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6579556308493133}} {"text": "// This file implements the Levenberg-Marquardt method\n// for pose projection matrix refinement\n#include \"marker.hpp\"\n#include \n#include \n#include \n#include \n\n#define ERROR_EPS 0.001\n#define MAX_ITER 10\n\n/////////////////////////////////////////////////////////////////\n// objective: min(sum(p - K M q)^2)\n// where\n// K: 3x3 matrix\n// M: 3x4 matrix\n// q: 4x1 vector (obj points)\n// p: 3x1 vector (img points)\n// variable: M\n/////////////////////////////////////////////////////////////////\n// let's say an update of delta on M\n// brings us closer to local minimum\n// S = sum(p - K M q - J delta)^2\n// where\n// J: gradient of function (K M q) with respect to M\n// take derivative of S with respect to delta and set to zero:\n// (J^T J) delta = J^T (p - K M q)\n// which is replaced to: (by Levenberg)\n// (J^T J + lambda I) delta = J^T (p - K M q)\n// where\n// lambda: a damping factor adjusted each iteration\n// finally, to make solution scale invariant:\n// (J^T J + lambda diag(J^T J)) delta = J^T (p - K M q)\n/////////////////////////////////////////////////////////////////\n\n// refer to: https://github.com/opencv/opencv/blob/master/modules/calib3d/src/compat_ptsetreg.cpp#L121\n// refer to book \"Augmented Reality: Principles and Practice\"\n// refer to: https://en.wikipedia.org/wiki/Levenberg%E2%80%93Marquardt_algorithm\n// refine pose matrix\nvoid Marker::refinePoseM(\n const glm::mat3& cameraInvK,\n const std::vector& objPoints,\n const std::vector& imgPoints\n)\n{\n if(objPoints.size() < 4 || imgPoints.size() < 4)\n return;\n // camera matrix in eigen\n Eigen::Matrix3f Kinv;\n Kinv << cameraInvK[0][0], cameraInvK[1][0], cameraInvK[2][0],\n cameraInvK[0][1], cameraInvK[1][1], cameraInvK[2][1],\n cameraInvK[0][2], cameraInvK[1][2], cameraInvK[2][2];\n // pose matrix\n Eigen::Matrix M;\n M << _poseM[0][0], _poseM[1][0], _poseM[2][0], _poseM[3][0],\n _poseM[0][1], _poseM[1][1], _poseM[2][1], _poseM[3][1],\n _poseM[0][2], _poseM[1][2], _poseM[2][2], _poseM[3][2];\n Eigen::Matrix Mshaped = Eigen::MatrixXf::Constant(3, 4, 0.0f);\n // point matrix\n Eigen::Matrix4f objMatrix;\n objMatrix << objPoints[0].x, objPoints[1].x, objPoints[2].x, objPoints[3].x,\n objPoints[0].y, objPoints[1].y, objPoints[2].y, objPoints[3].y,\n 0.0f, 0.0f, 0.0f, 0.0f,\n 1.0f, 1.0f, 1.0f, 1.0f;\n Eigen::Matrix imgMatrix;\n imgMatrix << imgPoints[0].x, imgPoints[1].x, imgPoints[2].x, imgPoints[3].x,\n imgPoints[0].y, imgPoints[1].y, imgPoints[2].y, imgPoints[3].y,\n 0.0f, 0.0f, 0.0f, 0.0f;\n // here we are minimizing sum(K^-1 p - M q)^2\n // if K M q = p, then M q = K^-1 p\n imgMatrix = Kinv * imgMatrix;\n // Jacobian\n // mxn matrix\n // m: number of points\n // n: number of parameters\n Eigen::Matrix J = Eigen::MatrixXf::Constant(12, 12, 0.0f);\n // initialize Jacobian\n for(int i = 0; i < 4; i++)\n {\n // J(i+0, Eigen::seqN(0, 4)) = objMatrix.col(i);\n // J(i+4, Eigen::seqN(4, 4)) = objMatrix.col(i);\n // J(i+8, Eigen::seqN(8, 4)) = objMatrix.col(i);\n J(i*3+0, Eigen::seqN(0, 4)) = objMatrix.col(i);\n J(i*3+1, Eigen::seqN(4, 4)) = objMatrix.col(i);\n J(i*3+2, Eigen::seqN(8, 4)) = objMatrix.col(i);\n }\n Eigen::Matrix JT = J.transpose();\n Eigen::Matrix JTJ = JT * J;\n Eigen::Matrix JTJdiag = Eigen::MatrixXf::Constant(12, 12, 0.0f);\n JTJdiag.diagonal() += JTJ.diagonal();\n // delta matrix\n Eigen::Vector delta = Eigen::VectorXf::Constant(12, 0.0f);\n // left and right hand side of equation\n Eigen::Matrix eqLeft;\n Eigen::Vector eqRight;\n // damping factor (same as OpenCV)\n // lambda = 1.0 + exp(lambdaLog10 * log10val)\n const float log10val = std::log(10.0f);\n int lambdaLog10 = -3;\n // start iteration\n int iter = 0;\n float err = std::numeric_limits::max();\n float prevErr = std::numeric_limits::max();\n while(iter++ < MAX_ITER)\n {\n float lambda = 1.0f + std::exp(lambdaLog10 * log10val);\n // (J^T J + lambda diag(J^T J)) delta = J^T (p - K M q)\n eqLeft = JTJ + lambda * JTJdiag;\n Mshaped = imgMatrix - M * objMatrix;\n Eigen::Map flatten(Mshaped.data(), Mshaped.size());\n eqRight = JT * flatten;\n delta = eqLeft.colPivHouseholderQr().solve(eqRight);\n // update M\n M.row(0) += delta(Eigen::seqN(0, 4));\n M.row(1) += delta(Eigen::seqN(4, 4));\n M.row(2) += delta(Eigen::seqN(8, 4));\n // compute error\n prevErr = err;\n err = 0.0f;\n Eigen::Matrix residual = imgMatrix - M * objMatrix;\n Eigen::Map residualVec(residual.data(), residual.size());\n for(int i = 0; i < 12; i++)\n err += residualVec[i] * residualVec[i];\n // std::cout << iter << \",\" << lambdaLog10 << \"|\" << err << std::endl;\n if(err <= ERROR_EPS) break;\n if(err > prevErr)\n {\n lambdaLog10 = std::min(lambdaLog10+1, 16);\n err = std::numeric_limits::max();\n continue;\n }\n // update lambda\n lambdaLog10 = std::max(lambdaLog10-1, -16);\n }\n _err_LM = err;\n // std::cout << \"LM err: \" << err << \"(\" << iter << \")\" << std::endl;\n // record new M and interpolate\n if(_poseMRefined[3][2] == 0.0f)\n {\n _poseMRefined = glm::mat4x3(\n glm::vec3(M.col(0)[0], M.col(0)[1], M.col(0)[2]),\n glm::vec3(M.col(1)[0], M.col(1)[1], M.col(1)[2]),\n glm::vec3(M.col(2)[0], M.col(2)[1], M.col(2)[2]),\n glm::vec3(M.col(3)[0], M.col(3)[1], M.col(3)[2])\n );\n }\n else\n {\n _poseMRefined = _poseM_interpolate * _poseMRefined +\n (1.0f - _poseM_interpolate) * glm::mat4x3(\n glm::vec3(M.col(0)[0], M.col(0)[1], M.col(0)[2]),\n glm::vec3(M.col(1)[0], M.col(1)[1], M.col(1)[2]),\n glm::vec3(M.col(2)[0], M.col(2)[1], M.col(2)[2]),\n glm::vec3(M.col(3)[0], M.col(3)[1], M.col(3)[2])\n );\n }\n}", "meta": {"hexsha": "e68ca7247a107bbb962ad9a6908f1f959480f358", "size": 6408, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PC/src/markerLM.cpp", "max_stars_repo_name": "teamclouday/Marker", "max_stars_repo_head_hexsha": "3dc0e48db1a2c297d7962dd6280078e57409b2cb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PC/src/markerLM.cpp", "max_issues_repo_name": "teamclouday/Marker", "max_issues_repo_head_hexsha": "3dc0e48db1a2c297d7962dd6280078e57409b2cb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PC/src/markerLM.cpp", "max_forks_repo_name": "teamclouday/Marker", "max_forks_repo_head_hexsha": "3dc0e48db1a2c297d7962dd6280078e57409b2cb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8152866242, "max_line_length": 102, "alphanum_fraction": 0.5349563046, "num_tokens": 2155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587817066392, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6578364642562851}} {"text": "/*************************************************************************\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 \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define SIM_TIME 50.0\n#define DT 0.1\n#define PI 3.141592653\n\n\n// x_{t+1} = F@x_{t}+B@u_t\nEigen::Vector4f motion_model(Eigen::Vector4f x, Eigen::Vector2f u){\n Eigen::Matrix4f F_;\n F_<<1.0, 0, 0, 0,\n 0, 1.0, 0, 0,\n 0, 0, 1.0, 0,\n 0, 0, 0, 1.0;\n\n Eigen::Matrix B_;\n B_<< DT * std::cos(x(2,0)), 0,\n DT * std::sin(x(2,0)), 0,\n 0.0, DT,\n 1.0, 0.0;\n\n return F_ * x + B_ * u;\n};\n\nEigen::Matrix4f jacobF(Eigen::Vector4f x, Eigen::Vector2f u){\n Eigen::Matrix4f jF_ = Eigen::Matrix4f::Identity();\n float yaw = x(2);\n float v = u(0);\n jF_(0,2) = -DT * v * std::sin(yaw);\n jF_(0,3) = DT * std::cos(yaw);\n jF_(1,2) = DT * v * std::cos(yaw);\n jF_(1,3) = DT * std::sin(yaw);\n return jF_;\n};\n\n//observation mode H\nEigen::Vector2f observation_model(Eigen::Vector4f x){\n Eigen::Matrix H_;\n H_<< 1, 0, 0, 0,\n 0, 1, 0, 0;\n return H_ * x;\n};\n\nEigen::Matrix jacobH(){\n Eigen::Matrix jH_;\n jH_<< 1, 0, 0, 0,\n 0, 1, 0, 0;\n return jH_;\n};\n\nvoid ekf_estimation(Eigen::Vector4f& xEst, Eigen::Matrix4f& PEst,\n Eigen::Vector2f z, Eigen::Vector2f u,\n Eigen::Matrix4f Q, Eigen::Matrix2f R){\n Eigen::Vector4f xPred = motion_model(xEst, u);\n Eigen::Matrix4f jF = jacobF(xPred, u);\n Eigen::Matrix4f PPred = jF * PEst * jF.transpose() + Q;\n\n Eigen::Matrix jH = jacobH();\n Eigen::Vector2f zPred = observation_model(xPred);\n Eigen::Vector2f y = z - zPred;\n Eigen::Matrix2f S = jH * PPred * jH.transpose() + R;\n Eigen::Matrix K = PPred * jH.transpose() * S.inverse();\n xEst = xPred + K * y;\n PEst = (Eigen::Matrix4f::Identity() - K * jH) * PPred;\n};\n\ncv::Point2i cv_offset(\n Eigen::Vector2f e_p, int image_width=2000, int image_height=2000){\n cv::Point2i output;\n output.x = int(e_p(0) * 100) + image_width/2;\n output.y = image_height - int(e_p(1) * 100) - image_height/3;\n return output;\n};\n\nvoid ellipse_drawing(\n cv::Mat bg_img, Eigen::Matrix2f pest, Eigen::Vector2f center,\n cv::Scalar ellipse_color=cv::Scalar(0, 0, 255)\n){\n Eigen::EigenSolver ces(pest);\n Eigen::Matrix2f e_value = ces.pseudoEigenvalueMatrix();\n Eigen::Matrix2f e_vector = ces.pseudoEigenvectors();\n\n double angle = std::atan2(e_vector(0, 1), e_vector(0, 0));\n cv::ellipse(\n bg_img,\n cv_offset(center, bg_img.cols, bg_img.rows),\n cv::Size(e_value(0,0)*1000, e_value(1,1)*1000),\n angle / PI * 180,\n 0,\n 360,\n ellipse_color,\n 2,\n 4);\n};\n\nint main(){\n float time=0.0;\n\n // control input\n Eigen::Vector2f u;\n u<<1.0, 0.1;\n\n // nosie control input\n Eigen::Vector2f ud;\n\n // observation z\n Eigen::Vector2f z;\n\n // dead reckoning\n Eigen::Vector4f xDR;\n xDR<<0.0,0.0,0.0,0.0;\n\n // ground truth reading\n Eigen::Vector4f xTrue;\n xTrue<<0.0,0.0,0.0,0.0;\n\n // Estimation\n Eigen::Vector4f xEst;\n xEst<<0.0,0.0,0.0,0.0;\n\n std::vector hxDR;\n std::vector hxTrue;\n std::vector hxEst;\n std::vector hz;\n\n Eigen::Matrix4f PEst = Eigen::Matrix4f::Identity();\n\n // Motional model covariance\n Eigen::Matrix4f Q = Eigen::Matrix4f::Identity();\n Q(0,0)=0.1 * 0.1;\n Q(1,1)=0.1 * 0.1;\n Q(2,2)=(1.0/180 * M_PI) * (1.0/180 * M_PI);\n Q(3,3)=0.1 * 0.1;\n\n // Observation model covariance\n Eigen::Matrix2f R = Eigen::Matrix2f::Identity();\n R(0,0)=1.0;\n R(1,1)=1.0;\n\n // Motion model simulation error\n Eigen::Matrix2f Qsim = Eigen::Matrix2f::Identity();\n Qsim(0,0)=1.0;\n Qsim(1,1)=(30.0/180 * M_PI) * (30.0/180 * M_PI);\n\n // Observation model simulation error\n Eigen::Matrix2f Rsim = Eigen::Matrix2f::Identity();\n Rsim(0,0)=0.5 * 0.5;\n Rsim(1,1)=0.5 * 0.5;\n\n std::random_device rd{};\n std::mt19937 gen{rd()};\n std::normal_distribution<> gaussian_d{0,1};\n\n //for visualization\n cv::namedWindow(\"ekf\", cv::WINDOW_NORMAL);\n int count = 0;\n\n while(time <= SIM_TIME){\n time += DT;\n\n ud(0) = u(0) + gaussian_d(gen) * Qsim(0,0);\n ud(1) = u(1) + gaussian_d(gen) * Qsim(1,1);\n\n xTrue = motion_model(xTrue, u);\n xDR = motion_model(xDR, ud);\n\n z(0) = xTrue(0) + gaussian_d(gen) * Rsim(0,0);\n z(1) = xTrue(1) + gaussian_d(gen) * Rsim(1,1);\n\n ekf_estimation(xEst, PEst, z, ud, Q, R);\n\n hxDR.push_back(xDR);\n hxTrue.push_back(xTrue);\n hxEst.push_back(xEst);\n hz.push_back(z);\n\n //visualization\n cv::Mat bg(3500,3500, CV_8UC3, cv::Scalar(255,255,255));\n for(unsigned int j=0; j\n#include \n\nusing Eigen::MatrixXd;\n\ntypedef Eigen::Matrix MyMatrix33f;\ntypedef Eigen::Matrix MyVector3f;\ntypedef Eigen::Matrix MyMatrix;\n\n\n\nint main() {\n //Definitions\n MyMatrix33f a;\n MyVector3f v;\n MyMatrix mym(10, 15);\n MatrixXd m(2, 2);\n\n // Initializations\n a = MyMatrix33f::Zero(); \n a = MyMatrix33f::Identity(); \n v = MyVector3f::Random();\n\n // Assignments\n m(0,0) = 3;\n m(1,0) = 2.5;\n m(0,1) = -1;\n m(1,1) = m(1,0) + m(0,1);\n a << 1,2,3,\n 4,5,6,\n 7,8,9;\n\n // Output\n std::cout << m << std::endl;\n\n // Mapping (shallow copy)\n int data[] = {1, 2, 3, 4};\n Eigen::Map r(data, 4);\n std::vector data2 = {1,2,3,4,5,6,8,9};\n Eigen::Map n(data2.data());\n\n // Math\n // what are the types?\n auto x = Eigen::Matrix2d::Random();\n auto y = Eigen::Matrix2d::Random();\n auto res = x + y;\n auto res2 = x.array() * y.array(); // element wise multiplication\n // x = y + x;\n auto res3 = x.array() / y.array();\n //x += y;\n //r = x * y; // matrix multi\n auto res4 = x.array() * 3;\n\n}\n", "meta": {"hexsha": "0f0a84ff40715e872a7d9476dcb0cd1fe5bfeec4", "size": 1154, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "app/linear_algebra/main.cpp", "max_stars_repo_name": "weberdaniel/ml", "max_stars_repo_head_hexsha": "714249d52578cffd6c8e5f08904a84f179dc1090", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app/linear_algebra/main.cpp", "max_issues_repo_name": "weberdaniel/ml", "max_issues_repo_head_hexsha": "714249d52578cffd6c8e5f08904a84f179dc1090", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2022-01-06T18:34:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-15T22:57:31.000Z", "max_forks_repo_path": "app/linear_algebra/main.cpp", "max_forks_repo_name": "weberdaniel/ml", "max_forks_repo_head_hexsha": "714249d52578cffd6c8e5f08904a84f179dc1090", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.9818181818, "max_line_length": 71, "alphanum_fraction": 0.5771230503, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9449947101574298, "lm_q2_score": 0.6959583187272711, "lm_q1q2_score": 0.6576769296873297}} {"text": "/* Copyright (C) 2016-2018 Alibaba Group Holding Limited\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*/\n\n#include \"orthogonal_initializer.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ps-plus/common/types.h\"\n#include \"random/random.h\"\n#include \"random/random_ops.h\"\n#include \"normal_initializer.h\"\n\nusing namespace Eigen; \nusing namespace Eigen::internal; \nusing namespace Eigen::Architecture; \n\nnamespace ps {\nnamespace initializer {\n\nOrthogonalInitializer::OrthogonalInitializer(\n int64_t dim, int seed, float gain)\n : dim_(dim)\n , seed_(seed)\n , gain_(gain) {\n normal_initializer_.reset(new NormalInitializer(seed, 0.0, 1.0));\n}\n\nbool OrthogonalInitializer::Accept(DataType type) {\n if (type == DataType::kFloat || \n type == DataType::kDouble) {\n return true;\n }\n\n return false;\n}\n\nvoid OrthogonalInitializer::Init(void* data, \n DataType type, \n size_t size) {\n if (size % dim_ != 0) {\n printf(\"error size\\n\");\n abort();\n }\n\n normal_initializer_->Init(data, type, size);\n int64_t row = size / dim_;\n int64_t col = dim_;\n if (type == DataType::kFloat) {\n Eigen::Map> m((float*)data, row, col); \n Eigen::JacobiSVD svd(m, Eigen::ComputeThinV | Eigen::ComputeThinU);\n Eigen::MatrixXf u = svd.matrixU() * gain_;\n Eigen::MatrixXf v = svd.matrixV() * gain_; \n if ((row == u.rows() && col == u.cols()) ||\n (row == u.cols() && col == u.rows())) {\n Eigen::MatrixXf trans_u = u.transpose();\n memcpy(data, trans_u.data(), size * sizeof(float));\n } else if ((row == v.rows() && col == v.cols()) ||\n (row == v.cols() && col == v.rows())) {\n memcpy(data, v.data(), size * sizeof(float)); \n } else {\n printf(\"svd result shape[%d,%d|%d,%d] not match\\n\", u.rows(), u.cols(), v.rows(), v.cols());\n abort();\n }\n } else {\n Eigen::Map> m((double*)data, row, col); \n Eigen::JacobiSVD svd(m, Eigen::ComputeThinV | Eigen::ComputeThinU);\n Eigen::MatrixXd u = svd.matrixU() * gain_;\n Eigen::MatrixXd v = svd.matrixV() * gain_;\n if ((row == u.rows() && col == u.cols()) ||\n (row == u.cols() && col == u.rows())) {\n Eigen::MatrixXd trans_u = u.transpose();\n memcpy(data, trans_u.data(), size * sizeof(double));\n } else if ((row == v.rows() && col == v.cols()) ||\n (row == v.cols() && col == v.rows())) {\n memcpy(data, v.data(), size * sizeof(double)); \n } else {\n printf(\"svd result shape[%d,%d|%d,%d] not match\\n\", u.rows(), u.cols(), v.rows(), v.cols());\n abort();\n }\n }\n}\n\nInitializer* OrthogonalInitializer::Clone() {\n return new OrthogonalInitializer(\n dim_, seed_, gain_);\n}\n\n} //namespace initializer\n} //ps\n\n", "meta": {"hexsha": "957587ccff02ee9ebd9da11339348c156ba68057", "size": 3589, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xdl/ps-plus/ps-plus/common/initializer/orthogonal_initializer.cpp", "max_stars_repo_name": "Ru-Xiang/x-deeplearning", "max_stars_repo_head_hexsha": "04cc0497150920c64b06bb8c314ef89977a3427a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4071.0, "max_stars_repo_stars_event_min_datetime": "2018-12-13T04:17:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T03:29:35.000Z", "max_issues_repo_path": "xdl/ps-plus/ps-plus/common/initializer/orthogonal_initializer.cpp", "max_issues_repo_name": "laozhuang727/x-deeplearning", "max_issues_repo_head_hexsha": "781545783a4e2bbbda48fc64318fb2c6d8bbb3cc", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 359.0, "max_issues_repo_issues_event_min_datetime": "2018-12-21T01:14:57.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T07:18:02.000Z", "max_forks_repo_path": "xdl/ps-plus/ps-plus/common/initializer/orthogonal_initializer.cpp", "max_forks_repo_name": "laozhuang727/x-deeplearning", "max_forks_repo_head_hexsha": "781545783a4e2bbbda48fc64318fb2c6d8bbb3cc", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1054.0, "max_forks_repo_forks_event_min_datetime": "2018-12-20T09:57:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T07:16:53.000Z", "avg_line_length": 33.2314814815, "max_line_length": 120, "alphanum_fraction": 0.6057397604, "num_tokens": 906, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797027760038, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.657637765648437}} {"text": "#include \r\n#include \"partitionlist.hpp\"\r\n\r\nusing namespace Eigen;\r\n\r\n\r\ntemplate \r\nclass AssemblyOp : public EigenBase< AssemblyOp > {\r\n\tprivate:\r\n\t\tconst MatrixXd& A;\r\n\t\tconst MatrixXd& B;\r\n\t\tconst PartitionList& states;\r\n\r\n\tpublic:\r\n\t\t// eigen boilerplate\r\n\t\ttypedef double Scalar;\r\n\t\ttypedef double RealScalar;\r\n\t\ttypedef int StorageIndex;\r\n\t\tenum {\r\n\t\t\tColsAtCompileTime = Eigen::Dynamic,\r\n\t\t\tMaxColsAtCompileTime = Eigen::Dynamic,\r\n\t\t\tIsRowMajor = true\r\n\t\t};\r\n\t\tIndex rows() const { return states.size(); }\r\n\t\tIndex cols() const { return states.size(); }\r\n\t\ttemplate \r\n\t\tProduct< AssemblyOp, Rhs, AliasFreeProduct > operator*(const Eigen::MatrixBase& x) const {\r\n\t\t\treturn Product< AssemblyOp, Rhs, AliasFreeProduct >(*this, x.derived()); \r\n\t\t}\r\n\r\n\r\n\r\n\t\tAssemblyOp() {}\r\n\t\tAssemblyOp(const PartitionList& states_, const MatrixXd& A_, const MatrixXd& B_) : states(states_), A(A_), B(B_) {}\r\n\t\t//VectorXd operator*(const VectorXd& x) const { return this->apply(x); }\r\n\r\n\t\tVectorXd apply(const VectorXd& x) const {\r\n\t\t\tVectorXd b = VectorXd::Zero(x.size());\r\n\r\n\t\t\tuint index = 0, nbrIndex, n, m, len = (*(states.cbegin())).getLength();\r\n\t\t\tPartition nbr;\r\n\r\n\t\t\tfor (const auto& state : states) {\r\n\t\t\t\tfor (size_t i = 1; i <= len; i++) { // size to react with\r\n\t\t\t\t\tn = state.get(i);\r\n\t\t\t\t\tif (n == 0) // make sure we can react\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (size_t j = 1; j <= i-1; j++) {\r\n\t\t\t\t\t\t// fragment\r\n\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\tnbr.increment(j);\r\n\t\t\t\t\t\tnbr.increment(i-j);\r\n\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\tb(index) += B(j-1,i-j-1) * (double) n * (x(index) - x(nbrIndex));\r\n\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tb(index) += A(i-1,j-1) * (double) (n * m) * (x(index) - x(nbrIndex));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tb(index) += A(i-1,j-1) * (double) (n * m) * x(index);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (n > 1) {\r\n\t\t\t\t\t\tif (2*i <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.increment(2*i);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tb(index) += A(i-1,i-1) * (double) (n*(n-1)) * (x(index) - x(nbrIndex));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tb(index) += A(i-1,i-1) * (double) (n*(n-1)) * x(index);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfor (size_t j = i+1; j <= len; j++) {\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tb(index) += A(i-1,j-1) * (double) (n * m) * (x(index) - x(nbrIndex));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\tb(index) += A(i-1,j-1) * (double) (n * m) * x(index);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t++index;\r\n\t\t\t}\r\n\t\t\treturn b;\r\n\t\t}\r\n\r\n\t\tVectorXd adjointApply(const VectorXd& x) const {\r\n\t\t\tVectorXd b = VectorXd::Zero(x.size());\r\n\r\n\t\t\tuint index = 0, nbrIndex, n, m, len = (*(states.cbegin())).getLength();\r\n\t\t\tPartition nbr;\r\n\t\t\tdouble rate;\r\n\r\n\t\t\tfor (const auto& state : states) {\r\n\t\t\t\tfor (size_t i = 1; i <= len; i++) { // size to react with\r\n\t\t\t\t\tn = state.get(i);\r\n\t\t\t\t\tif (n == 0) // make sure we can react\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (size_t j = 1; j <= i-1; j++) {\r\n\t\t\t\t\t\t// fragment\r\n\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\tnbr.increment(j);\r\n\t\t\t\t\t\tnbr.increment(i-j);\r\n\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\trate = B(j-1,i-j-1) * (double) n * x(index);\r\n\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\tb(nbrIndex) -= rate;\r\n\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\trate = A(i-1,j-1) * (double) (n * m) * x(index);\r\n\t\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\t\tb(nbrIndex) -= rate;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\trate = A(i-1,j-1) * (double) (n * m) * x(index);\r\n\t\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (n > 1) {\r\n\t\t\t\t\t\tif (2*i <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.increment(2*i);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\trate = A(i-1,i-1) * (double) (n*(n-1)) * x(index);\r\n\t\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\t\tb(nbrIndex) -= rate;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\trate = A(i-1,i-1) * (double) (n*(n-1)) * x(index);\r\n\t\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfor (size_t j = i+1; j <= len; j++) {\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\trate = A(i-1,j-1) * (double) (n * m) * x(index);\r\n\t\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\t\tb(nbrIndex) -= rate;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\trate = A(i-1,j-1) * (double) (n * m) * x(index);\r\n\t\t\t\t\t\t\tb(index) += rate;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t++index;\r\n\t\t\t}\r\n\t\t\treturn b;\r\n\t\t}\r\n/*\r\n\t\tMatrix split_apply(const VectorXd& x) const {\r\n\t\t\tMatrix b(x.size(),4);\r\n\t\t\tb.setConstant(0.0);\r\n\t\t\t\r\n\t\t\tuint index = 0, nbrIndex, n, m, len = (*(states.cbegin())).getLength();\r\n\t\t\tPartition nbr;\r\n\r\n\t\t\tdouble rate = 0.0;\r\n\t\t\tfor (const auto& state : states) {\r\n\t\t\t\tfor (size_t i = 1; i <= len; i++) { // size to react with\r\n\t\t\t\t\tn = state.get(i);\r\n\t\t\t\t\tif (n == 0) // make sure we can react\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (size_t j = 1; j <= i-1; j++) {\r\n\t\t\t\t\t\t// fragment\r\n\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\tnbr.increment(j);\r\n\t\t\t\t\t\tnbr.increment(i-j);\r\n\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\r\n\t\t\t\t\t\trate = B(j-1,i-j-1) * (double) n;\r\n\t\t\t\t\t\tb(index,0) -= rate * x(nbrIndex);\r\n\t\t\t\t\t\tb(index,1) += rate * x(index);\r\n\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\trate = A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t\tb(index,2) += rate * x(index);\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tb(index,3) -= rate * x(nbrIndex);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (n > 1) {\r\n\t\t\t\t\t\trate = A(i-1,i-1) * (double) (n*(n-1));\r\n\t\t\t\t\t\tb(index,2) += rate * x(index);\r\n\t\t\t\t\t\tif (2*i <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.increment(2*i);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tb(index,3) -= rate * x(nbrIndex);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfor (size_t j = i+1; j <= len; j++) {\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\trate = A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t\tb(index,2) += rate * x(index);\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tb(index,3) -= rate * x(nbrIndex);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\t++index;\r\n\t\t\t}\r\n\t\t\treturn b;\r\n\t\t}*/\r\n\r\n\t\tVectorXd solve_diagonal(const VectorXd& b) const {\r\n\t\t\tVectorXd x = b;\r\n\r\n\t\t\tuint index = 0, nbrIndex, n, m, len = (*(states.cbegin())).getLength();\r\n\t\t\tPartition nbr;\r\n\t\t\tdouble currentRate, totalRate = 0.0;\r\n\r\n\t\t\tfor (const auto& state : states) {\r\n\t\t\t\tfor (size_t i = 1; i <= len; i++) { // size to react with\r\n\t\t\t\t\tn = state.get(i);\r\n\t\t\t\t\tif (n == 0) // make sure we can react\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (size_t j = 1; j <= i-1; j++) {\r\n\t\t\t\t\t\t// fragment\r\n\t\t\t\t\t\ttotalRate += B(j-1,i-j-1) * (double) n;\r\n\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\ttotalRate += A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\ttotalRate += A(i-1,i-1) * (double) (n*(n-1));\r\n\r\n\t\t\t\t\tfor (size_t j = i+1; j <= len; j++) {\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\ttotalRate += A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tx(index) /= totalRate;\r\n\t\t\t\t++index;\r\n\t\t\t}\r\n\t\t\treturn x;\r\n\t\t}\r\n\r\n\r\n\r\n\t\tVectorXd solve_lower(const VectorXd& b, double omega) const {\r\n\t\t\tVectorXd x = b;\r\n\r\n\t\t\tuint index = 0, nbrIndex, n, m, len = (*(states.cbegin())).getLength();\r\n\t\t\tPartition nbr;\r\n\t\t\tdouble currentRate, totalRate;\r\n\r\n\t\t\tfor (const auto& state : states) {\r\n\t\t\t\ttotalRate = 0.0;\r\n\t\t\t\tfor (size_t i = 1; i <= len; i++) { // size to react with\r\n\t\t\t\t\tn = state.get(i);\r\n\t\t\t\t\tif (n == 0) // make sure we can react\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (size_t j = 1; j <= i-1; j++) {\r\n\t\t\t\t\t\t// fragment\r\n\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\tnbr.increment(j);\r\n\t\t\t\t\t\tnbr.increment(i-j);\r\n\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\tcurrentRate = B(j-1,i-j-1) * (double) n;\r\n\t\t\t\t\t\ttotalRate += currentRate;\r\n\t\t\t\t\t\tx(index) += currentRate * x(nbrIndex);\r\n\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\ttotalRate += A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\ttotalRate += A(i-1,i-1) * (double) (n*(n-1));\r\n\r\n\t\t\t\t\tfor (size_t j = i+1; j <= len; j++) {\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\ttotalRate += A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tx(index) /= totalRate/omega;\r\n\t\t\t\t++index;\r\n\t\t\t}\r\n\t\t\treturn x;\r\n\t\t}\r\n\r\n\t\tVectorXd solve_upper(const VectorXd& b, double omega) const {\r\n\t\t\tVectorXd x = b;\r\n\r\n\t\t\tuint index = 0, nbrIndex, n, m, len = (*(states.cbegin())).getLength();\r\n\t\t\tPartition nbr;\r\n\t\t\tdouble currentRate, totalRate;\r\n\r\n\t\t\tindex = states.size();\r\n\t\t\tauto stateit = states.end();\r\n\t\t\twhile (index-->0) {\r\n\t\t\t\t--stateit;\r\n\r\n\t\t\t\tauto state = *stateit;\r\n\t\t\t\ttotalRate = 0.0;\r\n\t\t\t\tfor (size_t i = 1; i <= len; i++) { // size to react with\r\n\t\t\t\t\tn = state.get(i);\r\n\t\t\t\t\tif (n == 0) // make sure we can react\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (size_t j = 1; j <= i-1; j++) {\r\n\t\t\t\t\t\t// fragment\r\n\t\t\t\t\t\ttotalRate += B(j-1,i-j-1) * (double) n;\r\n\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tcurrentRate = A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t\ttotalRate += currentRate;\r\n\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tx(index) += currentRate * x(nbrIndex);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (n > 1) {\r\n\t\t\t\t\t\tcurrentRate = A(i-1,i-1) * (double) (n*(n-1));\r\n\t\t\t\t\t\ttotalRate += currentRate;\r\n\t\t\t\t\t\tif (2*i <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.increment(2*i);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tx(index) += currentRate * x(nbrIndex);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tfor (size_t j = i+1; j <= len; j++) {\r\n\t\t\t\t\t\t// aggregate\r\n\t\t\t\t\t\tm = state.get(j);\r\n\t\t\t\t\t\tif (m == 0)\r\n\t\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\t\tcurrentRate = A(i-1,j-1) * (double) (n * m);\r\n\t\t\t\t\t\ttotalRate += currentRate;\r\n\t\t\t\t\t\tif (i+j <= len) {\r\n\t\t\t\t\t\t\tnbr = state;\r\n\t\t\t\t\t\t\tnbr.decrement(i);\r\n\t\t\t\t\t\t\tnbr.decrement(j);\r\n\t\t\t\t\t\t\tnbr.increment(i+j);\r\n\t\t\t\t\t\t\tnbrIndex = states.indexOf(nbr);\r\n\t\t\t\t\t\t\tx(index) += currentRate * x(nbrIndex);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tx(index) /= totalRate/omega;\r\n\t\t\t}\r\n\t\t\treturn x;\r\n\t\t}\r\n};\r\n\r\n\r\n\r\nnamespace Eigen {\r\nnamespace internal {\r\n template\r\n struct traits< AssemblyOp > : public Eigen::internal::traits > {};\r\n}\r\n}\r\n\r\n\r\n\r\n\r\n\r\n// Implementation of MatrixReplacement * Eigen::DenseVector though a specialization of internal::generic_product_impl:\r\nnamespace Eigen {\r\nnamespace internal {\r\n template\r\n struct generic_product_impl, Rhs, SparseShape, DenseShape, GemvProduct> // GEMV stands for matrix-vector\r\n : generic_product_impl_base,Rhs,generic_product_impl,Rhs> >\r\n {\r\n typedef typename Product,Rhs>::Scalar Scalar;\r\n template\r\n static void scaleAndAddTo(Dest& dst, const AssemblyOp& lhs, const Rhs& rhs, const Scalar& alpha)\r\n {\r\n // This method should implement \"dst += alpha * lhs * rhs\" inplace,\r\n // however, for iterative solvers, alpha is always equal to 1, so let's not bother about it.\r\n assert(alpha==Scalar(1) && \"scaling is not implemented\");\r\n // Here we could simply call dst.noalias() += lhs.my_matrix() * rhs,\r\n // but let's do something fancier (and less efficient):\r\n dst.noalias() += lhs.apply(rhs.matrix());\r\n }\r\n };\r\n}\r\n}\r\n", "meta": {"hexsha": "48470bb31211f9110df72c231cdee6999a01f05e", "size": 12414, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "moment-solver/src/assemblyop.hpp", "max_stars_repo_name": "jasondark/dissertation", "max_stars_repo_head_hexsha": "3e1117ef0d14aa8d659f80df3edde1c266815856", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "moment-solver/src/assemblyop.hpp", "max_issues_repo_name": "jasondark/dissertation", "max_issues_repo_head_hexsha": "3e1117ef0d14aa8d659f80df3edde1c266815856", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "moment-solver/src/assemblyop.hpp", "max_forks_repo_name": "jasondark/dissertation", "max_forks_repo_head_hexsha": "3e1117ef0d14aa8d659f80df3edde1c266815856", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-03-18T01:05:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-18T01:05:58.000Z", "avg_line_length": 26.0798319328, "max_line_length": 124, "alphanum_fraction": 0.4992750121, "num_tokens": 3804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7217431943271999, "lm_q1q2_score": 0.65763774580606}} {"text": "#include \n#include \n#include \n#include \n\nusing std::vector;\n\n\ndouble interest(double rate, int years)\n{\n return pow(1 + rate, years);\n}\n\ndouble compound(double rate, int compound_amount, int years)\n{\n double acutal_rate = rate / compound_amount;\n double result = pow(1 + acutal_rate, years * compound_amount);\n return result;\n}\n\ndouble continous_compound(double rate, int years)\n{\n double rT = rate * years;\n return pow(M_E, rT);\n}\n\ndouble annuity(vectorpayments_per_year)\n{\n double increase = 0;\n for (auto&& amount : payments_per_year) {\n increase += amount;\n }\n return increase;\n}\n\n\nBOOST_PYTHON_MODULE(finance_formulas)\n{\n using namespace boost::python;\n class_ >(\"double_vector\")\n .def(vector_indexing_suite >() );\n def(\"interest\", interest);\n def(\"compound\", compound);\n def(\"continous_compound\", continous_compound);\n def(\"annuity\", annuity);\n}\n", "meta": {"hexsha": "ea45439bc52aa03e327999d8b42ed533f9dfb9b1", "size": 1048, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "formulas/finance_formulas.cpp", "max_stars_repo_name": "banjocat/finance-fun", "max_stars_repo_head_hexsha": "3b57b20d01db14971feff265a5e004de39b20cc2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "formulas/finance_formulas.cpp", "max_issues_repo_name": "banjocat/finance-fun", "max_issues_repo_head_hexsha": "3b57b20d01db14971feff265a5e004de39b20cc2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "formulas/finance_formulas.cpp", "max_forks_repo_name": "banjocat/finance-fun", "max_forks_repo_head_hexsha": "3b57b20d01db14971feff265a5e004de39b20cc2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.2978723404, "max_line_length": 66, "alphanum_fraction": 0.6870229008, "num_tokens": 252, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521253, "lm_q2_score": 0.7217431943271998, "lm_q1q2_score": 0.6576377458060599}} {"text": "// Deal.ii\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n// STL\n#include \n#include \n#include \n#include \n\n\nnamespace Helmholtz\n{\n using namespace dealii;\n\n ///////////////////////////////////////////////////////\n ///////////////////////////////////////////////////////\n\n template \n class Solution : public Function\n {\n public:\n virtual double value(const Point & p,\n const unsigned int component = 0) const override;\n\n virtual Tensor<1, dim>\n gradient(const Point & p,\n const unsigned int component = 0) const override;\n };\n\n\n template \n double Solution::value(const Point &p, const unsigned int) const\n {\n double return_value = 1;\n\n for (unsigned int i = 0; i\n Tensor<1, 1> Solution<1>::gradient(const Point<1> &p,\n const unsigned int) const\n {\n Tensor<1, 1> return_value;\n\n\treturn_value[0] = - 2 * numbers::PI * sin(2*numbers::PI*p(0));\n\n return return_value;\n }\n\n\n template <>\n Tensor<1, 2> Solution<2>::gradient(const Point<2> &p,\n const unsigned int) const\n {\n Tensor<1, 2> return_value;\n\n\treturn_value[0] = - 2 * numbers::PI * sin(2*numbers::PI*p(0)) * cos(2*numbers::PI*p(1));\n\treturn_value[1] = - 2 * numbers::PI * cos(2*numbers::PI*p(0)) * sin(2*numbers::PI*p(1));\n\n return return_value;\n }\n\n\n template <>\n Tensor<1, 3> Solution<3>::gradient(const Point<3> &p,\n const unsigned int) const\n {\n Tensor<1, 3> return_value;\n\n return_value[0] = - 2 * numbers::PI * sin(2*numbers::PI*p(0)) * cos(2*numbers::PI*p(1)) * cos(2*numbers::PI*p(2));\n return_value[1] = - 2 * numbers::PI * cos(2*numbers::PI*p(0)) * sin(2*numbers::PI*p(1)) * cos(2*numbers::PI*p(2));\n return_value[2] = - 2 * numbers::PI * cos(2*numbers::PI*p(0)) * cos(2*numbers::PI*p(1)) * sin(2*numbers::PI*p(2));\n\n return return_value;\n }\n\n\n ///////////////////////////////////////////////////////\n ///////////////////////////////////////////////////////\n\n\n template \n class RightHandSide : public Function\n {\n public:\n virtual double value(const Point & p,\n const unsigned int component = 0) const override;\n };\n\n\n template \n double RightHandSide::value(const Point &p,\n const unsigned int) const\n {\n double return_value = (1 + 4 * dim * std::pow(numbers::PI,2));\n\n for (unsigned int i = 0; i\n class HelmholtzSolver\n {\n public:\n HelmholtzSolver(const FiniteElement &fe);\n\n ~HelmholtzSolver();\n\n void run();\n\n private:\n void setup_system();\n void assemble_system();\n void solve();\n void process_solution(const unsigned int cycle);\n void output_vtk(const unsigned int cycle);\n\n Triangulation triangulation;\n DoFHandler dof_handler;\n\n SmartPointer> fe;\n\n AffineConstraints constraints;\n\n SparsityPattern sparsity_pattern;\n SparseMatrix system_matrix;\n\n Vector solution;\n Vector system_rhs;\n\n ConvergenceTable convergence_table;\n };\n\n\n template \n HelmholtzSolver::HelmholtzSolver(const FiniteElement &fe)\n : dof_handler(triangulation)\n , fe(&fe)\n {}\n\n\n template \n HelmholtzSolver::~HelmholtzSolver()\n {\n dof_handler.clear();\n }\n\n\n template \n void HelmholtzSolver::setup_system()\n {\n dof_handler.distribute_dofs(*fe);\n DoFRenumbering::Cuthill_McKee(dof_handler);\n\n constraints.clear();\n DoFTools::make_hanging_node_constraints(dof_handler,\n constraints);\n\n Solution\texact_solution;\n\n VectorTools::interpolate_boundary_values(dof_handler,\n 0,\n exact_solution,\n constraints);\n\n constraints.close();\n\n DynamicSparsityPattern dsp(dof_handler.n_dofs(), dof_handler.n_dofs());\n DoFTools::make_sparsity_pattern(dof_handler, dsp);\n constraints.condense(dsp);\n sparsity_pattern.copy_from(dsp);\n\n system_matrix.reinit(sparsity_pattern);\n\n solution.reinit(dof_handler.n_dofs());\n system_rhs.reinit(dof_handler.n_dofs());\n }\n\n\n template \n void HelmholtzSolver::assemble_system()\n {\n QGauss quadrature_formula(fe->degree + 1);\n\n const unsigned int n_q_points = quadrature_formula.size();\n\n const unsigned int dofs_per_cell = fe->dofs_per_cell;\n\n FullMatrix cell_matrix(dofs_per_cell, dofs_per_cell);\n Vector cell_rhs(dofs_per_cell);\n\n std::vector local_dof_indices(dofs_per_cell);\n\n FEValues fe_values(*fe,\n quadrature_formula,\n update_values | update_gradients |\n update_quadrature_points | update_JxW_values);\n\n RightHandSide right_hand_side;\n std::vector rhs_values(n_q_points);\n\n for (const auto &cell : dof_handler.active_cell_iterators())\n {\n cell_matrix = 0.;\n cell_rhs = 0.;\n\n fe_values.reinit(cell);\n\n right_hand_side.value_list(fe_values.get_quadrature_points(),\n rhs_values);\n\n for (unsigned int q_point = 0; q_point < n_q_points; ++q_point)\n for (unsigned int i = 0; i < dofs_per_cell; ++i)\n {\n for (unsigned int j = 0; j < dofs_per_cell; ++j)\n cell_matrix(i, j) +=\n ((fe_values.shape_grad(i, q_point) * // grad phi_i(x_q)\n fe_values.shape_grad(j, q_point) // grad phi_j(x_q)\n + //\n fe_values.shape_value(i, q_point) * // phi_i(x_q)\n fe_values.shape_value(j, q_point)) * // phi_j(x_q)\n fe_values.JxW(q_point)); // dx\n\n\n cell_rhs(i) += (fe_values.shape_value(i, q_point) * // phi_i(x_q)\n rhs_values[q_point] * // f(x_q)\n fe_values.JxW(q_point)); // dx\n }\n\n cell->get_dof_indices(local_dof_indices);\n constraints.distribute_local_to_global(\n cell_matrix, cell_rhs, local_dof_indices, system_matrix, system_rhs);\n }\n }\n\n\n template \n void HelmholtzSolver::solve()\n {\n SolverControl solver_control(1000, 1e-12);\n SolverCG<> cg(solver_control);\n\n PreconditionSSOR<> preconditioner;\n preconditioner.initialize(system_matrix, 1.2);\n\n cg.solve(system_matrix, solution, system_rhs, preconditioner);\n\n std::cout << \" \" << solver_control.last_step()\n << \" CG iterations needed to obtain convergence.\" << std::endl;\n\n constraints.distribute(solution);\n }\n\n\n template \n void HelmholtzSolver::process_solution(const unsigned int cycle)\n {\n\tSolution exact_solution;\n\n Vector difference_per_cell(triangulation.n_active_cells());\n VectorTools::integrate_difference(dof_handler,\n solution,\n exact_solution,\n difference_per_cell,\n QGauss(fe->degree + 1),\n VectorTools::L2_norm);\n const double L2_error =\n VectorTools::compute_global_error(triangulation,\n difference_per_cell,\n VectorTools::L2_norm);\n\n\n VectorTools::integrate_difference(dof_handler,\n solution,\n Solution(),\n difference_per_cell,\n QGauss(fe->degree + 1),\n VectorTools::H1_seminorm);\n const double H1_error =\n VectorTools::compute_global_error(triangulation,\n difference_per_cell,\n VectorTools::H1_seminorm);\n\n\n const unsigned int n_active_cells = triangulation.n_active_cells();\n const unsigned int n_dofs = dof_handler.n_dofs();\n\n std::cout << \"Cycle \" << cycle << ':' << std::endl\n << \" Number of active cells: \" << n_active_cells\n << std::endl\n << \" Number of degrees of freedom: \" << n_dofs << std::endl;\n\n convergence_table.add_value(\"cycle\", cycle);\n convergence_table.add_value(\"cells\", n_active_cells);\n convergence_table.add_value(\"dofs\", n_dofs);\n convergence_table.add_value(\"L2\", L2_error);\n convergence_table.add_value(\"H1\", H1_error);\n }\n\n\n template \n void HelmholtzSolver::output_vtk(const unsigned int cycle)\n {\n\tstd::string vtk_filename\n\t\t= \"solution-\" + Utilities::int_to_string(dim,1) + \"D\";\n\n\tswitch (fe->degree)\n\t {\n\t\tcase 1:\n\t\t vtk_filename += \"_q1\";\n\t\t break;\n\t\tcase 2:\n\t\t vtk_filename += \"_q2\";\n\t\t break;\n\t\tdefault:\n\t\t Assert(false, ExcNotImplemented());\n\t }\n\n\tvtk_filename += \"_cycle-\" + Utilities::int_to_string(cycle,1);\n\tvtk_filename += \".vtk\";\n\n\tstd::ofstream output(vtk_filename);\n\n\tDataOut data_out;\n\tdata_out.attach_dof_handler(dof_handler);\n\tdata_out.add_data_vector(solution, \"solution\");\n\n\tdata_out.build_patches(fe->degree);\n\tdata_out.write_vtk(output);\n}\n\n\n template \n void HelmholtzSolver::run()\n {\n\n const unsigned int n_cycles = 6;\n\n for (unsigned int cycle = 0; cycle < n_cycles; ++cycle)\n {\n if (cycle == 0)\n {\n GridGenerator::hyper_cube(triangulation, 0, 1);\n triangulation.refine_global(1);\n }\n else\n \ttriangulation.refine_global();\n\n setup_system();\n\n assemble_system();\n solve();\n\n process_solution(cycle);\n\n output_vtk(cycle);\n }\n\n\n convergence_table.set_precision(\"L2\", 3);\n convergence_table.set_precision(\"H1\", 3);\n\n convergence_table.set_scientific(\"L2\", true);\n convergence_table.set_scientific(\"H1\", true);\n\n convergence_table.set_tex_caption(\"cells\", \"\\\\# cells\");\n convergence_table.set_tex_caption(\"dofs\", \"\\\\# dofs\");\n convergence_table.set_tex_caption(\"L2\", \"$L^2$-error\");\n convergence_table.set_tex_caption(\"H1\", \"$H^1$-error\");\n\n convergence_table.set_tex_format(\"cells\", \"r\");\n convergence_table.set_tex_format(\"dofs\", \"r\");\n\n std::cout << std::endl;\n convergence_table.write_text(std::cout);\n\n // Write table into a LaTeX file.\n std::string error_filename\n\t\t= \"error-\" + Utilities::int_to_string(dim,1) + \"D\";\n\n switch (fe->degree)\n {\n case 1:\n error_filename += \"_q1\";\n break;\n case 2:\n error_filename += \"_q2\";\n break;\n default:\n Assert(false, ExcNotImplemented());\n }\n\n error_filename += \".tex\";\n std::ofstream error_table_file(error_filename);\n\n convergence_table.write_tex(error_table_file);\n\n /////////////////\n\n\tconvergence_table.add_column_to_supercolumn(\"cycle\", \"n cells\");\n\tconvergence_table.add_column_to_supercolumn(\"cells\", \"n cells\");\n\n\tstd::vector new_order;\n\tnew_order.emplace_back(\"n cells\");\n\tnew_order.emplace_back(\"H1\");\n\tnew_order.emplace_back(\"L2\");\n\tconvergence_table.set_column_order(new_order);\n\n\tconvergence_table.evaluate_convergence_rates(\n\t \"L2\", ConvergenceTable::reduction_rate);\n\tconvergence_table.evaluate_convergence_rates(\n\t \"L2\", ConvergenceTable::reduction_rate_log2);\n\tconvergence_table.evaluate_convergence_rates(\n\t \"H1\", ConvergenceTable::reduction_rate);\n\tconvergence_table.evaluate_convergence_rates(\n\t \"H1\", ConvergenceTable::reduction_rate_log2);\n\n\tstd::cout << std::endl;\n\tconvergence_table.write_text(std::cout);\n\n\tstd::string conv_filename\n\t\t= \"convergence-\" + Utilities::int_to_string(dim,1) + \"D\";\n\n\tswitch (fe->degree)\n\t {\n\t\tcase 1:\n\t\t conv_filename += \"_q1\";\n\t\t break;\n\t\tcase 2:\n\t\t conv_filename += \"_q2\";\n\t\t break;\n\t\tdefault:\n\t\t Assert(false, ExcNotImplemented());\n\t }\n\tconv_filename += \".tex\";\n\n\tstd::ofstream table_file(conv_filename);\n\tconvergence_table.write_tex(table_file);\n }\n\n} // namespace Helmholtz\n\n\n ///////////////////////////////////////////\n ///////////////////////////////////////////\n ///////////////////////////////////////////\n\n\nint main()\n{\n const unsigned int dim = 1;\n\n try\n {\n using namespace dealii;\n\n {\n std::cout << \"Solving with Q1 elements in \" << dim << \"D\" << std::endl\n << std::endl\n << \"==============================\"\n << std::endl\n << std::endl;\n\n FE_Q fe(1);\n Helmholtz::HelmholtzSolver helmholtz_problem_2d(fe);\n\n helmholtz_problem_2d.run();\n\n std::cout << std::endl;\n }\n\n {\n std::cout << \"Solving with Q2 elements in \" << dim << \"D\" << std::endl\n << \"==============================\" << std::endl\n << std::endl;\n\n FE_Q fe(2);\n Helmholtz::HelmholtzSolver helmholtz_problem_2d(fe);\n\n helmholtz_problem_2d.run();\n\n std::cout << std::endl;\n }\n }\n catch (std::exception &exc)\n {\n std::cerr << std::endl\n << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n std::cerr << \"Exception on processing: \" << std::endl\n << exc.what() << std::endl\n << \"Aborting!\" << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n return 1;\n }\n catch (...)\n {\n std::cerr << std::endl\n << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n std::cerr << \"Unknown exception!\" << std::endl\n << \"Aborting!\" << std::endl\n << \"----------------------------------------------------\"\n << std::endl;\n return 1;\n }\n\n return 0;\n}\n", "meta": {"hexsha": "6e0291a83520e1bfeee5cc3958a26cb68af49a87", "size": 15786, "ext": "cc", "lang": "C++", "max_stars_repo_path": "helmholtz.cc", "max_stars_repo_name": "konsim83/Demo_Dealii", "max_stars_repo_head_hexsha": "14cd7c53d1771cd14e26d58bfda16463b1712797", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-09T10:10:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-09T10:10:47.000Z", "max_issues_repo_path": "helmholtz.cc", "max_issues_repo_name": "konsim83/Demo_Dealii", "max_issues_repo_head_hexsha": "14cd7c53d1771cd14e26d58bfda16463b1712797", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "helmholtz.cc", "max_forks_repo_name": "konsim83/Demo_Dealii", "max_forks_repo_head_hexsha": "14cd7c53d1771cd14e26d58bfda16463b1712797", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.3920863309, "max_line_length": 120, "alphanum_fraction": 0.5591030027, "num_tokens": 3736, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942145139149, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6575760113049395}} {"text": "#ifndef _EIGEN_SPACE_\n#define _EIGEN_SPACE_ 1\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"naive_bayes.cpp\"\n\n#define _l_ std::cout<<__LINE__<& p,\n const std::pair& q) {\n\n return p.first < q.first;\n}\n\nEigen::MatrixXd\nGetSortedEigenvectors(const Eigen::MatrixXd& matrix) {\n Eigen::EigenSolver eigenSolver;\n eigenSolver.compute(matrix, true);\n\n std::vector> sortedEigenvectors;\n for (unsigned i = 0; i < eigenSolver.eigenvalues().size(); ++i) {\n if (eigenSolver.eigenvalues().imag()(i) == 0) {\n sortedEigenvectors.push_back(\n {\n eigenSolver.eigenvalues().real()(i),\n eigenSolver.eigenvectors().col(i).real()\n }\n );\n }\n }\n std::sort(sortedEigenvectors.begin(), sortedEigenvectors.end(), EigenvectorCompare);\n\n Eigen::MatrixXd rowMatrixOfSortedEigenvectors;\n rowMatrixOfSortedEigenvectors.resizeLike(matrix);\n\n for (unsigned i = 0; i < matrix.cols(); ++i) {\n\tif (sortedEigenvectors[i].second.rows() == rowMatrixOfSortedEigenvectors.rows()) {\t\n \t rowMatrixOfSortedEigenvectors.col(i) = sortedEigenvectors[i].second;\n\t} else {\n\t\trowMatrixOfSortedEigenvectors.col(i).setZero();\n\t}\n }\n\n return rowMatrixOfSortedEigenvectors.transpose();\n}\n\n\nReducedDimClassInfo\nComputeClassInfoInPcaDimensionReducedSpace(\n const std::vector& data,\n const ClassInfo& cartesianClassInfo,\n const unsigned reducedDimensionality) {\n\n // create the space transformation matrix\n unsigned originalDimensionality = cartesianClassInfo.mean.size();\n Eigen::MatrixXd eigenspaceTransformMatrix(\n reducedDimensionality,\n originalDimensionality\n );\n\n eigenspaceTransformMatrix =\n (GetSortedEigenvectors(cartesianClassInfo.covariance)).topLeftCorner(\n reducedDimensionality,\n originalDimensionality\n );\n\n // transform all of the data to the new space\n std::vector reducedData;\n reducedData.reserve(data.size());\n for (unsigned i = 0; i < data.size(); ++i) {\n ClassificationObject temp;\n temp.label = data[i].label;\n\n temp.features.resize(reducedDimensionality);\n temp.features = eigenspaceTransformMatrix * data[i].features;\n\n reducedData.push_back(temp);\n }\n\n // compute the new class info\n ReducedDimClassInfo info;\n info.longMean = cartesianClassInfo.mean;\n info.transformationMatrix = eigenspaceTransformMatrix;\n info.ci = ComputeClassInfo(\n reducedData,\n cartesianClassInfo.label,\n reducedDimensionality\n );\n\n return info;\n}\n\nunsigned\nPcaClassifyObject(const ClassificationObject& object, const std::vector& classSummaries) {\n unsigned mostLikelyClass = classSummaries.front().ci.label;\n double highestProbability = 0.0;\n\n for (const ReducedDimClassInfo& classSummary : classSummaries) {\n Eigen::VectorXd scaledFeatureVector = object.features - classSummary.longMean;\n Eigen::VectorXd reducedFeatureVector = classSummary.transformationMatrix * scaledFeatureVector;\n double probability = GaussianPdf(reducedFeatureVector, classSummary.ci) * classSummary.ci.prior;\n if (probability > highestProbability) {\n mostLikelyClass = classSummary.ci.label;\n highestProbability = probability;\n }\n }\n\nstd::cout<\n#include \n#include \n#include \n#include \n#include \n\n\nusing namespace Upp;\n\n\nvoid TestMooring(bool test) {\n\tUppLog() << \"\\n\\nCatenary mooring demo\";\n\t\n\tdouble rho_m = 346.7;\t\t// Kg/m \n\tdouble rho_m3 = 7850;\n\tdouble rho_water = 1025;\n\t\n\tdouble BL = 1.49E9;\t\t\t// Mooring line break load\n\tdouble moorlen = 490;\n\t\n\tdouble xanchorvessel = 480;\t\n\tdouble zanchor = 0;\n\tdouble zvessel = 54;\n\n\tdouble Fhanchorvessel, Fvanchor, Fvvessel, xonfloor;\n\tVector x, z;\n\tMooringStatus status;\n\t\n\tCatenary(moorlen, xanchorvessel, zanchor, zvessel, xonfloor);\n\n\tdouble moorlen2;\n\tCatenaryGetLen(xonfloor, xanchorvessel, zanchor, zvessel, moorlen2);\n\tVERIFY(EqualDecimals(moorlen, moorlen2, 4));\n\n\tCatenaryGetLen(0.1*xanchorvessel, xanchorvessel, 0, zvessel, moorlen2);\n\tVERIFY(EqualDecimals(484.4677, moorlen2, 4));\n\tCatenaryGetLen(0.15*xanchorvessel, xanchorvessel, 0, zvessel, moorlen2);\n\tVERIFY(EqualDecimals(484.7264, moorlen2, 4));\n\tCatenaryGetLen(0.2*xanchorvessel, xanchorvessel, 0, zvessel, moorlen2);\n\tVERIFY(EqualDecimals(485.0166, moorlen2, 4));\n\tCatenaryGetLen(0.25*xanchorvessel, xanchorvessel, 0, zvessel, moorlen2);\n\tVERIFY(EqualDecimals(485.3445, moorlen2, 4));\n\tCatenaryGetLen(0.3*xanchorvessel, xanchorvessel, 0, zvessel, moorlen2);\n\tVERIFY(EqualDecimals(485.7176, moorlen2, 4));\n\t\n\tstatus = Catenary(rho_m, rho_m3, rho_water, moorlen, BL, xanchorvessel, zanchor, zvessel, Fhanchorvessel, Fvanchor, Fvvessel, xonfloor, x, z, 10);\n\tUppLog() << \"\\nStatus is: \" << MooringStatusStr(status);\n\tVERIFY(status == CATENARY_ON_FLOOR);\n\tVERIFY(EqualDecimals(xonfloor, 292.5933, 4));\n\tVERIFY(EqualDecimals(Fhanchorvessel, 987138.9765, 4));\n\tVERIFY(EqualDecimals(Fvvessel, 583737.6409, 4));\n\t\n\tdouble Fanchor = sqrt(sqr(Fhanchorvessel) + sqr(Fvanchor));\n\tdouble anganchor = atan2(Fvanchor, Fhanchorvessel)*180./M_PI;\n\tdouble Fvessel = sqrt(sqr(Fhanchorvessel) + sqr(Fvvessel));\n\tdouble angvessel = atan2(Fvvessel, Fhanchorvessel)*180./M_PI;\n\tUppLog() << Format(\"\\nFhanchorvessel=%.2f, Fvanchor=%.2f, Fanchor=%.2f, ang_anchor=%.1f grad\\nFvvessel=%.2f, Fvessel=%.2f, ang_vessel=%.1f, xonfloor=%.1f\", \n\t\tFhanchorvessel, -Fvanchor, Fanchor, anganchor, -Fvvessel, Fvessel, angvessel, xonfloor);\n\tVERIFY(FormatF(angvessel, 4) == \"30.5976\");\n\t\t\n\tUppLog() << \"\\nX\\tY\";\n\tfor (int i = 0; i < x.size(); ++i) \n\t\tUppLog() << Format(\"\\n%.2f\\t%.4f\", x[i], z[i]);\n\tVERIFY(FormatF(z[7], 4) == \"9.8116\");\n\t\n\tif (!test) {\n\t\tint num = 100;\n\t\tVector> xx(5), zz(5);\n\t\tString dir = AppendFileNameX(GetDesktopFolder(), \"STEM4U_Demo\");\n\t\tRealizeDirectory(dir);\n\t\tScatterDraw scatter;\n\t\tscatter.SetLabelX(\"Distance from anchor to vessel [m]\").\n\t\t\t\tSetLabelY(\"Height from floor to vessel [m]\").\n\t\t\t\tSetLeftMargin(70).SetBottomMargin(50).SetSize(Size(1000, 400)).\n\t\t\t\tSetLegendAnchor(ScatterDraw::LEFT_TOP);\n\t\t{\n\t\t\tscatter.RemoveAllSeries().SetTitle(\"Shifting the vessel to the anchor\");\n\t\t\tfor (int iz = 0; iz < 5; ++iz) {\n\t\t\t\tCatenary(rho_m, rho_m3, rho_water, moorlen, BL, \n\t\t\t\t\txanchorvessel-iz*15, zanchor, zvessel, Fhanchorvessel, Fvanchor, Fvvessel, \n\t\t\t\t\txonfloor, xx[iz], zz[iz], num);\n\t\t\t\tString legend = Format(\"Xanchorvessel:%.0f, Fx:%.0f, Fzanchor:%.0f, Fzvessel:%.0f, xonfloor:%.1f\", \n\t\t\t\t\t\txanchorvessel-iz*15, Fhanchorvessel/1000., Fvanchor/1000., Fvvessel/1000., xonfloor);\n\t\t\t\tscatter.AddSeries(xx[iz], zz[iz]).Legend(legend).NoMark();\n\t\t\t\tscatter.AddSeries(&zz[iz][0], 1, xx[iz][0], 0).NoSeriesLegend().MarkStyle().MarkWidth(15);\n\t\t\t\tscatter.AddSeries(&zz[iz].Top(), 1, xx[iz].Top(), 0).NoSeriesLegend().MarkStyle().MarkWidth(15);\n\t\t\t}\n\t\t\tscatter.ZoomToFit(true, true);\n\t\t\tPNGEncoder().SaveFile(AppendFileNameX(dir, \"Moor xanchorvessel.png\"), scatter.GetImage());\n\t\t}\n\t\t{\n\t\t\tscatter.RemoveAllSeries().SetTitle(\"Raising the vessel\");\n\t\t\tfor (int iz = 0; iz < 5; iz++) {\n\t\t\t\tCatenary(rho_m, rho_m3, rho_water, moorlen, BL, \n\t\t\t\t\txanchorvessel, zanchor, zvessel+iz*10, Fhanchorvessel, Fvanchor, Fvvessel, \n\t\t\t\t\txonfloor, xx[iz], zz[iz], num);\n\t\t\t\tString legend = Format(\"Zvessel:%.0f, Fx:%.0f, Fzanchor:%.0f, Fzvessel:%.0f, xonfloor:%.1f\", \n\t\t\t\t\t\tzvessel+iz*10, Fhanchorvessel/1000., Fvanchor/1000., Fvvessel/1000., xonfloor);\n\t\t\t\tscatter.AddSeries(xx[iz], zz[iz]).Legend(legend).NoMark();\n\t\t\t\tscatter.AddSeries(&zz[iz][0], 1, xx[iz][0], 0).NoSeriesLegend().MarkStyle().MarkWidth(15);\n\t\t\t\tscatter.AddSeries(&zz[iz].Top(), 1, xx[iz].Top(), 0).NoSeriesLegend().MarkStyle().MarkWidth(15);\n\t\t\t}\n\t\t\tscatter.ZoomToFit(true, true);\n\t\t\tPNGEncoder().SaveFile(AppendFileNameX(dir, \"Moor zvessel.png\"), scatter.GetImage());\n\t\t}\n\t\t{\n\t\t\tscatter.RemoveAllSeries().SetTitle(\"Raising the anchor\");\n\t\t\tfor (int iz = 0; iz < 5; iz++) {\n\t\t\t\tCatenary(rho_m, rho_m3, rho_water, moorlen, BL, \n\t\t\t\t\txanchorvessel, zanchor+iz*30, zvessel, Fhanchorvessel, Fvanchor, Fvvessel, \n\t\t\t\t\txonfloor, xx[iz], zz[iz], num);\n\t\t\t\tString legend = Format(\"Zanchor:%.0f, Fx:%.0f, Fzanchor:%.0f, Fzvessel:%.0f, xonfloor:%.1f\", \n\t\t\t\t\t\tzanchor+iz*30, Fhanchorvessel/1000., Fvanchor/1000., Fvvessel/1000., xonfloor);\n\t\t\t\tscatter.AddSeries(xx[iz], zz[iz]).Legend(legend).NoMark();\n\t\t\t\tscatter.AddSeries(&zz[iz][0], 1, xx[iz][0], 0).NoSeriesLegend().MarkStyle().MarkWidth(15);\n\t\t\t\tscatter.AddSeries(&zz[iz].Top(), 1, xx[iz].Top(), 0).NoSeriesLegend().MarkStyle().MarkWidth(15);\n\t\t\t}\n\t\t\tscatter.ZoomToFit(true, true);\n\t\t\tPNGEncoder().SaveFile(AppendFileNameX(dir, \"Moor zanchor.png\"), scatter.GetImage());\n\t\t}\n\t}\n}", "meta": {"hexsha": "49e85e940268d9893094f379602a752606abc264", "size": 5688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/STEM4U_demo_test_cl/TestMooring.cpp", "max_stars_repo_name": "anboto/Anboto", "max_stars_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-02-28T12:07:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-14T19:40:45.000Z", "max_issues_repo_path": "examples/STEM4U_demo_test_cl/TestMooring.cpp", "max_issues_repo_name": "anboto/Anboto", "max_issues_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2021-03-20T10:46:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-27T19:50:32.000Z", "max_forks_repo_path": "examples/STEM4U_demo_test_cl/TestMooring.cpp", "max_forks_repo_name": "anboto/Anboto", "max_forks_repo_head_hexsha": "fc40730e87b85bba4d9387724fcece7e98069843", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T09:15:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-20T09:15:18.000Z", "avg_line_length": 45.504, "max_line_length": 157, "alphanum_fraction": 0.6965541491, "num_tokens": 2077, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84594244507642, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6575509494838334}} {"text": "\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nclass FractalRenderer\r\n{\r\npublic:\r\n\tstruct Color\r\n\t{\r\n\t\tColor() {}\r\n\t\tColor(double r, double g, double b) : r(r), g(g), b(b) {}\r\n\t\tdouble r, g, b;\r\n\r\n\t\tColor operator * (double factor)\r\n\t\t{\r\n\t\t\treturn Color(r*factor, g*factor, b*factor);\r\n\t\t}\r\n\r\n\t\tColor operator + (const Color& other)\r\n\t\t{\r\n\t\t\treturn Color(r + other.r, g + other.g, b + other.b);\r\n\t\t}\r\n\t};\r\n\r\n\tstruct Job\r\n\t{\r\n\t\tsize_t y_start;\r\n\t\tsize_t y_count;\r\n\t\tdouble scale;\r\n\t\tstd::complex offset;\r\n\t};\r\n\r\n\tstatic const int max_iterations = 1000;\r\n\tstatic const int max_colors = 50;\r\n\r\n\tFractalRenderer(unsigned char* texture_data, Color* color_ramp, double texture_width, double texture_height)\r\n\t\t: texture_data(texture_data), color_ramp(color_ramp), texture_width(texture_width), texture_height(texture_height), job_done(false), running(true)\r\n\t{\r\n\t}\r\n\r\n\ttypedef boost::lock_guard lock_guard;\r\n\r\n\tvoid setJob(Job new_job)\r\n\t{\r\n\t\tcurrent_job = new_job;\r\n\t\tlock_guard lock(job_mutex);\r\n\t\tjob_done = false;\r\n\t}\r\n\r\n\tbool jobDone()\r\n\t{\r\n\t\tlock_guard lock(job_mutex);\r\n\t\treturn job_done;\r\n\t}\r\n\r\n\tvoid stop()\r\n\t{\r\n\t\tlock_guard lock(running_mutex);\r\n\t\trunning = false;\r\n\t}\r\n\r\n\tvoid operator () ()\r\n\t{\r\n\t\tbool _running;\r\n\r\n\t\tdo\r\n\t\t{\r\n\t\t\tbool done;\r\n\t\t\t{\r\n\t\t\t\tlock_guard lock(job_mutex);\r\n\t\t\t\tdone = job_done;\r\n\t\t\t}\r\n\r\n\t\t\tif (!done)\r\n\t\t\t{\r\n\t\t\t\tfor (size_t _y = current_job.y_start; _y < current_job.y_start + current_job.y_count; ++_y)\r\n\t\t\t\t{\r\n\t\t\t\t\tfor (size_t _x = 0; _x < (size_t)texture_width; ++_x)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tstd::complex c(((double)_x / texture_width) * 2.0 - 1.0,\r\n\t\t\t\t\t\t\t\t\t\t\t ((double)_y / texture_height) * 2.0 - 1.0);\r\n\r\n\t\t\t\t\t\tc *= current_job.scale;\r\n\t\t\t\t\t\tc += current_job.offset;\r\n\r\n\t\t\t\t\t\tstd::complex z(0.0, 0.0);\r\n\r\n\t\t\t\t\t\tdouble q = (z.real() - 1/4)*(z.real() - 1/4) + z.imag()*z.imag();\r\n\t\t\t\t\t\tbool inside_cardioid = q * (q + (z.real() - 1/4)) < (1/4)*z.imag()*z.imag();\r\n\t\t\t\t\t\tbool inside_period2_bulb = (z.real() + 1)*(z.real() + 1) + z.imag()*z.imag() < 1/16;\r\n\r\n\t\t\t\t\t\tsize_t i = 0;\r\n\t\t\t\t\t\tif (!inside_cardioid || !inside_period2_bulb)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\twhile (i < max_iterations && z.real()*z.real() + z.imag()*z.imag() < 2.0*2.0)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tz = z*z + c;\r\n\t\t\t\t\t\t\t\ti += 1;\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\ti = max_iterations;\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif (z.real()*z.real() + z.imag()*z.imag() < 2.0*2.0 || i == max_iterations)\r\n\t\t\t\t\t\t\tWritePixel(_x, _y, -1, 0, 0.0);\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tdouble s = i + (log(log((double)max_iterations)) - log(log(abs(z))))/log(2.0);\r\n\r\n\t\t\t\t\t\t\tint first = (int)s;\r\n\t\t\t\t\t\t\tint second = first + 1;\r\n\t\t\t\t\t\t\tdouble factor = s - first;\r\n\t\t\t\t\t\t\tWritePixel(_x, _y, first, second, factor);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tlock_guard lock(job_mutex);\r\n\t\t\t\tjob_done = true;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tboost::thread::sleep(boost::get_system_time() + boost::posix_time::milliseconds(1));\r\n\t\t\t}\r\n\r\n\t\t\tlock_guard lock(running_mutex);\r\n\t\t\t_running = running;\r\n\t\t} while (_running);\r\n\t}\r\n\r\nprivate:\r\n\tFractalRenderer(FractalRenderer& other);\r\n\r\n\tJob current_job;\r\n\tbool job_done;\r\n\tbool running;\r\n\r\n\tboost::mutex job_mutex, running_mutex;\r\n\r\n\tdouble texture_width;\r\n\tdouble texture_height;\r\n\r\n\tunsigned char* texture_data;\r\n\tColor* color_ramp;\r\n\r\n\tvoid WritePixel(size_t x, size_t y, int first, int second, double factor)\r\n\t{\r\n\t\tsize_t offset = y * (size_t)texture_width + x;\r\n\t\t\r\n\t\tColor color;\r\n\t\tif (first == -1)\r\n\t\t\tcolor = Color(0, 0, 0);\r\n\t\telse\r\n\t\t\tcolor = color_ramp[second % (max_colors*2)] * factor + color_ramp[first % (max_colors*2)] * (1.0 - factor);\r\n\r\n\t\ttexture_data[offset * 3 + 0] = (unsigned char)(color.r * 255.0);\r\n\t\ttexture_data[offset * 3 + 1] = (unsigned char)(color.g * 255.0);\r\n\t\ttexture_data[offset * 3 + 2] = (unsigned char)(color.b * 255.0);\r\n\t}\r\n};\r\n\r\nclass Application : public Limbus::OpenglWindow::EventHandler\r\n{\r\n\tbool running;\r\n\r\n\tvoid onClose(Limbus::OpenglWindow& self)\r\n\t{\r\n\t\trunning = false;\r\n\t}\r\n\r\n\tLimbus::OpenglWindow window;\r\n\tPingo::SpriteBuffer* sprite_buffer;\r\n\tPingo::Texture* texture;\r\n\tunsigned char* texture_data;\r\n\r\n\tFractalRenderer::Color color_ramp[FractalRenderer::max_colors*2];\r\n\r\npublic:\r\n\tvoid run()\r\n\t{\r\n\t\trunning = true;\r\n\t\twindow.setCaption(\"Fractal Demo\");\r\n\t\twindow.addEventHandler(this);\r\n\t\twindow.setWidth(256);\r\n\t\twindow.setHeight(256);\r\n\t\twindow.create();\r\n\r\n\t\tglClearColor( 0.0f, 0.0f, 0.0f, 0.0f );\r\n\t\tglDisable( GL_DEPTH_TEST );\r\n\t\tglEnable( GL_BLEND );\r\n\t\tglBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );\r\n\t\tglEnable( GL_TEXTURE_2D );\r\n\r\n\t\tglMatrixMode( GL_PROJECTION );\r\n\t\tglLoadIdentity();\r\n\t\tglOrtho( 0.0f, window.getWidth(), window.getHeight(), 0.0f, -100.0f, 100.0f );\r\n\t\tglMatrixMode( GL_MODELVIEW );\r\n\t\tglLoadIdentity();\r\n\r\n\t\ttexture_data = new unsigned char[window.getWidth() * window.getHeight() * 3];\r\n\r\n\t\ttexture = new Pingo::Texture();\r\n\t\ttexture->loadFromMemory(texture_data, window.getWidth(), window.getHeight(), 3);\r\n\t\tsprite_buffer = new Pingo::SpriteBuffer(texture, 1, true);\r\n\t\t\r\n\t\tsprite_buffer->setWritable(true);\r\n\t\tsprite_buffer->setRectangle(0, 0.0f, 0.0f, (float)window.getWidth(), (float)window.getHeight());\r\n\t\tsprite_buffer->setColor(0, 1.0f, 1.0f, 1.0f, 1.0f);\r\n\t\tsprite_buffer->setTextureRectangle(0, 0.0f, 0.0f, (float)window.getWidth(), (float)window.getHeight());\r\n\t\tsprite_buffer->setWritable(false);\r\n\r\n\t\tfor (size_t i = 0; i < FractalRenderer::max_colors; ++i)\r\n\t\t{\r\n\t\t\tfloat factor = (float)i / FractalRenderer::max_colors;\r\n\t\t\tfloat inverse_factor = (float)(FractalRenderer::max_colors - i) / FractalRenderer::max_colors;\r\n\r\n\t\t\tcolor_ramp[i] = FractalRenderer::Color(sqrt(sqrt(factor)), factor, inverse_factor * 0.5f);\r\n\t\t\tcolor_ramp[FractalRenderer::max_colors*2 - 1 - i] = color_ramp[i];\r\n\t\t}\r\n\r\n\t\tFractalRenderer worker(texture_data, color_ramp, (double)window.getWidth(), (double)window.getHeight());\r\n\t\tFractalRenderer worker2(texture_data, color_ramp, (double)window.getWidth(), (double)window.getHeight());\r\n\t\t\r\n\t\tFractalRenderer::Job job;\r\n\t\tjob.offset = std::complex(+0.001643721971153, +0.822467633298876);\r\n\t\tjob.scale = 2.0;\r\n\t\tjob.y_start = 0;\r\n\t\tjob.y_count = window.getHeight() / 2;\r\n\r\n\t\tFractalRenderer::Job job2;\r\n\t\tjob2.offset = std::complex(+0.001643721971153, +0.822467633298876);\r\n\t\tjob2.scale = 2.0;\r\n\t\tjob2.y_start = window.getHeight() / 2;\r\n\t\tjob2.y_count = window.getHeight() - job2.y_start;\r\n\t\t\r\n\t\tworker.setJob(job);\r\n\t\tworker2.setJob(job2);\r\n\t\t\r\n\t\tboost::thread worker_thread(boost::ref(worker));\r\n\t\tboost::thread worker_thread2(boost::ref(worker2));\r\n\r\n\t\tLimbus::Timer timer;\r\n\t\twhile (running)\r\n\t\t{\r\n\t\t\twindow.pollEvents();\r\n\t\t\tdouble elapsed = 1.0f + timer.getElapsed() * 0.005;\r\n\t\t\t\r\n\t\t\tif (worker.jobDone() && worker2.jobDone())\r\n\t\t\t{\r\n\t\t\t\ttexture->update(texture_data);\r\n\r\n\t\t\t\tjob.scale = 1.0 / (elapsed * (1.0 / job.scale));\r\n\t\t\t\tif (job.scale < 0.00000000001)\r\n\t\t\t\t\tjob.scale = 0.00000000001;\r\n\t\t\t\tworker.setJob(job);\r\n\r\n\t\t\t\tjob2.scale = job.scale;\r\n\t\t\t\tworker2.setJob(job2);\r\n\t\t\t}\r\n\r\n\t\t\tsprite_buffer->draw(0, 1, 0, 0);\r\n\t\t\twindow.swapBuffers();\r\n\t\t}\r\n\r\n\t\tworker.stop();\r\n\t\tworker2.stop();\r\n\t\tworker_thread.join();\r\n\t\tworker_thread2.join();\r\n\r\n\t\tdelete sprite_buffer;\r\n\t\tdelete texture;\r\n\t\tdelete [] texture_data;\r\n\t}\r\n};\r\n\r\nvoid main()\r\n{\r\n\tApplication app;\r\n\tapp.run();\r\n}\r\n", "meta": {"hexsha": "b93558489a6ae07eb30a62b1656ffe7bbadd1e22", "size": 7447, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/main.cpp", "max_stars_repo_name": "redien/mandelbrot", "max_stars_repo_head_hexsha": "5a604a5c2225efbcc9d76ae849fbf1fe65300040", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2015-11-04T02:29:50.000Z", "max_stars_repo_stars_event_max_datetime": "2015-11-04T02:29:50.000Z", "max_issues_repo_path": "source/main.cpp", "max_issues_repo_name": "redien/mandelbrot", "max_issues_repo_head_hexsha": "5a604a5c2225efbcc9d76ae849fbf1fe65300040", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/main.cpp", "max_forks_repo_name": "redien/mandelbrot", "max_forks_repo_head_hexsha": "5a604a5c2225efbcc9d76ae849fbf1fe65300040", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5910652921, "max_line_length": 149, "alphanum_fraction": 0.6240096683, "num_tokens": 2195, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.927363293639213, "lm_q2_score": 0.7090191337850932, "lm_q1q2_score": 0.6575183191601658}} {"text": "/*\n * Copyright (c) 2015, Jonathan Ventura\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef POLYNOMIAL_INTERNAL_HPP\n#define POLYNOMIAL_INTERNAL_HPP\n\n#include \n#include \n#include \n\nnamespace polynomial\n{\n namespace Internal\n {\n \n template struct max{ static const int value=(a struct min{ static const int value=(a>b)?b:a; };\n \n template \n inline\n Eigen::Map< Eigen::Matrix > vecmap(double *data)\n {\n return Eigen::Map< Eigen::Matrix >(data);\n }\n \n template \n inline\n Eigen::Map< const Eigen::Matrix > vecmap(const double *data)\n {\n return Eigen::Map< const Eigen::Matrix >(data);\n }\n \n template \n struct\n _PolyConv\n {\n static void\n compute( double *coefout, const double *coef1, const double *coef2 )\n {\n coefout[k] =\n (\n vecmap::value-max<0,k-deg2>::value+1>\n (\n coef1+max<0,k-deg2>::value\n )\n .array()\n *\n vecmap::value-max<0,k-deg2>::value+1>\n (\n coef2+k-min::value\n ).reverse().array()\n ).sum();\n _PolyConv::compute( coefout, coef1, coef2 );\n }\n };\n \n template \n struct\n _PolyConv\n {\n static void\n compute( double *coefout, const double *coef1, const double *coef2 )\n {\n }\n };\n \n template \n struct\n PolyConv\n {\n static void\n compute( Eigen::Matrix &coefout, const Eigen::Matrix &coef1, const Eigen::Matrix &coef2 )\n {\n _PolyConv::compute(coefout.data(),coef1.data(),coef2.data());\n }\n };\n\n template <>\n struct\n PolyConv\n {\n static void\n compute( Eigen::VectorXd &coefout, const Eigen::VectorXd &coef1, const Eigen::VectorXd &coef2 )\n {\n int deg1 = coef1.rows()-1;\n int deg2 = coef2.rows()-1;\n \n for ( int k = deg1+deg2; k >= 0; k-- )\n {\n coefout[k] =\n (\n coef1.block(\n std::max(0,k-deg2),0,\n std::min(k,deg1)-std::max(0,k-deg2)+1,1\n ).array()\n *\n coef2.block(\n k-std::min(k,deg1),0,\n std::min(k,deg1)-std::max(0,k-deg2)+1,1\n ).reverse().array()\n ).sum();\n }\n }\n };\n\n template\n struct\n _PolyVal\n {\n static double\n compute( const Eigen::Matrix &coef, const double &x )\n {\n return coef[k] + x*_PolyVal::compute(coef,x);\n }\n };\n \n template\n struct\n _PolyVal\n {\n static double\n compute( const Eigen::Matrix &coef, const double &x )\n {\n return coef[0];\n }\n };\n \n template\n struct\n PolyVal\n {\n static double\n compute( const Eigen::Matrix &coef, const double &x )\n {\n return Internal::_PolyVal::compute( coef, x );\n }\n };\n\n template<>\n struct\n PolyVal\n {\n static double\n compute( const Eigen::VectorXd &coef, const double &x )\n {\n int deg = coef.rows()-1;\n double val = 0;\n for ( int i = 0; i <= deg; i++ ) val = coef(i) + x*val;\n return val;\n }\n };\n\n template\n struct BisectionMethod\n {\n static double compute(const Eigen::Matrix &coef, const double lower, const double upper )\n {\n double a = lower;\n double fa = PolyVal::compute(coef,a);\n char fapos = (fa>0);\n double b = upper;\n double c = 0.5*(a+b);\n \n for ( int i = 0; i < 24; i++ )\n {\n const double fc = PolyVal::compute(coef,c);\n const char fcpos = (fc>0);\n if ( fcpos == fapos )\n {\n a = c;\n fa = fc;\n } else {\n b = c;\n }\n c = 0.5*(a+b);\n }\n \n return c;\n }\n };\n\n template<>\n struct BisectionMethod\n {\n static double compute(const Eigen::VectorXd &coef, const double lower, const double upper )\n {\n double a = lower;\n double fa = PolyVal::compute(coef,a);\n char fapos = (fa>0);\n double b = upper;\n double c = 0.5*(a+b);\n \n for ( int i = 0; i < 100; i++ )\n {\n const double fc = PolyVal::compute(coef,c);\n const char fcpos = (fc>0);\n if ( fcpos == fapos )\n {\n a = c;\n fa = fc;\n } else {\n b = c;\n }\n c = 0.5*(a+b);\n }\n \n return c;\n }\n };\n \n template\n struct SturmChain\n {\n Eigen::Matrix coef;\n SturmChain next;\n };\n \n template<>\n struct SturmChain<0>\n {\n Eigen::Matrix coef;\n };\n \n template\n struct _GetSturmChain\n {\n static SturmChain& compute( SturmChain &sc )\n {\n return _GetSturmChain::compute(sc.next);\n }\n };\n \n template\n struct _GetSturmChain\n {\n static SturmChain& compute( SturmChain &sc )\n {\n return sc;\n }\n };\n \n template\n struct GetSturmChain\n {\n static SturmChain& compute( SturmChain &sc )\n {\n return _GetSturmChain::compute(sc);\n }\n };\n \n template \n struct _ModPoly\n {\n static const void compute( SturmChain &sc )\n {\n const Eigen::Matrix &u( GetSturmChain::compute(sc).coef );\n const Eigen::Matrix &v( GetSturmChain::compute(sc).coef );\n Eigen::Matrix r = u;\n const double s = v(0)/fabs(v(0));\n r(k+2) *= s;\n const int blocklength = k+1;\n r.block(1,0,blocklength,1) = s * r.block(1,0,blocklength,1) - r(0) * v.block(1,0,blocklength,1);\n r.block(2,0,blocklength,1) = s * r.block(2,0,blocklength,1) - r(1) * v.block(1,0,blocklength,1);\n Eigen::Matrix &rout( GetSturmChain::compute(sc).coef );\n rout = r.block(2,0,k+1,1);\n double f = -fabs(rout(0));\n rout /= f;\n _ModPoly::compute(sc);\n }\n };\n \n template \n struct _ModPoly\n {\n static const void compute( SturmChain &sc )\n {\n const Eigen::Matrix &u( GetSturmChain::compute(sc).coef );\n const Eigen::Matrix &v( GetSturmChain::compute(sc).coef );\n Eigen::Matrix r = u;\n const double s = v(0)/fabs(v(0));\n r(2) *= s;\n r(1) = s * r(1) - r(0) * v(1);\n r(2) = s * r(2) - r(1) * v(1);\n GetSturmChain::compute(sc).coef[0] = -r(2);\n }\n };\n \n template \n struct ModPoly\n {\n static const void compute( SturmChain &sc )\n {\n _ModPoly::compute(sc);\n }\n };\n \n template \n struct _SignChanges\n {\n static const void compute( SturmChain &sc, const double x, const double lf, int &count )\n {\n double f = PolyVal::compute( sc.coef, x );\n count += (f*lf<0);\n _SignChanges::compute( sc.next, x, f, count );\n }\n };\n \n template <>\n struct _SignChanges<0>\n {\n static const void compute( SturmChain<0> &sc, const double x, const double lf, int &count )\n {\n double f = sc.coef[0];\n count += (f*lf<0);\n }\n };\n \n template \n struct SignChanges\n {\n static const void compute( SturmChain &sc, const double x, int &count )\n {\n double f = PolyVal::compute( sc.coef, x );\n count = 0;\n _SignChanges::compute( sc.next, x, f, count );\n }\n };\n \n template <>\n struct SignChanges<0>\n {\n static const void compute( SturmChain<0> &sc, const double x, int &count )\n {\n count = 0;\n }\n };\n \n struct SturmInterval\n {\n double lb, ub;\n int sclb, scub;\n SturmInterval(const double _lb, const double _ub, const int _sclb, const int _scub)\n : lb(_lb), ub(_ub), sclb(_sclb), scub(_scub) { }\n };\n \n struct RootInterval\n {\n double lb, ub;\n RootInterval(const double _lb, const double _ub)\n : lb(_lb), ub(_ub) { }\n };\n \n template\n class SturmRootFinder\n {\n void bisection(const double lb, const double ub, std::vector &roots)\n {\n int sclb = 0;\n int scub = 0;\n SignChanges::compute(sc,lb,sclb);\n SignChanges::compute(sc,ub,scub);\n std::queue intervals;\n intervals.push( SturmInterval(lb,ub,sclb,scub) );\n \n std::vector root_intervals;\n \n while ( !intervals.empty() )\n {\n SturmInterval interval = intervals.front();\n intervals.pop();\n \n // get num roots in interval\n int n = interval.sclb-interval.scub;\n \n if ( n == 0 )\n {\n \n }\n else if ( n == 1 )\n {\n root_intervals.push_back( RootInterval(interval.lb,interval.ub) );\n }\n else if ( fabs(interval.ub-interval.lb)>1e-15 )\n {\n double m = (interval.lb+interval.ub)*0.5;\n \n // get sign changes at m\n int scm = 0;\n SignChanges::compute(sc,m,scm);\n \n // add [lb,m] interval\n intervals.push( SturmInterval(interval.lb,m,interval.sclb,scm) );\n \n // add [m,ub] interval\n intervals.push( SturmInterval(m,interval.ub,scm,interval.scub) );\n }\n }\n \n roots.resize(root_intervals.size());\n for ( int i = 0; i < root_intervals.size(); i++ )\n {\n roots[i] = BisectionMethod::compute(sc.coef,root_intervals[i].lb,root_intervals[i].ub);\n }\n }\n public:\n SturmChain sc;\n \n SturmRootFinder( const Eigen::Matrix &coef )\n {\n sc.coef = coef;\n sc.next.coef = coef.head(deg);\n double f = fabs(sc.coef[0] * deg);\n for ( int i = 0; i < deg; i++ ) sc.next.coef[i] *= (deg-i)/f;\n ModPoly::compute(sc);\n }\n \n void realRoots(const double lb, const double ub, std::vector &roots)\n {\n bisection(lb,ub,roots);\n }\n };\n\n template<>\n class SturmRootFinder\n {\n std::vector sc;\n\n Eigen::VectorXd modpoly( const Eigen::VectorXd &u, const Eigen::VectorXd &v )\n {\n int udeg = u.rows()-1;\n Eigen::VectorXd r = u;\n double s = v(0)/fabs(v(0));\n r(udeg) *= s;\n int blocklength = udeg-1;\n r.block(1,0,blocklength,1) = s * r.block(1,0,blocklength,1) - r(0) * v.block(1,0,blocklength,1);\n r.block(2,0,blocklength,1) = s * r.block(2,0,blocklength,1) - r(1) * v.block(1,0,blocklength,1);\n return r.block(2,0,blocklength,1);\n }\n \n int signchanges(double x)\n {\n int deg = sc[0].rows()-1;\n Eigen::VectorXd f(deg+1);\n for ( int i = 0; i < deg+1; i++ ) f[i] = PolyVal::compute(sc[i],x);\n int n = 0;\n // NB: not skipping zeros here\n for ( int i = 1; i < deg+1; i++ ) n += (f[i]*f[i-1]<0);\n return n;\n }\n \n void bisection(const double lb, const double ub, std::vector &roots)\n {\n int sclb = signchanges(lb);\n int scub = signchanges(ub);\n std::queue intervals;\n intervals.push( SturmInterval(lb,ub,sclb,scub) );\n \n std::vector root_intervals;\n \n while ( !intervals.empty() )\n {\n SturmInterval interval = intervals.front();\n intervals.pop();\n \n // get num roots in interval\n int n = interval.sclb-interval.scub;\n \n if ( n == 0 )\n {\n \n }\n else if ( n == 1 )\n {\n root_intervals.push_back( RootInterval(interval.lb,interval.ub) );\n }\n else if ( fabs(interval.ub-interval.lb)>1e-15 )\n {\n double m = (interval.lb+interval.ub)*0.5;\n \n // get sign changes at m\n int scm = signchanges(m);\n \n // add [lb,m] interval\n intervals.push( SturmInterval(interval.lb,m,interval.sclb,scm) );\n \n // add [m,ub] interval\n intervals.push( SturmInterval(m,interval.ub,scm,interval.scub) );\n }\n }\n \n roots.resize(root_intervals.size());\n for ( int i = 0; i < root_intervals.size(); i++ )\n {\n roots[i] = BisectionMethod::compute(sc[0],root_intervals[i].lb,root_intervals[i].ub);\n }\n }\n public:\n SturmRootFinder( const Eigen::VectorXd &coef )\n {\n int deg = coef.rows()-1;\n sc.resize(deg+1);\n \n sc[0] = coef;\n \n double f = fabs(sc[0](0) * deg);\n sc[1] = sc[0].block(0,0,deg,1);\n for ( int i = 0; i < deg; i++ ) sc[1][i] *= (deg-i)/f;\n \n for ( int i = 2; i < deg+1; i++ )\n {\n sc[i] = modpoly(sc[i-2],sc[i-1]);\n if ( i != deg )\n {\n double f = -fabs(sc[i](0));\n sc[i] /= f;\n }\n else\n {\n sc[i] = -sc[i];\n }\n }\n }\n \n void realRoots(const double lb, const double ub, std::vector &roots)\n {\n bisection(lb,ub,roots);\n }\n };\n\n template\n struct RootFinder\n {\n static void compute( const Eigen::Matrix &p, std::vector &roots )\n {\n Eigen::PolynomialSolver ps;\n ps.compute(p.reverse());\n ps.realRoots(roots);\n }\n };\n\n template<>\n struct RootFinder\n {\n static void compute( const Eigen::Matrix &p, std::vector &roots )\n {\n Eigen::PolynomialSolver ps;\n ps.compute(p.reverse());\n ps.realRoots(roots);\n }\n };\n \n template<>\n struct RootFinder<2>\n {\n static void compute( const Eigen::Matrix &p, std::vector &roots )\n {\n const double discrim = p[1]*p[1] - 4.*p[0]*p[2];\n if ( discrim < 0 )\n {\n roots.clear();\n }\n else if ( discrim == 0 )\n {\n roots.resize(1);\n roots[0] = -p[1] / ( 2. * p[0] );\n }\n else\n {\n const double twoa = 2. * p[0];\n const double sqrt_discrim = sqrt(discrim);\n roots.resize(2);\n roots[0] = (-p[1] + sqrt_discrim) / twoa;\n roots[1] = (-p[1] - sqrt_discrim) / twoa;\n }\n }\n };\n\n } // end namespace Internal\n \n} // end namespace Polynomial\n\n#endif\n", "meta": {"hexsha": "7449519270c59563830c678816560870ca79ad8b", "size": 20850, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Polynomial/PolynomialInternal.hpp", "max_stars_repo_name": "jonathanventura/polynomial", "max_stars_repo_head_hexsha": "ab737843199ed48881da6dcf5dc05d34903af059", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2017-04-28T11:46:50.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-01T11:41:00.000Z", "max_issues_repo_path": "Polynomial/PolynomialInternal.hpp", "max_issues_repo_name": "jonathanventura/polynomial", "max_issues_repo_head_hexsha": "ab737843199ed48881da6dcf5dc05d34903af059", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-14T00:31:47.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-14T00:31:47.000Z", "max_forks_repo_path": "Polynomial/PolynomialInternal.hpp", "max_forks_repo_name": "jonathanventura/polynomial", "max_forks_repo_head_hexsha": "ab737843199ed48881da6dcf5dc05d34903af059", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 11.0, "max_forks_repo_forks_event_min_datetime": "2016-02-27T11:37:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-08T05:58:18.000Z", "avg_line_length": 35.1602023609, "max_line_length": 758, "alphanum_fraction": 0.4289208633, "num_tokens": 4743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.657442693836752}} {"text": "#include \n#include \n\n// Actually, you may replace dynamic bitset with anything else\n// like std::bitset or std::vector, I made my choice because of\n// this totally reliable (random link from google) research:\n// https://www.researchgate.net/publication/220803585_Performance_of_C_bit-vector_implementations\n\nstatic bool buildAtkinSieve(boost::dynamic_bitset<>& sieve) {\n\tif (&sieve == nullptr || sieve.size() < 2)\n\t\treturn false;\n\tint size = sieve.size() - 1;\n\tsieve[2] = true;\n\tsieve[3] = true;\n\tint n, x = 0, y;\n\tint sizeSqrt = sqrt(size);\n\tfor (int i = 1; i <= sizeSqrt; ++i) {\n\t\tx += (i << 1) - 1;\n\t\ty = 0;\n\t\tfor (int j = 1; j <= sizeSqrt; ++j) {\n\t\t\ty += (j << 1) - 1;\n\t\t\tn = (x << 2) + y;\n\t\t\tif ((n <= size) && (n % 12 == 1 || n % 12 == 5))\n\t\t\t\tsieve[n].flip();\n\t\t\tn -= x;\n\t\t\tif ((n <= size) && (n % 12 == 7))\n\t\t\t\tsieve[n].flip();\n\t\t\tn -= (y << 1);\n\t\t\tif ((i > j) && (n <= size) && (n % 12 == 11))\n\t\t\t\tsieve[n].flip();\n\t\t}\n\t}\n\tfor (int i = 5; i <= sizeSqrt; ++i) {\n\t\tif (sieve[i]) {\n\t\t\tn = i * i;\n\t\t\tfor (int j = n; j <= size; j += n)\n\t\t\t\tsieve[j] = false;\n\t\t}\n\t}\n\treturn true;\n}\n\nint main() {\n\tstd::cout << \"Enter the initial capacity of the sieve: \";\n\tint size;\n\tstd::cin >> size;\n\tboost::dynamic_bitset<> sieve(size + 1);\n\tif (!buildAtkinSieve(sieve)) {\n\t\tstd::cout << \"It's too small for me to work with, so I'm done\";\n\t\treturn 1;\n\t}\n\tint answer;\n\twhile (true) {\t// feel free to Alt + F4\n\t\tstd::cout << \"\\nEnter the number to check if it's prime: \";\n\t\tstd::cin >> answer;\n\t\tif (answer >= sieve.size() || answer < 1) {\n\t\t\tstd::cout << \"Wrong input\\n\";\n\t\t\tstd::cin.clear();\n\t\t\tstd::cin.ignore(INT_MAX, '\\n');\t\t// ignores current input just in case\n\t\t}\n\t\telse\n\t\t\tstd::cout << (sieve[answer] ? \"It's prime.\\n\" : \"It's not prime.\\n\");\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "efd64dfe58fd0bf9a9e4e363695fa9bde19c3c0d", "size": 1791, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Sieve_of_Atkin/AtkinSieve.cpp", "max_stars_repo_name": "antessial/algorithms", "max_stars_repo_head_hexsha": "bcd4e1855c0567e981a366c597279860a8bed5d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Sieve_of_Atkin/AtkinSieve.cpp", "max_issues_repo_name": "antessial/algorithms", "max_issues_repo_head_hexsha": "bcd4e1855c0567e981a366c597279860a8bed5d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Sieve_of_Atkin/AtkinSieve.cpp", "max_forks_repo_name": "antessial/algorithms", "max_forks_repo_head_hexsha": "bcd4e1855c0567e981a366c597279860a8bed5d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1363636364, "max_line_length": 97, "alphanum_fraction": 0.5633724176, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.82893881677331, "lm_q2_score": 0.7931059438487663, "lm_q1q2_score": 0.6574363026698756}} {"text": "#include \"basic_functions.h\"\n#include \"mlfe/device_context/cpu_context.h\"\n#include \n\nnamespace mlfe{ namespace math{\n\ntemplate <>\nvoid squared_difference(const int size,\n const float *x1_ptr,\n const float *x2_ptr,\n float *y_ptr){\n for(int n = 0; n < size; ++n){\n y_ptr[n] = std::pow(x1_ptr[n] - x2_ptr[n], 2);\n }\n}\n\ntemplate <>\nvoid squared_difference(const int size,\n const double *x1_ptr,\n const double *x2_ptr,\n double *y_ptr){\n for(int n = 0; n < size; ++n){\n y_ptr[n] = std::pow(x1_ptr[n] - x2_ptr[n], 2);\n }\n}\n\ntemplate <>\nvoid rowwise_max(const int m,\n const int n,\n const float *a_ptr,\n float *b_ptr\n )\n{\n Eigen::Map(b_ptr, m) =\n Eigen::Map(a_ptr, n, m).colwise().maxCoeff();\n}\n\ntemplate <>\nvoid rowwise_max(const int m,\n const int n,\n const double *a_ptr,\n double *b_ptr\n )\n{\n Eigen::Map(b_ptr, m) =\n Eigen::Map(a_ptr, n, m).colwise().maxCoeff();\n}\n\ntemplate <>\nvoid rowwise_normalize(const int m, const int n,\n const float *scaler_ptr,\n float *norm_dest\n )\n{\n for(int i = 0; i < m; ++i){\n for(int j = 0; j < n; ++j){\n norm_dest[i * n + j] /= scaler_ptr[i];\n }\n }\n}\n\ntemplate <>\nvoid rowwise_normalize(const int m,\n const int n,\n const double *scaler_ptr,\n double *norm_dest\n )\n{\n for(int i = 0; i < m; ++i){\n for(int j = 0; j < n; ++j){\n norm_dest[i * n + j] /= scaler_ptr[i];\n }\n }\n}\n\n\ntemplate<>\nvoid exp(const int size,\n const float *x_ptr,\n float *y_ptr\n )\n{\n Eigen::Map(y_ptr, size) =\n Eigen::Map(x_ptr, size).array().exp();\n}\n\ntemplate<>\nvoid exp(const int size,\n const double *x_ptr,\n double *y_ptr\n )\n{\n Eigen::Map(y_ptr, size) =\n Eigen::Map(x_ptr, size).array().exp();\n}\n\ntemplate<>\nvoid axpy(int size,\n const float alpha,\n const float *x_ptr,\n float *y_ptr\n )\n{\n Eigen::Map(y_ptr, size) +=\n alpha * Eigen::Map(x_ptr, size);\n}\n\ntemplate<>\nvoid axpy(int size,\n const double alpha,\n const double *x_ptr,\n double *y_ptr\n )\n{\n Eigen::Map(y_ptr, size) +=\n alpha * Eigen::Map(x_ptr, size);\n}\n\ntemplate <>\nvoid scal(const int size,\n const float alpha,\n const float *x_ptr,\n float *y_ptr\n )\n{\n Eigen::Map y(y_ptr, size);\n if(alpha != 0.f){\n y = alpha * Eigen::Map(x_ptr, size);\n }\n else{\n y.setZero();\n }\n}\n\ntemplate <>\nvoid scal(const int size,\n const double alpha,\n const double *x_ptr,\n double *y_ptr\n )\n{\n Eigen::Map y(y_ptr, size);\n if(alpha != 0.){\n y = alpha * Eigen::Map(x_ptr, size);\n }\n else{\n y.setZero();\n }\n}\n\ntemplate <>\nvoid sum(\n const int size,\n const float *x_ptr,\n float *y_ptr\n )\n{\n y_ptr[0] = Eigen::Map(x_ptr, size).sum();\n}\n\ntemplate <>\nvoid sum(\n const int size,\n const double *x_ptr,\n double *y_ptr\n )\n{\n y_ptr[0] = Eigen::Map(x_ptr, size).sum();\n}\n\ntemplate<>\nvoid set(\n const int size,\n const float val,\n float *x_ptr\n )\n{\n Eigen::Map(x_ptr, size).setConstant(val);\n}\n\ntemplate<>\nvoid set(const int size,\n const double val,\n double *x_ptr\n )\n{\n Eigen::Map(x_ptr, size).setConstant(val);\n}\n\n} // end namespace math\n} // end namespace mlfe\n", "meta": {"hexsha": "f3dc940997d6e64f04583d84fa6780a7bba6404f", "size": 5649, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mlfe/math/basic_functions.cc", "max_stars_repo_name": "shi510/mlfe", "max_stars_repo_head_hexsha": "aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T11:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-20T18:25:11.000Z", "max_issues_repo_path": "mlfe/math/basic_functions.cc", "max_issues_repo_name": "shi510/mlfe", "max_issues_repo_head_hexsha": "aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mlfe/math/basic_functions.cc", "max_forks_repo_name": "shi510/mlfe", "max_forks_repo_head_hexsha": "aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T12:40:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T05:23:36.000Z", "avg_line_length": 29.421875, "max_line_length": 72, "alphanum_fraction": 0.4253850239, "num_tokens": 1168, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213799730774, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6573104085957557}} {"text": "#ifndef _NB_SAMPLE_HPP\n#define _NB_SAMPLE_HPP\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n\n#include \"misc.hpp\" \n\ntypedef dlib::matrix column_vector;\nusing namespace std::placeholders;\n\nclass NBModelC {\n\n public:\n NBModelC (std::vector lvec) : sample_vec(lvec){\n\n }\n\n double value(const column_vector &m) {\n\n double r_val = m(0);\n double lmean = do_mean(sample_vec);\n double lpval = lmean / (lmean + r_val);\n double total_ll = 0;\n\n for (int j_ind = 0; j_ind < sample_vec.size(); j_ind++) {\n double xi_val = (double)sample_vec[j_ind];\n\n double lval1 = lgamma(xi_val + r_val) -lgamma(xi_val + 1) -\n lgamma(r_val) + xi_val * log (lpval) + \n r_val * log(1 - lpval);\n total_ll += lval1;\n }\n\n return (total_ll);\n }\n\n\n const column_vector gradient(const column_vector &m) {\n \n double r_val = m(0);\n double lmean = do_mean(sample_vec);\n double lpval = lmean / (lmean + r_val);\n \n double total_derivative = 0;\n\n for (int j_ind = 0; j_ind < sample_vec.size(); j_ind++) {\n double xi_val = sample_vec[j_ind];\n\n double lval1 = boost::math::digamma(xi_val + r_val) -\n boost::math::digamma(r_val) + log(1-lpval);\n \n total_derivative += lval1;\n }\n const column_vector final_grad = {total_derivative};\n return final_grad;\n\n }\n\n\n double get_r_val_0 () {\n int n = sample_vec.size();\n double lmean = do_mean(sample_vec);\n\n double lsum = 0;\n for (int j = 0; j < n; j++) {\n lsum += pow((sample_vec[j] - lmean), 2.0);\n }\n double lvar = lsum / (n-1);\n\n double r_val_0 = 0;\n if (lvar > lmean) {\n r_val_0 = pow(lmean, 2.0) / (lvar - lmean);\n } else {\n r_val_0 = 100;\n }\n return r_val_0;\n }\n\n double find_r_val() {\n \n if (r_val_ready) {\n return (final_r_val);\n }\n\n auto value_funct = std::bind(&NBModelC::value, this, _1);\n auto gradient_funct = std::bind(&NBModelC::gradient, this, _1);\n double r_val_0 = get_r_val_0();\n column_vector starting_point = {r_val_0};\n const column_vector x_lower1 = {0.0000001};\n const column_vector x_upper1 = {1000000};\n\n\n find_max_box_constrained(dlib::bfgs_search_strategy(),\n dlib::objective_delta_stop_strategy(1e-9),\n value_funct, gradient_funct, \n starting_point,\n x_lower1, x_upper1);\n\n final_r_val = starting_point(0);\n r_val_ready = true;\n return final_r_val;\n }\n\n double find_p_val() {\n\n if (p_val_ready) {\n return (final_p_val);\n }\n double lrval = find_r_val();\n \n double lmean = do_mean(sample_vec);\n final_p_val = lmean / (lmean + lrval);\n p_val_ready = true;\n return (final_p_val);\n \n }\n\n double find_mean_val() {\n\n double lmean = do_mean(sample_vec);\n return (lmean);\n }\n\n\n private:\n std::vector sample_vec;\n double final_p_val;\n double final_r_val;\n bool p_val_ready = false;\n bool r_val_ready = false;\n\n};\n\n#endif\n", "meta": {"hexsha": "c23ea359cf043de420cd94f5e9c71680243aa252", "size": 3877, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "NBModel.hpp", "max_stars_repo_name": "nirmalya-broad/NB_EM", "max_stars_repo_head_hexsha": "de1bc4d1ee905c62b7427b00b5d9f6e513edbca2", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NBModel.hpp", "max_issues_repo_name": "nirmalya-broad/NB_EM", "max_issues_repo_head_hexsha": "de1bc4d1ee905c62b7427b00b5d9f6e513edbca2", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NBModel.hpp", "max_forks_repo_name": "nirmalya-broad/NB_EM", "max_forks_repo_head_hexsha": "de1bc4d1ee905c62b7427b00b5d9f6e513edbca2", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.1118881119, "max_line_length": 79, "alphanum_fraction": 0.5006448285, "num_tokens": 913, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.657310401351212}} {"text": "#include \n\n#include \n#include \n#include \n#include \n\nnamespace Euclid\n{\n\ntemplate\nvoid OBB::build(const std::vector& positions)\n{\n if (positions.empty()) {\n throw std::invalid_argument(\"Input is empty.\");\n }\n if (positions.size() % 3 != 0) {\n throw std::runtime_error(\"Size of input is not divisble by 3.\");\n }\n\n Eigen::Map>\n v(positions.data(), positions.size() / 3, 3);\n _build(v);\n}\n\ntemplate\ntemplate\nvoid OBB::build(ForwardIterator first,\n ForwardIterator beyond,\n VPMap vpmap)\n{\n std::vector positions;\n while (first != beyond) {\n positions.push_back(get(vpmap, *first).x());\n positions.push_back(get(vpmap, *first).y());\n positions.push_back(get(vpmap, *first).z());\n ++first;\n }\n build(positions);\n}\n\ntemplate\ntemplate\nvoid OBB::build(const Eigen::MatrixBase& v)\n{\n if (v.rows() == 0) {\n throw std::invalid_argument(\"Input is empty.\");\n }\n\n _build(v);\n}\n\ntemplate\ntypename OBB::Point_3 OBB::center() const\n{\n return _center;\n}\n\ntemplate\ntypename OBB::Vector_3 OBB::axis(int n) const\n{\n if (n < 0 || n >= 3) {\n throw std::invalid_argument(\"Invalid argument for OBB::length(int).\");\n }\n return Euclid::normalized(_directions[n]);\n}\n\ntemplate\ntypename OBB::FT OBB::length(int n) const\n{\n if (n < 0 || n >= 3) {\n throw std::invalid_argument(\"Invalid argument for OBB::length(int).\");\n }\n return Euclid::length(_directions[n]) * 2;\n}\n\ntemplate\ntemplate\nvoid OBB::_build(const Eigen::MatrixBase& points)\n{\n using namespace boost::math::constants;\n\n // Conduct pca by eigen decompose the covariance matrix of points\n Eigen::Matrix covariance;\n Euclid::covariance_matrix(points, covariance);\n Eigen::SelfAdjointEigenSolver> eigs;\n eigs.compute(covariance);\n if (eigs.info() != Eigen::Success) {\n throw std::runtime_error(\"PCA no convergence.\");\n }\n\n // Unit lengh, sorted in descending order w.r.t. eigen values\n Euclid::eigen_to_cgal(eigs.eigenvectors().col(2), _directions[0]);\n Euclid::eigen_to_cgal(eigs.eigenvectors().col(1), _directions[1]);\n Euclid::eigen_to_cgal(eigs.eigenvectors().col(0), _directions[2]);\n\n // Transform points to pca coordinate system\n Eigen::Matrix tpoints = points * eigs.eigenvectors();\n Eigen::Matrix tmax = tpoints.colwise().maxCoeff();\n Eigen::Matrix tmin = tpoints.colwise().minCoeff();\n\n // Record center and length of box\n _center = CGAL::ORIGIN + half() * (tmax(2) + tmin(2)) * _directions[0] +\n half() * (tmax(1) + tmin(1)) * _directions[1] +\n half() * (tmax(0) + tmin(0)) * _directions[2];\n _directions[0] *= half() * (tmax(2) - tmin(2));\n _directions[1] *= half() * (tmax(1) - tmin(1));\n _directions[2] *= half() * (tmax(0) - tmin(0));\n}\n\n} // namespace Euclid\n", "meta": {"hexsha": "4c6a5159c38652111025a4950d0322e7fc8a4a53", "size": 3510, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "include/Euclid/BoundingVolume/src/OBB.cpp", "max_stars_repo_name": "unclejimbo/euclid", "max_stars_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 31.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T07:04:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T10:00:01.000Z", "max_issues_repo_path": "include/Euclid/BoundingVolume/src/OBB.cpp", "max_issues_repo_name": "unclejimbo/euclid", "max_issues_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/Euclid/BoundingVolume/src/OBB.cpp", "max_forks_repo_name": "unclejimbo/euclid", "max_forks_repo_head_hexsha": "e118abdcdf51b6bc05cf5aa056bf228e052cf501", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-07-02T17:59:35.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-18T07:01:17.000Z", "avg_line_length": 31.0619469027, "max_line_length": 80, "alphanum_fraction": 0.6387464387, "num_tokens": 987, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6573066366222741}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \"pose_estimator.h\"\n#include \"re_projection_error.h\"\n#include \"timer.h\"\n#include \"type.h\"\n#include \"viewer/viewer.h\"\n\nusing ceres::Problem;\nusing ceres::AutoDiffCostFunction;\nusing ceres::SizedCostFunction;\n\nVec6d isoMat2Vector(const Eigen::Matrix4d pose) {\n Eigen::Matrix3d rotation = pose.block(0, 0, 3, 3);\n Eigen::AngleAxisd angle_axis(rotation);\n Eigen::Vector3d rv = angle_axis.angle() * angle_axis.axis();\n Vec6d v;\n v << rv.x(), rv.y(), rv.z(), pose(0, 3), pose(1, 3), pose(2, 3);\n return v;\n}\n\nEigen::Matrix4d vector2IsoMat(const Vec6d &v) {\n double angle = sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);\n Eigen::Vector3d axis(v[0], v[1], v[2]);\n axis /= angle;\n Eigen::AngleAxisd angle_axis(angle, axis);\n\n Eigen::MatrixX4d pose = Eigen::Matrix4d::Identity();\n pose.block(0, 0, 3, 3) = angle_axis.toRotationMatrix();\n\n pose(0, 3) = v[3];\n pose(1, 3) = v[4];\n pose(2, 3) = v[5];\n return pose;\n}\n\nvoid addNoise(Vec6d &v, double rotation_noise, double translation_noise) {\n const double mean = 0.0;\n std::default_random_engine generator;\n std::normal_distribution dist_rotation(mean, rotation_noise);\n std::normal_distribution dist_translation(mean, translation_noise);\n for (int i = 0; i < 3; i++) {\n v[i] += dist_rotation(generator);\n v[i + 3] += dist_translation(generator);\n }\n}\n\nint main(int argc, char **argv) {\n if (argc != 3) {\n std::cout << \" args error \" << std::endl;\n return 1;\n }\n bool use_analytic = false;\n\n std::cout << kColorGreen << (use_analytic ? \" Use Analytic Derivatives \"\n : \" Use Automatic Derivatives\")\n << kColorReset << std::endl;\n\n std::string str_map_points = std::string(argv[1]);\n std::string str_observation = std::string(argv[2]);\n\n Mat44d ground_truth_pose;\n ground_truth_pose << -0.38773203, -0.29730779, 0.872509, -1.8075688,\n 0.29847804, 0.85506284, 0.42400289, 0.0065075331, -0.87210935, 0.42482427,\n -0.24279539, 0.75284511, 0, 0, 0, 1;\n\n auto init_parameter = isoMat2Vector(ground_truth_pose);\n\n // add noise to ground_truth\n addNoise(init_parameter, 0.1, 0.2);\n\n // Setup Viewer\n\n Viewer viewer;\n viewer.LoadMappoints(str_map_points);\n viewer.SetGroundTruthPose(ground_truth_pose);\n viewer.SetInitialPose(vector2IsoMat(init_parameter));\n std::thread *viewer_thread = new std::thread(&Viewer::Run, &viewer);\n viewer_thread->detach();\n\n // start solving pose estimation problem\n\n std::shared_ptr pose_estimation =\n std::make_shared();\n pose_estimation->loadFile(str_observation);\n pose_estimation->setInitialParameter(init_parameter.data());\n\n ceres::Problem problem;\n\n // camera intrinsic parameters\n double fx = 458.65399169921875;\n double fy = 457.29598999023438;\n double cx = 367.21499633789062;\n double cy = 248.375;\n CameraInt cam_int(fx, fy, cx, cy);\n\n if (use_analytic) {\n problem.AddParameterBlock(pose_estimation->mutable_camera_pose(), 6,\n new PoseSE3Parameterization());\n } else {\n problem.AddParameterBlock(pose_estimation->mutable_camera_pose(), 6);\n }\n for (int i = 0; i < pose_estimation->num_observations(); ++i) {\n auto point = pose_estimation->point_position_for_observation(i);\n auto observation = pose_estimation->observation(i);\n\n if (use_analytic) {\n ceres::CostFunction *cost_function =\n new ReprojectionErrorSE3(cam_int, observation.x(), observation.y(),\n point.x(), point.y(), point.z());\n problem.AddResidualBlock(cost_function, NULL,\n pose_estimation->mutable_camera_pose());\n } else // auto-diff\n {\n ceres::CostFunction *cost_function =\n ReprojectionError::create(cam_int, observation.x(), observation.y(),\n point[0], point[1], point[2]);\n problem.AddResidualBlock(cost_function, nullptr /* squared loss */,\n pose_estimation->mutable_camera_pose());\n }\n }\n\n ceres::Solver::Options options;\n options.linear_solver_type = ceres::DENSE_SCHUR;\n options.minimizer_progress_to_stdout = true;\n\n ceres::Solver::Summary summary;\n ceres::Solve(options, &problem, &summary);\n std::cout << summary.FullReport() << \"\\n\";\n\n // display optimized result\n auto final_result = pose_estimation->mutable_camera_pose();\n Eigen::Map final_result_vector = Eigen::Map(final_result);\n viewer.SetEstimatePose(vector2IsoMat(final_result_vector));\n\n while (true) {\n std::this_thread::sleep_for(std::chrono::milliseconds(1000));\n }\n\n return 1;\n}\n", "meta": {"hexsha": "9181499e6d6eb819511bab73a8e1cbb98e6729df", "size": 4772, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/pose_estimation_test.cc", "max_stars_repo_name": "JackeyLin-ss/AutoDiff_on_Manifold", "max_stars_repo_head_hexsha": "c67cad0f2aac6bbb3dd7935c1a48f46f0c3c9406", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pose_estimation_test.cc", "max_issues_repo_name": "JackeyLin-ss/AutoDiff_on_Manifold", "max_issues_repo_head_hexsha": "c67cad0f2aac6bbb3dd7935c1a48f46f0c3c9406", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pose_estimation_test.cc", "max_forks_repo_name": "JackeyLin-ss/AutoDiff_on_Manifold", "max_forks_repo_head_hexsha": "c67cad0f2aac6bbb3dd7935c1a48f46f0c3c9406", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6849315068, "max_line_length": 80, "alphanum_fraction": 0.6670159262, "num_tokens": 1341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.877476793890012, "lm_q2_score": 0.749087201911703, "lm_q1q2_score": 0.6573066362775212}} {"text": "//\tObjective: To implement the option class that is defined in the header file: AsianGeometricOption.hpp\r\n//\r\n// (c) Sudhansh Dua\r\n\r\n#include \"AsianGeometricOption.hpp\"\r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n\r\ndouble AsianGeometricOption::CallPrice() const\r\n{\r\n\treturn ::AsianGeometricCallPrice(S, K, T, r, sig, b, type);\r\n}\r\n\r\ndouble AsianGeometricOption::PutPrice() const\r\n{\r\n\treturn ::AsianGeometricPutPrice(S, K, T, r, sig, b, type);\r\n}\r\n\r\n\r\nvoid AsianGeometricOption::init()\t\t\t\t\t// Initialising all the default values\r\n{\r\n\t//\tDefault values\r\n\tT = 0.25;\r\n\tr = 0.05;\r\n\tsig = 0.2;\r\n\tK = 85;\r\n\tS = 80;\t\t\t\r\n\tb = 0.08;\t\t\t\r\n\r\n\ttype = \"C\";\t\t\t//\tCall option as the default\r\n\r\n}\r\n\r\nvoid AsianGeometricOption::copy(const AsianGeometricOption& option)\r\n{\r\n\tT = option.T;\r\n\tr = option.r;\r\n\tsig = option.sig;\r\n\tK = option.K;\r\n\tb = option.b;\r\n\ttype = option.type;\r\n\tS = option.S;\r\n}\r\n\r\n//\tConstructors and destructor\r\n//\tDefault Constructor\r\nAsianGeometricOption::AsianGeometricOption() : Option()\r\n{\r\n\tinit();\r\n}\r\n\r\n//\tCopy constructor\r\nAsianGeometricOption::AsianGeometricOption(const AsianGeometricOption& option) : Option(option)\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nAsianGeometricOption::AsianGeometricOption(const double& S1, const double& K1, const double& T1, const double& r1, const double& sig1,\r\n\tconst double& b1, const string type1) : Option(), S(S1), K(K1), T(T1), r(r1), sig(sig1), b(b1), type(type1) {}\r\n\r\n//\tDestructor\r\nAsianGeometricOption::~AsianGeometricOption() {}\r\n\r\n\r\n//\tAssignment Operator\r\nAsianGeometricOption& AsianGeometricOption::operator = (const AsianGeometricOption& option)\r\n{\r\n\tif (this == &option)\r\n\t{\r\n\t\treturn *this;\t\t//\tSelf-assignment check!\r\n\t}\r\n\tOption::operator = (option);\r\n\tcopy(option);\r\n\treturn *this;\r\n}\r\n\r\n\r\n// Functions that calculate the option price\r\ndouble AsianGeometricOption::Price() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallPrice();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutPrice();\r\n\t}\r\n}\r\n\r\n\r\n// Modifier functions\r\nvoid AsianGeometricOption::toggle()\t\t\t\t\t\t\t\t//\tChange the option type\r\n{\r\n\ttype = ((type == \"C\") ? \"P\" : \"C\");\r\n}\r\n\r\n// Global Functions\r\ndouble AsianGeometricCallPrice(const double S, const double K, const double T, const double r, const double sig, const double b, const string type)\r\n{\r\n\tdouble sig_adj = sig / sqrt(3);\t\t\t\t\t\t//\tadjusted volatility \r\n\tdouble b_adj = 0.5 * (b - ((sig * sig) / 6));\t\t//\tadjusted cost-of-carry\r\n\r\n\tdouble d1 = (log(S / K) + (b_adj + (sig_adj * sig_adj * 0.5)) * T) / sig_adj * sqrt(T);\r\n\tdouble d2 = d1 - sig_adj * sqrt(T);\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn ((S * exp((b_adj - r) * T) * cdf(standard_normal, d1)) - (K * exp(-r * T) * cdf(standard_normal, d2)));\r\n}\r\n\r\ndouble AsianGeometricPutPrice(const double S, const double K, const double T, const double r, const double sig, const double b, const string type)\r\n{\r\n\tdouble sig_adj = sig / sqrt(3);\t\t\t\t\t\t//\tadjusted volatility \r\n\tdouble b_adj = 0.5 * (b - ((sig * sig) / 6));\t\t//\tadjusted cost-of-carry\r\n\r\n\tdouble d1 = (log(S / K) + (b_adj + (sig_adj * sig_adj * 0.5)) * T) / sig_adj * sqrt(T);\r\n\tdouble d2 = d1 - sig_adj * sqrt(T);\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn ((K * exp(-r * T) * cdf(standard_normal, -d2)) - (S * exp((b_adj - r) * T) * cdf(standard_normal, -d1)));\r\n}\r\n\r\n", "meta": {"hexsha": "28412f2f25cc68e0527452cf76621d67f40ce53d", "size": 3396, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "AsianGeometricOption.cpp", "max_stars_repo_name": "sudhanshdua/Option_Classes", "max_stars_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "AsianGeometricOption.cpp", "max_issues_repo_name": "sudhanshdua/Option_Classes", "max_issues_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AsianGeometricOption.cpp", "max_forks_repo_name": "sudhanshdua/Option_Classes", "max_forks_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3255813953, "max_line_length": 148, "alphanum_fraction": 0.6472320377, "num_tokens": 982, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577681049901037, "lm_q2_score": 0.7662936377487304, "lm_q1q2_score": 0.6573022415177014}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace cv;\n\nvoid find_feature_matches (\n const Mat& img_1, const Mat& img_2,\n std::vector& keypoints_1,\n std::vector& keypoints_2,\n std::vector< DMatch >& matches );\n\n// 像素坐标转相机归一化坐标\nPoint2d pixel2cam ( const Point2d& p, const Mat& K );\n\nPoint2d cam2pixel ( const Mat& p, const Mat& K );\n\nvoid bundleAdjustment (\n const vector points_3d,\n const vector points_2d,\n const Mat& K,\n Mat& R, Mat& t\n);\n\nint main ( int argc, char** argv )\n{\n if ( argc != 5 )\n {\n cout<<\"usage: pose_estimation_3d2d img1 img2 depth1 depth2\"< keypoints_1, keypoints_2;\n vector matches;\n // 匹配对只是从RGB图里找,深度图作为3D坐标值来源\n find_feature_matches ( img_1, img_2, keypoints_1, keypoints_2, matches );\n cout<<\"一共找到了\"< ( 3,3 ) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n // 用于存储世界坐标系的3D点\n vector pts_3d;\n vector pts_2d;\n // 准备solve_pnp的输入,分别是2d和3d的匹配对,其中3d即为第1个view的世界坐标系下的坐标值\n for ( DMatch m:matches )\n {\n // ()[]是基本的mat操作,取数据值的方法\n // []()是Lambda expression\n // 首先定义了一个指针d1.ptr<..> (int i),表示第i行\n // 然后根据首地址,取其中的元素,直接调取第j个元素,从而获得了深度值\n ushort d = d1.ptr (int ( keypoints_1[m.queryIdx].pt.y )) [ int ( keypoints_1[m.queryIdx].pt.x ) ];\n // VIP:depth异常值处理,直接跳过\n if ( d == 0 ) // bad depth\n continue;\n // TUM定义:The depth images are scaled by a factor of 5000\n // 不同的dataset的设定不同,之后自己实现要注意细节\n float dd = d/5000.0;\n // 图像坐标系转化成相机坐标系的归一化坐标\n Point2d p1 = pixel2cam ( keypoints_1[m.queryIdx].pt, K );\n // 再转成相机坐标系的坐标\n pts_3d.push_back ( Point3f ( p1.x*dd, p1.y*dd, dd ) );\n // 问题:trainIdx和queryIdx的区别?\n // queryIdx refers to keypoints1 and trainIdx refers to keypoints2\n pts_2d.push_back ( keypoints_2[m.trainIdx].pt );\n }\n cout<<\"3d-2d pairs: \"<第2个view,得到p1_2_3d\n Mat_ p1_2_3d = R * (Mat_(3,1)<& keypoints_1,\n std::vector& keypoints_2,\n std::vector< DMatch >& matches )\n{\n //-- 初始化\n Mat descriptors_1, descriptors_2;\n // used in OpenCV3\n Ptr detector = ORB::create();\n Ptr descriptor = ORB::create();\n // use this if you are in OpenCV2\n // Ptr detector = FeatureDetector::create ( \"ORB\" );\n // Ptr descriptor = DescriptorExtractor::create ( \"ORB\" );\n Ptr matcher = DescriptorMatcher::create ( \"BruteForce-Hamming\" );\n //-- 第一步:检测 Oriented FAST 角点位置\n detector->detect ( img_1,keypoints_1 );\n detector->detect ( img_2,keypoints_2 );\n\n //-- 第二步:根据角点位置计算 BRIEF 描述子\n descriptor->compute ( img_1, keypoints_1, descriptors_1 );\n descriptor->compute ( img_2, keypoints_2, descriptors_2 );\n\n //-- 第三步:对两幅图像中的BRIEF描述子进行匹配,使用 Hamming 距离\n vector match;\n // BFMatcher matcher ( NORM_HAMMING );\n matcher->match ( descriptors_1, descriptors_2, match );\n\n //-- 第四步:匹配点对筛选\n double min_dist=10000, max_dist=0;\n\n //找出所有匹配之间的最小距离和最大距离, 即是最相似的和最不相似的两组点之间的距离\n for ( int i = 0; i < descriptors_1.rows; i++ )\n {\n double dist = match[i].distance;\n if ( dist < min_dist ) min_dist = dist;\n if ( dist > max_dist ) max_dist = dist;\n }\n\n printf ( \"-- Max dist : %f \\n\", max_dist );\n printf ( \"-- Min dist : %f \\n\", min_dist );\n\n //当描述子之间的距离大于两倍的最小距离时,即认为匹配有误.但有时候最小距离会非常小,设置一个经验值30作为下限.\n for ( int i = 0; i < descriptors_1.rows; i++ )\n {\n if ( match[i].distance <= max ( 2*min_dist, 30.0 ) )\n {\n matches.push_back ( match[i] );\n }\n }\n}\n\nPoint2d pixel2cam ( const Point2d& p, const Mat& K )\n{\n return Point2d\n (\n ( p.x - K.at ( 0,2 ) ) / K.at ( 0,0 ),\n ( p.y - K.at ( 1,2 ) ) / K.at ( 1,1 )\n );\n}\n\n// 3d相机坐标系转换成2d图像坐标系\nPoint2d cam2pixel ( const Mat& p, const Mat& K )\n{\n return Point2d\n (\n p.at ( 0,0 ) * K.at ( 0,0 ) / p.at ( 2,0 ) + K.at ( 0,2 ),\n p.at ( 1,0 ) * K.at ( 0,0 ) / p.at ( 2,0 ) + K.at ( 1,2 )\n );\n}\n\n// 用到了g2o求解器\nvoid bundleAdjustment (\n const vector< Point3f > points_3d,\n const vector< Point2f > points_2d,\n const Mat& K,\n Mat& R, Mat& t )\n{\n // 初始化g2o\n // pose:XYZ,3个角度;landmark:XYZ\n typedef g2o::BlockSolver< g2o::BlockSolverTraits<6,3> > Block; // pose 维度为 6, landmark 维度为 3\n Block::LinearSolverType* linearSolver = new g2o::LinearSolverCSparse(); // 线性方程求解器\n Block* solver_ptr = new Block ( linearSolver ); // 矩阵块求解器\n // 从结果上来看,3D2D比3D3D要难,3D2D必须要给定好的初值,而3D3D要求很宽松\n // 从原理上,是因为ICP的极小值就是全局最优值,因此可以任意选择初值\n // g2o::OptimizationAlgorithmGaussNewton* solver = new g2o::OptimizationAlgorithmGaussNewton( solver_ptr );\n g2o::OptimizationAlgorithmLevenberg* solver = new g2o::OptimizationAlgorithmLevenberg ( solver_ptr );\n g2o::SparseOptimizer optimizer;\n optimizer.setAlgorithm ( solver );\n\n // vertex,首先设置顶点\n // se3经过指数映射得到SE3\n // se3-李代数,SE3-李群\n // 最终希望用李代数,即se3表示的相机位姿\n // 使用g2o自带的相机位姿顶点类VertexSE3Expmap\n // SE3 Vertex parameterized internally with a transformation matrix\n // and externally with its exponential map\n g2o::VertexSE3Expmap* pose = new g2o::VertexSE3Expmap(); // camera pose\n Eigen::Matrix3d R_mat;\n // 拷贝一下rotation matrix,不直接用可能是怕被修改了\n R_mat <<\n R.at ( 0,0 ), R.at ( 0,1 ), R.at ( 0,2 ),\n R.at ( 1,0 ), R.at ( 1,1 ), R.at ( 1,2 ),\n R.at ( 2,0 ), R.at ( 2,1 ), R.at ( 2,2 );\n pose->setId ( 0 ); // 首先设置Id\n // Quat就是quaternion,四元数\n // sets the initial estimate from an array of double\n // 此处需要外界的初始化,因此必须先用solvepnp\n // 当然也可以把这里的初值人为设定了\n pose->setEstimate ( g2o::SE3Quat (\n R_mat,\n // translation vector\n Eigen::Vector3d ( t.at ( 0,0 ), t.at ( 1,0 ), t.at ( 2,0 ) )\n // 以下用于测试,即给定一个固定的初值\n // Eigen::Matrix3d::Identity(),\n // Eigen::Vector3d( 0,0,0 )\n ) );\n optimizer.addVertex ( pose );\n\n // 加完了pose,接下来加3D坐标点\n int index = 1;\n for ( const Point3f p:points_3d ) // landmarks\n {\n // 3D路标点类VertexSBAPointXYZ\n g2o::VertexSBAPointXYZ* point = new g2o::VertexSBAPointXYZ();\n // 设置Id\n point->setId ( index++ );\n // 设置初始值,将landmark坐标赋值\n point->setEstimate ( Eigen::Vector3d ( p.x, p.y, p.z ) );\n // TO-DO: 等之后研究,即为marginalization\n point->setMarginalized ( true ); // g2o 中必须设置 marg 参见第十讲内容\n // 最后加到optimizer里去\n optimizer.addVertex ( point );\n }\n\n // parameter: camera intrinsics\n g2o::CameraParameters* camera = new g2o::CameraParameters (\n // f和(cx,cy),默认fx=fy\n K.at ( 0,0 ), Eigen::Vector2d ( K.at ( 0,2 ), K.at ( 1,2 ) ), 0\n );\n camera->setId ( 0 );\n optimizer.addParameter ( camera );\n\n // edges,然后设置边\n index = 1;\n for ( const Point2f p:points_2d )\n {\n // 重投影误差边类EdgeProjectXYZ2UV\n // 把XYZ投影到UV平面上,做成了一个误差\n // 在这里有一个computeError函数,可以看到reprojection error的定义!\n g2o::EdgeProjectXYZ2UV* edge = new g2o::EdgeProjectXYZ2UV();\n // 设置Id\n edge->setId ( index );\n // 每个边的两侧分别是pose和Landmark\n edge->setVertex ( 0, dynamic_cast ( 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 // 最后求解\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 time_used = chrono::duration_cast> ( t2-t1 );\n cout<<\"optimization costs time: \"<estimate() ).matrix() <estimate() ).matrix();\n Eigen::Matrix3d R_out = output.block(0,0,3,3); // 利用Eigen的block函数获取子矩阵\n Eigen::Vector3d T_out = output.block(0,3,3,4);\n cout<<\"R_out=\"<\n#include \n#include \n#include \n#include \n#include \n\nstruct Element\n{\n\tvoid CalculateStiffnessMatrix(const Eigen::Matrix3f& D, std::vector >& triplets);\n\n\tEigen::Matrix B;\n\tint nodesIds[3];\n};\n\nstruct Constraint\n{\n\tenum Type\n\t{\n\t\tUX = 1 << 0,\n\t\tUY = 1 << 1,\n\t\tUXY = UX | UY\n\t};\n\tint node;\n\tType type;\n};\n\nint \tnodesCount;\nEigen::VectorXf \tnodesX;\nEigen::VectorXf \tnodesY;\nEigen::VectorXf \tloads;\nstd::vector< Element > \telements;\nstd::vector< Constraint >\tconstraints;\n\nvoid Element::CalculateStiffnessMatrix(const Eigen::Matrix3f& D, std::vector >& triplets)\n{\n\tEigen::Vector3f x, y;\n\tx << nodesX[nodesIds[0]], nodesX[nodesIds[1]], nodesX[nodesIds[2]];\n\ty << nodesY[nodesIds[0]], nodesY[nodesIds[1]], nodesY[nodesIds[2]];\n\t\n\tEigen::Matrix3f C;\n\tC << Eigen::Vector3f(1.0f, 1.0f, 1.0f), x, y;\n\t\n\tEigen::Matrix3f IC = C.inverse();\n\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tB(0, 2 * i + 0) = IC(1, i);\n\t\tB(0, 2 * i + 1) = 0.0f;\n\t\tB(1, 2 * i + 0) = 0.0f;\n\t\tB(1, 2 * i + 1) = IC(2, i);\n\t\tB(2, 2 * i + 0) = IC(2, i);\n\t\tB(2, 2 * i + 1) = IC(1, i);\n\t}\n\tEigen::Matrix K = B.transpose() * D * B * std::abs(C.determinant()) / 2.0f;\n\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tfor (int j = 0; j < 3; j++)\n\t\t{\n\t\t\tEigen::Triplet trplt11(2 * nodesIds[i] + 0, 2 * nodesIds[j] + 0, K(2 * i + 0, 2 * j + 0));\n\t\t\tEigen::Triplet trplt12(2 * nodesIds[i] + 0, 2 * nodesIds[j] + 1, K(2 * i + 0, 2 * j + 1));\n\t\t\tEigen::Triplet trplt21(2 * nodesIds[i] + 1, 2 * nodesIds[j] + 0, K(2 * i + 1, 2 * j + 0));\n\t\t\tEigen::Triplet trplt22(2 * nodesIds[i] + 1, 2 * nodesIds[j] + 1, K(2 * i + 1, 2 * j + 1));\n\n\t\t\ttriplets.push_back(trplt11);\n\t\t\ttriplets.push_back(trplt12);\n\t\t\ttriplets.push_back(trplt21);\n\t\t\ttriplets.push_back(trplt22);\n\t\t}\n\t}\n}\n\nvoid SetConstraints(Eigen::SparseMatrix::InnerIterator& it, int index)\n{\n\tif (it.row() == index || it.col() == index)\n\t{\n\t\tit.valueRef() = it.row() == it.col() ? 1.0f : 0.0f;\n\t}\n}\n\nvoid ApplyConstraints(Eigen::SparseMatrix& K, const std::vector& constraints)\n{\n\tstd::vector indicesToConstraint;\n\n\tfor (std::vector::const_iterator it = constraints.begin(); it != constraints.end(); ++it)\n\t{\n\t\tif (it->type & Constraint::UX)\n\t\t{\n\t\t\tindicesToConstraint.push_back(2 * it->node + 0);\n\t\t}\n\t\tif (it->type & Constraint::UY)\n\t\t{\n\t\t\tindicesToConstraint.push_back(2 * it->node + 1);\n\t\t}\n\t}\n\n\tfor (int k = 0; k < K.outerSize(); ++k)\n\t{\n\t\tfor (Eigen::SparseMatrix::InnerIterator it(K, k); it; ++it)\n\t\t{\n\t\t\tfor (std::vector::iterator idit = indicesToConstraint.begin(); idit != indicesToConstraint.end(); ++idit)\n\t\t\t{\n\t\t\t\tSetConstraints(it, *idit);\n\t\t\t}\n\t\t}\n\t}\n}\n\nint main(int argc, char *argv[])\n{\n\tif ( argc != 3 )\n {\n std::cout<<\"usage: \"<< argv[0] <<\" const& v) : x{v.x}, y{v.y} {}\n\t};\n\n\tusing Vector2f = Vector2;\n\tusing Vector2d = Vector2;\n\tusing Vector2ld = Vector2;\n\n\ttemplate \n\tbool operator==(Vector2 const& v1, Vector2 const& v2)\n\t{\n\t\treturn v1.x == v2.x && v1.y == v2.y;\n\t}\n\n\ttemplate \n\tVector2& operator+=(Vector2& v1, Vector2 const& v2)\n\t{\n\t\tv1.x += v2.x;\n\t\tv1.y += v2.y;\n\t\treturn v1;\n\t}\n\n\ttemplate \n\tVector2& operator-=(Vector2& v1, Vector2 const& v2)\n\t{\n\t\tv1.x -= v2.x;\n\t\tv1.y -= v2.y;\n\t\treturn v1;\n\t}\n\n\ttemplate \n\tVector2& operator*=(Vector2& v, T t)\n\t{\n\t\tv.x *= t;\n\t\tv.y *= t;\n\t\treturn v;\n\t}\n\n\ttemplate \n\tVector2& operator/=(Vector2& v, T t)\n\t{\n\t\tv.x /= t;\n\t\tv.y /= t;\n\t\treturn v;\n\t}\n\n\ttemplate \n\tVector2 operator+(Vector2 const& v)\n\t{\n\t\treturn v;\n\t}\n\n\ttemplate \n\tVector2 operator-(Vector2 const& v)\n\t{\n\t\treturn {-v.x, -v.y};\n\t}\n\n\ttemplate \n\tT dot(Vector2 const& v1, Vector2 const& v2)\n\t{\n\t\treturn v1.x * v2.x + v1.y * v2.y;\n\t}\n\n\ttemplate \n\tT norm(Vector2 const& v)\n\t{\n\t\treturn std::sqrt(dot(v, v));\n\t}\n\n\ttemplate \n\tVector2 normalize(Vector2 const& v)\n\t{\n\t\treturn v / norm(v);\n\t}\n\n} // namespace ext\n\n#endif // !HEADER_EXT_VECTOR2_HPP_INCLUDED\n", "meta": {"hexsha": "5bff431f0bda6cf28f77ea7b84ffcbb544679233", "size": 2393, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ext/vector2.hpp", "max_stars_repo_name": "Biolunar/ext", "max_stars_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/ext/vector2.hpp", "max_issues_repo_name": "Biolunar/ext", "max_issues_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/ext/vector2.hpp", "max_forks_repo_name": "Biolunar/ext", "max_forks_repo_head_hexsha": "2035c73a1abae89a392dc75d0228c200d05387d9", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7768595041, "max_line_length": 75, "alphanum_fraction": 0.6498119515, "num_tokens": 738, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933359135361, "lm_q2_score": 0.8006920020959544, "lm_q1q2_score": 0.6564820366377401}} {"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"AlgorithmUtils.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \n#include \n#include \n#include \n\nnamespace fluid {\nnamespace algorithm {\n\nclass OnsetDetectionFuncs\n{\n\npublic:\n enum class ODF {\n kEnergy,\n kHFC,\n kSpectralFlux,\n kMKL,\n kIS,\n kCosine,\n kPhaseDev,\n kWPhaseDev,\n kComplexDev,\n kRComplexDev\n };\n\n using ArrayXcd = Eigen::ArrayXcd;\n using ArrayXd = Eigen::ArrayXd;\n using ODFMap =\n std::map>;\n\n static ArrayXd wrapPhase(ArrayXd phase)\n {\n return phase.unaryExpr([=](const double p) {\n return p > (-pi) && p > pi\n ? p\n : p + (twoPi) * (1.0 + floor((-pi - p) / twoPi));\n });\n }\n\n static ODFMap& map()\n {\n static ODFMap _funcs = {\n\n {ODF::kEnergy,\n [](ArrayXcd cur, ArrayXcd /*prev*/, ArrayXcd /*prevprev*/) {\n return cur.abs().real().square().mean();\n }},\n {ODF::kHFC,\n [](ArrayXcd cur, ArrayXcd /*prev*/, ArrayXcd /*prevprev*/) {\n index n = cur.size();\n ArrayXd space = ArrayXd(n);\n space.setLinSpaced(0, n);\n return (space * cur.abs().real().square()).mean();\n }},\n {ODF::kSpectralFlux,\n [](ArrayXcd cur, ArrayXcd prev, ArrayXcd /*prevprev*/) {\n return (cur.abs().real() - prev.abs().real()).max(0.0).mean();\n }},\n {ODF::kMKL,\n [](ArrayXcd cur, ArrayXcd prev, ArrayXcd /*prevprev*/) {\n ArrayXd mag1 = cur.abs().real().max(epsilon);\n ArrayXd mag2 = prev.abs().real().max(epsilon);\n return (mag1 / mag2).max(epsilon).log().mean();\n }},\n {ODF::kIS,\n [](ArrayXcd cur, ArrayXcd prev, ArrayXcd /*prevprev*/) {\n ArrayXd mag1 = cur.abs().real().max(epsilon);\n ArrayXd mag2 = prev.abs().real().max(epsilon);\n ArrayXd ratio = (mag1 / mag2).square().max(epsilon);\n return (ratio - ratio.log() - 1).mean();\n }},\n {ODF::kCosine,\n [](ArrayXcd cur, ArrayXcd prev, ArrayXcd /*prevprev*/) {\n ArrayXd mag1 = cur.abs().real().max(epsilon);\n ArrayXd mag2 = prev.abs().real().max(epsilon);\n double norm = mag1.matrix().norm() * mag2.matrix().norm();\n double dot = mag1.matrix().dot(mag2.matrix());\n return dot / norm;\n }},\n {ODF::kPhaseDev,\n [](ArrayXcd cur, ArrayXcd prev, ArrayXcd prevprev) {\n ArrayXd phaseAcc = (cur.atan().real() - prev.atan().real()) -\n (prev.atan().real() - prevprev.atan().real());\n return wrapPhase(phaseAcc).mean();\n }},\n {ODF::kWPhaseDev,\n [](ArrayXcd cur, ArrayXcd prev, ArrayXcd prevprev) {\n ArrayXd mag1 = cur.abs().real().max(epsilon);\n ArrayXd phaseAcc = (cur.atan().real() - prev.atan().real()) -\n (prev.atan().real() - prevprev.atan().real());\n return wrapPhase(mag1 * phaseAcc).mean();\n }},\n {ODF::kComplexDev,\n [](ArrayXcd cur, ArrayXcd prev, ArrayXcd prevprev) {\n ArrayXcd target(cur.size());\n ArrayXd prevMag = prev.abs().real().max(epsilon);\n ArrayXd prevPhase = prev.atan().real();\n ArrayXd phaseEst = wrapPhase(\n prevPhase + (prev.atan().real() - prevprev.atan().real()));\n target.real() = prevMag * phaseEst.cos();\n target.imag() = prevMag * phaseEst.sin();\n return (target - cur).abs().real().mean();\n }},\n {ODF::kRComplexDev,\n [](ArrayXcd cur, ArrayXcd prev, ArrayXcd prevprev) {\n ArrayXcd target(cur.size());\n ArrayXd prevMag = prev.abs().real().max(epsilon);\n ArrayXd prevPhase = prev.atan().real();\n ArrayXd phaseEst = wrapPhase(\n prevPhase + (prev.atan().real() - prevprev.atan().real()));\n target.real() = prevMag * phaseEst.cos();\n target.imag() = prevMag * phaseEst.sin();\n return (target - cur).abs().real().max(0.0).mean();\n }},\n };\n return _funcs;\n }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "a97f3008163594431c1b5b785e69da83d4d26bbf", "size": 4661, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/OnsetDetectionFuncs.hpp", "max_stars_repo_name": "elgiano/flucoma-core", "max_stars_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/algorithms/util/OnsetDetectionFuncs.hpp", "max_issues_repo_name": "elgiano/flucoma-core", "max_issues_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/algorithms/util/OnsetDetectionFuncs.hpp", "max_forks_repo_name": "elgiano/flucoma-core", "max_forks_repo_head_hexsha": "d34a04e7a68f24eaf09b24df57020d45664061fc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.5259259259, "max_line_length": 76, "alphanum_fraction": 0.5509547307, "num_tokens": 1232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9343951588871156, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6564406787832269}} {"text": "#include \"BayesFilters/WhiteNoiseAcceleration.h\"\n\n#include \n#include \n\n#include \n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration(float T, float tilde_q, unsigned int seed) noexcept :\n T_(T), tilde_q_(tilde_q),\n generator_(std::mt19937_64(seed)), distribution_(std::normal_distribution(0.0, 1.0)), gauss_rnd_sample_([&] { return (distribution_)(generator_); })\n{\n F_ << 1.0, T_, 0.0, 0.0,\n 0.0, 1.0, 0.0, 0.0,\n 0.0, 0.0, 1.0, T_,\n 0.0, 0.0, 0.0, 1.0;\n\n float q11 = 1.0/3.0 * std::pow(T_, 3.0);\n float q2 = 1.0/2.0 * std::pow(T_, 2.0);\n Q_ << q11, q2, 0.0, 0.0,\n q2, T_, 0.0, 0.0,\n 0.0, 0.0, q11, q2,\n 0.0, 0.0, q2, T_;\n Q_ *= tilde_q;\n\n LDLT chol_ldlt(Q_);\n sqrt_Q_ = (chol_ldlt.transpositionsP() * Matrix4f::Identity()).transpose() * chol_ldlt.matrixL() * chol_ldlt.vectorD().real().cwiseSqrt().asDiagonal();\n}\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration(float T, float tilde_q) noexcept :\n WhiteNoiseAcceleration(T, tilde_q, 1) { }\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration() noexcept :\n WhiteNoiseAcceleration(1.0, 1.0, 1) { }\n\n\nWhiteNoiseAcceleration::~WhiteNoiseAcceleration() noexcept { }\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration(const WhiteNoiseAcceleration& wna) :\n T_(wna.T_), F_(wna.F_), Q_(wna.Q_), tilde_q_(wna.tilde_q_),\n sqrt_Q_(wna.sqrt_Q_), generator_(wna.generator_), distribution_(wna.distribution_), gauss_rnd_sample_(wna.gauss_rnd_sample_) { }\n\n\nWhiteNoiseAcceleration::WhiteNoiseAcceleration(WhiteNoiseAcceleration&& wna) noexcept :\n T_(wna.T_), F_(std::move(wna.F_)), Q_(std::move(wna.Q_)), tilde_q_(wna.tilde_q_),\n sqrt_Q_(std::move(wna.sqrt_Q_)), generator_(std::move(wna.generator_)), distribution_(std::move(wna.distribution_)), gauss_rnd_sample_(std::move(wna.gauss_rnd_sample_))\n{\n wna.T_ = 0.0;\n wna.tilde_q_ = 0.0;\n}\n\n\nWhiteNoiseAcceleration& WhiteNoiseAcceleration::operator=(const WhiteNoiseAcceleration& wna)\n{\n WhiteNoiseAcceleration tmp(wna);\n *this = std::move(tmp);\n\n return *this;\n}\n\n\nWhiteNoiseAcceleration& WhiteNoiseAcceleration::operator=(WhiteNoiseAcceleration&& wna) noexcept\n{\n T_ = wna.T_;\n F_ = std::move(wna.F_);\n Q_ = std::move(wna.Q_);\n tilde_q_ = wna.tilde_q_;\n\n sqrt_Q_ = std::move(wna.sqrt_Q_);\n generator_ = std::move(wna.generator_);\n distribution_ = std::move(wna.distribution_);\n gauss_rnd_sample_ = std::move(wna.gauss_rnd_sample_);\n\n wna.T_ = 0.0;\n wna.tilde_q_ = 0.0;\n\n return *this;\n}\n\n\nvoid WhiteNoiseAcceleration::propagate(const Ref& cur_states, Ref prop_states)\n{\n prop_states = F_ * cur_states;\n}\n\n\nvoid WhiteNoiseAcceleration::motion(const Ref& cur_states, Ref prop_states)\n{\n propagate(cur_states, prop_states);\n\n prop_states += getNoiseSample(prop_states.cols());\n}\n\n\nMatrixXf WhiteNoiseAcceleration::getNoiseSample(const int num)\n{\n MatrixXf rand_vectors(4, num);\n for (int i = 0; i < rand_vectors.size(); i++)\n *(rand_vectors.data() + i) = gauss_rnd_sample_();\n\n return sqrt_Q_ * rand_vectors;\n}\n\n\nMatrixXf WhiteNoiseAcceleration::getNoiseCovarianceMatrix()\n{\n return Q_;\n}\n", "meta": {"hexsha": "7b784c0ccab9c2b68e339677f9861c88820865bb", "size": 3346, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesFilters/src/WhiteNoiseAcceleration.cpp", "max_stars_repo_name": "claudiofantacci/bayes-filters-lib", "max_stars_repo_head_hexsha": "06a7f88c028a709e8a5288432d057d41d705603b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BayesFilters/src/WhiteNoiseAcceleration.cpp", "max_issues_repo_name": "claudiofantacci/bayes-filters-lib", "max_issues_repo_head_hexsha": "06a7f88c028a709e8a5288432d057d41d705603b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BayesFilters/src/WhiteNoiseAcceleration.cpp", "max_forks_repo_name": "claudiofantacci/bayes-filters-lib", "max_forks_repo_head_hexsha": "06a7f88c028a709e8a5288432d057d41d705603b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0956521739, "max_line_length": 172, "alphanum_fraction": 0.6772265392, "num_tokens": 1062, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942203004185, "lm_q2_score": 0.7371581684030621, "lm_q1q2_score": 0.6562876567764888}} {"text": "#pragma once\n\n#include \n#include \n#include \n\nnamespace dr {\n\n/// Calculate average orientation using quaternions\ntemplate\nEigen::Quaternion averageQuaternions(ForwardIterator const & begin, ForwardIterator const & end) {\n\n\tif (begin == end) {\n\t\tthrow std::logic_error(\"Cannot average orientations over an empty range.\");\n\t}\n\n\tEigen::Matrix A = Eigen::Matrix::Zero();\n\tuint sum(0);\n\tfor (ForwardIterator it = begin; it != end; ++it) {\n\t\tEigen::Matrix q(1,4);\n\t\tq(0) = it->w();\n\t\tq(1) = it->x();\n\t\tq(2) = it->y();\n\t\tq(3) = it->z();\n\t\tA += q.transpose()*q;\n\t\tsum++;\n\t}\n\tA /= sum;\n\n\tEigen::EigenSolver> es(A);\n\n\tEigen::Matrix, 4, 1> mat(es.eigenvalues());\n\tint index;\n\tmat.real().maxCoeff(&index);\n\tEigen::Matrix largest_ev(es.eigenvectors().real().block(0, index, 4, 1));\n\n\treturn Eigen::Quaternion(largest_ev(0), largest_ev(1), largest_ev(2), largest_ev(3));\n}\n\n/// Overloaded function to calculate the average quaternion for some container types\ntemplate\ntypename Eigen::Quaternion averageQuaternions(Container const & container) {\n\treturn averageQuaternions(container.begin(), container.end());\n}\n\n/// Calculate average position\ntemplate\nEigen::Matrix averagePositions(ForwardIterator const & begin, ForwardIterator const & end) {\n\tif (begin == end) {\n\t\tthrow std::logic_error(\"Cannot average orientations over an empty range.\");\n\t}\n\n\tDataType x(0), y(0), z(0);\n\tuint count(0);\n\tfor (ForwardIterator it = begin; it!=end; ++it) {\n\t\tx += it->x();\n\t\ty += it->y();\n\t\tz += it->z();\n\t\tcount++;\n\t}\n\tx /= count;\n\ty /= count;\n\tz /= count;\n\n\treturn Eigen::Matrix(x,y,z);\n}\n\n/// Overloaded function to calculate the average position for some container types\ntemplate\ntypename Eigen::Matrix averagePositions(Container const & container) {\n\treturn averagePositions(container.begin(), container.end());\n}\n\ntemplate\nEigen::Transform averageIsometries(ForwardIterator const & begin, ForwardIterator const & end) {\n\n\tstd::vector positions;\n\tstd::vector quaternions;\n\n\tfor (auto it = begin; it != end; ++it) {\n\t\tpositions.push_back(it->translation());\n\t\tquaternions.push_back(Eigen::Quaternion(it->rotation()));\n\t}\n\n\treturn Eigen::Translation(averagePositions(positions)) * averageQuaternions(quaternions);\n}\n\ntemplate\nEigen::Transform averageIsometries(Container const & container) {\n\treturn averageIsometries(container.begin(), container.end());\n}\n\n}\n", "meta": {"hexsha": "c0769803cdbbd8cc75adf1d195661d0fdbdb0b9b", "size": 3000, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dr_eigen/average.hpp", "max_stars_repo_name": "delftrobotics/dr_eigen", "max_stars_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-06-02T14:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2017-06-02T14:14:37.000Z", "max_issues_repo_path": "include/dr_eigen/average.hpp", "max_issues_repo_name": "delftrobotics/dr_eigen", "max_issues_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/dr_eigen/average.hpp", "max_forks_repo_name": "delftrobotics/dr_eigen", "max_forks_repo_head_hexsha": "47022c2e1648c1b514ff493b25b3ebe54a7ddc7d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.914893617, "max_line_length": 126, "alphanum_fraction": 0.7153333333, "num_tokens": 785, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553433, "lm_q2_score": 0.7310585844894971, "lm_q1q2_score": 0.6562678575545094}} {"text": "/*\n * This file is part of the ProVANT simulator project.\n * Licensed under the terms of the MIT open source license. More details at\n * https://github.com/Guiraffo/ProVANT-Simulator/blob/master/LICENSE.md\n */\n/**\n * @file This file contains the implementation of the LQRQuadcopter class.\n *\n * @author Jonatan Campos\n */\n\n#include \n#include \n#include \"simulator_msgs/Sensor.h\"\n#include \n\nstatic const int NINPUTS = 4;\nstatic const int NSTATES = 12;\n\n/**\n * @brief The LQRQuadcopter implements a Linear Quadratic Regulator control\n * strategy for the quadrotor UAV that is available in the ProVANT simulator.\n *\n * This controller uses a helicoidal reference trajectory.\n *\n * This control strategy expects a state vector composed of the generalized\n * coordinates and their derivatives in the following order:\n * [x y z phi theta psi x_dot y_dot z_dot phi_dot theta_dot psi_dot]\n *\n * x, y and z are the cartesian coordinates of the UAV center of rotation in\n * relation with the inertial reference frame and expressed in meters,\n * phi is the rotation around the x axis, theta is the rotation around the y\n * axis and psi is the rotation around the z axis, all of the angles of rotation\n * are expressed in radians.\n *\n * x_dot, y_dot and z_dot are the time derivatives of the cartesian coordinates,\n * that equal the linear velocities of the UAV in relation with the inertial\n * frame. The values are given in m/s.\n *\n * Finally, phi_dot, theta_dot and psi_dot are the time derivatives of the Euler\n * Angles, given in rad/s.\n *\n * The control inputs of this system are the forces generated by each propeller\n * in the order f1, f2, f3 and f4, where fi is the force of the i-th propeller.\n * All of the forces are expressed in Newtons.\n *\n */\nclass LQRQuadcopter : public Icontroller\n{\nprivate:\n //! Stores the reference vector\n Eigen::VectorXd Xref;\n //! Stores the error vector\n Eigen::VectorXd Erro;\n //! Stores the control inputs\n Eigen::VectorXd Input;\n //! Stores the gain matrix of the system\n Eigen::MatrixXd K;\n //! Stores the state vector\n Eigen::VectorXd X;\n\npublic:\n /**\n * @brief Construct a new LQRQuadcopter object and initialize the size of\n * the matrices used in the controller.\n */\n LQRQuadcopter() : Xref(NSTATES), K(NINPUTS, NSTATES), X(NSTATES), Erro(NSTATES), Input(NINPUTS)\n {\n config();\n }\n\n /**\n * @brief Destroy the LQRQuadcopter object.\n */\n virtual ~LQRQuadcopter()\n {\n }\n\n /**\n * @brief Initialize the gain matrix K.\n */\n void config()\n {\n K << -70.711, 2.1302e-11, 7.0711, -2.3813e-12, -156.46, 5, -165.1, 4.7388e-11, 11.53, 8.2065e-13, -7.5435, 5.7987,\n 1.3204e-11, -70.711, 7.0711, 156.46, 8.257e-11, -5, 3.1756e-11, -165.1, 11.53, 7.5435, 8.1385e-12, -5.7987,\n 70.711, 3.9104e-11, 7.0711, -4.7265e-11, 156.46, 5, 165.1, 8.9701e-11, 11.53, 9.2039e-13, 7.5435, 5.7987,\n -5.6384e-12, 70.711, 7.0711, -156.46, 6.4636e-11, -5, -8.3103e-12, 165.1, 11.53, -7.5435, 8.4109e-12, -5.7987;\n }\n\n /**\n * @brief Execute the LQR control law.\n *\n * This method is called every simulation step.\n * It is responsible for reading the state vector from the arraymsg,\n * calculating the reference trajectory, the error vector, and must return\n * the control inputs to be applied on the system.\n *\n * @param arraymsg Array of simulator messages containing the sensors\n * of the quadrotor model. In this case, the only sensor is the state vector.\n * @returns Control inputs vector to be applied on the system. See the\n * class documentation for more details.\n */\n std::vector execute(simulator_msgs::SensorArray arraymsg)\n {\n // Search for the state vector in the recevied messages\n simulator_msgs::Sensor msg;\n bool found = false;\n for (int i = 0; i < arraymsg.values.size(); i++)\n {\n if (arraymsg.values.at(i).name == \"Estados\")\n {\n msg = arraymsg.values.at(i);\n found = true;\n break;\n }\n }\n if (!found)\n {\n // In case of error, report the problem in a ROS_LOG, and returns an\n // empty array\n ROS_FATAL(\"[lqr_quadcopter] State vector not found.\");\n std::vector out(Input.data(), Input.data() + Input.size());\n return out;\n }\n\n // Get the current simulation time and calculate the reference trajectory.\n ros::Time time = ros::Time::now();\n double tempo = time.toSec();\n\n Xref << sin(tempo / 2), cos(tempo / 2), tempo / 10, 0, 0, 0, 0, 0, 0, 0, 0, 0;\n\n // Read the values of the state vector from the message\n X << msg.values.at(0), // x\n msg.values.at(1), // y\n msg.values.at(2), // z\n msg.values.at(3), // roll\n msg.values.at(4), // pitch\n msg.values.at(5), // yaw\n msg.values.at(6), // x_dot\n msg.values.at(7), // y_dot\n msg.values.at(8), // z_dot\n msg.values.at(9), // roll_dot\n msg.values.at(10), // pitch_dot\n msg.values.at(11); // yaw_dot\n\n // Calculate the error vector of the system\n Erro = X - Xref;\n\n // Execute the control law (Multiply the gain matrix by the error vector)\n Input = -K * Erro;\n\n // Add equilibirium forces to the outputs.\n\n Input(0) = Input(0) + 5.77611;\n Input(1) = Input(1) + 5.77611;\n Input(2) = Input(2) + 5.77611;\n Input(3) = Input(3) + 5.77611;\n\n ROS_DEBUG_STREAM_NAMED(\"lqr_quadcopter\", \"[LQRQuadcopter]: F1: \" << Input(0));\n ROS_DEBUG_STREAM_NAMED(\"lqr_quadcopter\", \"[LQRQuadcopter]: F2: \" << Input(1));\n ROS_DEBUG_STREAM_NAMED(\"lqr_quadcopter\", \"[LQRQuadcopter]: F3: \" << Input(2));\n ROS_DEBUG_STREAM_NAMED(\"lqr_quadcopter\", \"[LQRQuadcopter]: F4: \" << Input(3));\n \n // Copy the control inputs values to the output vector\n std::vector out(Input.data(), Input.data() + Input.size());\n return out;\n }\n\n /**\n * @brief Reference()\n *\n * This method is called by the logging functions to report the\n * reference values for the current step.\n *\n * @returns Reference vector for the current step. This vector is in the same\n * order of the state vector.\n */\n std::vector Reference()\n {\n // Copy the references to a std::vector\n std::vector out(Xref.data(), Xref.data() + Xref.rows() * Xref.cols());\n return out;\n }\n\n /**\n * @brief Error()\n *\n * This method is called by the logging functions to get the error vector\n * used in the control law execution.\n *\n * @returns The error vector of the system in the current step. The error\n * vector is in the same order of the state vector.\n */\n std::vector Error()\n {\n // Copy the references to a std::vector\n std::vector out(Erro.data(), Erro.data() + Erro.rows() * Erro.cols());\n return out;\n }\n\n /**\n * @brief State()\n *\n * This method is called by the logging functions to get the state vector\n * used in the control law execution.\n * Note that if the implmeneted controller uses an augmented state vector,\n * for example, with integral sates, these values should also be returned\n * by this function.\n *\n * @returns The state vector of the system used in the calculation of the\n * control law in the current step time. This vector is in the same order\n * as the states vector.\n */\n std::vector State()\n {\n std::vector out(X.data(), X.data() + X.rows() * X.cols());\n return out;\n }\n};\n\n// Functions used by the ProVANT Simulator to instantiate this control law\nextern \"C\" {\nIcontroller* create(void)\n{\n return new LQRQuadcopter;\n}\nvoid destroy(Icontroller* p)\n{\n delete p;\n}\n}\n", "meta": {"hexsha": "a77007091ab3246596ef82739c5a6e0d29253b1e", "size": 7646, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/Structure/control_strategies/lqr_quadcopter/src/main.cpp", "max_stars_repo_name": "Guiraffo/ProVANT_Simulator", "max_stars_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/Structure/control_strategies/lqr_quadcopter/src/main.cpp", "max_issues_repo_name": "Guiraffo/ProVANT_Simulator", "max_issues_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/Structure/control_strategies/lqr_quadcopter/src/main.cpp", "max_forks_repo_name": "Guiraffo/ProVANT_Simulator", "max_forks_repo_head_hexsha": "ef2260204b13f39a9f83ad2ab88a9552a0699bff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.9568965517, "max_line_length": 118, "alphanum_fraction": 0.655898509, "num_tokens": 2223, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9173026595857203, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.656260339629384}} {"text": "#ifndef _CELERITE2_FORWARD_HPP_DEFINED_\n#define _CELERITE2_FORWARD_HPP_DEFINED_\n\n#include \n#include \"internal.hpp\"\nnamespace celerite2 {\nnamespace core {\n\n/**\n * \\brief Get the dense representation of a celerite matrix\n *\n * @param t (N,): The input coordinates (must be sorted)\n * @param c (J,): The transport coefficients\n * @param a (N,): The diagonal component\n * @param U (N, J): The first low rank matrix\n * @param V (N, J): The second low rank matrix\n * @param K_out (N, N): The dense matrix\n */\ntemplate \nvoid to_dense(const Eigen::MatrixBase &t, // (N,)\n const Eigen::MatrixBase &c, // (J,)\n const Eigen::MatrixBase &a, // (N,)\n const Eigen::MatrixBase &U, // (N, J)\n const Eigen::MatrixBase &V, // (N, J)\n Eigen::MatrixBase const &K_out // (N,)\n) {\n typedef typename Eigen::internal::plain_row_type::type RowVector;\n\n Eigen::Index N = U.rows(), J = U.cols();\n CAST_MAT(Dense, K, N, N);\n\n RowVector p(1, J);\n for (Eigen::Index m = 0; m < N; ++m) {\n p.setConstant(1.0);\n K(m, m) = a(m);\n for (Eigen::Index n = m + 1; n < N; ++n) {\n p.array() *= exp(-c.array() * (t(n) - t(n - 1)));\n K(n, m) = (U.row(n).array() * V.row(m).array() * p.array()).sum();\n K(m, n) = K(n, m);\n }\n }\n}\n\n/**\n * \\brief Compute the Cholesky factorization of the system\n *\n * This computes `d` and `W` such that:\n *\n * `K = L*diag(d)*L^T`\n *\n * where `K` is the celerite matrix and\n *\n * `L = 1 + tril(U*W^T)`\n *\n * This can be safely applied in place: `d_out` can point to `a` and `W_out` can\n * point to `V`, and the memory will be reused. In this particular case, the\n * `celerite2::core::factor_rev` function doesn't use `a` and `V`, but this\n * won't be true for all `_rev` functions.\n *\n * @param t (N,): The input coordinates (must be sorted)\n * @param c (J,): The transport coefficients\n * @param a (N,): The diagonal component\n * @param U (N, J): The first low rank matrix\n * @param V (N, J): The second low rank matrix\n * @param d_out (N,): The diagonal component of the Cholesky factor\n * @param W_out (N, J): The second low rank component of the Cholesky factor\n * @param S_out (N, J*J): The cached value of the S matrix at each step\n */\ntemplate \nEigen::Index factor(const Eigen::MatrixBase &t, // (N,)\n const Eigen::MatrixBase &c, // (J,)\n const Eigen::MatrixBase &a, // (N,)\n const Eigen::MatrixBase &U, // (N, J)\n const Eigen::MatrixBase &V, // (N, J)\n Eigen::MatrixBase const &d_out, // (N,)\n Eigen::MatrixBase const &W_out, // (N, J)\n Eigen::MatrixBase const &S_out // (N, J*J)\n) {\n ASSERT_ROW_MAJOR(Work);\n\n typedef typename Diag::Scalar Scalar;\n typedef typename Eigen::internal::plain_row_type::type RowVector;\n typedef typename Eigen::internal::plain_col_type::type CoeffVector;\n\n Eigen::Index N = U.rows(), J = U.cols();\n CAST_VEC(DiagOut, d, N);\n CAST_MAT(LowRankOut, W, N, J);\n CAST_BASE(Work, S);\n if (update_workspace) {\n S.derived().resize(N, J * J);\n S.row(0).setZero();\n }\n\n // This is a temporary vector used to minimize computations internally\n RowVector tmp;\n CoeffVector p;\n\n // This holds the accumulated value of the S matrix at each step\n Eigen::Matrix Sn(J, J);\n\n // This is a flattened pointer to Sn that is used for copying the data\n Eigen::Map::type> ptr(Sn.data(), 1, J * J);\n\n // First row\n Sn.setZero();\n d(0) = a(0);\n W.row(0).noalias() = V.row(0) / d(0);\n\n // The rest of the rows\n for (Eigen::Index n = 1; n < N; ++n) {\n p = exp(c.array() * (t(n - 1) - t(n)));\n\n // Update S_n = diag(P) * (S_n-1 + d*W*W.T) * diag(P)\n Sn.noalias() += d(n - 1) * W.row(n - 1).transpose() * W.row(n - 1);\n Sn = p.asDiagonal() * Sn;\n\n // Save the current value of Sn to the workspace\n // Note: This is actually `diag(P) * (S + d*W*W.T)` without the final `* diag(P)`\n internal::update_workspace::apply(n, ptr, S);\n\n // Incorporate the second diag(P) that we didn't include above for bookkeeping\n Sn *= p.asDiagonal();\n\n // Update d = a - U * S * U.T\n tmp = U.row(n) * Sn;\n d(n) = a(n) - tmp * U.row(n).transpose();\n if (d(n) <= 0.0) return n;\n\n // Update W = (V - U * S) / d\n W.row(n).noalias() = (V.row(n) - tmp) / d(n);\n }\n\n return 0;\n}\n\n/**\n * \\brief Apply a strictly lower matrix multiply\n *\n * This computes:\n *\n * `Z += tril(U * V^T) * Y`\n *\n * where `tril` is the strictly lower triangular function.\n *\n * Note that this will *update* the value of `Z`.\n *\n * @param t (N,): The input coordinates (must be sorted)\n * @param c (J,): The transport coefficients\n * @param U (N, J): The first low rank matrix\n * @param W (N, J): The second low rank matrix\n * @param Y (N, Nrhs): The matrix to be multiplied\n * @param Z_out (N, Nrhs): The matrix to be updated\n * @param F_out (N, J*Nrhs): The workspace\n */\ntemplate \nvoid solve_lower(const Eigen::MatrixBase &t, // (N,)\n const Eigen::MatrixBase &c, // (J,)\n const Eigen::MatrixBase &U, // (N, J)\n const Eigen::MatrixBase &W, // (N, J)\n const Eigen::MatrixBase &Y, // (N, nrhs)\n Eigen::MatrixBase const &Z_out, // (N, nrhs)\n Eigen::MatrixBase const &F_out // (N, J*nrhs)\n) {\n ASSERT_ROW_MAJOR(Work);\n CAST_BASE(RightHandSideOut, Z);\n Z = Y;\n internal::forward(t, c, U, W, Y, Z, F_out);\n}\n\n/**\n * \\brief Compute the solution of a upper triangular linear equation\n *\n * This computes `Z` such that:\n *\n * `Y = L^T * Y`\n *\n * where\n *\n * `L = 1 + tril(U*W^T)`\n *\n * This can be safely applied in place.\n *\n * @param t (N,): The input coordinates (must be sorted)\n * @param c (J,): The transport coefficients\n * @param U (N, J): The first low rank matrix\n * @param W (N, J): The second low rank matrix\n * @param Y (N, Nrhs): The right hand side\n * @param Z_out (N, Nrhs): The solution of this equation\n * @param F_out (N, J*Nrhs): The workspace\n */\ntemplate \nvoid solve_upper(const Eigen::MatrixBase &t, // (N,)\n const Eigen::MatrixBase &c, // (J,)\n const Eigen::MatrixBase &U, // (N, J)\n const Eigen::MatrixBase &W, // (N, J)\n const Eigen::MatrixBase &Y, // (N, nrhs)\n Eigen::MatrixBase const &Z_out, // (N, nrhs)\n Eigen::MatrixBase const &F_out // (N, J*nrhs)\n) {\n ASSERT_ROW_MAJOR(Work);\n CAST_BASE(RightHandSideOut, Z);\n Z = Y;\n internal::backward(t, c, U, W, Y, Z, F_out);\n}\n\n/**\n * \\brief Apply a strictly lower matrix multiply\n *\n * This computes:\n *\n * `Z += tril(U * V^T) * Y`\n *\n * where `tril` is the strictly lower triangular function.\n *\n * Note that this will *update* the value of `Z`.\n *\n * @param t (N,): The input coordinates (must be sorted)\n * @param c (J,): The transport coefficients\n * @param U (N, J): The first low rank matrix\n * @param V (N, J): The second low rank matrix\n * @param Y (N, Nrhs): The matrix to be multiplied\n * @param Z_out (N, Nrhs): The matrix to be updated\n * @param F_out (N, J*Nrhs): The workspace\n */\ntemplate \nvoid matmul_lower(const Eigen::MatrixBase &t, // (N,)\n const Eigen::MatrixBase &c, // (J,)\n const Eigen::MatrixBase &U, // (N, J)\n const Eigen::MatrixBase &V, // (N, J)\n const Eigen::MatrixBase &Y, // (N, nrhs)\n Eigen::MatrixBase const &Z_out, // (N, nrhs)\n Eigen::MatrixBase const &F_out // (N, J*nrhs)\n) {\n internal::forward(t, c, U, V, Y, Z_out, F_out);\n}\n\n/**\n * \\brief Apply a strictly upper matrix multiply\n *\n * This computes:\n *\n * `Z += triu(V * U^T) * Y`\n *\n * where `triu` is the strictly lower triangular function.\n *\n * Note that this will *update* the value of `Z`.\n *\n * @param t (N,): The input coordinates (must be sorted)\n * @param c (J,): The transport coefficients\n * @param U (N, J): The first low rank matrix\n * @param V (N, J): The second low rank matrix\n * @param Y (N, Nrhs): The matrix to be multiplied\n * @param Z_out (N, Nrhs): The matrix to be updated\n * @param F_out (N, J*Nrhs): The workspace\n */\ntemplate \nvoid matmul_upper(const Eigen::MatrixBase &t, // (N,)\n const Eigen::MatrixBase &c, // (J,)\n const Eigen::MatrixBase &U, // (N, J)\n const Eigen::MatrixBase &V, // (N, J)\n const Eigen::MatrixBase &Y, // (N, nrhs)\n Eigen::MatrixBase const &Z_out, // (N, nrhs)\n Eigen::MatrixBase const &F_out // (N, J*nrhs)\n) {\n internal::backward(t, c, U, V, Y, Z_out, F_out);\n}\n\n/**\n * \\brief The general lower-triangular dot product of a rectangular celerite system\n *\n * @param t1 (N,): The left input coordinates (must be sorted)\n * @param t2 (M,): The right input coordinates (must be sorted)\n * @param c (J,): The transport coefficients\n * @param U (N, J): The first low rank matrix\n * @param V (M, J): The second low rank matrix\n * @param Y (M, Nrhs): The matrix that will be left multiplied by the celerite model\n * @param Z_out (N, Nrhs): The result of the operation\n * @param F_out (M, J*Nrhs): The workspace\n */\ntemplate \nvoid general_matmul_lower(const Eigen::MatrixBase &t1, // (N,)\n const Eigen::MatrixBase &t2, // (M,)\n const Eigen::MatrixBase &c, // (J,)\n const Eigen::MatrixBase &U, // (N, J)\n const Eigen::MatrixBase &V, // (M, J)\n const Eigen::MatrixBase &Y, // (M, nrhs)\n Eigen::MatrixBase const &Z_out, // (N, nrhs)\n Eigen::MatrixBase const &F_out // (M, J*nrhs)\n) {\n ASSERT_ROW_MAJOR(Work);\n\n typedef typename LowRank::Scalar Scalar;\n typedef typename Eigen::internal::plain_col_type::type CoeffVector;\n typedef typename Eigen::Matrix Inner;\n\n Eigen::Index N = t1.rows(), M = t2.rows(), J = c.rows(), nrhs = Y.cols();\n\n CAST_BASE(RightHandSideOut, Z);\n CAST_BASE(Work, F);\n if (do_update) {\n F.derived().resize(M, J * nrhs);\n F.row(0).setZero();\n }\n\n CoeffVector p(J);\n Inner Fm = V.row(0).transpose() * Y.row(0);\n Eigen::Map::type> ptr(Fm.data(), 1, J * nrhs);\n internal::update_workspace::apply(0, ptr, F);\n\n Scalar tn = t2(0);\n Eigen::Index n, m = 1;\n for (n = 0; n < N; ++n)\n if (t1(n) >= tn) break;\n for (; n < N; ++n) {\n tn = t1(n);\n while (m < M && t2(m) <= tn) {\n p = exp(c.array() * (t2(m - 1) - t2(m)));\n Fm = p.asDiagonal() * Fm;\n Fm.noalias() += V.row(m).transpose() * Y.row(m);\n internal::update_workspace::apply(m, ptr, F);\n m++;\n }\n p = exp(c.array() * (t2(m - 1) - tn));\n Z.row(n).noalias() += U.row(n) * p.asDiagonal() * Fm;\n }\n}\n\n/**\n * \\brief The general upper-triangular dot product of a rectangular celerite system\n *\n * @param t1 (N,): The left input coordinates (must be sorted)\n * @param t2 (M,): The right input coordinates (must be sorted)\n * @param c (J,): The transport coefficients\n * @param U (N, J): The first low rank matrix\n * @param V (M, J): The second low rank matrix\n * @param Y (M, Nrhs): The matrix that will be left multiplied by the celerite model\n * @param Z_out (N, Nrhs): The result of the operation\n * @param F_out (M, J*Nrhs): The workspace\n */\ntemplate \nvoid general_matmul_upper(const Eigen::MatrixBase &t1, // (N,)\n const Eigen::MatrixBase &t2, // (M,)\n const Eigen::MatrixBase &c, // (J,)\n const Eigen::MatrixBase &U, // (N, J)\n const Eigen::MatrixBase &V, // (M, J)\n const Eigen::MatrixBase &Y, // (M, nrhs)\n Eigen::MatrixBase const &Z_out, // (N, nrhs)\n Eigen::MatrixBase const &F_out // (M, J*nrhs)\n) {\n ASSERT_ROW_MAJOR(Work);\n\n typedef typename LowRank::Scalar Scalar;\n typedef typename Eigen::internal::plain_col_type::type CoeffVector;\n typedef typename Eigen::Matrix Inner;\n\n Eigen::Index N = t1.rows(), M = t2.rows(), J = c.rows(), nrhs = Y.cols();\n\n CAST_BASE(RightHandSideOut, Z);\n CAST_BASE(Work, F);\n if (do_update) {\n F.derived().resize(M, J * nrhs);\n F.row(0).setZero();\n }\n\n CoeffVector p(J);\n Inner Fm = V.row(M - 1).transpose() * Y.row(M - 1);\n Eigen::Map::type> ptr(Fm.data(), 1, J * nrhs);\n\n Scalar tn = t2(M - 1);\n Eigen::Index n, m = M - 2;\n for (n = N - 1; n >= 0; --n)\n if (t1(n) < tn) break;\n for (; n >= 0; --n) {\n tn = t1(n);\n while (m >= 0 && t2(m) > tn) {\n p = exp(c.array() * (t2(m) - t2(m + 1)));\n Fm = p.asDiagonal() * Fm;\n Fm.noalias() += V.row(m).transpose() * Y.row(m);\n internal::update_workspace::apply(m, ptr, F);\n m--;\n }\n p = exp(c.array() * (tn - t2(m + 1)));\n Z.row(n).noalias() += U.row(n) * p.asDiagonal() * Fm;\n }\n}\n\n} // namespace core\n} // namespace celerite2\n\n#endif // _CELERITE2_FORWARD_HPP_DEFINED_\n", "meta": {"hexsha": "b5b9a39ca749422af64c591c003edef599aa3654", "size": 15977, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "c++/include/celerite2/forward.hpp", "max_stars_repo_name": "jacksonloper/celerite2", "max_stars_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 38.0, "max_stars_repo_stars_event_min_datetime": "2020-10-10T02:43:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T09:59:21.000Z", "max_issues_repo_path": "c++/include/celerite2/forward.hpp", "max_issues_repo_name": "jacksonloper/celerite2", "max_issues_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 34.0, "max_issues_repo_issues_event_min_datetime": "2020-10-06T18:50:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-28T10:33:04.000Z", "max_forks_repo_path": "c++/include/celerite2/forward.hpp", "max_forks_repo_name": "jacksonloper/celerite2", "max_forks_repo_head_hexsha": "e413e28dc43ba33e67960b51a9cbbac43c2f58df", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-11-09T18:12:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-03T20:20:59.000Z", "avg_line_length": 40.1432160804, "max_line_length": 144, "alphanum_fraction": 0.5757651624, "num_tokens": 4677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.84997116805678, "lm_q2_score": 0.7718435030872968, "lm_q1q2_score": 0.6560447238761465}} {"text": "#ifndef SE3_HPP_\n#define SE3_HPP_\n\n#include \n\n\n/**\n * @brief Bare-bones implementation of the SE(3) Lie Group\n *\n * For benchmarking purposes only---do not use in important code.\n */\ntemplate\nstruct SE3\n{\n using Scalar = _Scalar;\n using Tangent = Eigen::Matrix;\n\n // group composition\n SE3 operator*(const SE3 & other) const\n {\n return SE3{q * other.q, t + q * other.t};\n }\n\n // in-place group composition\n SE3 & operator*=(const SE3 & other)\n {\n t += q * other.t;\n q *= other.q;\n return *this;\n }\n\n // group action on 3-vector\n template\n Derived operator*(const Eigen::EigenBase & vec) const\n {\n EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Derived, 3)\n\n return t + q * vec;\n }\n\n // group inverse\n SE3 inv() const\n {\n return SE3{q.inverse(), -(q.inverse() * t)};\n }\n\n // cast to different scalar type\n template\n SE3 cast() const\n {\n return SE3{q.template cast(), t.template cast()};\n }\n\n // exponential (does not work for special case of zero orientation (yields 0/0))\n template\n static SE3 exp(const Eigen::MatrixBase & tangent)\n {\n EIGEN_STATIC_ASSERT_SAME_VECTOR_SIZE(Tangent, Derived)\n\n using std::sin, std::cos;\n\n const Scalar w_norm = tangent.template tail<3>().norm();\n const Eigen::Matrix q_diff_n = tangent.template tail<3>().normalized();\n\n Eigen::Matrix what;\n what << Scalar(0), -q_diff_n(2), q_diff_n(1),\n q_diff_n(2), Scalar(0), -q_diff_n(0),\n -q_diff_n(1), q_diff_n(0), Scalar(0);\n\n const Eigen::Matrix J = Eigen::Matrix::Identity() +\n ((w_norm - sin(w_norm)) / w_norm) * what * what +\n ((Scalar(1.) - cos(w_norm)) / w_norm) * what;\n\n return SE3{\n Eigen::Quaternion(Eigen::AngleAxis(w_norm, q_diff_n)),\n J * tangent.template head<3>()\n };\n }\n\n // log (does not work for special case of zero orientation (yields 0/0))\n Tangent log() const\n {\n using std::atan2;\n\n const Scalar alpha = atan2(q.coeffs().template head<3>().norm(), q.w());\n\n const Eigen::Matrix so3log =\n Scalar(2.) * (alpha / sin(alpha)) * q.coeffs().template head<3>();\n\n // TODO: could derive more efficient expression for the inverse...\n const Scalar w_norm = so3log.norm();\n const Eigen::Matrix q_diff_n = so3log.normalized();\n\n Eigen::Matrix what;\n what << Scalar(0), -q_diff_n(2), q_diff_n(1),\n q_diff_n(2), Scalar(0), -q_diff_n(0),\n -q_diff_n(1), q_diff_n(0), Scalar(0);\n\n const Eigen::Matrix J = Eigen::Matrix::Identity() +\n ((w_norm - sin(w_norm)) / w_norm) * what * what +\n ((Scalar(1.) - cos(w_norm)) / w_norm) * what;\n\n return (Tangent() << J.inverse() * t, so3log).finished();\n }\n\n Eigen::Quaternion q = Eigen::Quaternion::Identity();\n Eigen::Matrix t = Eigen::Matrix::Zero();\n\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n};\n\n\n/**\n * @brief boost::numerical::odeint operations for numerical integration on lie groups\n */\nstruct lie_operations\n{\n template\n struct scale_sum2\n {\n const Fac2 m_alpha2;\n\n scale_sum2(Fac1 alpha1, Fac2 alpha2)\n : m_alpha2(alpha2)\n {\n if (alpha1 != Fac1(1.0)) {\n std::cerr << \"alpha1 != 1 not expected for Lie type\" << std::endl;\n exit(EXIT_FAILURE);\n }\n }\n\n template\n void operator()(T1 & t1, const T2 & t2, const T3 & t3) const\n {\n t1 = t2 * T2::exp(t3 * m_alpha2);\n }\n\n typedef void result_type;\n };\n\n\n template\n struct scale_sum3\n {\n const Fac2 m_alpha2;\n const Fac3 m_alpha3;\n\n scale_sum3(Fac1 alpha1, Fac2 alpha2, Fac3 alpha3)\n : m_alpha2(alpha2), m_alpha3(alpha3)\n {\n if (alpha1 != Fac1(1.0)) {\n std::cerr << \"alpha1 != 1 not expected for Lie type\" << std::endl;\n exit(EXIT_FAILURE);\n }\n }\n\n template\n void operator()(T1 & t1, const T2 & t2, const T3 & t3, const T4 & t4) const\n {\n t1 = t2 * T2::exp(t3 * m_alpha2 + t4 * m_alpha3);\n }\n\n typedef void result_type;\n };\n\n\n template\n struct scale_sum4\n {\n const Fac2 m_alpha2;\n const Fac3 m_alpha3;\n const Fac4 m_alpha4;\n\n scale_sum4(Fac1 alpha1, Fac2 alpha2, Fac3 alpha3, Fac4 alpha4)\n : m_alpha2(alpha2), m_alpha3(alpha3), m_alpha4(alpha4)\n {\n if (alpha1 != Fac1(1.0)) {\n std::cerr << \"alpha1 != 1 not expected for Lie type\" << std::endl;\n exit(EXIT_FAILURE);\n }\n }\n\n template\n void operator()(T1 & t1, const T2 & t2, const T3 & t3, const T4 & t4, const T5 & t5) const\n {\n t1 = t2 * T2::exp(t3 * m_alpha2 + t4 * m_alpha3 + t5 * m_alpha4);\n }\n\n typedef void result_type;\n };\n\n\n template\n struct scale_sum5\n {\n const Fac2 m_alpha2;\n const Fac3 m_alpha3;\n const Fac4 m_alpha4;\n const Fac5 m_alpha5;\n\n scale_sum5(Fac1 alpha1, Fac2 alpha2, Fac3 alpha3, Fac4 alpha4, Fac5 alpha5)\n : m_alpha2(alpha2), m_alpha3(alpha3), m_alpha4(alpha4), m_alpha5(alpha5)\n {\n if (alpha1 != Fac1(1.0)) {\n std::cerr << \"alpha1 != 1 not expected for Lie type\" << std::endl;\n exit(EXIT_FAILURE);\n }\n }\n\n template\n void operator()(\n T1 & t1, const T2 & t2, const T3 & t3, const T4 & t4, const T5 & t5,\n const T6 & t6) const\n {\n t1 = t2 * T2::exp(t3 * m_alpha2 + t4 * m_alpha3 + t5 * m_alpha4 + t6 * m_alpha5);\n }\n\n typedef void result_type;\n };\n};\n\n#endif // SE3_HPP_\n", "meta": {"hexsha": "45f02a7f92842826b69a1b6e7cbe7697ca7006a6", "size": 6133, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "benchmarks/src/se3.hpp", "max_stars_repo_name": "pettni/autodiff", "max_stars_repo_head_hexsha": "d8621dcab51a5a071e0b02436686cc3faf6a1d44", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benchmarks/src/se3.hpp", "max_issues_repo_name": "pettni/autodiff", "max_issues_repo_head_hexsha": "d8621dcab51a5a071e0b02436686cc3faf6a1d44", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benchmarks/src/se3.hpp", "max_forks_repo_name": "pettni/autodiff", "max_forks_repo_head_hexsha": "d8621dcab51a5a071e0b02436686cc3faf6a1d44", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.3794642857, "max_line_length": 94, "alphanum_fraction": 0.6191097342, "num_tokens": 1939, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757870046160258, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6560408563813768}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"igl/components.h\"\n#include \"igl/jet.h\"\n#include \"igl/polygon_mesh_to_triangle_mesh.h\"\n#include \"igl/readOFF.h\"\n#include \"igl/viewer/Viewer.h\"\n#include \"igl/writeOFF.h\"\n\ndouble volume(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F) {\n\n double total_det = 0;\n\n for (int i = 0; i < F.rows(); ++i) {\n Eigen::Matrix3d p;\n p << V(F(i, 0), 0), V(F(i, 1), 0), V(F(i, 2), 0),\n V(F(i, 0), 1), V(F(i, 1), 1), V(F(i, 2), 1),\n V(F(i, 0), 2), V(F(i, 1), 2), V(F(i, 2), 2);\n\n total_det += p.determinant();\n }\n\n return std::abs(total_det / 6.0);\n}\n\nvoid selectValidVerts(const Eigen::MatrixXd &Vi, const Eigen::MatrixXi &Fi,\n const Eigen::VectorXi &Ci, int comp_num,\n Eigen::MatrixXd &Vo, Eigen::MatrixXi &Fo) {\n printf(\"Extracting component number %d\\n\", comp_num);\n\n std::map old_to_new;\n int n_i = 0;\n for (int i = 0; i < Vi.rows(); ++i) {\n if (Ci(i) == comp_num) {\n old_to_new[i] = n_i;\n n_i++;\n } else {\n // not valid\n old_to_new[i] = -1;\n }\n }\n printf(\" Found %d/%d valid vertices\\n\", n_i, Vi.rows());\n\n // Resize the vertices to be the number we need.\n Vo.resize(n_i, 3);\n int v_idx = 0;\n for (int i = 0; i < Vi.rows(); ++i) {\n if (old_to_new[i] != -1) {\n Vo.row(v_idx++) = Vi.row(i);\n }\n }\n // Same thing for the faces.\n // Do this twice so we know how many we need.\n std::vector f_idxs;\n for (int i = 0; i < Fi.rows(); ++i) {\n bool contained = true;\n for (int j = 0; j < Fi.row(i).size(); ++j) {\n if (old_to_new[Fi(i, j)] == -1) {\n contained = false;\n break;\n }\n }\n if (contained) {\n f_idxs.push_back(i);\n }\n }\n fprintf(stderr,\" Found %d/%d valid faces\\n\", f_idxs.size(), Fi.rows());\n Fo.resize(f_idxs.size(), 3);\n for (int i = 0; i < f_idxs.size(); ++i) {\n for (int j = 0; j < 3; ++j) {\n Fo(i, j) = old_to_new[Fi(f_idxs[i], j)];\n }\n }\n printf(\" Done! has size %dx%d\\n\", Fo.rows(), Fo.cols());\n}\n\nvoid extractValidVerts(const Eigen::MatrixXd &Vi, const Eigen::MatrixXi &Fi,\n const Eigen::VectorXi &Ci, const std::vector &valid,\n Eigen::MatrixXd &Vo, Eigen::MatrixXi &Fo, Eigen::VectorXi &Co) {\n std::map old_to_new;\n int n_i = 0;\n for (int i = 0; i < Vi.rows(); ++i) {\n if (valid[Ci(i)]) {\n old_to_new[i] = n_i;\n n_i++;\n } else {\n // not valid\n old_to_new[i] = -1;\n }\n }\n printf(\" Found %d/%d valid vertices\\n\", n_i, Vi.rows());\n\n // Resize the vertices to be the number we need.\n Vo.resize(n_i, 3);\n Co.resize(n_i);\n int v_idx = 0;\n for (int i = 0; i < Vi.rows(); ++i) {\n if (old_to_new[i] != -1) {\n Co(v_idx) = Ci(i);\n Vo.row(v_idx++) = Vi.row(i);\n }\n }\n // Same thing for the faces.\n // Do this twice so we know how many we need.\n std::vector f_idxs;\n for (int i = 0; i < Fi.rows(); ++i) {\n bool contained = true;\n for (int j = 0; j < Fi.row(i).size(); ++j) {\n if (old_to_new[Fi(i, j)] == -1) {\n contained = false;\n break;\n }\n }\n if (contained) {\n f_idxs.push_back(i);\n }\n }\n printf(\" Found %d/%d valid faces\\n\", f_idxs.size(), Fi.rows());\n Fo.resize(f_idxs.size(), 3);\n for (int i = 0; i < f_idxs.size(); ++i) {\n for (int j = 0; j < 3; ++j) {\n Fo(i, j) = old_to_new[Fi(f_idxs[i], j)];\n }\n }\n printf(\" Done! has size %dx%d\\n\", Fo.rows(), Fo.cols());\n}\n\nint main(int argc, char* argv[]) {\n if (argc < 3) {\n fprintf(stderr, \"Used for selecting connected components and saving them to a file.\\n\");\n fprintf(stderr, \"usage: %s \\n\", argv[0]);\n return -1;\n }\n\n Eigen::MatrixXd Vi, Vo;\n Eigen::MatrixXi Fi, Fo;\n Eigen::VectorXi Comps;\n\n // Read in the input file.\n igl::readOFF(argv[1], Vi, Fi);\n igl::components(Fi, Comps);\n // Get the number of components\n int max_comp = Comps.maxCoeff();\n std::vector valid_comps(max_comp + 1);\n\n int component_num = 0;\n igl::viewer::Viewer viewer;\n viewer.callback_init = [&](igl::viewer::Viewer& viewer) {\n viewer.callback_key_down = [&](igl::viewer::Viewer& viewer, unsigned char key, int modifier) {\n // Can increase or decrease number of components.\n if (key == 'C' || key == 'V') {\n if (key == 'C') {\n printf(\"Increasing component with %c\\n\", key);\n component_num++;\n if (component_num > max_comp) {\n component_num = 0;\n }\n } else {\n printf(\"Decreasing component with %c\\n\", key);\n component_num--;\n component_num = std::max(component_num, 0);\n }\n selectValidVerts(Vi,Fi,Comps, component_num, Vo,Fo);\n double comp_vol = volume(Vo,Fo);\n printf(\"Selecting component %d with volume %lf. Press 'X' to delete, ' ' to include\\n\",\n component_num, comp_vol);\n viewer.data.clear();\n viewer.data.set_mesh(Vo, Fo);\n return true;\n\n } else if (key == ' ' || key == 'X') {\n if (key == ' ') {\n valid_comps[component_num] = true;\n } else {\n valid_comps[component_num] = false;\n }\n \n Eigen::VectorXi Co;\n Eigen::MatrixXd cols;\n extractValidVerts(Vi,Fi,Comps, valid_comps, Vo,Fo,Co);\n igl::jet(Co, true, cols);\n viewer.data.clear();\n viewer.data.set_mesh(Vo, Fo);\n viewer.data.set_colors(cols);\n return true;\n } else if (key == 'w' || key == 'W') {\n int n_comps = 0;\n for (int i = 0; i < valid_comps.size(); ++i) {\n if (valid_comps[i]) ++n_comps;\n }\n printf(\"Writing output with %d components to %s\\n\", n_comps, argv[2]);\n igl::writeOFF(argv[2], Vo,Fo);\n printf(\"Finished! You may close the program.\\n\");\n }\n return false;\n };\n viewer.screen->performLayout();\n return false;\n };\n\n Eigen::MatrixXd cols;\n igl::jet(Comps, true, cols);\n viewer.data.set_mesh(Vi, Fi);\n viewer.data.set_colors(cols);\n printf(\"Press 'C' or 'V' to (respectively) increase or decrease the components id.\\n\");\n printf(\"Press ' ' to add the current component to the total components\\n\");\n printf(\"Press 'x' to remove the current component from the total components\\n\");\n printf(\"Press 'w' to write the resulting mesh to the output file\\n\");\n viewer.launch();\n}\n\n", "meta": {"hexsha": "ab9156cb53db83a47e1633f2eb406188311c3bb0", "size": 6479, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cgal_mesh_generation/select_components.cpp", "max_stars_repo_name": "chipbuster/skull-atlas", "max_stars_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cgal_mesh_generation/select_components.cpp", "max_issues_repo_name": "chipbuster/skull-atlas", "max_issues_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cgal_mesh_generation/select_components.cpp", "max_forks_repo_name": "chipbuster/skull-atlas", "max_forks_repo_head_hexsha": "7f3ee009e1d5f65f101fe853a2cf6e12662970ee", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7201834862, "max_line_length": 98, "alphanum_fraction": 0.5513196481, "num_tokens": 1983, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7490872243177518, "lm_q1q2_score": 0.6560408515242657}} {"text": "#ifndef SDM_STATS_HPP_\n#define SDM_STATS_HPP_\n\n#include \"utils.hpp\"\n\n#include \n\nnamespace sdm {\n\n// Eigen's Matrix class has mean function\n\ntemplate double mean(const std::vector &vec) {\n double sum = 0.0;\n if (!vec.empty()) {\n for (auto i = vec.begin(); i != vec.end(); ++i)\n sum += *i;\n sum /= static_cast(vec.size());\n }\n return sum;\n}\n\n// trimProb% trimmed mean\ntemplate \ninline double\ntrimedMean(const Eigen::Matrix &vec,\n const double trimProb = 0.5) {\n int l = vec.size();\n Eigen::Matrix v_copy = vec;\n std::sort(v_copy.data(), v_copy.data() + v_copy.size());\n return (v_copy.segment((int)(nearbyint(l * trimProb)),\n (int)(nearbyint(l * (1.0 - trimProb))))).mean();\n}\n\n// ----- scale mesure -----\ntemplate \ninline double\nvari(const Eigen::Matrix &vec,\n const double the_mean) {\n double v = 0.0;\n if (vec.size() > 2)\n v = ((vec.array() - the_mean).square().sum()) / (vec.size() - 1);\n return v;\n}\n\ntemplate \ninline double vari(\n const Eigen::Matrix &mat,\n const double the_mean) {\n double v = 0.0;\n if (mat.rows() * mat.cols() > 2)\n v = ((mat.array() - the_mean).square().sum()) /\n (mat.rows() * mat.cols() - 1);\n return v;\n}\n\ntemplate \ninline double\nvari(const Eigen::Matrix &vec) {\n return vari(vec, vec.mean());\n}\n\ntemplate \ninline double vari(const Eigen::Matrix &mat) {\n return vari(mat, mat.mean());\n}\n\ntemplate \ninline double\nstdv(const Eigen::Matrix &vec,\n const double the_mean) {\n return sqrt(vari(vec, the_mean));\n}\n\ntemplate \ninline double stdv(\n const Eigen::Matrix &mat,\n const double the_mean) {\n return sqrt(vari(mat, the_mean));\n}\n\ntemplate \ninline double\nstdv(const Eigen::Matrix &vec) {\n return sqrt(vari(vec));\n}\n\ntemplate \ninline double stdv(const Eigen::Matrix &mat) {\n return sqrt(vari(mat));\n}\n\ntemplate \ninline double\nMLvari(const Eigen::Matrix &vec,\n const double the_mean) {\n double v = 0.0;\n if (!vec.empty())\n v = ((vec.array() - the_mean).squared().sum()) / (vec.size());\n return v;\n}\n\ntemplate \ninline double MLvari(\n const Eigen::Matrix &mat,\n const double the_mean) {\n double v = 0.0;\n if (mat.rows() * mat.cols() > 1)\n v = ((mat.array() - the_mean).square().sum()) / (mat.rows() * mat.cols());\n return v;\n}\n\ntemplate \ninline double\nMLvari(const Eigen::Matrix &vec) {\n return MLvari(vec, vec.mean());\n}\n\ntemplate \ninline double MLvari(const Eigen::Matrix &mat) {\n return MLvari(mat, mat.mean());\n}\n\ntemplate \ninline double\nMLstdv(const Eigen::Matrix &vec,\n const double the_mean) {\n return sqrt(MLvari(vec, the_mean));\n}\n\ntemplate \ninline double MLstdv(\n const Eigen::Matrix &mat,\n const double the_mean) {\n return sqrt(MLvari(mat, the_mean));\n}\n\ntemplate \ninline double\nMLstdv(const Eigen::Matrix &vec) {\n return sqrt(MLvari(vec));\n}\n\ntemplate \ninline double MLstdv(const Eigen::Matrix &mat) {\n return sqrt(MLvari(mat));\n}\n\ntemplate \ninline double\nquantileSorted(const Eigen::Matrix &vec,\n const double order) {\n // SDMAssert(0.0 <= order && order <= 1.0);\n int l = vec.size();\n double tmp = (l - 1) * order;\n int lowerIndex = int(floor(tmp));\n int upperIndex = int(ceil(tmp));\n tmp -= lowerIndex;\n return (1.0 - tmp) * vec[lowerIndex] + tmp * vec[upperIndex];\n}\n\ntemplate \ninline double\nquantileUnsorted(const Eigen::Matrix &vec,\n const double order) {\n Eigen::Matrix vv = vec;\n std::sort(vv.data(), vv.data() + vv.size());\n return quantileSorted(vv, order);\n}\n\ntemplate \ninline double\nquantile(const Eigen::Matrix &vec,\n const double order) {\n return quantileUnsorted(vec, order);\n}\n\ntemplate \ninline double\nquartileRange(const Eigen::Matrix &vec) {\n Eigen::Matrix vv = vec;\n std::sort(vv.data(), vv.data() + vv.size());\n return quantileSorted(vv, 0.75) - quantileSorted(vv, 0.25);\n}\n\ntemplate \ninline double meanAbsoluteDeviation(\n const Eigen::Matrix &vec) {\n return meanAbsoluteDeviation(vec, vec.maen());\n}\n\ntemplate \ninline double meanAbsoluteDeviation(\n const Eigen::Matrix &vec,\n const double the_mean) {\n int l = vec.size();\n double ans = 0.0;\n if (!vec.empty()) {\n for (int i = 0; i < l; ++i)\n ans += fabs(vec[i] - the_mean);\n ans /= static_cast(l);\n }\n return ans;\n}\n\ntemplate \nRealType range(const Eigen::Matrix &vec) {\n return static_cast(vec.maxCoeff() - vec.minCoeff());\n}\n\ntemplate \ninline double stdvByQuartileRange(\n const Eigen::Matrix &vec) {\n Eigen::Matrix vv = vec;\n std::sort(vv.data(), vv.data() + vv.size());\n boost::math::normal_distribution n_dstr(0.0, 1.0);\n double x = boost::math::quantile(n_dstr, 0.75);\n return (quantileSorted(vv, 0.75) - quantileSorted(vv, 0.25)) / x;\n}\n\ntemplate \ninline double\nlpNorm(const Eigen::Matrix &vec,\n const int order) {\n double ans;\n if (order == 1) {\n ans = vec.cwiseAbs().sum();\n } else if (order == 2) {\n ans = vec.norm();\n } else {\n using std::pow;\n ans = pow(vec.cwiseAbs().array().pow(order).sum(), RealType(1) / order);\n }\n return ans;\n}\n\ntemplate \ninline double\nmoment(const Eigen::Matrix &vec,\n const int order) {\n double lp = lpNorm(vec, order);\n return lp / static_cast(vec.size());\n}\n\ntemplate \ninline double\nnormalizedMoment(const Eigen::Matrix &vec,\n const int order, const double the_mean,\n const double the_stdv) {\n Eigen::Matrix vv =\n ((vec.array() - the_mean) / the_stdv).matrix();\n return moment(vv, order);\n}\n\ntemplate \ninline double\nnormalizedMoment(const Eigen::Matrix &vec,\n const int order) {\n double m = vec.mean();\n double s = stdv(vec, m);\n return normalizedMoment(vec, order, m, s);\n}\n\ntemplate \ninline double\nskew(const Eigen::Matrix &vec) {\n return normalizedMoment(vec, 3);\n}\n\ntemplate \ninline double\nskew(const Eigen::Matrix &vec,\n const double the_mean, const double the_stdv) {\n return normalizedMoment(vec, 3, the_mean, the_stdv);\n}\n\ntemplate \ninline double\nkurt(const Eigen::Matrix &vec) {\n return normalizedMoment(vec, 4) - 3.0;\n}\n\ntemplate \ninline double\nkurt(const Eigen::Matrix &vec,\n const double the_mean, const double the_stdv) {\n return normalizedMoment(vec, 4, the_mean, the_stdv) - 3.0;\n}\n\ntemplate \ndouble median(const Eigen::Matrix &vec) {\n return quantile(vec, 0.5);\n}\n\ntemplate \ndouble medianAbsoluteDeviation(\n const Eigen::Matrix &vec,\n double the_median) {\n Eigen::Matrix mad =\n ((vec.array() - the_median).abs()).matrix();\n return median(mad);\n}\n\ntemplate \ndouble medianAbsoluteDeviation(\n const Eigen::Matrix &vec) {\n double the_median = median(vec);\n return medianAbsoluteDeviation(vec, the_median);\n}\n\ntemplate \nvoid meanAndVari(const Eigen::Matrix &vec,\n double &the_mean, double &the_vari) {\n the_mean = vec.mean();\n the_vari = vari(vec, the_mean);\n}\n\ntemplate \nvoid meanAndStdv(const Eigen::Matrix &vec,\n double &the_mean, double &the_stdv) {\n the_mean = vec.mean();\n the_stdv = stdv(vec, the_mean);\n}\n\ntemplate \ndouble coefficientOfVariation(\n const Eigen::Matrix &vec) {\n double m, s;\n meanAndVari(vec, m, s);\n // if (fabs(m) < 1e-12)\n // SDMError(\"in coefficientOfVariation(...), the mean is almost 0\");\n return s / m;\n}\n\ntemplate \nEigen::Matrix covMat(\n const Eigen::Matrix &mat,\n const Eigen::Matrix &mean_vec) {\n int n = mat.cols();\n // SDMAssert(2 <= n);\n int p = mat.rows();\n Eigen::Matrix ans(p, p);\n double ans_jk = 0.0;\n for (int j = 0; j < p; ++j) {\n for (int k = j; k < p; ++k) {\n for (int i = 0; i < n; ++i)\n ans_jk += (mat.coeffRef(i, j) - mean_vec[j]) *\n (mat.coeffRef(i, k) - mean_vec[k]);\n ans.coeffRef(j, k) = ans.coeffRef(k, j) = ans_jk / (n - 1);\n }\n }\n return ans;\n}\n\ntemplate \nEigen::Matrix\ncorrelationMat(const Eigen::Matrix &covMat) {\n int p = covMat.cols();\n // if (p != covMat.rows())\n // SDMError(\"covMat must be square matrix\");\n Eigen::Matrix diag(p);\n for (int i = 0; i < p; ++i)\n diag[i] = sqrt(covMat.coeffRef(i, i));\n Eigen::Matrix ans = covMat;\n for (int i = 0; i < p; ++i) {\n for (int j = i + 1; j < p; ++j)\n ans.coeffRef(i, j) = ans.coeffRef(j, i) /= (diag[i] * diag[j]);\n ans.coeffRef(i, i) = 1.0;\n }\n return ans;\n}\n\ntemplate \nEigen::Matrix pooledCovMat(\n const Eigen::Matrix &\n data1,\n const Eigen::Matrix &\n data2,\n const Eigen::Matrix &meanVec1,\n const Eigen::Matrix &meanVec2) {\n int n1 = data1.cols();\n int n2 = data2.cols();\n int n = n1 + n2;\n int p = data1.rows();\n // SDMAssert(2 <= n1 && 2 <= n2 && data2.rows() == p);\n\n Eigen::Matrix ans(p, p);\n double ans_jk = 0.0;\n for (int j = 0; j < p; ++j) {\n for (int k = j; k < p; ++k) {\n for (int i = 0; i < n1; ++i)\n ans_jk += (data1.coeffRef(i, j) - meanVec1[j]) *\n (data1.coeffRef(i, k) - meanVec1[k]);\n for (int i = 0; i < n2; ++i)\n ans_jk += (data2.coeffRef(i, j) - meanVec2[j]) *\n (data2.coeffRef(i, k) - meanVec2[k]);\n ans.coeffRef(j, k) = ans.coeffRef(k, j) = ans_jk / (n - 2);\n }\n }\n return ans;\n\n // return static_cast(n1 - 1)/(n - 2)*covMat(data1, meanVec1) +\n // static_cast(n2 - 1)/(n - 2)*covMat(data2, meanVec2);\n}\n\ntemplate \nRealType correlationCoefficient(\n const Eigen::Matrix &v1,\n const Eigen::Matrix &v2) {\n int l = v1.size();\n // SDMAssert(v2.size() == l);\n RealType m1 = v1.mean();\n RealType m2 = v2.mean();\n RealType enumerator = 0.0, denominator1 = 0.0, denominator2 = 0.0;\n for (int i = 0; i < l; i++) {\n RealType tmp1 = v1[i] - m1;\n RealType tmp2 = v2[i] - m2;\n enumerator += tmp1 * tmp2;\n denominator1 += tmp1 * tmp1;\n denominator2 += tmp2 * tmp2;\n }\n return enumerator / sqrt(denominator1) / sqrt(denominator2);\n}\n\ntemplate \nEigen::Matrix correlationCoefficientTest(\n const Eigen::Matrix &v1,\n const Eigen::Matrix &v2) {\n Eigen::Matrix ans(3);\n RealType r = ans[0] = correlationCoefficient(v1, v2);\n RealType df = static_cast(v1.size() - 2.0);\n RealType t = ans[1] = r * sqrt(df) / sqrt(1.0 - r * r);\n boost::math::students_t_distribution st_dstr(df);\n ans[2] = 1.0 - boost::math::cdf(st_dstr, t);\n return ans;\n}\n\ntemplate \nEigen::Matrix extractEqualIndices(\n const Eigen::Matrix &v,\n const RealType &val) {\n Eigen::Matrix ans(v.size());\n int count = 0;\n for (int i = 0; i < v.size(); ++i)\n if (val == v[i])\n ans[count++] = i;\n ans.conservativeResize(count);\n return ans;\n}\n\ntemplate \nEigen::Matrix doubleMeanRank(\n const Eigen::Matrix &v,\n const Eigen::Matrix &rank) {\n int l = v.size();\n // SDMAssert(l == rank.size());\n Eigen::Matrix dRank(l);\n for (int i = 0; i < l; ++i) {\n Eigen::Matrix tmpVec1 =\n extractEqualIndices(v, v[i]);\n int len = tmpVec1.size();\n if (len > 1) {\n Eigen::Matrix tmpVec2(len);\n for (int j = 0; j < len; ++j)\n tmpVec2[j] = rank[tmpVec1[j]];\n\n dRank[i] = tmpVec2.mean();\n } else {\n dRank[i] = rank[i];\n }\n }\n return dRank;\n}\n\ntemplate \nEigen::Matrix argsortDecOrder(\n const Eigen::Matrix &vec) {\n\n using pair_sort = std::pair;\n std::vector sort_vec;\n for (int i = 0; i < vec.size(); ++i)\n sort_vec.push_back(i, vec[i]);\n std::sort(sort_vec.begin(), sort_vec.end(), lessPair);\n Eigen::Matrix ans(vec.size());\n for (int i = 0; i < vec.size(); ++i)\n ans[i] = (sort_vec[i])->first;\n return ans;\n}\n\ntemplate \nEigen::Matrix\nrankDecOrder(const Eigen::Matrix &vec) {\n Eigen::Matrix idx =\n argsortDecOrder(vec);\n Eigen::Matrix ans(vec.size());\n for (int i = 0; i < vec.size(); ++i)\n ans[idx[i]] = i;\n return ans;\n}\n\ntemplate \ndouble spearmanRankCorrelation(\n Eigen::Matrix &v1,\n Eigen::Matrix &v2) {\n int l = v1.size();\n // SDMAssert(v2.size() == l);\n // Eigen::Matrix rank1 =\n // rankDecOrder(v1);\n // Eigen::Matrix rank2 =\n // rankDecOrder(v2);\n Eigen::Matrix dRank1 =\n doubleMeanRank(v1, rankDecOrder(v1));\n Eigen::Matrix dRank2 =\n doubleMeanRank(v2, rankDecOrder(v2));\n double sum = 0.0;\n for (int i = 0; i < l; ++i) {\n double tmp_i = (dRank1[i] - dRank2[i]);\n sum += tmp_i * tmp_i;\n }\n return 1.0 - 6.0 * sum / (double)(l * (l * l - 1));\n}\n\ntemplate \ndouble mixQuantile(const Eigen::Matrix &v,\n const double order) {\n // SDMAssert(0.0 <= order && order <= 1.0);\n int numKernel = v.size() / 3;\n // SDMAssert(numKernel > 3);\n double ans = 0.0;\n boost::math::normal_distribution n_dstr(0.0, 1.0);\n for (int i = 0; i < numKernel; ++i)\n ans +=\n (boost::math::quantile(n_dstr, order) * v[i * 3 + 1] + v[i * 3 + 2]) *\n v[i * 3];\n\n return ans;\n}\n\ntemplate \ndouble quantileFromNormalMixture(\n const Eigen::Matrix &coefficient,\n const Eigen::Matrix &mu,\n const Eigen::Matrix &sigma,\n const double order) {\n int numComponent = coefficient.size();\n // SDMAssert(mu.size() == numComponent && sigma.size() == numComponent);\n // SDMAssert(0.0 <= order && order <= 1.0);\n double ans = 0.0;\n boost::math::normal_distribution n_dstr(0.0, 1.0);\n for (int k = 0; k < numComponent; ++k)\n ans += coefficient[k] *\n (boost::math::quantile(n_dstr, order) * sigma[k] + mu[k]);\n return ans;\n}\n\n} // namespace sdm\n\n#endif\n", "meta": {"hexsha": "72902df189ce34531662f316c3f0aeb90d0710ff", "size": 18829, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "lib/stats.hpp", "max_stars_repo_name": "husk214/libsdm", "max_stars_repo_head_hexsha": "7e4e72a60b0e37e6cceaa32c09b839a3895bfa40", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-01-15T14:57:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-24T08:12:45.000Z", "max_issues_repo_path": "lib/stats.hpp", "max_issues_repo_name": "husk214/libsdm", "max_issues_repo_head_hexsha": "7e4e72a60b0e37e6cceaa32c09b839a3895bfa40", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lib/stats.hpp", "max_forks_repo_name": "husk214/libsdm", "max_forks_repo_head_hexsha": "7e4e72a60b0e37e6cceaa32c09b839a3895bfa40", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2016-05-06T11:50:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-06-23T16:48:12.000Z", "avg_line_length": 33.4440497336, "max_line_length": 80, "alphanum_fraction": 0.6487333369, "num_tokens": 5563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6560162042841398}} {"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n\n#include \n\n#include \n\ntypedef unsigned long long nombre;\ntypedef std::vector vecteur;\n\nENREGISTRER_PROBLEME(175,\n \"Fractions involving the number of different ways a number can be expressed as a sum of powers of 2\") {\n // Define f(0)=1 and f(n) to be the number of ways to write n as a sum of powers of 2 where no power occurs more\n // than twice.\n //\n // For example, f(10)=5 since there are five different ways to express 10:\n // 10 = 8+2 = 8+1+1 = 4+4+2 = 4+2+2+1+1 = 4+4+1+1\n // \n // It can be shown that for every fraction p/q (p>0, q>0) there exists at least one integer n such that\n // f(n)/f(n-1)=p/q.\n // \n // For instance, the smallest n for which f(n)/f(n-1)=13/17 is 241.\n // The binary expansion of 241 is 11110001.\n // Reading this binary number from the most significant bit to the least significant bit there are 4 one's, 3 zeroes\n // and 1 one. We shall call the string 4,3,1 the Shortened Binary Expansion of 241.\n // \n // Find the Shortened Binary Expansion of the smallest n for which\n // f(n)/f(n-1)=123456789/987654321.\n //\n // Give your answer as comma separated integers, without any whitespaces.\n nombre p = 123456789;\n nombre q = 987654321;\n\n vecteur resultat;\n\n while (q != 0) {\n if (p > q) {\n resultat.push_back(p / q - (p % q == 0 ? 1 : 0));\n p = p % q == 0 ? q : p % q;\n } else {\n resultat.push_back(q / p);\n q %= p;\n }\n }\n\n std::ostringstream oss;\n bool premier = true;\n for (auto &i : boost::adaptors::reverse(resultat)) {\n if (premier)\n premier = false;\n else\n oss << \",\";\n\n oss << i;\n }\n\n return oss.str();\n}\n", "meta": {"hexsha": "eb1053ef8958b7f6c7e0e6c2a801b38e10ecaf48", "size": 1856, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme175.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme1xx/probleme175.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme1xx/probleme175.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.4576271186, "max_line_length": 124, "alphanum_fraction": 0.5856681034, "num_tokens": 544, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6560161994357857}} {"text": "/* =========================================================================\n Copyright (c) 2010-2016, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n Portions of this software are copyright by UChicago Argonne, LLC.\n\n -----------------\n ViennaCL - The Vienna Computing Library\n -----------------\n\n Project Head: Karl Rupp rupp@iue.tuwien.ac.at\n\n (A list of authors and contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/** \\example power-iter.cpp\n*\n* This tutorial demonstrates the calculation of the eigenvalue with largest modulus using the power iteration method.\n*\n* We start with including the necessary headers:\n**/\n\n// Sparse matrices in uBLAS are *very* slow if debug mode is enabled. Disable it:\n#ifndef NDEBUG\n #define BOOST_UBLAS_NDEBUG\n#endif\n\n// Include necessary system headers\n#include \n#include \n#include \n#include \n\n#define VIENNACL_WITH_UBLAS\n\n// Include basic scalar and vector types of ViennaCL\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n\n#include \"viennacl/linalg/power_iter.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n\n// Some helper functions for this tutorial:\n#include \n\n// Boost includes:\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n/**\n* To run the power iteration, we set up a sparse matrix using Boost.uBLAS, transfer it over to a ViennaCL matrix, and then run the algorithm.\n**/\nint main()\n{\n // This example relies on double precision to be available and will provide only poor results with single precision\n typedef double ScalarType;\n\n /**\n * Create the sparse uBLAS matrix and read the matrix from the matrix-market file:\n **/\n boost::numeric::ublas::compressed_matrix ublas_A;\n\n if (!viennacl::io::read_matrix_market_file(ublas_A, \"../examples/testdata/mat65k.mtx\"))\n {\n std::cout << \"Error reading Matrix file\" << std::endl;\n return EXIT_FAILURE;\n }\n\n /**\n * Transfer the data from the uBLAS matrix over to the ViennaCL sparse matrix:\n **/\n viennacl::compressed_matrix vcl_A(ublas_A.size1(), ublas_A.size2());\n viennacl::copy(ublas_A, vcl_A);\n\n /**\n * Run the power iteration up until the largest eigenvalue changes by less than the specified tolerance.\n * Print the results of running with uBLAS as well as ViennaCL and exit.\n **/\n viennacl::linalg::power_iter_tag ptag(1e-6);\n\n std::cout << \"Starting computation of eigenvalue with largest modulus (might take about a minute)...\" << std::endl;\n std::cout << \"Result of power iteration with ublas matrix (single-threaded): \" << viennacl::linalg::eig(ublas_A, ptag) << std::endl;\n std::cout << \"Result of power iteration with ViennaCL (OpenCL accelerated): \" << viennacl::linalg::eig(vcl_A, ptag) << std::endl;\n\n /**\n * You can also obtain the associated *approximated* eigenvector by passing it as a third argument to eig()\n * Tighten the tolerance passed to ptag above in order to obtain more accurate results.\n **/\n viennacl::vector eigenvector(vcl_A.size1());\n viennacl::linalg::eig(vcl_A, ptag, eigenvector);\n std::cout << \"First three entries in eigenvector: \" << eigenvector[0] << \" \" << eigenvector[1] << \" \" << eigenvector[2] << std::endl;\n viennacl::vector Ax = viennacl::linalg::prod(vcl_A, eigenvector);\n std::cout << \"First three entries in A*eigenvector: \" << Ax[0] << \" \" << Ax[1] << \" \" << Ax[2] << std::endl;\n\n return EXIT_SUCCESS;\n}\n\n", "meta": {"hexsha": "951d7d7e4841b1a7f65a1b609884759c73386b02", "size": 4089, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/power-iter.cpp", "max_stars_repo_name": "yuchengs/viennacl-dev", "max_stars_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 224.0, "max_stars_repo_stars_event_min_datetime": "2015-02-15T21:50:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-14T18:27:03.000Z", "max_issues_repo_path": "examples/tutorial/power-iter.cpp", "max_issues_repo_name": "yuchengs/viennacl-dev", "max_issues_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 189.0, "max_issues_repo_issues_event_min_datetime": "2015-01-09T17:08:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-04T06:23:22.000Z", "max_forks_repo_path": "examples/tutorial/power-iter.cpp", "max_forks_repo_name": "yuchengs/viennacl-dev", "max_forks_repo_head_hexsha": "99f250fdb729de01ff5e9aebbed7b2ed3b1d8dfa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 84.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T14:06:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-23T14:51:17.000Z", "avg_line_length": 38.214953271, "max_line_length": 142, "alphanum_fraction": 0.6651993152, "num_tokens": 1003, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6560161944443623}} {"text": "// Copyright 2020, Madhur Chauhan\n\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_SPECIAL_FIBO_HPP\n#define BOOST_MATH_SPECIAL_FIBO_HPP\n\n#include \n#include \n#include \n#include \n\n#ifdef _MSC_VER\n#pragma once\n#endif\n\nnamespace boost {\nnamespace math {\n\nnamespace detail {\n constexpr double fib_bits_phi = 0.69424191363061730173879026;\n constexpr double fib_bits_deno = 1.1609640474436811739351597;\n} // namespace detail\n\ntemplate \ninline BOOST_CXX14_CONSTEXPR T unchecked_fibonacci(unsigned long long n) noexcept(std::is_fundamental::value) {\n // This function is called by the rest and computes the actual nth fibonacci number\n // First few fibonacci numbers: 0 (0th), 1 (1st), 1 (2nd), 2 (3rd), ...\n if (n <= 2) return n == 0 ? 0 : 1;\n /* \n * This is based on the following identities by Dijkstra:\n * F(2*n) = F(n)^2 + F(n+1)^2\n * F(2*n+1) = (2 * F(n) + F(n+1)) * F(n+1)\n * The implementation is iterative and is unrolled version of trivial recursive implementation.\n */\n unsigned long long mask = 1;\n for (int ct = 1; ct != std::numeric_limits::digits && (mask << 1) <= n; ++ct, mask <<= 1)\n ;\n T a{1}, b{1};\n for (mask >>= 1; mask; mask >>= 1) {\n T t1 = a * a;\n a = 2 * a * b - t1, b = b * b + t1;\n if (mask & n) \n t1 = b, b = b + a, a = t1; // equivalent to: swap(a,b), b += a;\n }\n return a;\n}\n\ntemplate \nT inline BOOST_CXX14_CONSTEXPR fibonacci(unsigned long long n, const Policy &pol) {\n // check for overflow using approximation to binet's formula: F_n ~ phi^n / sqrt(5)\n if (n > 20 && n * detail::fib_bits_phi - detail::fib_bits_deno > std::numeric_limits::digits)\n return policies::raise_overflow_error(\"boost::math::fibonacci<%1%>(unsigned long long)\", \"Possible overflow detected.\", pol);\n return unchecked_fibonacci(n);\n}\n\ntemplate \nT inline BOOST_CXX14_CONSTEXPR fibonacci(unsigned long long n) {\n return fibonacci(n, policies::policy<>());\n}\n\n// generator for next fibonacci number (see examples/reciprocal_fibonacci_constant.hpp)\ntemplate \nclass fibonacci_generator {\n public:\n // return next fibonacci number\n T operator()() noexcept(std::is_fundamental::value) {\n T ret = a;\n a = b, b = b + ret; // could've simply: swap(a, b), b += a;\n return ret;\n }\n\n // after set(nth), subsequent calls to the generator returns consecutive\n // fibonacci numbers starting with the nth fibonacci number\n void set(unsigned long long nth) noexcept(std::is_fundamental::value) {\n n = nth;\n a = unchecked_fibonacci(n);\n b = unchecked_fibonacci(n + 1);\n }\n\n private:\n unsigned long long n = 0;\n T a = 0, b = 1;\n};\n\n} // namespace math\n} // namespace boost\n\n#endif\n", "meta": {"hexsha": "7aaf6dd85427bd64d80f51a36aedf817104dda1d", "size": 3112, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/special_functions/fibonacci.hpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "include/boost/math/special_functions/fibonacci.hpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "include/boost/math/special_functions/fibonacci.hpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 33.4623655914, "max_line_length": 136, "alphanum_fraction": 0.6526349614, "num_tokens": 873, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473813156294, "lm_q2_score": 0.752012562644147, "lm_q1q2_score": 0.6560161897390773}} {"text": "/**************************************************************************\nCopyright (c) 2012, Julio C. Estrada\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n+ Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n+ Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**************************************************************************/\n\n#include \"utils.h\"\n#include \n#include \n\n#define cimg_display 0\n#include \n\nvoid gradient(const Eigen::ArrayXXf& I, Eigen::ArrayXXf& dx, Eigen::ArrayXXf& dy)\n{\n dx.resize(I.rows(), I.cols());\n dy.resize(I.rows(), I.cols());\n\n for(int i=0; i n0(noise0.data(), noise0.cols(), noise0.rows(), 1, 1, true);\n CImg n1(noise1.data(), noise1.cols(), noise1.rows(), 1, 1, true);\n const float pi=M_PI;\n\n float sigma = speckle_size/6.0;\n n0.rand(-pi, pi);\n n1.rand(-pi, pi);\n n0.blur(sigma);\n n1.blur(sigma);\n noise0 = mapRange(noise0, -pi, pi);\n noise1 = mapRange(noise1, -pi, pi);\n\n Ic0 = wphase(noise0);\n Ic1 = wphase(noise1 + p + pi/2.);\n\n return wphase(Ic0-Ic1);\n}\n\nEigen::ArrayXXf wphase(const Eigen::ArrayXXf& p)\n{\n Eigen::ArrayXXf wp(p.rows(), p.cols());\n float *const __restrict__ pt_wp = (float*)wp.data();\n float *const __restrict__ pt_p = (float*)p.data();\n size_t idx;\n\n for(int i=0; i // std::minmax\n\n#include // boost::variant\n\n#include \"convex_polygon.hpp\"\n#include \"point.hpp\"\n#include \"rectangle.hpp\"\n#include \"segment.hpp\"\n\n// TODO uncheck this\n\nnamespace geometry {\n\n// ------------------------------------------------------------------------\n// Segment\n// ------------------------------------------------------------------------\n\n// These could return a point or an interval\ntemplate \nboost::variant> project_impl(const N& first, const N& second) {\n\n const auto order = first.compare(second);\n\n if (order < 0) {\n return Interval{first, second};\n }\n\n if (order > 0) {\n return Interval{second, first};\n }\n\n // Else they are equal, so just return the point\n return first;\n}\n\ntemplate \nboost::variant> project_x(const Segment& seg) {\n\n return project_impl(seg.start().x, seg.end().x);\n}\n\ntemplate \nboost::variant> project_y(const Segment& seg) {\n\n return project_impl(seg.start().y, seg.end().y);\n}\n\ntemplate \nboost::variant> project(const Segment& seg, const Point& axis) {\n\n const auto start_dot = Point::dot(seg.start(), axis);\n const auto end_dot = Point::dot(seg.end(), axis);\n\n return project_impl(start_dot, end_dot);\n}\n\n// ------------------------------------------------------------------------\n// Rectangle\n// ------------------------------------------------------------------------\n\n// Rectangles are always non-degenerate, so projection will always return intervals,\n// never points.\n\ntemplate \nInterval project_x(const Rectangle& rect) {\n return rect.interval_x;\n}\n\ntemplate \nInterval project_y(const Rectangle& rect) {\n return rect.interval_y;\n}\n\ntemplate \nInterval project(const Rectangle& rect, const Point& axis) {\n\n const auto ll_dot = Point::dot(rect.lower_left(), axis);\n\n const auto ul_dot = Point::dot(rect.upper_left(), axis);\n\n const auto ur_dot = Point::dot(rect.upper_right(), axis);\n\n const auto lr_dot = Point::dot(rect.lower_right(), axis);\n\n const auto minmax = std::minmax({ll_dot, ul_dot, ur_dot, lr_dot});\n\n return {minmax.first, minmax.second};\n}\n\n// ------------------------------------------------------------------------\n// Convex Polygon\n// ------------------------------------------------------------------------\n\n// Polygons are also always non-degenerate, so they always return intervals,\n// never points.\n\n// Find the min and max x values of all the points\ntemplate \nInterval project_x(const ConvexPolygon& poly) {\n\n const auto& first = poly.vertex(0);\n\n // Note: the polygon is normalized, so the first point always has the smallest\n // x coordinate.\n const auto min = first.x;\n auto max = first.x;\n\n for (size_t i = 1; i < poly.size(); ++i) {\n\n const auto& point = poly.vertex(i);\n\n if (point.x > max) {\n max = point.x;\n }\n }\n\n return {min, max};\n}\n\n// Find the min and max y values of all the points\ntemplate \nInterval project_y(const ConvexPolygon& poly) {\n\n const auto& first = poly.vertex(0);\n\n auto min = first.y;\n auto max = first.y;\n\n for (size_t i = 1; i < poly.size(); ++i) {\n\n const auto& point = poly.vertex(i);\n\n // We know min <= max, so we only need to do the following comparisons\n\n if (point.y < min) {\n min = point.y;\n } else if (point.y > max) {\n max = point.y;\n }\n\n // else min <= y <= max, so there are no changes to make\n }\n\n return {min, max};\n}\n\ntemplate \nInterval project(const ConvexPolygon& poly, const Point& axis) {\n\n const auto& first = poly.vertex(0);\n\n const auto first_dot = Point::dot(first, axis);\n\n auto min = first_dot;\n auto max = first_dot;\n\n for (size_t i = 1; i < poly.size(); ++i) {\n\n const auto& point = poly.vertex(i);\n\n const auto dot = Point::dot(point, axis);\n\n // We know min <= max, so we only need to do the following comparisons\n\n if (dot < min) {\n min = dot;\n } else if (dot > max) {\n max = dot;\n }\n\n // else min <= dot <= max, so there are no changes to make\n }\n\n return {min, max};\n}\n}\n", "meta": {"hexsha": "02abc4d6342c3cfe68ea4d145799465f35a5a8e8", "size": 4693, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/backend/headers/geometry/project.hpp", "max_stars_repo_name": "wadymwadim/normandeau", "max_stars_repo_head_hexsha": "2995a3293b22df269b88c3486e4f4009a1a5d76f", "max_stars_repo_licenses": ["Xnet", "X11"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/backend/headers/geometry/project.hpp", "max_issues_repo_name": "wadymwadim/normandeau", "max_issues_repo_head_hexsha": "2995a3293b22df269b88c3486e4f4009a1a5d76f", "max_issues_repo_licenses": ["Xnet", "X11"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/backend/headers/geometry/project.hpp", "max_forks_repo_name": "wadymwadim/normandeau", "max_forks_repo_head_hexsha": "2995a3293b22df269b88c3486e4f4009a1a5d76f", "max_forks_repo_licenses": ["Xnet", "X11"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.217877095, "max_line_length": 95, "alphanum_fraction": 0.564457703, "num_tokens": 1113, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267694452331, "lm_q2_score": 0.7549149813536518, "lm_q1q2_score": 0.6558903444553016}} {"text": "//==================================================================================================\n/*!\n @file\n\n @copyright 2016 NumScale SAS\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n\n**/\n//==================================================================================================\n#ifndef BOOST_SIMD_ARITHMETIC_HPP_INCLUDED\n#define BOOST_SIMD_ARITHMETIC_HPP_INCLUDED\n\nnamespace boost { namespace simd\n{\n /*!\n @ingroup group-functions\n @defgroup group-arithmetic Arithmetic functions\n\n Those functions provides scalar and SIMD algorithms for classical arithmetic operators and\n functions provided by the C and C++ standard library. Other functions are also provided, in particular,\n provision for saturated operations through the use of a @ref decorator.\n\n - **Possibly saturated operations**\n\n The functors:\n

\n | name | name | name | name |\n |:----------:|:---------------:|:------------:|:----------------:|\n | @ref abs | @ref minus | @ref oneminus| @ref unary_minus |\n | @ref dec | @ref multiplies | @ref sqr | @ref unary_plus |\n | @ref dist | @ref plus | @ref toint | @ref touint |\n | @ref inc | | | |\n
\n\n can be decorated with the @ref saturated \"saturated_\" @ref decorator. This decorator has no effect on floating\n calls, but on integer calls replaces the operation by its saturated equivalent.\n\n Typically overflows will be replaced by the @ref Valmin/@ref Valmax proper value instead of providing\n undefined behaviour for signed integral types or wrapping modulo Valmax+1 for unsigned ones.\n\n Peculiarly saturated_(@ref abs) and saturated_(@ref dist) ensure that the result will never be stricly\n negative (which is for instance the case of abs(Valmin()) for T being any signed integral type).\n\n toint is a rather common operation as it converts floating number to signed integers of the same bit size,\n nevertheless it probably is its saturated version you have to use because it acts properly on large or not finite\n values, this is why an alias for saturated_(toint) is provided as @ref ifix.\n\n - **Rounding operations**\n
\n | name | name | name | name |\n |:-----------:|:---------------:|:-----------:|:----------------:|\n | @ref ceil | @ref round | @ref ifloor | @ref inearbyint |\n | @ref floor | @ref nearbyint | @ref ifix | |\n | @ref fix | @ref iceil | @ref iround | |\n
\n\n -The operations prefixed by 'i' return a value of the integral type associated to the entry type. (If T is\n the entry type it is @ref as_integer_t)\n\n -The other ones return the same type as the entry.\n\n - **Division operations**\n\n @ref divides is the function associated to standard division. There is another one which provides more\n flexibility, namely rounded divisions.\n\n With two parameters @ref div and @ref divides are equivalent, but @ref div can admit a first option parameter\n that modifies its behaviour.\n\n The option parameter is described in the following table where a and b are of type T, fT is a\n supposed floating type associated to T (@ref as_floating_t if it exists) and iT is the integer type associated to T\n (@ref as_integer_t). (fT and iT are here only to support pseudo code description)\n\n
\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
\n\n - **Remainder operations**\n\n @ref rem is the remander functor providing same kind of facilities as @ref div\n\n With two parameters rem(a, b) is equivalent to rem(fix, a, b), but rem can admit\n a first optional parameter that modifies its behaviour and moreover can use the fast_ decorator if\n limiting case values are not a problem.\n\n The option parameter can be chosen between @ref ceil, @ref floor, @ref fix, @ref round, @ref nearbyint and if opt is the option,\n the call:\n\n rem(opt, a, b) is equivalent to a-b*div(opt, a, b)\n\n For floating entries the underlisted corner cases are handled in the following way (unless the @ref fast \"fast_\"\n decorator is used, the result in this case being undefined)\n - if x is \\f$\\pm\\infty\\f$ , @ref Nan is returned\n - if x is \\f$\\pm0\\f$ and y is not 0 x is returned\n - If y is \\f$\\pm0\\f$, @ref Nan is returned\n - If either argument is a nan, @ref a nan is returned\n\n - **complex operations**\n\n Boost.SIMD does not provides complex number operations yet, but it will soon. So the following functors that\n have a meaning as a restriction to real number of complex functions, can be seen as a prequel:\n\n
\n | name | name | name | name | name |\n |:-----------:|:---------------:|:-----------:|:----------------:|:----------------:|\n | @ref arg | @ref conj | @ref imag | @ref real | @ref sqr_abs |\n
\n\n For real entries conj and real are identity, imag always 0, sqr_abs coincide with sqr\n and arg results are always in the set \\f$\\{0, \\pi, Nan\\}\\f$\n\n - **Fused multiply-add operations**\n\n
\n | name | name | name | name |\n |:---------------:|:---------------:|:------------:|:----------------:|\n | @ref fma | @ref fms | @ref fnma | @ref fnms |\n | @ref correct_fma| @ref two_add, | @ref two_prod| @ref two_split |\n
\n\n Correct fused multiply/add implies\n\n - only one rounding\n - no \"intermediate\" overflow\n\n f?m? and fm? family provides this each time it is reasonable\n in terms of performance (mainly if the system has the hard\n wired capability).\n\n If you need \"real\" fma capabilities in all circumstances in your own\n code you can use @ref correct_fma (although it can be expansive) or\n (generally still more expansive) std_(fma) by using the decorator.\n\n @ref two_add, @ref two_prod and @ref two_split are used internally in @ref correct_fma and\n can be useful in searching extra-accuracy in other circumstances as double-double\n computations.\n\n @ref correct_fma is never used internally by Boost.SIMD\n\n - **Standard operations**\n\n The stdlibc++ provides them but only in scalar mode:\n\n
\n | name | name | name |\n |:----------:|:---------------:|:------------:|\n | @ref abs | @ref hypot | @ref remquo |\n | @ref ceil | @ref max | @ref round |\n | @ref floor | @ref min | @ref signbit |\n | @ref fma | @ref rem (%) | @ref sqrt |\n
\n\n Boost.SIMD provides its own scalar and simd versions, but allows\n the use of the @ref std \"std_\" @ref decorator to call the associated system\n library function if the user needs it.\n\n - **Other operations**\n\n
\n | name | name | name |\n |:------------:|:---------------:|:-------------:|\n | @ref average | @ref sqrt | @ref tenpower |\n | @ref meanof | @ref sqr | @ref tofloat |\n | @ref minmod | @ref sqrt1pm1 | |\n
\n **/\n} }\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#endif\n", "meta": {"hexsha": "dbb3db1089aa07595eb5548512dc9021f018971c", "size": 10959, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/arithmetic.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "third_party/boost/simd/arithmetic.hpp", "max_issues_repo_name": "xmar/pythran", "max_issues_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "third_party/boost/simd/arithmetic.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.6340425532, "max_line_length": 135, "alphanum_fraction": 0.5736837303, "num_tokens": 2657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.6558903345365102}} {"text": "// Copyright Nick Thompson, 2020\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0.\n// (See accompanying file LICENSE_1_0.txt\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n// See: https://blogs.mathworks.com/cleve/2019/04/29/makima-piecewise-cubic-interpolation/\n// And: https://doi.org/10.1145/321607.321609\n\n#ifndef BOOST_MATH_INTERPOLATORS_MAKIMA_HPP\n#define BOOST_MATH_INTERPOLATORS_MAKIMA_HPP\n#include \n#include \n#include \n\nnamespace boost {\nnamespace math {\nnamespace interpolators {\n\ntemplate\nclass makima {\npublic:\n using Real = typename RandomAccessContainer::value_type;\n\n makima(RandomAccessContainer && x, RandomAccessContainer && y,\n Real left_endpoint_derivative = std::numeric_limits::quiet_NaN(),\n Real right_endpoint_derivative = std::numeric_limits::quiet_NaN())\n {\n using std::isnan;\n using std::abs;\n if (x.size() < 4)\n {\n throw std::domain_error(\"Must be at least four data points.\");\n }\n RandomAccessContainer s(x.size(), std::numeric_limits::quiet_NaN());\n Real m2 = (y[3]-y[2])/(x[3]-x[2]);\n Real m1 = (y[2]-y[1])/(x[2]-x[1]);\n Real m0 = (y[1]-y[0])/(x[1]-x[0]);\n // Quadratic extrapolation: m_{-1} = 2m_0 - m_1:\n Real mm1 = 2*m0 - m1;\n // Quadratic extrapolation: m_{-2} = 2*m_{-1}-m_0:\n Real mm2 = 2*mm1 - m0;\n Real w1 = abs(m1-m0) + abs(m1+m0)/2;\n Real w2 = abs(mm1-mm2) + abs(mm1+mm2)/2;\n if (isnan(left_endpoint_derivative))\n {\n s[0] = (w1*mm1 + w2*m0)/(w1+w2);\n if (isnan(s[0]))\n {\n s[0] = 0;\n }\n }\n else\n {\n s[0] = left_endpoint_derivative;\n }\n\n w1 = abs(m2-m1) + abs(m2+m1)/2;\n w2 = abs(m0-mm1) + abs(m0+mm1)/2;\n s[1] = (w1*m0 + w2*m1)/(w1+w2);\n if (isnan(s[1])) {\n s[1] = 0;\n }\n\n for (decltype(s.size()) i = 2; i < s.size()-2; ++i) {\n Real mim2 = (y[i-1]-y[i-2])/(x[i-1]-x[i-2]);\n Real mim1 = (y[i ]-y[i-1])/(x[i ]-x[i-1]);\n Real mi = (y[i+1]-y[i ])/(x[i+1]-x[i ]);\n Real mip1 = (y[i+2]-y[i+1])/(x[i+2]-x[i+1]);\n w1 = abs(mip1-mi) + abs(mip1+mi)/2;\n w2 = abs(mim1-mim2) + abs(mim1+mim2)/2;\n s[i] = (w1*mim1 + w2*mi)/(w1+w2);\n if (isnan(s[i])) {\n s[i] = 0;\n }\n }\n // Quadratic extrapolation at the other end:\n \n decltype(s.size()) n = s.size();\n Real mnm4 = (y[n-3]-y[n-4])/(x[n-3]-x[n-4]);\n Real mnm3 = (y[n-2]-y[n-3])/(x[n-2]-x[n-3]);\n Real mnm2 = (y[n-1]-y[n-2])/(x[n-1]-x[n-2]);\n Real mnm1 = 2*mnm2 - mnm3;\n Real mn = 2*mnm1 - mnm2;\n w1 = abs(mnm1 - mnm2) + abs(mnm1+mnm2)/2;\n w2 = abs(mnm3 - mnm4) + abs(mnm3+mnm4)/2;\n\n s[n-2] = (w1*mnm3 + w2*mnm2)/(w1 + w2);\n if (isnan(s[n-2])) {\n s[n-2] = 0;\n }\n\n w1 = abs(mn - mnm1) + abs(mn+mnm1)/2;\n w2 = abs(mnm2 - mnm3) + abs(mnm2+mnm3)/2;\n\n\n if (isnan(right_endpoint_derivative))\n {\n s[n-1] = (w1*mnm2 + w2*mnm1)/(w1+w2);\n if (isnan(s[n-1])) {\n s[n-1] = 0;\n }\n }\n else\n {\n s[n-1] = right_endpoint_derivative;\n }\n\n impl_ = std::make_shared>(std::move(x), std::move(y), std::move(s));\n }\n\n Real operator()(Real x) const {\n return impl_->operator()(x);\n }\n\n Real prime(Real x) const {\n return impl_->prime(x);\n }\n\n friend std::ostream& operator<<(std::ostream & os, const makima & m)\n {\n os << *m.impl_;\n return os;\n }\n\n void push_back(Real x, Real y) {\n using std::abs;\n using std::isnan;\n if (x <= impl_->x_.back()) {\n throw std::domain_error(\"Calling push_back must preserve the monotonicity of the x's\");\n }\n impl_->x_.push_back(x);\n impl_->y_.push_back(y);\n impl_->dydx_.push_back(std::numeric_limits::quiet_NaN());\n // dydx_[n-2] was computed by extrapolation. Now dydx_[n-2] -> dydx_[n-3], and it can be computed by the same formula.\n decltype(impl_->size()) n = impl_->size();\n auto i = n - 3;\n Real mim2 = (impl_->y_[i-1]-impl_->y_[i-2])/(impl_->x_[i-1]-impl_->x_[i-2]);\n Real mim1 = (impl_->y_[i ]-impl_->y_[i-1])/(impl_->x_[i ]-impl_->x_[i-1]);\n Real mi = (impl_->y_[i+1]-impl_->y_[i ])/(impl_->x_[i+1]-impl_->x_[i ]);\n Real mip1 = (impl_->y_[i+2]-impl_->y_[i+1])/(impl_->x_[i+2]-impl_->x_[i+1]);\n Real w1 = abs(mip1-mi) + abs(mip1+mi)/2;\n Real w2 = abs(mim1-mim2) + abs(mim1+mim2)/2;\n impl_->dydx_[i] = (w1*mim1 + w2*mi)/(w1+w2);\n if (isnan(impl_->dydx_[i])) {\n impl_->dydx_[i] = 0;\n }\n\n Real mnm4 = (impl_->y_[n-3]-impl_->y_[n-4])/(impl_->x_[n-3]-impl_->x_[n-4]);\n Real mnm3 = (impl_->y_[n-2]-impl_->y_[n-3])/(impl_->x_[n-2]-impl_->x_[n-3]);\n Real mnm2 = (impl_->y_[n-1]-impl_->y_[n-2])/(impl_->x_[n-1]-impl_->x_[n-2]);\n Real mnm1 = 2*mnm2 - mnm3;\n Real mn = 2*mnm1 - mnm2;\n w1 = abs(mnm1 - mnm2) + abs(mnm1+mnm2)/2;\n w2 = abs(mnm3 - mnm4) + abs(mnm3+mnm4)/2;\n\n impl_->dydx_[n-2] = (w1*mnm3 + w2*mnm2)/(w1 + w2);\n if (isnan(impl_->dydx_[n-2])) {\n impl_->dydx_[n-2] = 0;\n }\n\n w1 = abs(mn - mnm1) + abs(mn+mnm1)/2;\n w2 = abs(mnm2 - mnm3) + abs(mnm2+mnm3)/2;\n\n impl_->dydx_[n-1] = (w1*mnm2 + w2*mnm1)/(w1+w2);\n if (isnan(impl_->dydx_[n-1])) {\n impl_->dydx_[n-1] = 0;\n }\n }\n\nprivate:\n std::shared_ptr> impl_;\n};\n\n}\n}\n}\n#endif\n", "meta": {"hexsha": "f69fe40733a11f70a26d9fb6041eeb34153e2c1e", "size": 6005, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/interpolators/makima.hpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "include/boost/math/interpolators/makima.hpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "include/boost/math/interpolators/makima.hpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 33.5474860335, "max_line_length": 128, "alphanum_fraction": 0.5097418818, "num_tokens": 2122, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278726384089, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.655792154813719}} {"text": "#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \"FEM1DWave.h\"\n\nnamespace fs = std::filesystem;\n\n// Class constructor for a vector field\nFEM1DWave::FEM1DWave(unsigned int order, unsigned int problem)\n\t:\n\tn(0),\n\tfe(FE_Q<1>(order), 1),\n\tdof_handler(triangulation),\n\tbasis(QGauss<1>(order + 1)),\n\tsrc(FEM1DGauSrc(Point<1>(0.5), 0.05, 0.05, 0.1 / T))\n{\n\tif (problem == 1 || problem == 2) {\n\t\tprob = problem;\n\t}\n\telse {\n\t\tstd::cout << \"Error: problem number should be 1 or 2.\\n\";\n\t\texit(0);\n\t}\n\n\t//Nodal Solution names - this is for writing the output file\n\tnodal_solution_names.push_back(\"p\");\n\tnodal_data_component_interpretation.push_back(DataComponentInterpretation::component_is_part_of_vector);\n}\n\n//Class destructor\nFEM1DWave::~FEM1DWave() {\n\tdof_handler.clear();\n}\n\n//Define the problem domain and generate the mesh\nvoid FEM1DWave::generate_mesh(unsigned int numberOfElements) {\n\n\t//Define the limits of your domain\n\tL = 1; //EDIT\n\tdouble x_min = 0.;\n\tdouble x_max = L;\n\n\tPoint<1, double> min(x_min), max(x_max);\n\tstd::vector meshDimensions(1, numberOfElements);\n\tGridGenerator::subdivided_hyper_rectangle(triangulation, meshDimensions, min, max);\n}\n\n//Setup data structures (sparse matrix, vectors)\nvoid FEM1DWave::setup_system() {\n\t//Let deal.II organize degrees of freedom\n\tdof_handler.distribute_dofs(fe);\n\t\n\t//Enter the global node x-coordinates into the vector \"nodeLocation\"\n\tstd::vector< Point<1, double> > dof_coords(dof_handler.n_dofs());\n\tnodeLocation.resize(dof_handler.n_dofs());\n\tDoFTools::map_dofs_to_support_points<1, 1>(mapping, dof_handler, dof_coords);\n\tfor (unsigned int i = 0; i < dof_coords.size(); i++) {\n\t\tnodeLocation[i] = dof_coords[i][0];\n\t}\n\n\t//Specify boundary condtions (call the function)\n\tdefine_boundary_conds();\n\n\t//Define the size of the global matrices and vectors\n\tsparsity_pattern.reinit(dof_handler.n_dofs(), dof_handler.n_dofs(),\n\t\tdof_handler.max_couplings_between_dofs());\n\tDoFTools::make_sparsity_pattern(dof_handler, sparsity_pattern);\n\tsparsity_pattern.compress();\n\tK.reinit(sparsity_pattern);\n\tM.reinit(sparsity_pattern);\n\tAu.reinit(sparsity_pattern);\n\tF.reinit(dof_handler.n_dofs());\n\tP1.reinit(dof_handler.n_dofs());\n\tP2.reinit(dof_handler.n_dofs());\n\tV.reinit(dof_handler.n_dofs());\n\tRHS.reinit(dof_handler.n_dofs());\n\tconstraints.close();\n\t\n\t//Just some notes...\n\tstd::cout << \" Number of active elems: \" << triangulation.n_active_cells() << std::endl;\n\tstd::cout << \" Number of degrees of freedom: \" << dof_handler.n_dofs() << std::endl;\n\n\n\t//make sure solution folder exists\n\tif (!fs::is_directory(\"sln\") || !fs::exists(\"sln\")) { // Check if src folder exists\n\t\tfs::create_directory(\"sln\"); // create src folder\n\t}\n}\n\n//Form elmental vectors and matrices and assemble to the global vector (F) and matrix (K)\nvoid FEM1DWave::assemble_system() {\n\tMatrixCreator::create_mass_matrix(dof_handler, basis, M);\n\tMatrixCreator::create_laplace_matrix(dof_handler, basis,K);\n\tAu.copy_from(M);\n\tAu.add(T*T*theta*theta, K);\n\n\t//zero initial conditions\n\tP1 = 0;\n\tP2 = 0;\n\tV = 0;\n\tF = 0;\n}\n\nvoid FEM1DWave::solve_p()\n{\n\tSolverControl solver_control(1000, 1e-8*RHS.l2_norm());\n\tSolverCG<> cg(solver_control);\n\n\tcg.solve(Au, P1, RHS, PreconditionIdentity());\n\tstd::cout << \" u-equation: \" << solver_control.last_step() << \" CG iterations.\" << std::endl;\n}\n\nvoid FEM1DWave::solve_v()\n{\n\tSolverControl solver_control(1000, 1e-8*RHS.l2_norm());\n\tSolverCG<> cg(solver_control);\n\tcg.solve(M, P2, RHS, PreconditionIdentity());\n\tV += P2;\n\tstd::cout << \" v-equation: \" << solver_control.last_step() << \" CG iterations.\" << std::endl;\n}\n\nvoid FEM1DWave::run() {\n\tVector tmp(P1.size());\n\tdouble t;\n\n\tfor (; n <= N;)\n\t{\n\t\t++n;\n\t\tt = n * T;\n\n\t\tstd::cout << \"Time step \" << n << \" at t=\" << t\t<< std::endl;\n\t\t\n\t\tP2 = P1;\n\t\ttmp = P2;\n\t\ttmp *= -T * T*theta*(1 - theta);\n\t\tK.vmult(RHS, tmp);\n\t\ttmp = V;\n\t\ttmp.sadd(T, P2);\n\t\tM.vmult_add(RHS, tmp);\n\n\t\ttmp = F;\n\t\ttmp *= (1 - theta);\n\t\tsrc.set_time(t);\n\t\tVectorTools::create_right_hand_side(mapping, dof_handler, basis, src, F);\n\t\ttmp.add(theta, F);\n\t\tRHS.add(T * T * theta, tmp);\n\n\t\t//if dirichlet boundary required... update matrix here\n\t\tsolve_p();\n\n\t\tRHS = tmp;\n\t\tRHS *= T;\n\t\tP2 *= -T * (1 - theta);\n\t\tP2.add(-T * theta,P1);\n\t\tK.vmult_add(RHS, P2);\n\t\tsolve_v();\n\n\t\t//write output file in vtk format for visualization\n\t\toutput_results();\n\n\t\tstd::cout << \" Total energy: \" << (M.matrix_norm_square(V) + K.matrix_norm_square(P1)) / 2 << std::endl;\n\t}\n}\n\n//Specify the Dirichlet boundary conditions\nvoid FEM1DWave::define_boundary_conds() {\n\t//const unsigned int totalNodes = dof_handler.n_dofs(); //Total number of nodes\n\n\t//Identify dirichlet boundary nodes and specify their values.\n\t//This function is called from within \"setup_system\"\n\n\t/*The vector \"nodeLocation\" gives the x-coordinate in the real domain of each node,\n\t organized by the global node number.*/\n\n\t /*This loops through all nodes in the system and checks to see if they are\n\t\tat one of the boundaries. If at a Dirichlet boundary, it stores the node number\n\t\tand the applied displacement value in the std::map \"boundary_values\". Deal.II\n\t\twill use this information later to apply Dirichlet boundary conditions.\n\t\tNeumann boundary conditions are applied when constructing Flocal in \"assembly\"*/\n\t\t/*\n\t\tfor(unsigned int globalNode=0; globalNode data_out;\n\tdata_out.attach_dof_handler(dof_handler);\n\n\t//Add nodal DOF data\n\tdata_out.add_data_vector(P1, nodal_solution_names, DataOut<1>::type_dof_data, nodal_data_component_interpretation);\n\tdata_out.build_patches();\n\tdata_out.write_vtk(output1);\n\toutput1.close();\n}\n\ndouble FEM1DWave::u_exact(double x) {\n\tdouble result = 0;\n\t//diriclet bc\n\tif (prob == 2)\n\t{\n\t}\n\telse\n\t{\n\t}\n\treturn result;\n}\n\ndouble FEM1DWave::l2norm_of_error() {\n\t/*\n\tdouble l2norm = 0.;\n\n\t//Find the l2 norm of the error between the finite element sol'n and the exact sol'n\n\tconst unsigned int \t\t\tdofs_per_elem = fe.dofs_per_cell; //This gives you dofs per element\n\tstd::vector local_dof_indices(dofs_per_elem);\n\tVector u_ex; u_ex.reinit(dof_handler.n_dofs());\n\tdouble u_h, x, h_e;\n\n\t//loop over elements \n\tfor (unsigned int q = 0; q < dof_handler.n_dofs(); q++)\n\t\tu_ex[q] = u_exact(nodeLocation[q]);\n\tu_ex.print(std::cout);\n\tfor (auto i = nodeLocation.begin(); i != nodeLocation.end(); ++i)\n\t\tstd::cout << *i << ' ';\n\tstd::cout << std::endl;\n\n\ttypename DoFHandler<1>::active_cell_iterator elem = dof_handler.begin_active(),\n\t\tendc = dof_handler.end();\n\tfor (; elem != endc; ++elem) {\n\t\t//Retrieve the effective \"connectivity matrix\" for this element\n\t\telem->get_dof_indices(local_dof_indices);\n\n\t\t//Find the element length\n\t\th_e = nodeLocation[local_dof_indices[1]] - nodeLocation[local_dof_indices[0]];\n\n\t\tdouble sum = 0.;\n\t\tfor (unsigned int q = 0; q < quadRule; q++) {\n\t\t\tx = 0.;\n\t\t\tu_h = 0.;\n\t\t\t//Find the values of x and u_h (the finite element solution) at the quadrature points\n\t\t\tfor (unsigned int B = 0; B < dofs_per_elem; B++) {\n\t\t\t\tu_h += D[local_dof_indices[B]] * basis_function(B, quad_points[q]);\n\t\t\t\tx += nodeLocation[local_dof_indices[B]] * basis_function(B, quad_points[q]);\n\t\t\t}\n\t\t\t//EDIT - Find the l2-norm of the error through numerical integration.\n\t\t\t//This includes evaluating the exact solution at the quadrature points\n\t\t\tsum += pow(u_exact(x) - u_h, 2) * quad_weight[q];\n\t\t}\n\t\tsum *= h_e / 2;\n\t\tl2norm += sum;\n\t}\n\treturn sqrt(l2norm);\n\t*/\n\treturn 0.0;\n}\n", "meta": {"hexsha": "51589bdaf653cb2c53f850828fff05dd5cd4fdf6", "size": 8482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FEM1D-Wave/FEM1DWave.cpp", "max_stars_repo_name": "lampuiho/FEM1D-Test", "max_stars_repo_head_hexsha": "32d580a4dc5ef1273d96d00c6f5adde549f427fc", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FEM1D-Wave/FEM1DWave.cpp", "max_issues_repo_name": "lampuiho/FEM1D-Test", "max_issues_repo_head_hexsha": "32d580a4dc5ef1273d96d00c6f5adde549f427fc", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FEM1D-Wave/FEM1DWave.cpp", "max_forks_repo_name": "lampuiho/FEM1D-Test", "max_forks_repo_head_hexsha": "32d580a4dc5ef1273d96d00c6f5adde549f427fc", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5540069686, "max_line_length": 135, "alphanum_fraction": 0.6953548691, "num_tokens": 2489, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6557921456223391}} {"text": "#pragma once\n\n// Eigen\n#include \n#include \n\n// offset from center of laser rotation\n#define AXIS_OFFSET 0.0 //-0.015\n\nusing namespace Eigen;\n\n/**\n * get the 3D minimum distance between 2 lines\n * following http://geomalgorithms.com/a07-_distance.html#Distance-between-Lines\n * @param pos0 origin line0\n * @param dir1 direction line0\n * @param pos1 origin line1\n * @param dir2 direction line1\n * @param tri0 point on line0 closest to line1\n * @param tri1 point on line1 closest to line0\n * @return distance between the lines\n */\ndouble dist3D_Line_to_Line( Vector3d &pos0, Vector3d &dir1,\n Vector3d &pos1, Vector3d &dir2,\n Vector3d &tri0, Vector3d &tri1);\n\n/**\n * This function triangulates the position of a sensor using the horizontal and vertical angles from two ligthouses\n * @param angles0 vertical/horizontal angles form first lighthouse\n * @param angles1 vertical/horizontal angles form second lighthouse\n * @param RT_0 pose matrix of first lighthouse\n * @param RT_1 pose matrix of second lighthouses\n * @param triangulated_position the triangulated position\n * @param ray0 ligthhouse ray\n * @param ray1 ligthhouse ray\n */\ndouble triangulateFromLighthouseAngles(Vector2d &angles0, Vector2d &angles1, Matrix4d &RT_0, Matrix4d &RT_1,\n Vector3d &triangulated_position, Vector3d &ray0, Vector3d &ray1);\n\ndouble triangulateFromRays(Vector3d &ray0, Vector3d &ray1, Matrix4d &RT_0, Matrix4d &RT_1, Vector3d &triangulated_position);\n\nvoid rayFromLighthouseAngles(Vector2d &angles, Vector3d &ray);", "meta": {"hexsha": "bcd5ad35cf7ff0f093dccd421b08c78d8fa02c7b", "size": 1636, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/darkroom/Triangulation.hpp", "max_stars_repo_name": "Roboy/DarkRoom_rviz", "max_stars_repo_head_hexsha": "8f049218bc600d4b179303493a70bfe2389df73c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-06T15:34:19.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-04T00:22:54.000Z", "max_issues_repo_path": "include/darkroom/Triangulation.hpp", "max_issues_repo_name": "Roboy/DarkRoom_rviz", "max_issues_repo_head_hexsha": "8f049218bc600d4b179303493a70bfe2389df73c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/darkroom/Triangulation.hpp", "max_forks_repo_name": "Roboy/DarkRoom_rviz", "max_forks_repo_head_hexsha": "8f049218bc600d4b179303493a70bfe2389df73c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.9523809524, "max_line_length": 124, "alphanum_fraction": 0.7194376528, "num_tokens": 442, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179018818865, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.65578879236537}} {"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"ConvolutionTools.hpp\"\n#include \"Toeplitz.hpp\"\n#include \"../public/WindowFuncs.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \n#include \n#include \n#include \n\nnamespace fluid {\nnamespace algorithm {\n\nclass ARModel\n{\n\n using MatrixXd = Eigen::MatrixXd;\n using ArrayXd = Eigen::ArrayXd;\n using VectorXd = Eigen::VectorXd;\n\npublic:\n ARModel(index order) : mParameters(VectorXd::Zero(order)) {}\n\n const double* getParameters() const { return mParameters.data(); }\n double variance() const { return mVariance; }\n index order() const { return mParameters.size(); }\n\n void estimate(const double* input, index size, index nIterations = 3,\n double robustFactor = 3.0)\n {\n if (nIterations > 0)\n robustEstimate(input, size, nIterations, robustFactor);\n else\n directEstimate(input, size, true);\n }\n\n double fowardPrediction(const double* input)\n {\n return modelPredict>(input);\n }\n\n double backwardPrediction(const double* input)\n {\n struct Identity\n {\n index operator()(index a) { return a; }\n };\n return modelPredict(input);\n }\n\n double forwardError(const double* input)\n {\n return modelError<&ARModel::fowardPrediction>(input);\n }\n\n double backwardError(const double* input)\n {\n return modelError<&ARModel::backwardPrediction>(input);\n }\n\n void forwardErrorArray(double* errors, const double* input, index size)\n {\n modelErrorArray<&ARModel::forwardError>(errors, input, size);\n }\n\n void backwardErrorArray(double* errors, const double* input, index size)\n {\n modelErrorArray<&ARModel::backwardError>(errors, input, size);\n }\n\n void setMinVariance(double variance) { mMinVariance = variance; }\n\nprivate:\n template \n double modelPredict(const double* input)\n {\n double estimate = 0.0;\n\n for (index i = 0; i < mParameters.size(); i++)\n estimate += mParameters(i) * input[Op()(i + 1)];\n\n return estimate;\n }\n\n template \n double modelError(const double* input)\n {\n return input[0] - (this->*Method)(input);\n }\n\n template \n void modelErrorArray(double* errors, const double* input, index size)\n {\n for (index i = 0; i < size; i++) errors[i] = (this->*Method)(input + i);\n }\n\n void directEstimate(const double* input, index size, bool updateVariance)\n {\n // copy input to a 32 byte aligned block (otherwise risk segfaults on Linux)\n VectorXd frame = Eigen::Map(input, size);\n\n if (mUseWindow)\n {\n if (mWindow.size() != size)\n {\n mWindow = ArrayXd::Zero(size);\n WindowFuncs::map()[WindowFuncs::WindowTypes::kHann](size, mWindow);\n }\n\n frame.array() *= mWindow;\n }\n\n\n VectorXd autocorrelation(size);\n algorithm::autocorrelateReal(autocorrelation.data(), frame.data(),\n asUnsigned(size));\n\n // Resize to the desired order (only keep coefficients for up to the order\n // we need)\n double pN = mParameters.size() < size ? autocorrelation(mParameters.size())\n : autocorrelation(0);\n autocorrelation.conservativeResize(mParameters.size());\n\n // Form a toeplitz matrix\n MatrixXd mat = toeplitz(autocorrelation);\n\n // Yule Walker\n autocorrelation(0) = pN;\n std::rotate(autocorrelation.data(), autocorrelation.data() + 1,\n autocorrelation.data() + mParameters.size());\n mParameters = mat.llt().solve(autocorrelation);\n\n if (updateVariance)\n {\n // Calculate variance\n double variance = mat(0, 0);\n\n for (index i = 0; i < mParameters.size() - 1; i++)\n variance -= mParameters(i) * mat(0, i + 1);\n\n setVariance((variance - (mParameters(mParameters.size() - 1) * pN)) /\n size);\n }\n }\n\n void robustEstimate(const double* input, index size, index nIterations,\n double robustFactor)\n {\n std::vector estimates(asUnsigned(size + mParameters.size()));\n\n // Calculate an initial estimate of parameters\n directEstimate(input, size, true);\n\n // Initialise Estimates\n for (index i = mParameters.size(); i < mParameters.size() + size; i++)\n estimates[asUnsigned(i)] = input[i - mParameters.size()];\n\n // Variance\n robustVariance(estimates.data() + mParameters.size(), input, size,\n robustFactor);\n\n // Iterate\n for (index iterations = nIterations; iterations--;)\n robustIteration(estimates.data() + mParameters.size(), input, size,\n robustFactor);\n }\n\n double robustResidual(double input, double prediction, double cs)\n {\n return cs * psiFunction((input - prediction) / cs);\n }\n\n void robustVariance(double* estimates, const double* input, index size,\n double robustFactor)\n {\n double residualSqSum = 0.0;\n\n // Iterate to find new filtered input\n for (index i = 0; i < size; i++)\n {\n const double residual =\n robustResidual(input[i], fowardPrediction(estimates + i),\n robustFactor * sqrt(mVariance));\n residualSqSum += residual * residual;\n }\n\n setVariance(residualSqSum / size);\n }\n\n void robustIteration(double* estimates, const double* input, index size,\n double robustFactor)\n {\n // Iterate to find new filtered input\n for (index i = 0; i < size; i++)\n {\n const double prediction = fowardPrediction(estimates);\n estimates[0] =\n prediction +\n robustResidual(input[i], prediction, robustFactor * sqrt(mVariance));\n }\n\n // New parameters\n directEstimate(estimates, size, false);\n robustVariance(estimates, input, size, robustFactor);\n }\n\n void setVariance(double variance)\n {\n if (variance > 0) variance = std::max(mMinVariance, variance);\n mVariance = variance;\n }\n\n // Huber PSI function\n double psiFunction(double x)\n {\n return fabs(x) > 1 ? std::copysign(1.0, x) : x;\n }\n\n VectorXd mParameters;\n double mVariance{0.0};\n ArrayXd mWindow;\n bool mUseWindow{true};\n double mMinVariance{0.0};\n};\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "76296b350fd7e56640ea6d7a092396f2e15ce630", "size": 6694, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/ARModel.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/util/ARModel.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/util/ARModel.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 28.0083682008, "max_line_length": 80, "alphanum_fraction": 0.646997311, "num_tokens": 1660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6557542848721257}} {"text": "/*\n * @Description: Kalman Filter utilities.\n * @Author: Ge Yao\n * @Date: 2020-11-12 15:14:07\n */\n\n#include \"lidar_localization/models/kalman_filter/kalman_filter.hpp\"\n\n// SVD for observability analysis:\n#include \n#include \n\n#include \n\n#include \"lidar_localization/tools/CSVWriter.hpp\"\n\n#include \"lidar_localization/global_defination/global_defination.h\"\n\n#include \"glog/logging.h\"\n\nnamespace lidar_localization {\n\nvoid KalmanFilter::AnalyzeQ(\n const int DIM_STATE,\n const double &time, const Eigen::MatrixXd &Q, const Eigen::VectorXd &Y,\n std::vector> &data\n) {\n // perform SVD analysis, thin for rectangular matrix:\n Eigen::JacobiSVD svd(Q, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\n // add record:\n std::vector record;\n\n // a. record timestamp:\n record.push_back(time);\n\n // b. record singular values:\n for (int i = 0; i < DIM_STATE; ++i) {\n record.push_back(svd.singularValues()(i, 0));\n }\n\n // c. record degree of observability:\n Eigen::MatrixXd X = (\n svd.matrixV() * \n svd.singularValues().asDiagonal().inverse()\n ) * (\n svd.matrixU().transpose() * Y\n ).asDiagonal();\n\n Eigen::VectorXd degree_of_observability = Eigen::VectorXd::Zero(DIM_STATE);\n for (int i = 0; i < DIM_STATE; ++i) {\n // find max. magnitude response in X:\n Eigen::MatrixXd::Index sv_index;\n X.col(i).cwiseAbs().maxCoeff(&sv_index);\n\n // associate with corresponding singular value:\n degree_of_observability(sv_index) = svd.singularValues()(i);\n }\n // normalize:\n degree_of_observability = 1.0 / svd.singularValues().maxCoeff() * degree_of_observability;\n\n for (int i = 0; i < DIM_STATE; ++i) {\n record.push_back(degree_of_observability(i));\n }\n\n // add to data:\n data.push_back(record);\n}\n\nvoid KalmanFilter::WriteAsCSV(\n const int DIM_STATE,\n const std::vector> &data,\n const std::string filename\n) {\n // init:\n CSVWriter csv(\",\");\n csv.enableAutoNewRow(1 + 2*DIM_STATE);\n\n // a. write header:\n csv << \"T\";\n for (int i = 0; i < DIM_STATE; ++i) {\n csv << (\"sv\" + std::to_string(i + 1)); \n }\n for (int i = 0; i < DIM_STATE; ++i) {\n csv << (\"doo\" + std::to_string(i + 1)); \n }\n\n // b. write contents:\n for (const auto &record: data) {\n // cast timestamp to int:\n csv << static_cast(record.at(0));\n\n for (size_t i = 1; i < record.size(); ++i) {\n csv << std::fabs(record.at(i));\n } \n }\n\n // save to persistent storage:\n csv.writeToFile(filename);\n}\n\n} // namespace lidar_localization", "meta": {"hexsha": "6b31a3c79e2a08d6f57f0ea7ee837e1f271c3127", "size": 2706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "FILTER/06-filtering-basic/src/lidar_localization/src/models/kalman_filter/kalman_filter.cpp", "max_stars_repo_name": "lanqing30/SensorFusionCourse", "max_stars_repo_head_hexsha": "3fcf935d6a4191563afcf2d95b34718fba7f705a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2021-03-19T05:51:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T06:10:16.000Z", "max_issues_repo_path": "06-filtering-basic/src/lidar_localization/src/models/kalman_filter/kalman_filter.cpp", "max_issues_repo_name": "WeihengXia0123/LiDar-SLAM", "max_issues_repo_head_hexsha": "834060da7ee0125cefd310d6215821551bac16c3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "06-filtering-basic/src/lidar_localization/src/models/kalman_filter/kalman_filter.cpp", "max_forks_repo_name": "WeihengXia0123/LiDar-SLAM", "max_forks_repo_head_hexsha": "834060da7ee0125cefd310d6215821551bac16c3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2021-02-17T12:31:08.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-22T17:12:44.000Z", "avg_line_length": 26.5294117647, "max_line_length": 94, "alphanum_fraction": 0.6175166297, "num_tokens": 748, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240895276223, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.655661949668016}} {"text": "#include \r\n#include \r\n\r\nusing namespace std;\r\nusing boost::multiprecision::cpp_int;\r\n\r\n/*\r\nThe lattice in this problem is just a very cleverly disguised combinatorics question. So we just need to calculate the factorials. \r\n*/\r\n\r\n// Generate the n'th term for the factorial sequence.\r\ncpp_int factorial(int n) {\r\n\tif(n > 1) {\r\n\t\treturn n * factorial(n - 1);\r\n\t} else {\r\n\t\treturn 1;\r\n\t}\r\n}\r\n\r\ncpp_int nCr(int n, int r) {\r\n\treturn (factorial(n) / (factorial(r) * factorial(n - r)));\r\n}\r\n\r\nint main(int argc, char *argv[]) {\r\n\tcout << nCr(40, 20) << endl;\r\n\treturn 0;\r\n}", "meta": {"hexsha": "ed4479a535e412ef011b2152b4bd14a4a2fd939b", "size": 611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Solutions/1-50/15/Solution.cpp", "max_stars_repo_name": "kitegi/Edmonton", "max_stars_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-07-16T13:30:10.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-16T18:17:40.000Z", "max_issues_repo_path": "Solutions/1-50/15/Solution.cpp", "max_issues_repo_name": "kitegi/Edmonton", "max_issues_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Solutions/1-50/15/Solution.cpp", "max_forks_repo_name": "kitegi/Edmonton", "max_forks_repo_head_hexsha": "774c9b2f72e7b2c6a3bc1b3329ef227ef39adf9d", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-16T22:56:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-16T22:56:07.000Z", "avg_line_length": 22.6296296296, "max_line_length": 132, "alphanum_fraction": 0.6546644845, "num_tokens": 163, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9465966671870766, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6556525867834221}} {"text": "// Boost.GIL (Generic Image Library) - tests\n//\n// Copyright 2020 Olzhas Zhumabek \n//\n// Use, modification and distribution are subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//\n#ifndef BOOST_GIL_IMAGE_PROCESSING_HOUGH_PARAMETER_HPP\n#define BOOST_GIL_IMAGE_PROCESSING_HOUGH_PARAMETER_HPP\n\n#include \n#include \n#include \n\nnamespace boost\n{\nnamespace gil\n{\n/// \\ingroup HoughTransform\n/// \\brief A type to encapsulate Hough transform parameter range\n///\n/// This type provides a way to express value range for a parameter\n/// as well as some factory functions to simplify initialization\ntemplate \nstruct hough_parameter\n{\n T start_point;\n T step_size;\n std::size_t step_count;\n\n /// \\ingroup HoughTransform\n /// \\brief Create Hough parameter from value neighborhood and step count\n ///\n /// This function will take start_point as middle point, and in both\n /// directions will try to walk half_step_count times until distance of\n /// neighborhood is reached\n static hough_parameter from_step_count(T start_point, T neighborhood,\n std::size_t half_step_count)\n {\n T step_size = neighborhood / half_step_count;\n std::size_t step_count = half_step_count * 2 + 1;\n // explicitly fill out members, as aggregate init will error out with narrowing\n hough_parameter parameter;\n parameter.start_point = start_point - neighborhood;\n parameter.step_size = step_size;\n parameter.step_count = step_count;\n return parameter;\n }\n\n /// \\ingroup HoughTransform\n /// \\brief Create Hough parameter from value neighborhood and step size\n ///\n /// This function will take start_point as middle point, and in both\n /// directions will try to walk step_size at a time until distance of\n /// neighborhood is reached\n static hough_parameter from_step_size(T start_point, T neighborhood, T step_size)\n {\n std::size_t step_count =\n 2 * static_cast(std::floor(neighborhood / step_size)) + 1;\n // do not use step_size - neighborhood, as step_size might not allow\n // landing exactly on that value when starting from start_point\n // also use parentheses on step_count / 2 because flooring is exactly\n // what we want\n\n // explicitly fill out members, as aggregate init will error out with narrowing\n hough_parameter parameter;\n parameter.start_point = start_point - step_size * (step_count / 2);\n parameter.step_size = step_size;\n parameter.step_count = step_count;\n return parameter;\n }\n};\n\n/// \\ingroup HoughTransform\n/// \\brief Calculate minimum angle which would be observable if walked on a circle\n///\n/// When drawing a circle or moving around a point in circular motion, it is\n/// important to not do too many steps, but also to not have disconnected\n/// trajectory. This function will calculate the minimum angle that is observable\n/// when walking on a circle or tilting a line.\n/// WARNING: do keep in mind IEEE 754 quirks, e.g. no-associativity,\n/// no-commutativity and precision. Do not expect expressions that are\n/// mathematically the same to produce the same values\ninline double minimum_angle_step(point_t dimensions)\n{\n auto longer_dimension = dimensions.x > dimensions.y ? dimensions.x : dimensions.y;\n return std::atan2(1, longer_dimension);\n}\n\n/// \\ingroup HoughTransform\n/// \\brief Create a Hough transform parameter with optimal angle step\n///\n/// Due to computational intensity and noise sensitivity of Hough transform,\n/// having any candidates missed or computed again is problematic. This function\n/// will properly encapsulate optimal value range around approx_angle with amplitude of\n/// neighborhood in each direction.\n/// WARNING: do keep in mind IEEE 754 quirks, e.g. no-associativity,\n/// no-commutativity and precision. Do not expect expressions that are\n/// mathematically the same to produce the same values\ninline hough_parameter make_theta_parameter(double approx_angle, double neighborhood,\n point_t dimensions)\n{\n auto angle_step = minimum_angle_step(dimensions);\n\n // std::size_t step_count =\n // 2 * static_cast(std::floor(neighborhood / angle_step)) + 1;\n // return {approx_angle - angle_step * (step_count / 2), angle_step, step_count};\n return hough_parameter::from_step_size(approx_angle, neighborhood, angle_step);\n}\n}} // namespace boost::gil\n#endif\n", "meta": {"hexsha": "97fcd8cde5d2e33b8894d0629fde1ffe7f079e69", "size": 4732, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/image_processing/hough_parameter.hpp", "max_stars_repo_name": "harsh-4/gil", "max_stars_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 153.0, "max_stars_repo_stars_event_min_datetime": "2015-02-03T06:03:54.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T15:06:34.000Z", "max_issues_repo_path": "include/boost/gil/image_processing/hough_parameter.hpp", "max_issues_repo_name": "harsh-4/gil", "max_issues_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 429.0, "max_issues_repo_issues_event_min_datetime": "2015-03-22T09:49:04.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T08:32:08.000Z", "max_forks_repo_path": "include/boost/gil/image_processing/hough_parameter.hpp", "max_forks_repo_name": "harsh-4/gil", "max_forks_repo_head_hexsha": "6da59cc3351e5657275d3a536e0b6e7a1b6ac738", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-03-15T09:20:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-30T12:40:07.000Z", "avg_line_length": 41.8761061947, "max_line_length": 93, "alphanum_fraction": 0.71386306, "num_tokens": 1031, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199795472731, "lm_q2_score": 0.7826624840223698, "lm_q1q2_score": 0.6555737338592353}} {"text": "// Copyright (c) 2020, ETH Zurich, CVG, Mihai Dusmanu (mihai.dusmanu@inf.ethz.ch)\n\n#include \n\n#include \"ceres/ceres.h\"\n\nclass BiquadraticInterpolator {\n public:\n explicit BiquadraticInterpolator(\n const std::vector& data, size_t n_channels\n ) : data_(data), n_channels_(n_channels) {}\n\n void Evaluate(double row, double col, double* f, double* dfdrow, double* dfdcol) const {\n // Clipping.\n const double row_ = row;\n const double col_ = col;\n row = std::max(std::min(row, row_end_), row_start_);\n col = std::max(std::min(col, col_end_), col_start_);\n \n const double lagrange_row[3] = {2. * row * (row - .5), (-4.) * (row - .5) * (row + .5), 2. * row * (row + 0.5)};\n const double deriv_lagrange_row[3] = {2. * row + 2. * (row - .5), (-4.) * (row - .5) + (-4.) * (row + .5), 2. * row + 2. * (row + 0.5)};\n const double lagrange_col[3] = {2. * col * (col - .5), (-4.) * (col - .5) * (col + .5), 2. * col * (col + 0.5)};\n const double deriv_lagrange_col[3] = {2. * col + 2. * (col - .5), (-4.) * (col - .5) + (-4.) * (col + .5), 2. * col + 2. * (col + 0.5)};\n\n for (size_t k = 0; k < n_channels_; ++k) {\n f[k] = 0.;\n if (dfdrow != NULL) {\n dfdrow[k] = 0.;\n dfdcol[k] = 0.;\n }\n\n for (size_t i = 0; i < n_rows_; ++i) {\n for (size_t j = 0; j < n_cols_; ++j) {\n double data = data_[n_channels_ * (i * n_cols_ + j) + k];\n f[k] += lagrange_row[i] * lagrange_col[j] * data;\n\n if (dfdrow != NULL) {\n if (row_ == row) {\n dfdrow[k] += deriv_lagrange_row[i] * lagrange_col[j] * data;\n }\n if (col_ == col) {\n dfdcol[k] += lagrange_row[i] * deriv_lagrange_col[j] * data;\n }\n }\n }\n }\n }\n }\n\n // The following two Evaluate overloads are needed for interfacing with automatic differentiation.\n // The first is for when a scalar evaluation is done, and the second one is for when Jets are used.\n void Evaluate(const double& r, const double& c, double* f) const {\n Evaluate(r, c, f, NULL, NULL);\n }\n\n template void Evaluate(const JetT& x, const JetT& y, JetT* f) const {\n double frc[n_channels_], dfdr[n_channels_], dfdc[n_channels_];\n Evaluate(x.a, y.a, frc, dfdr, dfdc);\n for (size_t k = 0; k < n_channels_; ++k) {\n f[k].a = frc[k];\n f[k].v = dfdr[k] * x.v + dfdc[k] * y.v;\n }\n }\n\n private:\n const std::vector data_;\n const size_t n_channels_;\n const double row_start_ = -.5; const double col_start_ = -.5;\n const double row_end_ = .5; const double col_end_ = .5;\n const double one_over_row_stride_ = 2.; const double one_over_col_stride_ = 2.;\n const size_t n_rows_ = 3; const size_t n_cols_ = 3;\n};\n\ntemplate struct InterpolatedCostFunctor {\n public:\n explicit InterpolatedCostFunctor(Interpolator&& interpolator) : interpolator_(std::move(interpolator)) {}\n\n template bool operator()(const T* x1, const T* x2, T* residuals) const {\n const Eigen::Map> x1_vec(x1);\n const Eigen::Map> x2_vec(x2);\n\n Eigen::Matrix disp;\n interpolator_.Evaluate(x1_vec[0], x1_vec[1], disp.data());\n\n Eigen::Map> residuals_vec(residuals);\n\n residuals_vec = x2_vec - x1_vec - disp;\n\n return true;\n }\n\n static ceres::CostFunction* Create(Interpolator&& interpolator) {\n return new ceres::AutoDiffCostFunction(new InterpolatedCostFunctor(std::move(interpolator)));\n }\n\n private:\n const Interpolator interpolator_;\n};\n", "meta": {"hexsha": "46186b154f7bf559d1f64b7d29330671b2749c2a", "size": 4224, "ext": "cc", "lang": "C++", "max_stars_repo_path": "multi-view-refinement/cost.cc", "max_stars_repo_name": "kudo1026/local-feature-refinement", "max_stars_repo_head_hexsha": "214edae3cd9aa1a89a7ec1471a84096cf16c2449", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 180.0, "max_stars_repo_stars_event_min_datetime": "2020-04-14T15:22:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T01:12:56.000Z", "max_issues_repo_path": "multi-view-refinement/cost.cc", "max_issues_repo_name": "kudo1026/local-feature-refinement", "max_issues_repo_head_hexsha": "214edae3cd9aa1a89a7ec1471a84096cf16c2449", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-09-13T05:30:18.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-07T12:18:27.000Z", "max_forks_repo_path": "multi-view-refinement/cost.cc", "max_forks_repo_name": "kudo1026/local-feature-refinement", "max_forks_repo_head_hexsha": "214edae3cd9aa1a89a7ec1471a84096cf16c2449", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 22.0, "max_forks_repo_forks_event_min_datetime": "2020-04-14T18:17:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-07T12:27:12.000Z", "avg_line_length": 42.6666666667, "max_line_length": 148, "alphanum_fraction": 0.5170454545, "num_tokens": 1194, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297807787536, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6555635767302445}} {"text": "#include \n// [[Rcpp::depends(\"RcppArmadillo\")]]\n// [[Rcpp::depends(\"BH\")]]\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace Rcpp;\nusing namespace arma;\nusing namespace std;\nusing namespace boost::multiprecision;\nusing namespace boost::math;\n\nboost::mt19937 rng; // seed for random sampling\n\ndouble rbeta_cpp(double shape1, double shape2) {\n double u = rand() / double(RAND_MAX);\n beta_distribution<> beta_dist(shape1, shape2);\n return quantile(beta_dist, u); \n}\n\n// [[Rcpp::export]]\narma::rowvec rDirichlet2(arma::rowvec param, int length) {\n vector ret;\n param *= 10000;\n vector param_vec = conv_to >::from(param);\n int len = length - 1;\n \n double paramSum = std::accumulate(param_vec.begin()+1,param_vec.end(),(double)0);\n ret.push_back(rbeta_cpp(param_vec[0], paramSum));\n for (int i=1; i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nconst int PRECISION = 100;\ntypedef boost::multiprecision::number > arbFloat;\n\nbool isStringValid(const std::string & str);\nbool isNumberValid(const arbFloat & x);\nenum returnID {success = 0, invalidString = 1, invalidNumber = 2};\ninline std::string resizeArbtoString(const arbFloat & x);\n\nint main() {\n // Input and check string\n std::cout << \"0 <= x < inf\\nW(x), x = \";\n std::string inputStr;\n std::getline(std::cin, inputStr);\n \n if(!isStringValid(inputStr)) return returnID::invalidString;\n \n arbFloat input = static_cast(inputStr);\n \n if(!isNumberValid(input)) return returnID::invalidNumber;\n \n // Starting guess\n arbFloat wnew = (input >= 2) ? log(input) - log(log(input)) + (log(log(input)) / log(input))\n : static_cast(0);\n \n std::cout << std::setprecision(PRECISION)\n << \"\\nInitial Guess: \" << wnew << \"\\nConvergence:\\n\";\n \n // Calculations\n int i;\n std::string preComp, postComp;\n for(i = 0; i == 0 || preComp != postComp; i++){\n std::cout << '\\t' << wnew << '\\n';\n preComp = resizeArbtoString(wnew);\n wnew -= ((wnew * exp(wnew)) - input) /\n (exp(wnew) * (wnew + 1) - ((wnew + 2) * (wnew * exp(wnew) - input) / ((2 * wnew) + 2)));\n postComp = resizeArbtoString(wnew);\n }\n \n std::cout << \"\\nW(\" + inputStr + \") = \" << wnew << \"\\n(rounded up to \"\n << PRECISION << \" digits, precise after \" << i << \" iterations)\\n\";\n \n return 0;\n}\n\n// Check input\nbool isStringValid(const std::string & str){\n // Check if string contains spaces\n if(std::count(str.begin(), str.end(), ' ') > 0){\n std::cout << \"\\nError: Input contains spaces\\n\";\n return false;\n }\n \n // Check if string contains multiple .\n if(std::count(str.begin(), str.end(), '.') > 1){\n std::cout << \"\\nError: Input contains multiple decimal marks\\n\";\n return false;\n }\n \n // Check if NaN or Out of bounds (due to parsing failure)\n try{\n boost::lexical_cast(str);\n } catch(std::runtime_error){\n std::cout << \"\\nError: Unable to parse (value too large or incorrect number type)\\n\";\n return false;\n } catch(...){\n std::cout << \"\\nError: Input is NaN\\n\";\n return false;\n }\n \n // Check if intentional NaN\n if(boost::icontains(str, \"nan\")){\n std::cout << \"\\nError: Intentional NaN\\n\";\n return false;\n }\n \n return true;\n}\n\n// Check number\nbool isNumberValid(const arbFloat & x){\n // Check if result is imaginary\n if(x < 0){\n std::cout << \"\\nError: Complex result\\n\";\n return false;\n }\n \n // Check if out of bounds (interpreted as infinity)\n if(x == std::numeric_limits::infinity()){\n std::cout << \"\\nError: Input is out of bounds\\n\";\n return false;\n }\n \n return true;\n}\n\n// Convert to string and resize using correct precision\ninline std::string resizeArbtoString(const arbFloat & x){\n std::string resizedStr = static_cast(x);\n resizedStr.resize(PRECISION + 2);\n return resizedStr;\n}\n", "meta": {"hexsha": "4dbe30b50df35d6c55f9aa16d2baf7b172ccfc61", "size": 3406, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lambert-W-function/Lambert-W-function-v4.cpp", "max_stars_repo_name": "esote/mathematical-functions", "max_stars_repo_head_hexsha": "0bdf761583a49b6479a82d7e0668744d9bb75dad", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lambert-W-function/Lambert-W-function-v4.cpp", "max_issues_repo_name": "esote/mathematical-functions", "max_issues_repo_head_hexsha": "0bdf761583a49b6479a82d7e0668744d9bb75dad", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lambert-W-function/Lambert-W-function-v4.cpp", "max_forks_repo_name": "esote/mathematical-functions", "max_forks_repo_head_hexsha": "0bdf761583a49b6479a82d7e0668744d9bb75dad", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.6846846847, "max_line_length": 104, "alphanum_fraction": 0.5957134469, "num_tokens": 904, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.6555635646731172}} {"text": "/**\n * \\file dcs/math/stats/distribution/normal.hpp\n *\n * \\brief The Normal probability distribution.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n *
\n *\n * Copyright 2009 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n#ifndef DCS_MATH_STATS_DISTRIBUTION_NORMAL_HPP\n#define DCS_MATH_STATS_DISTRIBUTION_NORMAL_HPP\n\n\n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace dcs { namespace math { namespace stats {\n\nusing ::std::size_t;\n\n\n/**\n * The Normal distribution with parameter \\f$\\mu\\f$ (the mean) and \\f$\\sigma\\f$\n * (the standard deviation).\n *\n * \\tparam RealT The type used for real numbers.\n * \\tparam PolicyT The policy type.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n */\ntemplate < typename RealT=double, typename PolicyT=::dcs::math::policies::policy<> >\nclass normal_distribution\n{\n\tpublic: typedef RealT support_type;\n\tpublic: typedef RealT value_type;\n\tpublic: typedef PolicyT policy_type;\n\n\tpublic: explicit normal_distribution(support_type mean=0, support_type stddev=1)\n\t\t: dist_(mean,stddev)\n//\t\t: mean_(mean),\n//\t\t stddev_(stddev)\n\t{\n\t\t// empty\n\t}\n\n\n\t// compiler-generated copy ctor and assignment operator are fine\n\n\n\t/**\n\t * \\brief Generate a vector of random numbers distributed according to this\n\t * normal distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\param n The number of random numbers to generate.\n\t * \\return A random number distributed according to this normal\n\t * distribution.\n\t *\n\t * A \\c normal random number distribution produces random numbers * \\f$x\\f$\n\t * distributed according to the probability density function:\n\t * \\f[\n\t * \\Pr(x|\\mu,\\sigma) = \\frac{1}{\\sigma\\sqrt{2\\pi}}\\exp\\left(-\\frac{(x-\\mu)^2}{2\\sigma^2}\\right)\n\t * \\f]\n\t */\n\tpublic: template \n\t\tsupport_type rand(UniformRandomGeneratorT& rng) const\n\t{\n\t\ttypedef ::boost::normal_distribution rdist_type;\n\t\ttypedef ::boost::variate_generator variate_type;\n\n\t\treturn variate_type(rng, rdist_type(dist_.mean(), dist_.standard_deviation()))();\n\t}\n\n\n\t/**\n\t * \\brief Generate a vector of random numbers distributed according to this\n\t * normal distribution.\n\t *\n\t * \\param rng A uniform random number generator.\n\t * \\param n The number of random numbers to generate.\n\t * \\return A vector of random numbers distributed according to this\n\t * normal distribution.\n\t *\n\t * A \\c normal random number distribution produces random numbers * \\f$x\\f$\n\t * distributed according to the probability density function:\n\t * \\f[\n\t * \\Pr(x|\\mu,\\sigma) = \\frac{1}{\\sigma\\sqrt{2\\pi}}\\exp\\left(-\\frac{(x-\\mu)^2}{2\\sigma^2}\\right)\n\t * \\f]\n\t */\n\tpublic: template \n\t\t::std::vector rand(UniformRandomGeneratorT& rng, size_t n)\n\t{\n\t\ttypedef ::boost::normal_distribution rdist_type;\n typedef ::boost::variate_generator variate_type;\n\n\t\t::std::vector rnds(n);\n\n for ( ; n > 0; --n)\n\t\t{\n\t\t\trnds.push_back(variate_type(rng, rdist_type(dist_.mean(), dist_.standard_deviation()))());\n\t\t}\n\n\t\treturn rnds;\n\t}\n\n\n\tpublic: support_type mean() const\n\t{\n\t\treturn dist_.mean();\n\t}\n\n\n\tpublic: support_type stddev() const\n\t{\n\t\treturn dist_.standard_deviation();\n\t}\n\n\n\tpublic: support_type location() const\n\t{\n\t\treturn dist_.location();\n\t}\n\n\n\tpublic: support_type scale() const\n\t{\n\t\treturn dist_.scale();\n\t}\n\n\n\tpublic: support_type quantile(value_type p) const\n\t{\n\t\treturn ::boost::math::quantile(dist_, p);\n\t}\n\n\n\t//private: support_type mean_;\n\t//private: support_type stddev_;\n\tprivate: ::boost::math::normal_distribution dist_;\n};\n\n\ntemplate <\n\ttypename CharT,\n\ttypename CharTraitsT,\n\ttypename RealT,\n\ttypename PolicyT\n>\n::std::basic_ostream& operator<<(::std::basic_ostream& os, normal_distribution const& dist)\n{\n\treturn os << \"Normal(\"\n\t\t\t << \"mean=\" << dist.mean()\n\t\t\t << \", stddev=\" << dist.stddev()\n\t\t\t << \")\";\n}\n\n}}} // Namespace dcs::math::stats\n\n#endif // DCS_MATH_STATS_DISTRIBUTION_NORMAL_HPP\n", "meta": {"hexsha": "b4d1c6e64125f0ae2364400693f9cc317738a835", "size": 5027, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "inc/dcs/math/stats/distribution/normal.hpp", "max_stars_repo_name": "sguazt/dcsxx-commons", "max_stars_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "inc/dcs/math/stats/distribution/normal.hpp", "max_issues_repo_name": "sguazt/dcsxx-commons", "max_issues_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "inc/dcs/math/stats/distribution/normal.hpp", "max_forks_repo_name": "sguazt/dcsxx-commons", "max_forks_repo_head_hexsha": "0fc1fd8a38b7c412941b401c00a9293bc5df8b21", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.8823529412, "max_line_length": 144, "alphanum_fraction": 0.7171275114, "num_tokens": 1305, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740729, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6555217127620131}} {"text": "//\n// Created by matt on 20/01/2021.\n//\n\n#include \n\n#include \n\n#include \"simple_kf.h\"\n#include \"standard_kf.h\"\n#include \"extended_kf.h\"\n#include \"unscented_kf.h\"\n#include \"system.h\"\n#include \"numeric_differentiation.h\"\n\n\nint main() {\n\n const int iterations = 3;\n using SS = systems::SimpleSystem;\n const SS::MeasurementVector z(1.0, 2.0);\n\n ////////////////////////////////////////////////////////////////////\n std::cout << \"Simple kalman filter\\n\";\n kf0::KalmanFilter skf;\n skf.SetCov(systems::SimpleSystem::StateMatrix::Identity());\n std::cout << \"Intial state:\\n\";\n std::cout << skf.GetState().transpose() << '\\n';\n std::cout << skf.GetCov() << '\\n';\n for (int i = 0; i < iterations; i++) {\n std::cout << \"Iteration: \" << i << '\\n';\n std::cout << \"Predict: \" << skf.Predict().transpose() << '\\n';\n std::cout << skf.GetCov() << '\\n';\n std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n std::cout << \"Update: \" << skf.Update(z * (double) i).transpose() << \"\\n\";\n std::cout << skf.GetCov() << \"\\n\\n\";\n }\n\n ////////////////////////////////////////////////////////////////////\n std::cout << \"Templated kalman filter 1\\n\";\n\n kf1::KalmanFilter<4> kf1;\n kf1::ProcessModel<4> process = [](const Eigen::Matrix& x) -> Eigen::Matrix {\n Eigen::Matrix F = Eigen::Matrix::Identity();\n F(0, 2) = 0.1; // px' = px + vx*dt\n F(1, 3) = 0.1; // py' = py + vy*dt\n return F * x;\n };\n kf1::MeasurementModel<4, 2> measurement_model = [](\n const Eigen::Matrix& x) -> Eigen::Matrix {\n Eigen::Matrix H = Eigen::Matrix::Zero();\n // Measure position only\n H(0, 0) = 1.0;\n H(1, 1) = 1.0;\n return H * x;\n };\n\n kf1.SetCov(Eigen::Matrix4d::Identity());\n Eigen::Matrix4d Q = Eigen::Matrix4d::Identity() * 2.0;\n Eigen::Matrix2d R = Eigen::Matrix2d::Identity();\n\n std::cout << kf1.GetState().transpose() << '\\n';\n std::cout << kf1.GetCov() << '\\n';\n for (int i = 0; i < iterations; i++) {\n std::cout << \"Iteration: \" << i << '\\n';\n kf1.Predict(process, Q);\n std::cout << \"Predict: \" << kf1.GetState().transpose() << '\\n';\n std::cout << kf1.GetCov() << '\\n';\n kf1.Update<2>(measurement_model, z * (double) i, R);\n std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n std::cout << \"Update: \" << kf1.GetState().transpose() << \"\\n\\n\";\n std::cout << kf1.GetCov() << '\\n';\n }\n\n ////////////////////////////////////////////////////////////////////\n\n std::cout << \"Templated kalman filter 2\\n\";\n\n kf2::KalmanFilter<4, 2>::ProcessModel process_model_2 = [](\n const Eigen::Matrix& x) -> Eigen::Matrix {\n Eigen::Matrix F = Eigen::Matrix::Identity();\n F(0, 2) = 0.1; // px' = px + vx*dt\n F(1, 3) = 0.1; // py' = py + vy*dt\n return F * x;\n };\n kf2::KalmanFilter<4, 2>::MeasurementModel measurement_model_2 = [](\n const Eigen::Matrix& x) -> Eigen::Matrix {\n Eigen::Matrix H = Eigen::Matrix::Zero();\n // Measure position only\n H(0, 0) = 1.0;\n H(1, 1) = 1.0;\n return H * x;\n };\n\n kf2::KalmanFilter<4, 2> kf2(process_model_2, measurement_model_2);\n kf2.SetCov(Eigen::Matrix4d::Identity());\n\n for (int i = 0; i < iterations; i++) {\n std::cout << \"Iteration: \" << i << '\\n';\n kf2.Predict(Q);\n std::cout << \"Predict: \" << kf2.GetState().transpose() << '\\n';\n kf2.Update(z * (double) i, R);\n std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n std::cout << \"Update: \" << kf2.GetState().transpose() << \"\\n\\n\";\n }\n\n ////////////////////////////////////////////////////////////////////\n std::cout << \"Templated kalman filter 3\\n\";\n\n kf3::KalmanFilter<4, 2, SS> kf_3;\n kf_3.SetCov(Eigen::Matrix4d::Identity());\n\n for (int i = 0; i < iterations; i++) {\n std::cout << \"Iteration: \" << i << '\\n';\n kf_3.Predict(Q);\n std::cout << \"Predict: \" << kf_3.GetState().transpose() << '\\n';\n kf_3.Update(z * (double) i, R);\n std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n std::cout << \"Update: \" << kf_3.GetState().transpose() << \"\\n\\n\";\n }\n\n ////////////////////////////////////////////////////////////////////\n std::cout << \"Templated kalman filter 4\\n\";\n\n kf4::KalmanFilter kf_4;\n kf_4.SetCov(Eigen::Matrix4d::Identity());\n\n for (int i = 0; i < iterations; i++) {\n std::cout << \"Iteration: \" << i << '\\n';\n kf_4.Predict(Q);\n std::cout << \"Predict: \" << kf_4.GetState().transpose() << '\\n';\n kf_4.Update(z * (double) i, R);\n std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n std::cout << \"Update: \" << kf_4.GetState().transpose() << \"\\n\\n\";\n }\n\n ////////////////////////////////////////////////////////////////////\n std::cout << \"Another system\\n\";\n\n const Eigen::Vector3d z3(1.0, 2.0, 0.5);\n Eigen::Matrix Q3 = Eigen::Matrix::Identity() * 2.0;\n Eigen::Matrix3d R3 = Eigen::Matrix3d::Identity();\n\n kf4::KalmanFilter kf_5;\n for (int i = 0; i < iterations; i++) {\n std::cout << \"Iteration: \" << i << '\\n';\n kf_5.Predict(Q3);\n std::cout << \"Predict: \" << kf_5.GetState().transpose() << '\\n';\n kf_5.Update(z3 * (double) i, R3);\n std::cout << \"Measurement: \" << (z3 * (double) i).transpose() << \"\\n\";\n std::cout << \"Update: \" << kf_5.GetState().transpose() << \"\\n\\n\";\n }\n\n ////////////////////////////////////////////////////////////////////\n std::cout << \"Kalman filter using dynamic sized matrices\\n\";\n\n Eigen::VectorXd starting_state = Eigen::VectorXd::Zero(4);\n kf5::KalmanFilter kf_6(starting_state);\n kf_6.SetCov(Eigen::MatrixXd::Identity(4, 4));\n\n for (int i = 0; i < iterations; i++) {\n std::cout << \"Iteration: \" << i << '\\n';\n kf_6.Predict(Q);\n std::cout << \"Predict: \" << kf_6.GetState().transpose() << '\\n';\n kf_6.Update(z * (double) i, R);\n std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n std::cout << \"Update: \" << kf_6.GetState().transpose() << \"\\n\\n\";\n }\n\n ////////////////////////////////////////////////////////////////////\n\n Eigen::Vector4d current_state = Eigen::Vector4d::Zero();\n\n SS::StateMatrix JF = numeric_differentiation::CalculateJacobian(current_state, SS::processModel);\n std::cout << JF << \"\\n\\n\";\n Eigen::Matrix JH =\n numeric_differentiation::CalculateJacobian(current_state, SS::measurementModel);\n std::cout << JH << \"\\n\\n\";\n\n\n ////////////////////////////////////////////////////////////////////\n std::cout << \"EKF 1 (with linear system) \\n\";\n\n ekf1::ExtendedKalmanFilter ekf_1;\n ekf_1.SetCov(SS::StateMatrix::Identity());\n\n for (int i = 0; i < iterations; i++) {\n std::cout << \"Iteration: \" << i << '\\n';\n ekf_1.Predict(Q);\n std::cout << \"Predict: \" << ekf_1.GetState().transpose() << '\\n';\n ekf_1.Update(z * (double) i, R);\n std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n std::cout << \"Update: \" << ekf_1.GetState().transpose() << \"\\n\\n\";\n }\n\n ////////////////////////////////////////////////////////////////////\n std::cout << \"EKF 1 (with non-linear system) \\n\";\n\n using NLS = systems::NonLinearSystem;\n ekf1::ExtendedKalmanFilter ekf_2;\n NLS::ProcessNoiseMatrix Q_nl = NLS::ProcessNoiseMatrix::Identity() * 10.0;\n NLS::MeasurementNoiseMatrix R_nl = NLS::MeasurementNoiseMatrix::Identity() * 1.0;\n\n ekf_2.SetCov(Q_nl);\n for (int i = 0; i < iterations; i++) {\n std::cout << \"Iteration: \" << i << '\\n';\n ekf_2.Predict(Q_nl);\n std::cout << \"Predict: \" << ekf_2.GetState().transpose() << '\\n';\n ekf_2.Update(z, R_nl);\n std::cout << \"Measurement: \" << z.transpose() << \"\\n\";\n std::cout << \"Update: \" << ekf_2.GetState().transpose() << \"\\n\\n\";\n }\n\n // velocity is estimated correctly after a few iterations\n // why doesn't heading work out?\n\n ////////////////////////////////////////////////////////////////////\n std::cout << \"Unscented kalman filter 1\\n\";\n\n ukf1::UnscentedKalmanFilter ukf_1;\n ukf_1.SetCov(SS::StateMatrix::Identity());\n\n std::cout << ukf_1.GetState().transpose() << '\\n';\n std::cout << ukf_1.GetCov() << '\\n';\n for (int i = 0; i < iterations; i++) {\n std::cout << \"Iteration: \" << i << '\\n';\n ukf_1.Predict(Q);\n std::cout << \"Predict: \" << ukf_1.GetState().transpose() << '\\n';\n ukf_1.Update(z * (double) i, R);\n std::cout << \"Measurement: \" << (z * (double) i).transpose() << \"\\n\";\n std::cout << \"Update: \" << ukf_1.GetState().transpose() << \"\\n\";\n }\n\n\n\n\n return 0;\n}\n", "meta": {"hexsha": "03c32456e50ad41fc5ca5121f83d4d6fbb3caa9b", "size": 8809, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "matt769/kalman_filters", "max_stars_repo_head_hexsha": "f99c4f6dac316a674e25dadd80f0f6455d962515", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "matt769/kalman_filters", "max_issues_repo_head_hexsha": "f99c4f6dac316a674e25dadd80f0f6455d962515", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "matt769/kalman_filters", "max_forks_repo_head_hexsha": "f99c4f6dac316a674e25dadd80f0f6455d962515", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.8577405858, "max_line_length": 131, "alphanum_fraction": 0.5211715291, "num_tokens": 2834, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6555217095080877}} {"text": "#include \n#include \n\n\nint main()\n{\n // declare a matrix\n dlib::matrix y;\n dlib::matrix M;\n // initialize matrices\n M = 54.2, 65.2, 43,\n 23.4, 12.3, 55.4,\n 11, 34.6, 78.9;\n y = 3.5,\n 1.2,\n 6.7;\n // solve this linear system\n dlib::matrix x = dlib::inv(M)*y;\n std::cout << \"x: \\n\" << x << \"\\n\";\n // check if the calculation is correct\n std::cout << \"Check: M*x- y= \\n\" << M*x - y << \"\\n\";\n\n // sum the matrix\n double sumM = 0;\n for (int r = 0; r < M.nr(); ++r)\n {\n for (int c = 0; c < M.nc(); ++c)\n {\n sumM += M(r, c);\n }\n }\n std::cout << \"Sum of matrix by looping= \" << sumM << \"\\n\";\n std::cout << \"Sum of matrix by sum() function= \" << dlib::sum(M) << \"\\n\";\n // print using comma separator\n std::cout <<\"print matrix M using comma delimiter: \\n\" <\n#include \n#include \n\nnamespace GradientFlow {\n\n/* SAM_LISTING_BEGIN_0 */\nEigen::MatrixXd ButcherMatrix() {\n Eigen::MatrixXd A(6, 5);\n // clang-format off\n A << 0.25, 0., 0., 0., 0.,\n 0.5, 0.25, 0., 0., 0.,\n 17./50., -1./25., 0.25, 0., 0.,\n 371./1360., -137./2720., 15./544., 0.25, 0.,\n 25./24., -49./48., 125./16., -85./12., 0.25,\n 25./24., -49./48., 125./16., -85./12., 0.25;\n // clang-format on\n return A;\n}\n/* SAM_LISTING_END_0 */\n\n/* SAM_LISTING_BEGIN_1 */\nstd::vector solveGradientFlow(const Eigen::VectorXd &d,\n double lambda,\n const Eigen::VectorXd &y,\n double T, unsigned int N) {\n std::vector Y(N + 1);\n // TO DO (0-2.h)\n#if SOLUTION\n // Define the right hand side of the ODE y' = f(y), and the Jacobian of f.\n auto f = [d, lambda](const Eigen::VectorXd &yt) {\n Eigen::VectorXd val =\n -2. * std::cos(yt.squaredNorm()) * yt - 2. * lambda * d.dot(yt) * d;\n return val;\n };\n auto J = [d, lambda](const Eigen::VectorXd &yt) {\n int dim = yt.size();\n Eigen::MatrixXd term1 =\n 4. * std::sin(yt.squaredNorm()) * yt * yt.transpose();\n Eigen::MatrixXd term2 =\n -2. * std::cos(yt.squaredNorm()) * Eigen::MatrixXd::Identity(dim, dim);\n Eigen::MatrixXd term3 = -2. * lambda * d * d.transpose();\n Eigen::MatrixXd Jval = term1 + term2 + term3;\n return Jval;\n };\n\n // Split the interval [0,T] into N intervals of size h.\n double h = T / N;\n Eigen::VectorXd yt = y;\n Y.at(0) = y;\n // Evolve up to time T:\n for (int i = 1; i <= N; i++) {\n yt = discEvolSDIRK(f, J, yt, h);\n Y.at(i) = yt;\n }\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return Y;\n}\n/* SAM_LISTING_END_1 */\n\n} // namespace GradientFlow\n", "meta": {"hexsha": "07127e479aa00cdc771b1fb7a65cfefbf0b60bf9", "size": 2205, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/GradientFlow/mastersolution/gradientflow.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "developers/GradientFlow/mastersolution/gradientflow.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "developers/GradientFlow/mastersolution/gradientflow.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0131578947, "max_line_length": 79, "alphanum_fraction": 0.5188208617, "num_tokens": 694, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303236047049, "lm_q2_score": 0.828938806208442, "lm_q1q2_score": 0.6553012627204574}} {"text": "// Copyright Gunter Winkler 2004 - 2009.\r\n// Distributed under the Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt or copy at\r\n// http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n\r\n#include \r\n\r\n#include \r\n#include \r\n\r\n#include \r\n\r\nusing std::cout;\r\nusing std::endl;\r\n\r\n\r\n\r\nnamespace ublas = boost::numeric::ublas;\r\n\r\n\r\nint main(int argc, char * argv[] ) {\r\n\r\n ublas::matrix M (3, 3);\r\n for (std::size_t i=0; i < M.data().size(); ++i) { M.data()[i] = 1+i ; }\r\n\r\n std::cout << \"full M = \" << M << \"\\n\" ;\r\n\r\n ublas::triangular_matrix L;\r\n ublas::triangular_matrix UL;\r\n ublas::triangular_matrix SL;\r\n \r\n L = ublas::triangular_adaptor, ublas::lower> (M);\r\n SL = ublas::triangular_adaptor, ublas::strict_lower> (M); \r\n UL = ublas::triangular_adaptor, ublas::unit_lower> (M); \r\n \r\n std::cout << \"lower L = \" << L << \"\\n\" \r\n << \"strict lower SL = \" << SL << \"\\n\" \r\n << \"unit lower UL = \" << UL << \"\\n\" ;\r\n\r\n ublas::triangular_matrix U;\r\n ublas::triangular_matrix UU;\r\n ublas::triangular_matrix SU;\r\n \r\n U = ublas::triangular_adaptor, ublas::upper> (M);\r\n SU = ublas::triangular_adaptor, ublas::strict_upper> (M); \r\n UU = ublas::triangular_adaptor, ublas::unit_upper> (M); \r\n\r\n std::cout << \"upper U = \" << U << \"\\n\" \r\n << \"strict upper SU = \" << SU << \"\\n\" \r\n << \"unit upper UU = \" << UU << \"\\n\" ;\r\n\r\n std::cout << \"M = L + SU ? \" << ((norm_inf( M - (L + SU) ) == 0.0)?\"ok\":\"failed\") << \"\\n\";\r\n std::cout << \"M = U + SL ? \" << ((norm_inf( M - (U + SL) ) == 0.0)?\"ok\":\"failed\") << \"\\n\";\r\n\r\n}\r\n\r\n\r\n", "meta": {"hexsha": "dbde0e2dbb8b8b6130f96bec59114b9f5c4a94a8", "size": 2035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/ublas/doc/samples/ex_triangular.cpp", "max_stars_repo_name": "zyiacas/boost-doc-zh", "max_stars_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 198.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T05:47:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T04:46:46.000Z", "max_issues_repo_path": "libs/numeric/ublas/doc/samples/ex_triangular.cpp", "max_issues_repo_name": "sdfict/boost-doc-zh", "max_issues_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9.0, "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_forks_repo_path": "libs/numeric/ublas/doc/samples/ex_triangular.cpp", "max_forks_repo_name": "sdfict/boost-doc-zh", "max_forks_repo_head_hexsha": "689e5a3a0a4dbead1a960f7b039e3decda54aa2c", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 139.0, "max_forks_repo_forks_event_min_datetime": "2015-01-15T20:09:31.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-31T15:21:16.000Z", "avg_line_length": 34.4915254237, "max_line_length": 93, "alphanum_fraction": 0.572972973, "num_tokens": 648, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833841649233, "lm_q2_score": 0.8459424373085145, "lm_q1q2_score": 0.6552529558991527}} {"text": "/**\n * @file matode.cc\n * @brief NPDE homework MatODE code\n * @copyright Developed at ETH Zurich\n */\n\n#include \n\nnamespace MatODE {\n\n/* SAM_LISTING_BEGIN_3 */\n\tEigen::MatrixXd eeulstep(const Eigen::MatrixXd &A, const Eigen::MatrixXd &Y0,\n\t double h) {\n\t\treturn Y0 + A * Y0 * h;\n\t}\n/* SAM_LISTING_END_3 */\n\n/* SAM_LISTING_BEGIN_4 */\n\tEigen::MatrixXd ieulstep(const Eigen::MatrixXd &A, const Eigen::MatrixXd &Y0,\n\t double h) {\n\n\t\tEigen::MatrixXd Y1 = (Eigen::MatrixXd::Identity(A.rows(), A.cols()) - h * A).lu().solve(Y0);\n\n\t\treturn Y1;\n\t}\n/* SAM_LISTING_END_4 */\n\n/* SAM_LISTING_BEGIN_5 */\n\tEigen::MatrixXd impstep(const Eigen::MatrixXd &A, const Eigen::MatrixXd &Y0,\n\t double h) {\n\n\t\tEigen::MatrixXd I = Eigen::MatrixXd::Identity(A.rows(), A.cols());\n\n\t\treturn \t(I - 0.5 * h * A).lu().solve((I + 0.5 * h * A) * Y0);\n\t}\n/* SAM_LISTING_END_5 */\n\n} // namespace MatODE\n", "meta": {"hexsha": "53d98561ac9b7c8c36f295072230bc48a9573fc3", "size": 951, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/MatODE/mysolution/matode.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/MatODE/mysolution/matode.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/MatODE/mysolution/matode.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.3846153846, "max_line_length": 94, "alphanum_fraction": 0.5993690852, "num_tokens": 280, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7745833737577158, "lm_q2_score": 0.8459424295406087, "lm_q1q2_score": 0.6552529410783635}} {"text": "#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n\n/*\n Notes:\n Theo's guide\n\n There are three PyKiln folders: \n - PyKiln - Output from each test\n - PyKiln2 - Output from each test\n - Optimize_Heat_Model - Theo's work on optimising the heat transfer coefficients\n\n You need to install assimulo to use it. Do this by downloading the\n source code, replacing all StrictVersion by LooseVersion in\n setup.py, then build/install.\n\n You also need to install PyChemEng. The folders in dropbox are not\n installable (old versions) It seems that PyChemEngLocal is the\n newest version, followed by PyChemEng-Marcus, then PyChemEng. You\n need to install from git@dynamomd.org:PyChemEng.\n\n You also need pyopt!\n\n Each PyKiln folder has the following structure:\n - Kiln_Classes.py - All pilot kiln trial data.\n - KilnSolverXXXX.py - The actual workhorse for fitting data, all copies of KilnSolverXXX.py\n - Kiln_Plotter.py - Plotting of data files from KilnSolver\n \n run PyKiln2/KilnSolverAssimulo.py, then run Kiln_Plotter.py\n*/\nnamespace simcem {\n /*! \\brief Heat transfer correlations and expressions. */\n namespace HT {\n /*! \\brief Conductive heat transfer. */\n namespace conduction {\n /*! \\brief Conduction resistance for a cylindrical shell of unit length.*/\n double R_cyl(const double Rout, const double Rin, const double k) {\n\treturn std::log(Rout / Rin) / (2 * Database::pi * k);\n }\n\n /*! \\brief The Maxwell model for combining thermal conductivities. \n\t\n\tThis requires that one phase is identified as \"continuous\" and\n\tanother phase is \"discrete\". Then the volume fraction of\n\tdiscontinuous phase is requred.\n */\n double maxwell(const double kcont, const double kdisc, const double discfrac) {\n\treturn kcont * (2*kcont + kdisc + 2 * discfrac * (kdisc - kcont)) / (2 * kcont + kdisc + discfrac * (kcont - kdisc));\n }\n }\n \n /*! \\brief Natural convection heat transfer. */\n namespace natConv {\n /*! \\brief The overall convective heat transfer from smooth\n\tcircular cylinders.\n\t\n\tTaken from Heat Transfer, J.P Holman pg 334, VT Morgan.\n\n\tA big collection of available expressions is in Boetcher_2014. \n */\n double Nu_horiz_cyl(const double Gr, const double Pr) {\n\tconst double Ra = Gr * Pr;\n\n\t//A wide range expression (Eq.7-36 in Holman, Eq 5-35 in Perrys)\n\t//\tif ((1e-5 <= Ra) && (Ra <= 1e12))\n\t//\t return std::pow(0.60 + 0.387*std::pow(Ra/std::pow(1+std::pow(0.559/Pr, 9.0/16), 16/9.0), 1.0/6), 2);\n\n\t//The table from Holman favouring the \"preferred\" expressions where possible\n\tif (Ra < 1e-10)\n\t return 0.4;\n\tif (Ra < 1e-2)\n\t return 0.675 * std::pow(Ra, 0.058);\n\tif (Ra < 1e2)\n\t return 1.02 * std::pow(Ra, 0.148);\n\tif (Ra < 1e4)\n\t return 0.850 * std::pow(Ra, 0.188);\n\tif (Ra < 1e7)\n\t return 0.480 * std::pow(Ra, 1.0/4);\n\tif (Ra < 1e12)\n\t return 0.125 * std::cbrt(Ra);\n \t\n\tstator_throw() << \"Ra=\" << Ra << \" over upper range.\";\n }\n }\n\n /*!\\brief Radiative heat transfer. */\n namespace rad {\n\n /*! \\brief Simple radiative heat transfer coefficient.\n\t\n\tThe Steffan-Boltzmann coefficient \n */\n double h_rad_simple(const double T1, const double T2, const double emissivity,\n\t\t\t const double steffanBoltzmannConstant = 5.670367e-8) {\n\treturn emissivity *\n\t steffanBoltzmannConstant\n\t * (T1 * T1 + T2 * T2) * (T1 + T2);\n }\n\n \n /*! \\brief Hottel calculation for the emissivity of gases\n\tcontaining CO2 and H2O.\n\t\n\tThis is taken from Perry's Chemical Engineering Handbook,\n\tchapter 5. This assumes that the primary radiative\n\tproperties of the gas are derived from the H2O and CO2\n\tcomponents only. It also uses bilinear\n\tinterpolation/extrapolation.\n\n\tErrors up to 20% are expected. The temperature argument is\n\tonly provided for absorptivity calculations (which should be\n\tcarried out via the Hottel_absorptivity function), and if it\n\tis left at the default of 0 it is taken from the gas phase\n\tautomatically.\n */\n double Hottel_emissivity(const simcem::Model& gas, const double pathLength, double Tgas = 0) {\n\tif (Tgas == 0) Tgas = gas.T();\n\t//Fraction of H2O versus CO2+H2O\n\tconst double pw_frac = gas[\"H2O\"] / (gas[\"H2O\"]+gas[\"CO2\"]);\n\n\t//Partial pressure of H2O and CO2 in atms\n\tconst double p = (gas[\"H2O\"]+gas[\"CO2\"]) / gas.N() * gas.p() / 1.01325e5;\n\tconst double pL = p * pathLength;\n\tif (pL > 10)\n\t stator_throw() << \"pL out of range \" << pL;\n\n\tif (pL < 0.005)\n\t return 0; //This is an approximation!\n\t //stator_throw() << \"pL out of range \" << pL;\n\t\n\tconst double logpL = std::log10(pL);\n\n\t//Perform bilinear interpolation where x is T, and y is pw_frac.\n\tconst double x_range[] = {1000, 1500, 2000};\n\tconst double y_range[] = {0, 1.0/3.0, 1.0/2.0, 2.0/3.0, 3.0/4.0, 1.0};\n\n\t//Calculation of the indices of the data points are around the sample point\n\tsize_t x_idx = 0;\n\tif (Tgas > x_range[1]) x_idx = 1;\n\t\n\tsize_t y_idx = 0;\n\tif (pw_frac > y_range[1]) y_idx = 1;\n\tif (pw_frac > y_range[2]) y_idx = 2;\n\tif (pw_frac > y_range[3]) y_idx = 3;\n\tif (pw_frac > y_range[4]) y_idx = 4;\n\t\n\tstatic const double coeffs[] = { 2.2661, 0.1742, -0.0390, 0.0040,\n\t\t\t\t\t 2.3954, 0.2203, -0.0433, 0.00562,\n\t\t\t\t\t 2.4104, 0.2602, -0.0651, -0.00155,\n\t\t\t\t\t 2.5754, 0.2792, -0.0648, 0.0017,\n\t\t\t\t\t 2.6451, 0.3418, -0.0685, -0.0043,\n\t\t\t\t\t 2.6504, 0.4279, -0.0674, -0.0120,\n\t\t\t\t\t 2.6090, 0.2799, -0.0745, -0.0006,\n\t\t\t\t\t 2.6862, 0.3450, -0.0816, -0.0039,\n\t\t\t\t\t 2.7029, 0.4440, -0.0859, -0.0135,\n\t\t\t\t\t 2.6367, 0.2723, -0.0804, 0.0030,\n\t\t\t\t\t 2.7178, 0.3386, -0.0990, -0.0030,\n\t\t\t\t\t 2.7482, 0.4464, -0.1086, -0.0139,\n\t\t\t\t\t 2.6432, 0.2715, -0.0816, 0.0052,\n\t\t\t\t\t 2.7257, 0.3355, -0.0981, 0.0045,\n\t\t\t\t\t 2.7592, 0.4372, -0.1122, -0.0065,\n\t\t\t\t\t 2.5995, 0.3015, -0.0961, 0.0119,\n\t\t\t\t\t 2.7083, 0.3969, -0.1309, 0.00123,\n\t\t\t\t\t 2.7709, 0.5099, -0.1646, -0.0165};\n\n\t//A routine to calculate the offset for the coefficients\n\tauto C = [&](size_t x_idx, size_t y_idx) { return coeffs + 4 * (x_idx + 3 * y_idx); };\n\n\t//A calculation of the function at the index point\n\tauto f = [&](const double* C) { return C[0] + logpL * (C[1] + logpL * (C[2] + logpL * C[3])); };\n\t\n\tconst double x = (Tgas - x_range[x_idx]) / (x_range[x_idx+1] - x_range[x_idx]);\n\tconst double y = (pw_frac - y_range[y_idx]) / (y_range[y_idx+1] - y_range[y_idx]);\n\n\tdouble log10eT = \n\t f(C(x_idx, y_idx)) * (1 - x) * (1 - y)\n\t + f(C(x_idx + 1, y_idx)) * x * (1 - y)\n\t + f(C(x_idx, y_idx + 1)) * (1 - x) * y\n\t + f(C(x_idx + 1, y_idx + 1)) * x * y;\n\t\n\treturn std::pow(10, log10eT) / Tgas;\n }\n\n /* \\brief Hottel calculation for the absorptivity of gases\n\t containing CO2 and H2O.\n\n\t This assumes ideal gas behaviour!\n */\n \n double Hottel_absorptivity(simcem::Model& gas, double pathLength, double Tsurface) {\n\t//Adjust pathlength, such that pL is scaled (this is a\n\t//horrible hack to adjust the pressure in the emissivity\n\t//calculations according to the ideal gas law!)\n\tconst double L = pathLength * Tsurface / gas.T();\n\tconst double e = Hottel_emissivity(gas, L, Tsurface);\n\treturn e * std::sqrt(gas.T() / Tsurface);\n }\n\n /*! \\brief Two-body radiation problem in third region.\n\t\n\t\\image html twobodygas_radiation_network.svg\n\t\n\tWe assume all resistances and the voltages \\f$V_a\\f$, \\f$V_b\\f$, and \\f$V_c\\f$ are known.\n\tThe total currents at the nodes \\f$\\alpha\\f$ and \\f$\\beta\\f$ must sum to zero, thus:\n\t\n\t\\f[\n\t(V_a - V_\\alpha)R^{-1}_1 + (V_\\beta - V_\\alpha)R^{-1}_2 + (V_c - V_\\alpha)R^{-1}_3 = 0\n\t\\f]\n\t\\f[\n\t(V_b - V_\\beta)R^{-1}_4 + (V_\\alpha - V_\\beta)R^{-1}_2 + (V_c - V_\\beta)R^{-1}_5 = 0\n\t\\f]\n\t\n\tSolving for \\f$V_\\beta\\f$:\n\t\n\t\\f[\n\tV_\\beta = \\frac{m_2\\,c_2+c_1}{1-m_1\\,m_2}\n\t\\f]\n\t\\f[\n\tV_\\alpha = m_2\\, V_\\beta + c_2\n\t\\f]\n\t\n\twhere:\n\t\\f[\n\tm_1 = \\frac{1}{R_2^{-1}}\\left(R_1^{-1} + R_2^{-1} + R_3^{-1}\\right)\n\t\\f]\n\t\\f[\n\tc_1 = -V_a\\frac{R_1^{-1}}{R_2^{-1}} -V_c\\frac{R_3^{-1}}{R_2^{-1}}\n\t\\f]\n\t\n\t\\f[\n\tm_2 = \\frac{1}{R_2^{-1}}\\left(R_4^{-1} + R_2^{-1} + R_5^{-1}\\right)\n\t\\f]\n\t\\f[\n\tc_2 = -V_b\\frac{R_4^{-1}}{R_2^{-1}} -V_c\\frac{R_5^{-1}}{R_2^{-1}}\n\t\\f]\n\n\tThe currents are returned as follows:\n\t\\f[\n\tI_a = R_1^{-1}(V_\\alpha-V_a) \\qquad I_b = R_4^{-1}(V_\\beta-V_b) \\qquad I_c = R_3^{-1}(V_\\alpha-V_c) + R_5^{-1}(V_\\beta-V_c)\n\t\\f]\n\t\n\tAs a test, we should have \\f$I_a+I_b+I_c=0\\f$.\n */\n std::array twobodygas_network(const std::array V, const std::array Rinv) {\n\tconst double m1 = (Rinv[0]+Rinv[1]+Rinv[2]) / Rinv[1];\n\tconst double m2 = (Rinv[3]+Rinv[1]+Rinv[4]) / Rinv[1];\n\tconst double c1 = -V[0]*Rinv[0]/Rinv[1] - V[2] * Rinv[2] / Rinv[1];\n\tconst double c2 = -V[1]*Rinv[3]/Rinv[1] - V[2] * Rinv[4] / Rinv[1];\n\tconst double Vbeta = (m1 * c2 + c1) / (1 - m1 * m2);\n\tconst double Valpha = m2 * Vbeta + c2;\n\n\treturn std::array{\n\t {Rinv[0] * (Valpha - V[0]),\n\t Rinv[3] * (Vbeta - V[1]),\n\t Rinv[2] * (Valpha - V[2]) + Rinv[4] * (Vbeta - V[2])\n\t }\n\t};\n }\n }\n\n /*! \\brief Specialised expressions for heat transfer in kilns. */\n namespace kiln {\n /*! \\brief Nusselt number correlation for heat transfer between\n\ta cylindrical wall and a granular bed of material which\n\tcovers it.\n\n\tThis is taken from Li_etal_2005. The Nusselt number uses the\n\tgas thermal conductivity and particle diameter as\n\tnormalisation factors.\n\n\t\\param Peclet The Peclet number for the bed (see Pe_bed_wall_Li_etal_2005).\n\t\\param chi A fitting parameter, which appears to be around 0.1, but is in the range 0.096-0.198.\n */\n double Nu_bed_wall_Li_etal_2005(const double Peclet, const double chi = 0.1) {\n\treturn 1 / (chi + 0.5 * std::sqrt(Database::pi / Peclet));\n }\n\n \n /*! \\brief Peclet number for Heat transfer between a cylindrical\n\twall and a granular bed of material which covers it.\n\n\tThis is taken from Li_etal_2005.\n\n\t\\param dp Particle diameter \\f$d_p\\f$.\n\t\\param kg Gas thermal conductivity \\f$k_g\\f$.\n\t\\param kb Solid bed thermal conductivity \\f$k_b\\f$.\n\t\\param vol_Cp Solid bed volumetric heat capacity, \\f$\\rho_b\\,c_{p,b}\\f$.\n\t\\param centralangle Central angle of bed, \\f$\\theta\\f$.\n\t\\param angularvel Angular velocity of cylinder, \\f$\\omega\\f$.\n */\n double Pe_bed_wall_Li_etal_2005(const double dp, const double kg, const double kb,\n\t\t\t\t const double vol_Cp, const double centralangle, const double angularvel ) {\n\treturn std::pow(dp/kg, 2) * vol_Cp * kb * angularvel / centralangle;\n }\n\n /*! \\brief Heat transfer coefficient between a wall and a\n\tgranular bed of material which covers it.\n\n\tThis is taken from Li_etal_2005.\n\n\t\\param dp Particle diameter \\f$d_p\\f$.\n\t\\param kg Gas thermal conductivity \\f$k_g\\f$.\n\t\\param kb Solid bed thermal conductivity \\f$k_b\\f$.\n\t\\param vol_Cp Solid bed volumetric heat capacity, \\f$\\rho_b\\,c_{p,b}\\f$.\n\t\\param centralangle Central angle of bed, \\f$\\theta\\f$.\n\t\\param angularvel Angular velocity of cylinder, \\f$\\omega\\f$.\n\t\\param chi A fitting parameter, which appears to be around 0.1, but is in the range 0.096-0.198.\n */\n double h_bed_wall_Li_etal_2005(const double dp, const double kg, const double kb,\n\t\t\t\t const double vol_Cp, const double centralangle, const double angularvel,\n\t\t\t\t const double chi = 0.1) {\n\tconst double Pe = Pe_bed_wall_Li_etal_2005(dp, kg, kb, vol_Cp, centralangle, angularvel);\n\tconst double Nu = Nu_bed_wall_Li_etal_2005(Pe, chi);\n\treturn Nu * kg / dp;\n }\n\n /*! \\brief Gas-wall Nusselt number for rotary kilns.\n\t\n\t\\f[\n\t\\text{Nu}_{g-ew} = 1.54\\,\\text{Re}_g^{0.575}\\,\\text{Re}_\\omega^{-0.292}\n\t\\f]\n\t\n\tThis is taken from Eq.9 of Li_etal_2005. This requires\n\t\\f$1600<\\text{Re}_g<7800\\f$ and \\f$20<\\text{Re}_\\omega<800\\f$.\n\t\n\t\\param Re_g Reynolds number for the gas, \\f$\\text{Re}_g\\f$, using the normal hydraulic diameter.\n\t\\param Re_w Angular rotation Reynolds number, \\f$\\text{Re}_\\omega\\f$.\n */\n double Nu_gas_wall_Li_etal_2005(const double Re_g, const double Re_w) {\n#ifndef NDEBUG\n\t//if (!((1600 < Re_g) && (Re_g < 7800)))\n\t//stator_throw() << \"Out of range for Re_g \" << Re_g;\n\n\t//if (!((20 < Re_w) && (Re_w < 800)))\n\t//stator_throw() << \"Out of range for Re_w \" << Re_w;\n#endif\n\n\treturn 1.54 * std::pow(Re_g, 0.575) * std::pow(Re_w, -0.292);\n }\n\n /*! \\brief Gas-bed Nusselt number for rotary kilns.\n\n\t\\f[\n\t\\text{Nu}_{g-eb} = 0.46\\,\\text{Re}_g^{0.535}\\,\\text{Re}_\\omega^{0.104}\\,\\eta^{-0.341}\n\t\\f]\n\n\tThis is taken from Eq.8 of Li_etal_2005. This requires\n\t\\f$1600<\\text{Re}_g<7800\\f$ and \\f$20<\\text{Re}_\\omega<800\\f$.\n\t\n\t\\param Re_g Reynolds number for the gas, \\f$\\text{Re}_g\\f$, using the normal hydraulic diameter.\n\t\\param Re_w Angular rotation Reynolds number, \\f$\\text{Re}_\\omega\\f$.\n\t\\param bed_frac Fraction of kiln filled with the bed, \\f$\\eta\\f$.\n */\n double Nu_gas_bed_Li_etal_2005(const double Re_g, const double Re_w, const double bed_frac) {\n#ifndef NDEBUG\n//\tif (!((1600 < Re_g) && (Re_g < 7800)))\n//\t stator_throw() << \"Out of range for Re_g \" << Re_g;\n//\n//\tif (!((20 < Re_w) && (Re_w < 800)))\n//\t stator_throw() << \"Out of range for Re_w \" << Re_w;\n#endif\n\treturn 0.46 * std::pow(Re_g, 0.535) * std::pow(Re_w, 0.104) * std::pow(bed_frac, -0.341);\n }\n\n \n /*! \\brief Correlation for mean beam length in a rotary kiln.\n\t\n\tThis is taken from Eq.50 of Gorog_etal_1981.\n\n\t\\param R Kiln radius.\n\t\\param h Bed height (at its deepest/central point);\n */\n double pathLength(const double R, const double h) {\n\treturn 2 * R * 0.95 * (1 - h / (2 * R));\n }\n }\n }\n\n \n \n namespace kiln {\n struct Slice {\n Slice(simcem::shared_ptr gas,\n\t simcem::shared_ptr solid,\n\t double Z = 0\n\t ):\n\t_Z(Z)\n {\n\t//Here we copy the phases to ensure the slice has a unique copy\n\t_gas = simcem::shared_ptr(new simcem::ModelIdealGasTp(*gas));\n\t_solid = simcem::shared_ptr(new simcem::ModelIncompressible(*solid));\n\n\t_T_ext_shell = 0.75*298.15 + 0.25 * _gas->T();\n\t_T_wall = 0.25*298.15 + 0.75 * _gas->T();\n }\n\n Slice(const Slice& s):\n\t_gas_k(s._gas_k),\n\t_gas_visc(s._gas_visc),\n\t_gas_density(s._gas_density),\n\t_gas_vel(s._gas_vel),\n\t_solid_k(s._solid_k),\n\t_solid_Cp(s._solid_Cp),\n\t_T_ext_shell(s._T_ext_shell),\n\t_T_wall(s._T_wall),\n\t_Z(s._Z)\n {\n\t_gas = simcem::shared_ptr(new simcem::ModelIdealGasTp(*s._gas));\n\t_solid = simcem::shared_ptr(new simcem::ModelIncompressible(*s._solid));\n }\n\n Slice(const simcem::Components solid,\n\t const double volAirFlow,\n\t const double volGasFlow,\n\t const double volO2Flow,\n\t const double volSO2Flow,\n\t const double Tsolid,\n\t const double Tgas,\n\t const double Z0,\n\t const simcem::shared_ptr db):\n\t_Z(Z0)\n {\n\tconst simcem::ModelIdealGasTp air(db, Database::getDryAir(), 298.15, 1.01325e5);\n\tconst simcem::Components inletair = Database::getDryAir() * ((volAirFlow) / air.V());\n \n\tconst simcem::ModelIdealGasTp oxy(db, Components({{\"O2\",1}}), 298.15, 1.01325e5);\n\tconst simcem::Components inletoxy = Components({{\"O2\",1}}) * ((volO2Flow) / oxy.V());\n\t\n\tconst simcem::ModelIdealGasTp so2(db, Components({{\"SO2\",1}}), 298.15, 1.01325e5);\n\tconst simcem::Components inletso2 = Components({{\"SO2\",1}}) * ((volSO2Flow) / oxy.V());\n\n\tconst simcem::ModelIdealGasTp fuel(db, {{\"CH4\",100.0}}, 298.15, 1.01325e5);\n\tconst simcem::Components inletfuel = Components(fuel) * (volGasFlow / fuel.V());\n\n\tconst simcem::Components combustion_outputs({{\"H2O\",0}, {\"CO2\", 0}});\n\n\t_gas = simcem::shared_ptr(new simcem::ModelIdealGasTp(db, inletfuel + inletair + inletoxy + inletso2 + combustion_outputs, 298.15, 1.01325e5));\n\tsimcem::System sys(simcem::Objective_t::p, simcem::Objective_t::H, true);\n\tsys.push_back(_gas);\n\n\ttry {\n\t sys.equilibrate();\n\t} catch (std::exception& e) {\n\t std::cout << \"Failed to equilibrate initial gas \" << _gas->str() << std::endl;\n\t}\n\n\t_solid = simcem::shared_ptr(new simcem::ModelIncompressible(db, solid, 298.15, 1.01325e5, \"solid\"));\n\n\t//Value of Tgas=0 means retain the adiabatic temperature\n\tif (Tgas != 0)\n\t _gas->set(simcem::Objective_t::T, Tgas, simcem::Objective_t::p);\n\t\n\t_solid->set(simcem::Objective_t::T, Tsolid, simcem::Objective_t::p);\n \n\t_T_ext_shell = 0.75*298.15 + 0.25 * _gas->T();\n\t_T_wall = 0.25*298.15 + 0.75 * _gas->T();\n }\n \n simcem::shared_ptr _gas;\n simcem::shared_ptr _solid;\n\n /*! \\brief Precompute a few frequently used values for the slice. */\n void compute_properties(const double gas_area, const double solid_k) {\n\t//Gas properties\n\tstd::tie(_gas_visc, _gas_k) = simcem::trans::NASA_transport(_gas);\n\t_gas_density = _gas->M() / _gas->V();\n\n\t//Solid properties\n\t_solid_Cp = _solid->Cp() / _solid->M();\n\t_gas_vel = _gas->V() / gas_area;\n\t_solid_k = solid_k;\n }\n\t\n //Cached values of the computed properties of the phases\n double _gas_k;\n double _gas_visc;\n double _gas_density;\n double _gas_vel;\n double _solid_k;\n double _solid_Cp;\n double _T_ext_shell;\n double _T_wall;\n double _Z;\n };\n \n /*! \\brief Abstract base class for models describing the solid bed dynamics.*/\n class BedModel {\n public:\n virtual double bedHeight(const Slice& slice) const = 0;\n };\n\n class ConstantHeightBed : public BedModel {\n public:\n ConstantHeightBed(double height):\n\t_height(height)\n {}\n\n virtual double bedHeight(const Slice& slice) const { return _height; }\n\n static simcem::shared_ptr fromFillingFraction(double frac, double kiln_radius) {\n\tconst double pi = boost::math::constants::pi();\n\t\n\tstd::pair central_angle_limits\n\t = boost::math::tools::bisect([pi, frac](double x) {return x - std::sin(x) - 2 * pi * frac;},\n\t\t\t\t 0.0, 2 * pi,\n\t\t\t\t boost::math::tools::eps_tolerance(10));\n\n\tdouble central_angle = (central_angle_limits.first + central_angle_limits.second) / 2;\n\n\treturn simcem::shared_ptr\n\t (new ConstantHeightBed(kiln_radius * (1.0 - std::cos(central_angle/2))));\n }\n \n protected:\n double _height;\n };\n\n\n /*! \\brief A process model for a rotary kiln.\n \n \\image html kiln_balance.svg\n \n Performing a differential balance of mass over a phase \\f$\\alpha\\f$:\n \\f[\n \\Delta z\\,A_\\alpha\\left(\\rho_\\alpha(z,\\,t+\\Delta t)-\\rho_\\alpha(z,\\,t)\\right)= \\Delta t\\,A_\\alpha\\left(\\dot{m}_\\alpha\\left(z\\right)-\\dot{m}_\\alpha\\left(z+\\Delta z\\right)\\right) + \\Delta t\\,\\Delta z\\,\\dot{m}_{\\beta\\to\\alpha}\n \\f]\n\n where \\f$\\dot{m}_{\\beta\\to\\alpha}\\f$ is the rate of mass\n transfer between the two phases per unit length of kiln and\n conservation of mass requires\n \\f$\\dot{m}_{\\beta\\to\\alpha}=-\\dot{m}_{\\alpha\\to\\beta}\\f$. Dividing\n by \\f$\\Delta t\\,\\Delta z\\f$ and taking the limit as they go to\n zero:\n\n \\f[\n \\frac{{\\rm d}\\,A_\\alpha\\,\\rho_\\alpha}{{\\rm d}t}= -\\frac{{\\rm d} A_\\alpha\\,\\dot{m}_\\alpha}{{\\rm d}z} + \\dot{m}_{\\beta\\to\\alpha}\n \\f]\n\n For enthalpy:\n \\f[\n \\Delta z\\,A_\\alpha\\left(\\rho_\\alpha(z,\\,t+\\Delta t)\\,h_\\alpha(z,\\,t+\\Delta t)-\\rho_\\alpha(z,\\,t)\\,h_\\alpha(z,\\,t)\\right)= \\Delta t\\,A_\\alpha\\left(\\dot{m}_\\alpha\\left(z\\right)\\,h_\\alpha(z,\\,t)-\\dot{m}_\\alpha\\left(z+\\Delta z\\right)\\,h_\\alpha(z+\\Delta z,\\,t)\\right) + \\Delta t\\,\\Delta z\\,Q_{\\to\\alpha}\n \\f]\n where \\f$Q_{\\to\\alpha}\\f$ is the heat transfer rate to phase \\f$\\alpha\\f$ per unit length of kiln. Again, a differential form results:\n \\f[\n \\frac{{\\rm d}\\,A_\\alpha\\,\\rho_\\alpha\\,h_\\alpha}{{\\rm d}t}= -\\frac{{\\rm d}\\,A_\\alpha\\,\\dot{m}_\\alpha\\,h_\\alpha}{{\\rm d}z} + Q_{\\to\\alpha}\n\n \n \\f]\n */\n class Kiln {\n public:\n struct Layer {\n\tstd::string _material;\n\tdouble _thickness;\n\tsym::Expr _k;\n };\n \n Kiln(double RPM, double innerRadius, double length,\n\t double particle_diam,\n\t double shell_emissivity,\n\t double bed_emissivity,\n\t double wall_emissivity,\n\t double solid_density,\n\t double bed_void_frac,\n\t sym::Expr solid_k,\n\t simcem::shared_ptr db\n\t ):\n\t_RPM(RPM), _innerRadius(innerRadius), _length(length),\n\t_particle_diam(particle_diam),\n\t_shell_emissivity(shell_emissivity),\n\t_bed_emissivity(bed_emissivity),\n\t_wall_emissivity(wall_emissivity),\n\t_solid_density(solid_density),\n\t_bed_void_frac(bed_void_frac),\n\t_solid_k(solid_k),\n\t_ambient(new simcem::ModelIdealGasTp(db, Database::getDryAir(), 298.15, 1.01325e5))\n {}\n\n void setFixedHeightBedModel(const double solidLoading) {\n\t_bedModel = simcem::kiln::ConstantHeightBed::fromFillingFraction(solidLoading, _innerRadius);\n }\n \n void add_layer(std::string material, double thickness, sym::Expr k) {\n\t_layers.push_back(Layer{material, thickness, k});\n }\n \n double solid_k(const double T) {\n\treturn sym::fast_sub(_solid_k, sym::Var>() = T);\n }\n\n double innerRadius() const { return _innerRadius; }\n \n double outerRadius() const {\n\treturn _innerRadius + std::accumulate(_layers.begin(), _layers.end(), 0.0, [](double a, Layer b){ return a + b._thickness; });\n }\n\n /*! \\brief Conductive heat transfer resistance in the kiln wall. */\n double R_wall_shell(const Slice& slice) const {\n\tdouble Ri = _innerRadius;\n\tdouble Rtotal = 0;\n\tfor (const auto& layer : _layers) {\n\t const double Ro = Ri + layer._thickness;\n\t const double k = sym::fast_sub(layer._k, sym::Var>() = slice._T_wall);\n\t Rtotal += std::log(Ro / Ri) / (2 * simcem::Database::pi * k);\n\t Ri = Ro;\n\t};\n\n\treturn Rtotal;\n }\n \n const BedModel& bedModel() const { return *_bedModel; }\n\n const std::vector& slices() const { return _slices; }\n std::vector& slices() { return _slices; }\n \n /*! \\brief The chord length of the bed.\n\t\n\tThe chord length can be calculated in two ways:\n\t\\f[\n\tL_{chord}= 2\\,R\\,\\sin(\\theta/2) = 2\\sqrt{h(2*R-h)}\n\t\\f]\n\n\tThe latter is used here.\n */\n double chordLength(const Slice& slice) const {\n\tconst double h = _bedModel->bedHeight(slice);\n\treturn 2 * std::sqrt(h * (2 * _innerRadius - h));\n }\n\n /*! \\brief The central angle is the radians of the cylinder\n\tcovered by the bed.\n */\n double centralAngle(const Slice& slice) const {\n\treturn 2 * std::asin(chordLength(slice) / 2 / _innerRadius);\n }\n\n double bedArea(const Slice& slice) const {\n\tconst double cAngle = centralAngle(slice);\n\treturn 0.5 * _innerRadius * _innerRadius * (cAngle - std::sin(cAngle));\n }\n\n double kilnArea() const {\n\treturn simcem::Database::pi * _innerRadius * _innerRadius;\n }\n\n double gasArea(const Slice& slice) const {\n\treturn kilnArea() - bedArea(slice);\n }\n\n double gasPerimeter(const Slice& slice) const {\n\treturn (2 * simcem::Database::pi - centralAngle(slice)) * _innerRadius + chordLength(slice);\n }\n \n double hydraulicDiameter(const Slice& slice) const {\n\treturn 4 * gasArea(slice) / gasPerimeter(slice);\n }\n\n double exposedWallPerimeter(const Slice& slice) const {\n\tconst double pi = boost::math::constants::pi();\n\tconst double cAngle = centralAngle(slice);\n\treturn (2 * pi - cAngle) * _innerRadius;\n }\n\n double coveredWallPerimeter(const Slice& slice) const {\n\tconst double cAngle = centralAngle(slice);\n\treturn cAngle * _innerRadius;\n }\n \n double angular_vel() const {\n\treturn _RPM / 60.0 * 2 * simcem::Database::pi;\n }\n \n /*! \\brief Heat transfer coefficient between the bed and the wall it covers, \\f$h_{cw-s}\\f$.\n */\n double h_bed_wall(const Slice& slice) const {\n\tconst double Cp_per_vol = slice._solid_Cp * _solid_density;\n\tconst double kb = HT::conduction::maxwell(slice._gas_k, slice._solid_k, _bed_void_frac);\n\treturn simcem::HT::kiln::h_bed_wall_Li_etal_2005(_particle_diam, slice._gas_k, kb,\n\t\t\t\t\t\t\t Cp_per_vol, centralAngle(slice), angular_vel());\n }\n\n /*! \\brief \\f$Q_{w\\to s}^{cd}\\f$ */\n double Q_wall_bed_cd(const Slice& slice) const {\n\treturn h_bed_wall(slice) * coveredWallPerimeter(slice) * (slice._T_wall - slice._solid->T());\n }\n \n /*! \\brief Free gas Reynolds number, \\f$\\text{Re}_g\\f$.\n\t\n\tThis is the Reynolds number for the gas above the solid bed.\n\t\n\t\\f[\n\t\\text{Re}_g = \\frac{\\rho_g\\,v_g\\,D_e}{\\mu_g}\n\t\\f]\n\n\twhere \\f$D_e\\f$ is the hydraulic diameter.\n */\n double Re_g(const Slice& slice) const {\n\tconst double De = hydraulicDiameter(slice);\n\treturn slice._gas_density * slice._gas_vel * De / slice._gas_visc;\n }\n \n /*! \\brief Rotational gas Reynolds number, \\f$\\text{Re}_\\omega\\f$.\n\t\n\tThis is the Reynolds number for the gas within the bed itself.\n\t\n\t\\f[\n\t\\text{Re}_\\omega = \\frac{\\rho_g\\,\\omega\\,D_e^2}{\\mu_g}\n\t\\f]\n\n\twhere \\f$D_e\\f$ is the hydraulic diameter. An example of this\n\tdefinition is given just below Eq.9 in Li_etal_2005.\n */\n double Re_w(const Slice& slice) const {\n\tconst double De = hydraulicDiameter(slice);\n\treturn std::pow(De, 2) * angular_vel() * slice._gas_density / slice._gas_visc;\n }\n \n /*! \\brief Heat transfer coefficient between the bed and the gas. \n */\n double h_gas_bed(const Slice& slice) const {\n\tconst double bed_frac = bedArea(slice) / kilnArea();\n\tconst double Nu = simcem::HT::kiln::Nu_gas_bed_Li_etal_2005(Re_g(slice), Re_w(slice), bed_frac);\n\tconst double De = hydraulicDiameter(slice);\n\treturn Nu * slice._gas_k / De;\n }\n\n /*! \\brief \\f$Q_{g\\to s}^{cv}\\f$. */\n double Q_gas_bed_cv(const Slice& slice) const {\n\treturn h_gas_bed(slice) * chordLength(slice) * (slice._gas->T() - slice._solid->T());\n }\n \n /*! \\brief Heat transfer coefficient between the bed and the gas. \n */\n double h_gas_wall(const Slice& slice) const {\n\tconst double Nu = simcem::HT::kiln::Nu_gas_wall_Li_etal_2005(Re_g(slice), Re_w(slice));\n\tconst double De = hydraulicDiameter(slice);\n\treturn Nu * slice._gas_k / De;\n }\n\n /*! \\brief \\f$Q_{g\\to s}^{cv}\\f$. */\n double Q_gas_wall_cv(const Slice& slice) const {\n\treturn h_gas_wall(slice) * exposedWallPerimeter(slice) * (slice._gas->T() - slice._T_wall);\n }\n \n double h_ext_amb_conv(const Slice& slice) const {\n\tdouble amb_visc, amb_k;\n\tstd::tie(amb_visc, amb_k) = simcem::trans::NASA_transport(_ambient);\n\tconst double amb_dens = _ambient->M() / _ambient->V();\n\t\n\tconst double outerDiam = 2 * outerRadius();\n\tconst double Pr = (_ambient->Cp() / _ambient->M()) * amb_visc / amb_k;\n\tconst double Tf = (_ambient->T() + slice._T_ext_shell) / 2.0;\n\tconst double Gr = simcem::Database::g * std::pow(amb_dens, 2) * (1/Tf) * std::abs(slice._T_ext_shell - _ambient->T()) * std::pow(outerDiam, 3) / std::pow(amb_visc, 2);\n\t \n\tconst double Nu = simcem::HT::natConv::Nu_horiz_cyl(Gr, Pr);\n\n\treturn Nu * amb_k / outerDiam;\n }\n\n /*! \\brief \\f$Q_{g\\to s}^{cv}\\f$. */\n double R_sh_ext_cv(const Slice& slice) const {\n\treturn 1.0 / (h_ext_amb_conv(slice) * outerRadius() * 2 * simcem::Database::pi);\n }\n\n \n /*! \\brief External radiative heat transfer coefficient. */\n double h_ext_amb_rad(const Slice& slice) const {\n\treturn simcem::HT::rad::h_rad_simple(_ambient->T(), slice._T_ext_shell,\n\t\t\t\t\t _shell_emissivity,\n\t\t\t\t\t _ambient->db()->steffanBoltzmannConstant);\n }\n \n double R_sh_ext_rd(const Slice& slice) const {\n\treturn 1.0 / (h_ext_amb_rad(slice) * outerRadius() * 2 * simcem::Database::pi);\n }\n\n double Q_w_ext(const Slice& slice) const {\n\tconst double Rtotal = R_wall_shell(slice) + 1.0 / (1.0 / R_sh_ext_rd(slice) + 1.0 / R_sh_ext_cv(slice));\n\n\treturn (slice._T_wall - _ambient->T()) / Rtotal;\n }\n\n double Q_w_sh(const Slice& slice) const {\n\treturn (slice._T_wall - slice._T_ext_shell) / R_wall_shell(slice);\n }\n \n /*! \\brief One-zone radiative network for a kiln slice.\n\n\tThe wall and bed are considered as two thermally homogeneous\n\tgray bodies which exchange radiative heat through a gray gas\n\t(gray implying that we are ignoring the frequency aspects of\n\tradiation). \n\n\tThe same network as Fig.6 in Li_etal_2005, but this is also\n\tFig.8-39 in JP Holman's Heat Transfer, 10th Ed.\n\t\n\t\\image html kiln_radiation_network.svg\n\t\n\tThe electrical resistance analogy is then used. The junctions\n\t(circles) are annotated with their \"potentials\"\n\t(\\f$E_{bed},\\,J_b,\\,J_w,\\,E_{gas}\\f$) whereas the other\n\tannotations are resistances. As the two nodes \\f$J_b\\f$ and\n\t\\f$J_w\\f$ are merely \"virtual\" junctions they cannot\n\taccumulate heat/current, so their heat/current must sum to\n\tzero:\n\n\t\\f[\n\t\\frac{E_{bed}-J_b}{\\left(1-\\varepsilon_b\\right)\\varepsilon_b^{-1}\\,A_b^{-1}} + \\frac{J_w-J_b}{\\tau_g^{-1}\\,F_{bw}^{-1}\\,A_b^{-1}} + \\frac{E_{gas}-J_b}{\\varepsilon_g^{-1}\\,F_{bg}^{-1}\\,A_b^{-1}}=0\n\t\\f]\\f[\n\t\\frac{E_{wall}-J_w}{\\left(1-\\varepsilon_w\\right)\\varepsilon_w^{-1}\\,A_w^{-1}} + \\frac{J_b-J_w}{\\tau_g^{-1}\\,F_{bw}^{-1}\\,A_b^{-1}} + \\frac{E_{gas}-J_w}{\\varepsilon_g^{-1}\\,F_{wg}^{-1}\\,A_w^{-1}}=0\n\t\\f]\n\n\tThe emission fluxes (potentials) are already known:\n\t\\f[\n\tE_{bed} = \\sigma\\,T^4_{bed} \\qquad E_{gas} = \\sigma\\,T^4_{gas} \\qquad E_{wall} = \\sigma\\,T^4_{wall}\n\t\\f]\n\n\tThus the task is to determine the radiosities \\f$J_{bed}\\f$\n\tand \\f$J_{wall}\\f$ by solving the two simultaneous equations\n\tabove. Once this is complete the heat fluxes/currents from the wall and\n\tbed are obtainable from the network's potentials and\n\tresistances:\n\t\n\t\\f[\n\tq_{bed} = \\frac{E_{bed}-J_b}{\\left(1-\\varepsilon_b\\right)^{-1}\\varepsilon_b\\,A_b}\n\t\\qquad\n\tq_{wall} = \\frac{E_{wall}-J_w}{\\left(1-\\varepsilon_w\\right)^{-1}\\varepsilon_w\\,A_w}\n\t\\f]\n\t\\f[\n\tq_{gas} = \\frac{J_b-E_{gas}}{\\varepsilon_g^{-1}\\,F_{bg}^{-1}\\,A_b^{-1}} + \\frac{J_w-E_{gas}}{\\varepsilon_g^{-1}\\,F_{wg}^{-1}\\,A_w^{-1}} = -q_{bed} -q_{wall}\n\t\\f]\n\tAlthough the reciprocity relationship\n\t(\\f$F_{12}A_{1}=F_{21}A_{2}\\f$) and summation rule (\\f$\\sum_b\n\tF_{ab}=1\\f$) allow us to change the view factors, the\n\tselection above has been made as \\f$F_{bw}=F_{bg}=F_{wg}=1\\f$\n\tthus these can be eliminated. For simplicity it is assumed\n\tthat spectral effects on the gas absorptivity (resulting from\n\tthe different temperatures of the wall and gas) can be ignored\n\tand \\f$\\tau_g=1-\\varepsilon_g\\f$. The areas are given in terms\n\tof per unit length of kiln, thus\n\t\\f$A_w=R\\left(2\\,\\pi-\\theta\\right)\\f$ and \\f$A_b\\f$ is the\n\tchord length (Li_etal_2005 incorrectly uses the covered\n\tperimeter of the inner kiln surface). All the resistance terms\n\tcan then be determined a priori.\n\t\n */\n std::array rad_fluxes(const Slice& slice) const {\n\tconst double Aw = exposedWallPerimeter(slice);\n\tconst double Abed = chordLength(slice);\n\tconst double h = _bedModel->bedHeight(slice);\n\tconst double pathLength = simcem::HT::kiln::pathLength(_innerRadius, h);\n\tconst Model& gas = *slice._gas;\n\tconst Model& solid = *slice._solid;\n\tconst double e_gas = simcem::HT::rad::Hottel_emissivity(gas, pathLength);\n\tconst double sigma = gas.db()->steffanBoltzmannConstant;\n\n\tconst std::array V = {{\n\t sigma * std::pow(solid.T(), 4),\n\t sigma * std::pow(slice._T_wall, 4),\n\t sigma * std::pow(gas.T(), 4)\n\t }};\n\t\n\tconst std::array Rinv = {{\n\t _bed_emissivity * Abed / (1 - _bed_emissivity),\n\t (1 - e_gas) * Abed,\n\t e_gas * Abed,\n\t _wall_emissivity * Aw / (1 - _wall_emissivity),\n\t e_gas * Aw\n\t }};\n\t\n\treturn simcem::HT::rad::twobodygas_network(V, Rinv);\n }\t\n\n void printFluxes(const Slice& slice) const {\n\tauto rad = rad_fluxes(slice);\n\tconst double Q_s_rad = rad[0], Q_w_rad = rad[1], Q_g_rad = rad[2];\n\t\n\tstd::cout << \"Z=\" << slice._Z << \", Tg=\" << slice._gas->T() << \", Ts=\" << slice._solid->T() << \", Tw=\" << slice._T_wall << \", Tshell=\" << slice._T_ext_shell << std::endl;\n\tstd::cout << \"Q_s_rad=\" << Q_s_rad << \", Q_w_rad=\"< stop_points, bool store_intermediate) {\n\tusing namespace sundials;\n\t\n\t//For debugging, output all kiln settings\n\t//std::cout << \"Kiln setup\" << std::endl;\n\t//std::cout << _RPM << \" \"\n\t//\t << _innerRadius << \" \"\n\t//\t << _length << \" \"\n\t//\t << _particle_diam << \" \"\n\t//\t << _shell_emissivity << \" \"\n\t//\t << _bed_emissivity << \" \"\n\t//\t << _wall_emissivity << \" \"\n\t//\t << _solid_density << \" \"\n\t//\t << _solid_k << \" \"\n\t//\t << _bedModel << \" \"\n\t//\t << _ambient << \" \"\n\t//\t << std::endl;\n\t//\n\t//for (const auto& layer : _layers)\n\t// std::cout << \"Layer: \" << layer._thickness << \" \" << layer._k << std::endl;\n\t//\n\t// TODO: add slice data output\n\t\n\tstruct SolverData {\n\t Kiln& kiln;\n\t Slice slice;\n\n\t void save_state(Serial_Vector& T) const {\n\t T[0] = slice._gas->T();\n\t T[1] = slice._solid->T();\n\t T[2] = slice._T_wall;\n\t T[3] = slice._T_ext_shell;\n\t }\n\n\t void load_state(Serial_Vector& T, const double Z) {\n\t slice._gas->set (simcem::Objective_t::T, T[0], simcem::Objective_t::p);\n\t slice._solid->set(simcem::Objective_t::T, T[1], simcem::Objective_t::p);\n\t slice._T_wall = T[2];\n\t slice._T_ext_shell = T[3];\n\t slice.compute_properties(kiln.gasArea(slice), kiln.solid_k(T[1]));\n\t slice._Z = Z;\n\t }\n\n\t static int resrob(realtype Z, N_Vector T_, N_Vector Tprime_, N_Vector residuals_, void *user_data) {\n\t Serial_Vector T(T_), Tprime(Tprime_), residuals(residuals_);\n\t SolverData& data = *((SolverData*)user_data);\n\t \n\t //Load the slice state\n\t data.load_state(T, Z);\n\n\t auto rad = data.kiln.rad_fluxes(data.slice);\n\t const double Q_s_rad = rad[0], Q_w_rad = rad[1], Q_g_rad = rad[2];\n\n\t //The solid energy balance\n\t //-ve as we're starting at the hot end\n\t //The gas energy balance\n\t residuals[0] = -(-data.kiln.Q_gas_bed_cv(data.slice) - data.kiln.Q_gas_wall_cv(data.slice) + Q_g_rad) - data.slice._gas->Cp() * Tprime[0];\n\n\t residuals[1] = (data.kiln.Q_gas_bed_cv(data.slice) + data.kiln.Q_wall_bed_cd(data.slice) + Q_s_rad) - data.slice._solid->Cp() * Tprime[1];\n\t \n\t //The shell-wall relationship\n\t residuals[2] = Q_w_rad + data.kiln.Q_gas_wall_cv(data.slice) - data.kiln.Q_wall_bed_cd(data.slice) - data.kiln.Q_w_ext(data.slice);\n\t residuals[3] = data.kiln.Q_w_sh(data.slice) - data.kiln.Q_w_ext(data.slice);\n\n\t return 0;\n\t }\n\t};\n\t\n\t//Set up the system data;\n\tSolverData data{*this, slice_in};\n\t\n\tSerial_Vector T(4);\n\tdata.save_state(T);\n\n\tSerial_Vector Tprime(4);\n\tTprime[0] = 0;\n\tTprime[1] = 0;\n\tTprime[2] = Tprime[3] = 0;\n\n\tIDA solver(slice_in._Z, SolverData::resrob, T, Tprime);\n\t\n\tsolver.setTol(1e-4, 1e-2);\n\tsolver.setUserData(data);\n\tsolver.denseSolver(T);\n\n\tSerial_Vector Id(4);\n\tId[0] = Id[1] = 1.0; //Differential \n\tId[2] = Id[3] = 0.0; //Algebraic\n\tsolver.setId(Id);\n\n\tsolver.calcIC(IDA_YA_YDP_INIT, _length);\n\n\tSerial_Vector T_interp(4);\n\tSerial_Vector Tprime_interp(4);\n\n\tstd::sort(stop_points.begin(), stop_points.end());\n\tauto stop_it = stop_points.begin();\n\t\n\twhile (stop_it != stop_points.end()) {\n\t const realtype Znext = solver.solve(*stop_it, T, Tprime, IDA_ONE_STEP);\n\n\t while (Znext > *stop_it) {\n\t solver.interpolate(*stop_it, T_interp, 0);\n\t solver.interpolate(*stop_it, Tprime_interp, 1);\n\t data.load_state(T_interp, *stop_it);\n\t _slices.push_back(data.slice);\n\t if (++stop_it == stop_points.end()) break;\n\t }\n\n\t if (store_intermediate && (stop_it != stop_points.end())) {\n\t data.load_state(T, Znext);\n\t _slices.push_back(data.slice);\n\t }\n\t}\n }\n\n std::vector& getSlices() { return _slices; }\n\n double length() const { return _length; }\n \n protected:\n \n const double _RPM;\n const double _innerRadius;\n const double _length;\n const double _particle_diam;\n const double _shell_emissivity;\n const double _bed_emissivity;\n const double _wall_emissivity;\n const double _solid_density;\n const double _bed_void_frac;\n\n sym::Expr _solid_k;\n \n std::vector _layers;\n simcem::shared_ptr _bedModel;\n simcem::shared_ptr _ambient; \n std::vector _slices;\n };\n }\n}\n", "meta": {"hexsha": "791ef700042804df3a5f2abe46893857250a97b6", "size": 37266, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/simcem/simcem/kiln.hpp", "max_stars_repo_name": "toastedcrumpets/SimCem", "max_stars_repo_head_hexsha": "d04a6948be435d4da234c0b5fe37a0ee84fdd9dc", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-04-21T17:29:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-22T14:53:37.000Z", "max_issues_repo_path": "src/simcem/simcem/kiln.hpp", "max_issues_repo_name": "toastedcrumpets/SimCem", "max_issues_repo_head_hexsha": "d04a6948be435d4da234c0b5fe37a0ee84fdd9dc", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/simcem/simcem/kiln.hpp", "max_forks_repo_name": "toastedcrumpets/SimCem", "max_forks_repo_head_hexsha": "d04a6948be435d4da234c0b5fe37a0ee84fdd9dc", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.2897727273, "max_line_length": 305, "alphanum_fraction": 0.6451188751, "num_tokens": 12196, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.7310585669110203, "lm_q1q2_score": 0.6552122363315641}} {"text": "#include \n#include \n\nusing boost::math::cdf, boost::math::complement;\nusing boost::math::students_t_distribution;\n\nnamespace learning::independences::continuous {\n\ndouble cor_pvalue(double cor, int df) {\n double statistic = cor * sqrt(df) / sqrt(1 - cor * cor);\n students_t_distribution tdist(static_cast(df));\n return 2 * cdf(complement(tdist, fabs(statistic)));\n}\n\ndouble LinearCorrelation::pvalue_cached(const std::string& v1, const std::string& v2) const {\n double cor = cor_0cond(m_cov, cached_index(v1), cached_index(v2));\n return cor_pvalue(cor, m_df->num_rows() - 2);\n}\n\ndouble LinearCorrelation::pvalue_impl(const std::string& v1, const std::string& v2) const {\n auto [cor, df] = [this, &v1, &v2]() {\n switch (m_df.col(v1)->type_id()) {\n case Type::DOUBLE: {\n auto cov_ptr = m_df.cov(v1, v2);\n auto& cov = *cov_ptr;\n double cor = cor_0cond(cov, 0, 1);\n return std::make_pair(cor, m_df.valid_rows(v1, v2) - 2);\n }\n case Type::FLOAT: {\n auto cov_ptr = m_df.cov(v1, v2);\n auto& cov = *cov_ptr;\n double cor = cor_0cond(cov, 0, 1);\n return std::make_pair(cor, m_df.valid_rows(v1, v2) - 2);\n }\n default:\n throw std::invalid_argument(\"Column \" + m_df.name(v1) + \" is not continuous\");\n }\n }();\n\n return cor_pvalue(cor, df);\n}\n\ndouble LinearCorrelation::pvalue_cached(const std::string& v1, const std::string& v2, const std::string& ev) const {\n double cor = cor_1cond(m_cov, cached_index(v1), cached_index(v2), cached_index(ev));\n return cor_pvalue(cor, m_df->num_rows() - 3);\n}\n\ndouble LinearCorrelation::pvalue_impl(const std::string& v1, const std::string& v2, const std::string& ev) const {\n auto [cor, df] = [this, &v1, &v2, &ev]() {\n switch (m_df.col(v1)->type_id()) {\n case Type::DOUBLE: {\n auto cov_ptr = m_df.cov(v1, v2, ev);\n auto& cov = *cov_ptr;\n double cor = cor_general(cov);\n return std::make_pair(cor, m_df.valid_rows(v1, v2, ev) - 3);\n }\n case Type::FLOAT: {\n auto cov_ptr = m_df.cov(v1, v2, ev);\n auto& cov = *cov_ptr;\n double cor = cor_general(cov);\n return std::make_pair(cor, m_df.valid_rows(v1, v2, ev) - 3);\n }\n default:\n throw std::invalid_argument(\"Column \" + m_df.name(v1) + \" is not continuous\");\n }\n }();\n\n return cor_pvalue(cor, df);\n}\n\ndouble LinearCorrelation::pvalue_cached(const std::string& v1,\n const std::string& v2,\n const std::vector& ev) const {\n std::vector cached_indices;\n\n cached_indices.push_back(cached_index(v1));\n cached_indices.push_back(cached_index(v2));\n\n for (auto it = ev.begin(), end = ev.end(); it != end; ++it) {\n cached_indices.push_back(cached_index(*it));\n }\n\n int k = cached_indices.size();\n MatrixXd cov(k, k);\n\n for (int i = 0; i < k; ++i) {\n cov(i, i) = m_cov(cached_indices[i], cached_indices[i]);\n for (int j = i + 1; j < k; ++j) {\n cov(i, j) = cov(j, i) = m_cov(cached_indices[i], cached_indices[j]);\n }\n }\n\n double cor = cor_general(cov);\n return cor_pvalue(cor, m_df->num_rows() - 2 - k);\n}\n\ndouble LinearCorrelation::pvalue_impl(const std::string& v1,\n const std::string& v2,\n const std::vector& ev) const {\n auto [cor, df] = [this, &v1, &v2, &ev]() {\n int k = ev.size();\n switch (m_df.col(v1)->type_id()) {\n case Type::DOUBLE: {\n auto cov_ptr = m_df.cov(v1, v2, ev);\n auto& cov = *cov_ptr;\n double cor = cor_general(cov);\n return std::make_pair(cor, m_df.valid_rows(v1, v2, ev) - 2 - k);\n }\n case Type::FLOAT: {\n auto cov_ptr = m_df.cov(v1, v2, ev);\n auto& cov = *cov_ptr;\n double cor = cor_general(cov);\n return std::make_pair(cor, m_df.valid_rows(v1, v2, ev) - 2 - k);\n }\n default:\n throw std::invalid_argument(\"Column \" + m_df.name(v1) + \" is not continuous\");\n }\n }();\n\n return cor_pvalue(cor, df);\n}\n\n} // namespace learning::independences::continuous", "meta": {"hexsha": "c1a7440819667a17942fe211186ea937982736c8", "size": 4768, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pybnesian/learning/independences/continuous/linearcorrelation.cpp", "max_stars_repo_name": "vishalbelsare/PyBNesian", "max_stars_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2021-06-22T19:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T13:08:05.000Z", "max_issues_repo_path": "pybnesian/learning/independences/continuous/linearcorrelation.cpp", "max_issues_repo_name": "vishalbelsare/PyBNesian", "max_issues_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "pybnesian/learning/independences/continuous/linearcorrelation.cpp", "max_forks_repo_name": "vishalbelsare/PyBNesian", "max_forks_repo_head_hexsha": "0190cd4cf6d133746741e2750004ccf0a9061fbd", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2021-08-20T13:44:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T02:57:02.000Z", "avg_line_length": 38.7642276423, "max_line_length": 116, "alphanum_fraction": 0.5503355705, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7371581626286833, "lm_q1q2_score": 0.6551557948869792}} {"text": "static char help[] = \"hello neural network!\\n\";\n#include \n#include \n\n\n\n\n\n//---------------------------------------------------------------------------\n/* autodiff include */\n#include \nusing namespace autodiff;\n\n\n// The multi-variable function for which derivatives are needed\nvar f(var x, var y, var z)\n{\n return 1 + x + y + z; // + x*y + y*z + x*z + x*y*z + exp(x/y + y/z);\n}\n\n\n\n//---------------------------------------------------------------------------\n// boost automatic differentiation \n#include \n#include \nusing namespace boost::math::differentiation;\n\n\ntemplate \npromote f(const W& w, const X& x, const Y& y, const Z& z) {\n using namespace std;\n return exp(w * sin(x * log(y) / z) + sqrt(w * z / (x * y))) + w * w / tan(z);\n}\n//--------------------------------------------------------------------------\n\n/* main */\n\nint main(int argc, char **argv) {\n PetscErrorCode ierr;\n Vec b;\n PetscReal ab[4] = {11.0, 12.0, 13.0, 14.0};\n PetscInt i, j[4]={0, 1, 2, 3};\n PetscRandom rand;\n/*\n var x = 1.0; // the input variable x\n var y = 2.0; // the input variable y\n var z = 3.0; // the input variable z\n var V[3] = {x,y,z};\n var u = f(x, y, z); // the output variable u\n auto [ux, uy, uz] = derivatives(u, wrt(x, y, z)); // evaluate the derivatives of u with respect to x, y, z\n std::cout << \"u = \" << u << std::endl; // print the evaluated output u\n std::cout << \"ux = \" << ux << std::endl; // print the evaluated derivative ux\n std::cout << \"uy = \" << uy << std::endl; // print the evaluated derivative uy\n std::cout << \"uz = \" << uz << std::endl; // print the evaluated derivative uz\n*/\n\n ierr = PetscInitialize(&argc, &argv, (char*) 0, help); CHKERRQ(ierr);\n\n VecCreate(PETSC_COMM_WORLD, &b);\n VecSetSizes(b, PETSC_DECIDE, 3);\n VecSetFromOptions(b);\n \n PetscRandomCreate(PETSC_COMM_WORLD,&rand);\n PetscRandomSetFromOptions(rand);\n\n\n PetscInt nloc;\n VecGetLocalSize(b,&nloc);\n var Vs[nloc];\n\n double *vec_p;\n VecGetArray(b, &vec_p);\n for (i=0; i(ab[0], ab[1], ab[2], ab[3]);//(11, 12, 13, 14);\n auto const& w = std::get<0>(variables);\n auto const& x = std::get<1>(variables); \n auto const& y = std::get<2>(variables); \n auto const& z = std::get<3>(variables); \n auto const v = f(w, x, y, z);\n // Calculated from Mathematica symbolic differentiation.\n std::cout << v.derivative(1, 1, 1, 1) << '\\n';\n*/\n\n\n VecDestroy(&b);\n PetscRandomDestroy(&rand);\n return PetscFinalize();\n}\n\n", "meta": {"hexsha": "5a83a20b7db7b34dccee575beef3e4f33da4c966", "size": 3482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/automatic_diff/obsolete/main_nn.cpp", "max_stars_repo_name": "pourion/OPERA", "max_stars_repo_head_hexsha": "b94b744970d97308d05d9c1195d74a24109aae57", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/automatic_diff/obsolete/main_nn.cpp", "max_issues_repo_name": "pourion/OPERA", "max_issues_repo_head_hexsha": "b94b744970d97308d05d9c1195d74a24109aae57", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/automatic_diff/obsolete/main_nn.cpp", "max_forks_repo_name": "pourion/OPERA", "max_forks_repo_head_hexsha": "b94b744970d97308d05d9c1195d74a24109aae57", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-13T02:38:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-13T02:38:41.000Z", "avg_line_length": 32.2407407407, "max_line_length": 120, "alphanum_fraction": 0.5689259047, "num_tokens": 1063, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7371581568543043, "lm_q1q2_score": 0.655155789754949}} {"text": "/*\n* Copyright 2019 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés\n*/\n\n#ifndef COORDINATETRANSFORM_HPP\n#define COORDINATETRANSFORM_HPP\n\n#include \"../Position.hpp\"\n#include \"../utils/Constants.hpp\"\n#include \n\n/*!\n* \\brief Coordinate transform class\n* \\author Guillaume Labbe-Morissette, Jordan McManus\n* \\date September 13, 2018, 3:39 PM\n*/\nclass CoordinateTransform {\npublic:\n\n // WGS84 ellipsoid Parameters\n\n /**WGS84 ellipsoid semi-major axis*/\n static constexpr double a = 6378137.0;\n\n /**WGS84 ellipsoid first eccentricity squared*/\n static constexpr double e2 = 0.081819190842622 * 0.081819190842622;\n\n /**WGS84 ellipsoid inverse flattening*/\n static constexpr double f = 1.0 / 298.257223563;\n\n /**WGS84 ellipsoid semi-minor axis*/\n static constexpr double b = a * (1-f); // semi-minor axis\n\n /**WGS84 ellipsoid second eccentricity squared*/\n static constexpr double epsilon = e2 / (1.0 - e2); // second eccentricity squared\n\n /**\n * Sets the position in navigation frame\n *\n * @param positionInNavigationFrame the value that needs to be set\n * @param positionGeographic the geographic position\n * @param navDCM the rotation matrix\n * @param originECEF the ECEF origin position\n */\n static void getPositionInNavigationFrame(Eigen::Vector3d & positionInNavigationFrame, Position & positionGeographic, Eigen::Matrix3d & navDCM, Eigen::Vector3d & originECEF) {\n Eigen::Vector3d positionECEF;\n getPositionECEF(positionECEF, positionGeographic);\n\n Eigen::Vector3d positionVector = navDCM * (positionECEF - originECEF);\n\n positionInNavigationFrame << positionVector(0), positionVector(1), positionVector(2);\n };\n\n /**\n * Sets the ECEF position by the given position\n *\n * @param positionECEF value that needs to be set\n * @param position the position used to get the ECEF position\n */\n static void getPositionECEF(Eigen::Vector3d & positionECEF, Position & position) {\n double N = a / (sqrt(1 - e2 * position.getSlat() * position.getSlat()));\n double xTRF = (N + position.getEllipsoidalHeight()) * position.getClat() * position.getClon();\n double yTRF = (N + position.getEllipsoidalHeight()) * position.getClat() * position.getSlon();\n double zTRF = (N * (1 - e2) + position.getEllipsoidalHeight()) * position.getSlat();\n\n positionECEF << xTRF, yTRF, zTRF;\n };\n\n /**\n * Gets the longitude, latitude and elevation of an ECEF position\n *\n * @param positionInNavigationFrame the position we need to get the latitude, longitude and elevation\n * @param positionGeographic the position where the latitude, longitude et elevation will be put in\n */\n static void convertECEFToLongitudeLatitudeElevation(Eigen::Vector3d & positionInNavigationFrame, Position & positionGeographic) {\n double x = positionInNavigationFrame(0);\n double y = positionInNavigationFrame(1);\n double z = positionInNavigationFrame(2);\n\n // Bowring (1985) algorithm\n double p2 = x * x + y*y;\n double r2 = p2 + z*z;\n double p = std::sqrt(p2);\n double r = std::sqrt(r2);\n\n double tanu = (1 - f) * (z / p) * (1 + epsilon * b / r);\n double tan2u = tanu * tanu;\n\n double cos2u = 1.0 / (1.0 + tan2u);\n double cosu = std::sqrt(cos2u);\n double cos3u = cos2u * cosu;\n\n double sinu = tanu * cosu;\n double sin2u = 1.0 - cos2u;\n double sin3u = sin2u * sinu;\n\n double tanlat = (z + epsilon * b * sin3u) / (p - e2 * a * cos3u);\n double tan2lat = tanlat * tanlat;\n double cos2lat = 1.0 / (1.0 + tan2lat);\n double sin2lat = 1.0 - cos2lat;\n\n double coslat = std::sqrt(cos2lat);\n double sinlat = tanlat * coslat;\n\n double longitude = std::atan2(y, x);\n double latitude = std::atan(tanlat);\n double height = p * coslat + z * sinlat - a * sqrt(1.0 - e2 * sin2lat);\n\n positionGeographic.setLatitude(latitude*R2D);\n positionGeographic.setLongitude(longitude*R2D);\n positionGeographic.setEllipsoidalHeight(height);\n }\n\n /**\n * Sets a terrestrial to a local geodetic reference frame matrix by the given position\n *\n * @param trf2lgf the terrestrial to local geodetic reference frame matrix that needs to be set\n * @param position the given position\n */\n static void getTerrestialToLocalGeodeticReferenceFrameMatrix(Eigen::Matrix3d & trf2lgf, Position & position) {\n double m00 = -position.getSlat() * position.getClon();\n double m01 = -position.getSlat() * position.getSlon();\n double m02 = position.getClat();\n\n double m10 = -position.getSlon();\n double m11 = position.getClon();\n double m12 = 0;\n\n double m20 = -position.getClat() * position.getClon();\n double m21 = -position.getClat() * position.getSlon();\n double m22 = -position.getSlat();\n\n trf2lgf <<\n m00, m01, m02,\n m10, m11, m12,\n m20, m21, m22;\n };\n\n /**\n * Sets rotation matrix from neutral/zero position to the given attitude\n *\n * @param outputMatrix matrix that needs to be set\n * @param attitude the given attitude\n */\n static void getDCM(Eigen::Matrix3d & outputMatrix,Attitude & attitude){\n outputMatrix << attitude.getCh()*attitude.getCp(), attitude.getCh()*attitude.getSp()*attitude.getSr()-attitude.getCr()*attitude.getSh(), attitude.getCh()*attitude.getCr()*attitude.getSp()+attitude.getSr()*attitude.getSh(),\n attitude.getCp()*attitude.getSh(), attitude.getCh()*attitude.getCr()+attitude.getSp()*attitude.getSr()*attitude.getSh(), attitude.getSh()*attitude.getCr()*attitude.getSp()-attitude.getCh()*attitude.getSr(),\n -attitude.getSp(), attitude.getCp()*attitude.getSr(), attitude.getCr()*attitude.getCp();\n }\n\n\n /**\n * NED Tangent plane at position to WGS84 ECEF\n *\n * @param outputMatrix the matrix that needs to be set\n * @param position the position to convert\n */\n static void ned2ecef(Eigen::Matrix3d & outputMatrix,Position & position){\n\n outputMatrix << -position.getClon()*position.getSlat(),-position.getSlon(),-position.getClat()*position.getClon(),\n -position.getSlat()*position.getSlon(),position.getClon(),-position.getClat()*position.getSlon(),\n position.getClat(),0,-position.getSlat();\n\n }\n\n\n /**\n * Converts spherical coordinates to cartesian\n *\n * @param outputVector the cartesian coordinates\n * @param theta the polar angle\n * @param phi the azimuthal angle\n * @param r the radial distance\n */\n static void spherical2cartesian(Eigen::Vector3d & outputVector,double theta,double phi,double r){\n outputVector(0) = r * sin(D2R*theta)*cos(D2R*phi);\n outputVector(1) = r * sin(D2R*theta)*sin(D2R*phi);\n outputVector(2) = r * cos(D2R*theta);\n }\n\n /**\n * Converts sonar coordinates (alpha,beta,r) to cartesian (NED)\n *\n * @param outputVector the cartesian coordinates\n * @param aphaDegrees the alpha degree\n * @param betaDegrees the beta degree\n * @param r the radical distance\n */\n static void sonar2cartesian(Eigen::Vector3d & outputVector,double alphaDegrees,double betaDegrees,double r){\n outputVector(0)=r * sin(alphaDegrees*D2R);\n outputVector(1)=r * cos(alphaDegrees*D2R) * sin(betaDegrees*D2R);\n outputVector(2)=r * cos(alphaDegrees*D2R) * cos(betaDegrees*D2R);\n }\n};\n\n#endif /* COORDINATETRANSFORM_HPP */\n", "meta": {"hexsha": "4dd52d1a2fe90b95dedfba68b8cf84536c155e9e", "size": 7203, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/math/CoordinateTransform.hpp", "max_stars_repo_name": "EmileGagne/MBES-lib", "max_stars_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/math/CoordinateTransform.hpp", "max_issues_repo_name": "EmileGagne/MBES-lib", "max_issues_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/math/CoordinateTransform.hpp", "max_forks_repo_name": "EmileGagne/MBES-lib", "max_forks_repo_head_hexsha": "fe68f3c513abe1f0292ed96549333bf501e3c5e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.5634517766, "max_line_length": 236, "alphanum_fraction": 0.696931834, "num_tokens": 2053, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9324533163686646, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6550764876742737}} {"text": "/*\nYou are asked to calculate factorials of some small positive integers.\n\n\n */\n\n#include \n#include \n\nusing boost::multiprecision::cpp_int;\nusing namespace std;\n\nint main() {\n \n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cpp_int t,n;\n cin>>t;\n while(t--){\n cin>>n;\n cpp_int fac = 1;\n if(n == 0 || n == 1)\n cout<\n* @date 2019-10-31\n* @copyright Deutsches Zentrum fuer Luft- und Raumfahrt e. V. (DLR), German Aerospace Center\n*\n**/\n\n// include guard\n#ifndef PITTS_TENSOR2_QB_DECOMPOSITION_HPP\n#define PITTS_TENSOR2_QB_DECOMPOSITION_HPP\n\n// includes\n#include \n#include \n#include \"pitts_tensor2.hpp\"\n#include \"pitts_tensor2_eigen_adaptor.hpp\"\n#include \"pitts_timer.hpp\"\n#pragma GCC push_options\n#pragma GCC optimize(\"no-unsafe-math-optimizations\")\n#include \n#pragma GCC pop_options\n\n\n//! namespace for the library PITTS (parallel iterative tensor train solvers)\nnamespace PITTS\n{\n //! QB-part in the SVQB orthogonalization algorithm from Stathopoulos and Wu, SISC 23 (6), pp. 2165-2182\n //!\n //! Computes the decomposition B^TB = M using a SVD of M for a symmetric positive semi-definite matrix M\n //!\n //! @tparam T underlying data type (double, complex, ...)\n //!\n //! @param M Symmetric positive semi-definite input matrix M, overwritten with the output matrix B\n //! @param Binv Pseudo-Inverse of the output matrix\n //! @return detected rank of the matrix\n //!\n template\n auto qb_decomposition(const Tensor2& M, Tensor2& B, Tensor2& Binv, T rankTolerance)\n {\n const auto timer = PITTS::timing::createScopedTimer>();\n\n // get dimension\n if( M.r1() != M.r2() )\n throw std::invalid_argument(\"qb_decomposition requires a quadratic matrix!\");\n const auto n = M.r1();\n\n // Helpful types\n using vec = Eigen::Matrix;\n using mat = Eigen::Matrix;\n using EigenSolver = Eigen::SelfAdjointEigenSolver;\n\n // use Eigen for matrix operations\n const auto mapM = ConstEigenMap(M);\n\n // compute sqrt(diag(M)) and its inverse\n vec d(n), dinv(n);\n for(int i = 0; i < n; i++)\n {\n if( std::abs(M(i,i)) <= rankTolerance )\n {\n d(i) = T(0);\n dinv(i) = T(0);\n }\n else\n {\n d(i) = std::sqrt(M(i,i));\n dinv(i) = T(1)/d(i);\n }\n }\n\n // scale input matrix from left and right by diag(dinv), so it's diagonal entries become 1\n const mat scaledM = dinv.asDiagonal() * mapM * dinv.asDiagonal();\n\n // compute eigenvalue decomposition\n EigenSolver eigSolv(scaledM);\n\n // determine rank of the input matrix and set w = sqrt(lambda), winv = 1/w\n // Eigen orders eigenvalues with increasing value (smallest first)\n int rank = n;\n const auto evMax = std::abs(eigSolv.eigenvalues()(n-1));\n vec w(n), winv(n);\n if( evMax <= rankTolerance )\n {\n w = vec::Zero(n);\n winv = vec::Zero(n);\n rank = 0;\n }\n else\n {\n for(int i = 0; i < n; i++)\n {\n if( eigSolv.eigenvalues()(i) <= rankTolerance*evMax )\n {\n rank--;\n w(i) = T(0);\n winv(i) = T(0);\n }\n else\n {\n w(i) = std::sqrt(eigSolv.eigenvalues()(i));\n winv(i) = T(1)/w(i);\n }\n }\n }\n\n // calculate B and Binv\n B.resize(n,n);\n Binv.resize(n,n);\n EigenMap(Binv) = dinv.asDiagonal() * eigSolv.eigenvectors() * winv.asDiagonal();\n EigenMap(B) = w.asDiagonal() * eigSolv.eigenvectors().transpose() * d.asDiagonal();\n\n // reorder, so the part corresponding to the largest eigenvalues are first\n for(int i = 0; i < n; i++)\n {\n for(int j = 0; j < n/2; j++)\n {\n int k = n-j-1;\n std::swap(B(j,i), B(k,i));\n std::swap(Binv(i,j), Binv(i,k));\n }\n }\n\n return rank;\n }\n\n}\n\n\n#endif // PITTS_TENSOR2_QB_DECOMPOSITION_HPP\n", "meta": {"hexsha": "8116c9a12da14750949d1153b73cf089e51c7b17", "size": 3800, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/pitts_tensor2_qb_decomposition.hpp", "max_stars_repo_name": "melven/pitts", "max_stars_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-12-31T08:28:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-12T14:48:49.000Z", "max_issues_repo_path": "src/pitts_tensor2_qb_decomposition.hpp", "max_issues_repo_name": "melven/pitts", "max_issues_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pitts_tensor2_qb_decomposition.hpp", "max_forks_repo_name": "melven/pitts", "max_forks_repo_head_hexsha": "491f503a99a7d1161a27672955ae53ca6b5d3412", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.0076335878, "max_line_length": 106, "alphanum_fraction": 0.6134210526, "num_tokens": 1120, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6547711318199639}} {"text": "#ifndef GENERATE_GALTON_WATSON_HPP\n#define GENERATE_GALTON_WATSON_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef _OPENMP\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n/**\n * Given:\n * (1) Distribution: Poisson, Negative Geometric, Binomial\n * (2) Number of nodes for the conditioned Galton-Watson process.\n * (3) Parameters needed for the distributions:\n * (a) Probability of success (p)\n * (b) Lambda if using Poisson distribution\n * (c) 'k', the total number of trials if we are using Binomial\n * (d) Seed value for the random number\n */\nstruct generate_Galton_Watson_t {\n typedef boost::mt19937 engine_type;\n typedef boost::binomial_distribution binomial_type;\n typedef boost::uniform_real uni_real_type;\n typedef boost::exponential_distribution exp_real_type;\n typedef boost::uniform_int uni_int_type;\n\n typedef boost::adjacency_list\n >,\n boost::property > graph_type;\n typedef boost::property_map::type \n vertex_index_map_t;\n typedef boost::property_map::type \n vertex_name_map_t;\n typedef boost::property_map::type \n vertex_distance_map_t;\n typedef boost::property_map::type\n edge_weight_map_t;\n typedef boost::graph_traits::vertex_descriptor vertex_t;\n\n private:\n\n struct always_1_t {\n typedef double result_type;\n result_type operator()() { return 1.0; }\n };\n\n struct Poisson_computer_t {\n typedef boost::poisson_distribution dist_type; \n int lambda;\n\n Poisson_computer_t (int lambda) : lambda(lambda) {}\n\n double operator()(int i) const { \n return (pow(lambda,i)*exp(-lambda)) / boost::math::factorial(i);\n }\n\n dist_type operator()() const { return dist_type(lambda); }\n };\n\n struct geometric_computer_t {\n typedef boost::geometric_distribution dist_type; \n double p;\n geometric_computer_t (double p) : p(p) {}\n\n double operator()(int i) const { return pow((1-p), i) * p; }\n\n dist_type operator()() const { return dist_type(p); }\n };\n\n struct binomial_computer_t {\n typedef boost::binomial_distribution dist_type; \n int k;\n double p;\n binomial_computer_t (int k, double p) : k(k), p(p) {}\n\n double operator()(int i) const { \n return\n boost::math::binomial_coefficient(k,i)*pow(p,i)*pow((1-p),(k-i));\n }\n\n dist_type operator()() const { return dist_type(k,p); }\n };\n\n struct binary_0_2_computer_t {\n struct binary_0_2_distribution {\n typedef int result_type;\n boost::bernoulli_distribution distro;\n \n binary_0_2_distribution(double p) : distro(p) {}\n\n template \n int operator()(EngineType& engine) {return (distro(engine))?2:0;}\n };\n typedef binary_0_2_distribution dist_type;\n\n binary_0_2_computer_t (double p) : p(p) {}\n\n double operator()(int i) const {\n if (2==i) return p;\n else if (0==i) return (1-p);\n else return 0;\n }\n\n dist_type operator()() const { return dist_type(p); }\n \n private:\n double p;\n };\n\n struct binary_0_1_2_computer_t {\n typedef boost::uniform_int dist_type;\n double operator()(int i) const { \n if (0==i || 1==i || 2==i) return 1./3.;\n else return 0;\n }\n\n dist_type operator()() const { return dist_type(0,2); }\n };\n\n /**\n * Thin wrapper around boost::uniform<> so that it conforms to random_shuffle.\n */\n struct random_functor_t : std::unary_function {\n engine_type engine;\n \n random_functor_t (engine_type engine) : engine(engine) {}\n\n int operator()(const int& ULIMIT) {\n uni_int_type dist (0, ULIMIT-1);\n return dist(engine);\n }\n };\n\n static void rotate_to_get_tree (std::vector& psi_vec) {\n /** Get the vector S for the queues in the tree */\n size_t n = psi_vec.size();\n std::vector S(n);\n\n for (size_t i=0; i::max();\n int min_index=-1;\n for (size_t i=0; iS[i]) { min_ele=S[i]; min_index=i; }\n\n std::rotate(psi_vec.begin(), psi_vec.begin()+min_index+1, psi_vec.end());\n }\n\n template \n static graph_type generate_impl (int n, \n const std::vector& psi_vec,\n WDistribution w_prng,\n int verbosity) {\n graph_type G;\n vertex_name_map_t name_map = boost::get (boost::vertex_name, G);\n vertex_distance_map_t dist_map = boost::get (boost::vertex_distance, G);\n edge_weight_map_t weight_map = boost::get (boost::edge_weight, G);\n\n /** Set up a queue for the children and add the root vertex */\n vertex_t root = boost::add_vertex(G);\n boost::put (name_map, root, boost::lexical_cast(0));\n boost::put (dist_map, root, 0);\n\n std::queue vertex_queue;\n vertex_queue.push(root);\n\n /** Count the number of children left */\n int n_left = (n-1);\n\n /** Iterate till we are left with nothing or we have maxed out children */\n while ((0<=n_left) && (false==vertex_queue.empty())) {\n const vertex_t parent = vertex_queue.front();\n vertex_queue.pop();\n\n#pragma omp critical\n if (1(child_number));\n\n /** \n * Duplicating a map here, but I think it's fine. We need the vertex\n * weights to easily be able to get the Dyck/Harris paths.\n */ \n double edge_weight = w_prng();\n boost::put (dist_map, child, edge_weight);\n boost::put (weight_map, \n (boost::add_edge (parent, child, G)).first,\n edge_weight);\n\n --n_left;\n }\n\n#pragma omp critical\n if (1\n static graph_type generate_tree_stupid (int n,\n int seed,\n ProbabilityComputer compute,\n bool use_random_weights,\n int verbosity) {\n // This is the stupid way of generating the required random tree.\n // We simply want to fill up the tree as long as it has at least\n // the required number of nodes, we are happy. Please use it only\n // as a counter example.\n\n // A vector to hold the number of children for each node\n std::vector psi_vec (n, 0);\n\n // Get a new random engine\n engine_type engine(seed);\n\n // Get the distribution that we are interested in\n typename ProbabilityComputer::dist_type prng = compute();\n\n // Now, all we need to do is iterate over and over again\n int num_children;\n do {\n\n // Start with 0 edges in the beginning\n num_children = 0;\n\n // Loop to assign edges/children to nodes\n for (int i=0; \n (num_children<(n-1)) && (i (n-1)) {\n num_children_for_i = (n-1) - num_children;\n }\n\n num_children += num_children_for_i;\n psi_vec[i] = num_children_for_i; \n }\n\n } while (num_children != (n-1));\n\n random_functor_t shuffle_prng (engine);\n std::random_shuffle (psi_vec.begin(), psi_vec.end(), shuffle_prng);\n\n if (2 \n w_prng (engine_type(), uni_real_type(0.0,1.0));\n return generate_impl (n, psi_vec, w_prng, verbosity);\n } else {\n return generate_impl (n, psi_vec, always_1_t(), verbosity);\n }\n }\n\n template \n static graph_type generate_tree (int n,\n int seed,\n ProbabilityComputer compute,\n bool use_random_weights,\n int verbosity) {\n\n std::vector N_j_vec;\n engine_type engine(seed);\n int j_times_N_j, j;\n\n do {\n\n j_times_N_j = j = 0;\n int sum_of_N_i = 0;\n int i = 0;\n double sum_of_p_i = 0;\n N_j_vec.resize(0);\n while (0 != (n-sum_of_N_i)) {\n const double p_i = compute(i);\n engine_type new_engine(engine());\n binomial_type dist((n-sum_of_N_i), p_i/(1-sum_of_p_i));\n const int N_j = dist(new_engine);\n N_j_vec.push_back (N_j);\n sum_of_N_i += N_j;\n sum_of_p_i += p_i;\n j_times_N_j += j*N_j;\n ++i;\n ++j;\n }\n\n if (2 < verbosity) std::cout << \"j*N_j = \" << j_times_N_j << std::endl;\n\n } while (j_times_N_j != (n-1));\n\n std::vector psi_vec (n, 0);\n int offset = 0;\n for (int j=0; j \n w_prng (engine_type(), uni_real_type(0.0,1.0));\n return generate_impl (n, psi_vec, w_prng, verbosity);\n } else {\n return generate_impl (n, psi_vec, always_1_t(), verbosity);\n }\n }\n\n template \n static graph_type generate_tree_dispatcher (int n,\n int seed,\n ProbabilityComputer compute,\n bool use_random_weights,\n int verbosity,\n bool use_stupid_tree_gen) {\n if (use_stupid_tree_gen) {\n return generate_tree_stupid (n, seed, compute, use_random_weights, \n verbosity);\n } else {\n return generate_tree (n, seed, compute, use_random_weights, verbosity);\n }\n }\n\n public:\n\n static graph_type generate_Poisson (int n,\n int seed,\n int lambda,\n bool use_random_weights,\n int verbosity,\n bool use_stupid_tree_gen) {\n return generate_tree_dispatcher (n, seed, Poisson_computer_t(lambda), \n use_random_weights, verbosity, use_stupid_tree_gen);\n }\n\n static graph_type generate_Geometric (int n,\n int seed,\n double p,\n bool use_random_weights,\n int verbosity,\n bool use_stupid_tree_gen) {\n return generate_tree_dispatcher (n, seed, geometric_computer_t(p), \n use_random_weights, verbosity, use_stupid_tree_gen);\n }\n\n static graph_type generate_Binomial (int n,\n int seed,\n int k,\n double p,\n bool use_random_weights,\n int verbosity,\n bool use_stupid_tree_gen) {\n return generate_tree_dispatcher (n, seed, binomial_computer_t(k, p), \n use_random_weights, verbosity, use_stupid_tree_gen);\n }\n\n static graph_type generate_Binary_0_2 (int n,\n int seed,\n double p,\n bool use_random_weights,\n int verbosity,\n bool use_stupid_tree_gen) {\n return generate_tree_dispatcher (n, seed, binary_0_2_computer_t(p),\n use_random_weights, verbosity, use_stupid_tree_gen);\n }\n\n static graph_type generate_Binary_0_1_2 (int n,\n int seed,\n bool use_random_weights,\n int verbosity,\n bool use_stupid_tree_gen) {\n return generate_tree_dispatcher (n, seed, binary_0_1_2_computer_t(), \n use_random_weights, verbosity, use_stupid_tree_gen);\n }\n};\n\n#endif // GENERATE_GALTON_WATSON_HPP\n", "meta": {"hexsha": "e1838fb6bfb22115e913bc166063452c58a93c20", "size": 14679, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "generate_Galton_Watson.hpp", "max_stars_repo_name": "karthikbharath/Trees_DyckPaths", "max_stars_repo_head_hexsha": "6fc9b5e603aa8bb89cb68964a06d3992f32085a7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "generate_Galton_Watson.hpp", "max_issues_repo_name": "karthikbharath/Trees_DyckPaths", "max_issues_repo_head_hexsha": "6fc9b5e603aa8bb89cb68964a06d3992f32085a7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generate_Galton_Watson.hpp", "max_forks_repo_name": "karthikbharath/Trees_DyckPaths", "max_forks_repo_head_hexsha": "6fc9b5e603aa8bb89cb68964a06d3992f32085a7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.0580046404, "max_line_length": 80, "alphanum_fraction": 0.5620955106, "num_tokens": 3410, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038784, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6547711264511651}} {"text": "// Copyright (c) 2009 INRIA Sophia-Antipolis (France).\n// All rights reserved.\n//\n// This file is part of CGAL (www.cgal.org)\n//\n// $URL$\n// $Id$\n// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial\n// \n//\n// Author(s) : Sebastien Loriot, Sylvain Pion\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace CGAL_pca{\n\n//~ typedef CGAL::Exact_predicates_exact_constructions_kernel Kernel;\ntypedef CGAL::Simple_cartesian Kernel;\n \nconst std::string Slab[] = {\n \"PCA\",\"Help\"\n};\n\nconst std::string Hmsg[] = {\n \"(Principal Component Analysis) given a set of points, draw a segment that is on the line defined by the eigen vector associated to the highest eigen value of the covariance matrix of the input points\"\n};\n\nclass pcaIpelet \n : public CGAL::Ipelet_base{\npublic:\n pcaIpelet()\n :CGAL::Ipelet_base(\"PCA\",Slab,Hmsg){}\n void protected_run(int);\n};\n\n\nvoid pcaIpelet::protected_run(int fn)\n{\n if (fn==1) {\n show_help();\n return;\n }\n\n \n std::list pt_list;\n std::list cir_list;\n std::list poly_list;\n std::list tri_list;\n std::list sg_list;\n \n Iso_rectangle_2 bbox=\n read_active_objects(\n CGAL::dispatch_or_drop_output(\n std::back_inserter(pt_list),\n std::back_inserter(poly_list),\n std::back_inserter(cir_list),\n std::back_inserter(sg_list)\n )\n );\n\n \n \n for (std::list::iterator it=poly_list.begin();it!=poly_list.end();++it)\n if (it->size()==3){\n tri_list.push_back(Kernel::Triangle_2(*(it->vertices_begin()),\n *boost::next(it->vertices_begin()),\n *boost::next(it->vertices_begin(),2)\n ));\n }\n else{\n print_error_message(\"This implementation is limited to triangles\");\n return; \n }\n \n \n int s=0;\n \n if (!pt_list.empty()) s=1;\n if (!cir_list.empty()) s+=2;\n if (!tri_list.empty()) s+=4;\n if (!sg_list.empty()) s+=8;\n \n \n if (s==0) {\n print_error_message(\"Nothing is selected\");\n return;\n }\n \n \n Kernel::Line_2 line;\n Kernel::Point_2 centroid;\n \n switch (s){\n case 1://points\n linear_least_squares_fitting_2(pt_list.begin(),pt_list.end(),line,centroid,CGAL::Dimension_tag<0>());\n break;\n case 2://circles\n linear_least_squares_fitting_2(cir_list.begin(),cir_list.end(),line,centroid,CGAL::Dimension_tag<2>());\n break;\n case 4://triangles\n linear_least_squares_fitting_2(tri_list.begin(),tri_list.end(),line,centroid,CGAL::Dimension_tag<2>());\n break;\n case 8://segments\n linear_least_squares_fitting_2(sg_list.begin(),sg_list.end(),line,centroid,CGAL::Dimension_tag<1>());\n break; \n default:\n print_error_message(\"Please select a set of points or segments or triangles or circles\");\n return; \n }\n \n \n \n CGAL::Object obj_cgal = CGAL::intersection(line,bbox);\n Segment_2 seg;\n if (CGAL::assign(seg, obj_cgal))\n draw_in_ipe(seg);\n\n \n\n}\n\n}\n\nCGAL_IPELET(CGAL_pca::pcaIpelet)\n\n", "meta": {"hexsha": "0f8a61f87b6fd68c009b90b08763dd8250e1f80f", "size": 3370, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CoreSystem/lib/CGAL/demo/CGAL_ipelets/pca.cpp", "max_stars_repo_name": "josuehfa/DAASystem", "max_stars_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T01:13:02.000Z", "max_stars_repo_stars_event_max_datetime": "2020-03-17T01:13:02.000Z", "max_issues_repo_path": "CoreSystem/lib/CGAL/demo/CGAL_ipelets/pca.cpp", "max_issues_repo_name": "josuehfa/DAASystem", "max_issues_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CoreSystem/lib/CGAL/demo/CGAL_ipelets/pca.cpp", "max_forks_repo_name": "josuehfa/DAASystem", "max_forks_repo_head_hexsha": "a1fe61ffc19f0781eeeddcd589137eefde078a45", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-02T11:11:36.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T11:11:36.000Z", "avg_line_length": 25.9230769231, "max_line_length": 203, "alphanum_fraction": 0.6400593472, "num_tokens": 924, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7185943985973772, "lm_q1q2_score": 0.6547686357300774}} {"text": "/*\n * Copyright 2011-2013 Mario Mulansky\n * Copyright 2012 Karsten Ahnert\n *\n * Distributed under the Boost Software License, Version 1.0.\n * (See accompanying file LICENSE_1_0.txt or\n * copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n\n\n#include \n\n#include \n#include \n\ntypedef boost::numeric::ublas::vector< double > state_type;\n\nvoid lorenz( const state_type &x , state_type &dxdt , const double t )\n{\n const double sigma( 10.0 );\n const double R( 28.0 );\n const double b( 8.0 / 3.0 );\n \n dxdt[0] = sigma * ( x[1] - x[0] );\n dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n dxdt[2] = -b * x[2] + x[0] * x[1];\n}\n\nusing namespace boost::numeric::odeint;\n\n//[ublas_main\nint main()\n{\n state_type x(3);\n x[0] = 10.0; x[1] = 5.0 ; x[2] = 0.0;\n typedef runge_kutta_dopri5< state_type > stepper;\n integrate_const( make_dense_output< stepper >( 1E-6 , 1E-6 ) , lorenz , x ,\n 0.0 , 10.0 , 0.1 );\n}\n//]\n", "meta": {"hexsha": "0e3958d07bc6a071f278731e0bdf3ae0bb2ae346", "size": 1009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/odeint/examples/ublas/lorenz_ublas.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/numeric/odeint/examples/ublas/lorenz_ublas.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/numeric/odeint/examples/ublas/lorenz_ublas.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 24.6097560976, "max_line_length": 79, "alphanum_fraction": 0.6075322101, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.654768623014384}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"mnist/reader.hpp\"\n#include \"perceptron/PerceptronMonoLayer.hpp\"\n#include \"perceptron/act_funs.hpp\"\n#include \"perceptron/ItemNN.hpp\"\n\nusing namespace cv;\nusing namespace boost;\nusing namespace boost::numeric;\nusing namespace std;\n\n\nvoid randomizeMatrix(boost::numeric::ublas::matrix &matrix);\n\nvoid randomizeVector(boost::numeric::ublas::vector &vect);\n\n\nublas::vector imageToVector(cv::Mat const &mat) {\n size_t nbPixels = mat.rows * mat.cols;\n ublas::vector v(nbPixels);\n for (size_t i = 0; i < nbPixels; i++) {\n auto a = (double) mat.at(i);\n v.insert_element(i, a>(255./2.)?1:0);\n }\n return v;\n}\n\nint main(int argc, char ** argv) {\n\n using namespace boost::numeric::ublas;\n\n int numCycles;\n if(argc > 1)\n numCycles = atoi(argv[1]);\n else\n numCycles =25;\n\n\n double (*seuil)(double) = act_f::noActFun;\n\n\n string filename = \"../res/train-images-idx3-ubyte\";\n size_t image_size = 28 * 28;\n\n std::vector vec_entrees;\n std::vector vec_labels;\n std::vector vec_entrees_test;\n std::vector vec_labels_test;\n read_Mnist(filename, vec_entrees);\n read_Mnist_Label(\"../res/train-labels-idx1-ubyte\", vec_labels);\n read_Mnist(\"../res/t10k-images-idx3-ubyte\", vec_entrees_test);\n read_Mnist_Label(\"../res/t10k-labels-idx1-ubyte\", vec_labels_test);\n\n std::vector> vec_train;\n for (int i = 0; i < vec_entrees.size(); ++i) {\n vec_train.emplace_back(vec_labels[i], vec_entrees[i], imageToVector);\n }\n vec_entrees.clear();\n vec_labels.clear();\n std::vector> vec_test;\n for (int i = 0; i < vec_entrees_test.size(); ++i) {\n vec_test.emplace_back(vec_labels_test[i], vec_entrees_test[i], imageToVector);\n }\n vec_entrees_test.clear();\n vec_labels_test.clear();\n\n std::vector neuronnes;\n for (int i = 0; i < 10; ++i) {\n ublas::vector weigthN(image_size);\n randomizeVector(weigthN);\n neuronnes.emplace_back(weigthN, seuil);\n }\n\n\n PerceptronMonoLayer perceptronMonoLayer(neuronnes);\n perceptronMonoLayer.learn(vec_train,numCycles);\n cout << \"End of learning\" << endl;\n cout << \"Begin tests\" << endl;\n perceptronMonoLayer.test(vec_test);\n\n neuronnes.clear();\n\n cv::Mat imageTest = imread(\"../res/test.png\",cv::ImreadModes::IMREAD_GRAYSCALE);\n\n ItemNN itemNN(5,imageTest,imageToVector);\n\n cout << \"test with gimp image(5):\" <<(\n perceptronMonoLayer.test(itemNN)? \"true\":\"false\") << endl;\n\n\n return 0;\n}\n\n/**\n * Fonction qui permet d'initialiser un vecteur a des poids aléatoires\n * entre -1 et 1\n * @param vect à initialiser\n */\nvoid randomizeVector(boost::numeric::ublas::vector &vect) {\n std::random_device rd;\n std::mt19937 mt(rd());\n std::uniform_real_distribution dist(0, 1);\n\n for (size_t i = 0; i < vect.size(); i++) {\n vect(i) = dist(mt);\n }\n}\n\n\n", "meta": {"hexsha": "6cd0ea62f35106a948d6e28802d768112dceb589", "size": 3318, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "SamBlaise/perceptron_cpp", "max_stars_repo_head_hexsha": "e2a7375f8254e2f683454f42e4c9089d99e59d66", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "SamBlaise/perceptron_cpp", "max_issues_repo_head_hexsha": "e2a7375f8254e2f683454f42e4c9089d99e59d66", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-07T21:44:33.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-13T23:10:24.000Z", "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "SamBlaise/perceptron_cpp", "max_forks_repo_head_hexsha": "e2a7375f8254e2f683454f42e4c9089d99e59d66", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1186440678, "max_line_length": 86, "alphanum_fraction": 0.6681735986, "num_tokens": 931, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237604, "lm_q2_score": 0.7185943805178139, "lm_q1q2_score": 0.6547686209895519}} {"text": "#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#if !defined(max)\n#define max(a, b) (a > b ? a : b)\n#endif\n\n#if !defined(min)\n#define min(a, b) (a < b ? a : b)\n#endif\n\n#define NSTATES 9\ntypedef std::array StateType;\n\n// odeing namespace access\nnamespace odeint = boost::numeric::odeint;\n\nSEIR::SEIR()\n : R0Table_(), Tinc_(2.5), Tinf_(5.0), Tfat_(30), Tmrec_(12), Threc_(30),\n pMild_(0.8), pFat_(0.01), duration_(300), population_(1000000), dt_(1),\n Hc_(1), pfat_increase_nohospital_(1.0)\n{\n SetR0(2.5);\n}\n\nstatic bool operator<(const R0TableElement &a, const R0TableElement &b)\n{\n return (a.time < b.time);\n}\n\nvoid SEIR::SetR0(double R0, double time)\n{\n if (time < 0) {\n R0Table_.clear();\n R0Table_.push_back(R0TableElement(R0, 0));\n return;\n }\n R0Table_.push_back(R0TableElement(R0, time));\n R0Table_.sort();\n}\n\nResultsType SEIR::compute(void)\n{\n StateType state0;\n memset(state0.data(), 0, sizeof(double) * NSTATES);\n state0[0] = 1.0;\n state0[1] = 1.0 / (double)population_;\n\n typedef odeint::runge_kutta_cash_karp54\n error_stepper_type;\n typedef odeint::controlled_runge_kutta\n controlled_stepper_type;\n // typedef odeint::dense_output_runge_kutta\n // dense_stepper_type;\n\n // Create an output\n double nsteps = (double)duration_ / (double)dt_;\n if (::fmod(nsteps, 1.0) < std::numeric_limits::epsilon())\n nsteps = nsteps + 1;\n else\n nsteps = ::ceil(nsteps);\n\n ResultsType results;\n results.resize((int)nsteps);\n uint32_t counter = 0;\n\n error_stepper_type stepper;\n odeint::integrate_const(\n stepper,\n [this](const StateType &state, StateType &statedot, double t) {\n // statedot.resize(NSTATES);\n\n double S = state[0]; // susceptible\n double E = state[1]; // exposed\n double Inf = state[2]; // Infectious\n double M = state[3]; // Mild case\n double Hrec = state[4];\n double Hfat = state[5];\n\n // Probability of fatal given hospitalized\n // and sufficient hospital capacity\n double pfs_hos = pFat_ / (1.0 - pMild_);\n\n // Probability of fatal given hospitalized,\n // and no hospital capacity\n double pfs_nohos = pfs_hos * (1.0 + pfat_increase_nohospital_);\n\n // weighted probability of fatal\n // given hospital capacity\n double H = Hrec + Hfat;\n double pfs = pfs_hos;\n if ((H > Hc_) && (H > 0)) {\n pfs = (Hc_ / H) * pfs_hos + (H - Hc_) / H * pfs_nohos;\n }\n\n // Get the current R0 from the table\n auto upper = std::lower_bound(R0Table_.begin(), R0Table_.end(),\n R0TableElement(0, t));\n //[](const R0TableElement &a, double b) { return a.second < b; });\n if (upper != R0Table_.begin())\n upper--;\n double R0 = upper->R0;\n\n // Update time derivates:\n\n // Susceptible population:\n // out: susceptible to exposed\n auto dS = -R0 / Tinf_ * Inf * S;\n // Exposed population:\n // in: susceptible to exposed\n // out: exposed to infectious\n auto dE = -dS - E / Tinc_;\n // Infectious population:\n // in: exposed to infectious\n // out: infectious to mild or hospital\n auto dI = E / Tinc_ - Inf / Tinf_;\n // Mild case population:\n // in: infectious to mild\n // out: mild to recovered (removed)\n auto dM = pMild_ * Inf / Tinf_ - M / Tmrec_;\n // Hospitalized population that will recover\n // in: infectious to hospitalized\n // out: hospitalized to recovered\n auto dHrec =\n (1.0 - pMild_) * (1.0 - pfs) * Inf / Tinf_ - Hrec / Threc_;\n // Hospitalized population that will not recover\n // in: infectious to hospitalized\n // out: hospitalized to fatal\n auto dHfat = (1.0 - pMild_) * pfs * Inf / Tinf_ - Hfat / Tfat_;\n // Fatal population:\n // in: hospitalized to fatal\n auto dF = Hfat / Tfat_;\n // Removed population:\n // in: mild to recovered\n // in: hospitalized to recovered\n auto dRm = M / Tmrec_;\n auto dRh = Hrec / Threc_;\n\n statedot[0] = dS;\n statedot[1] = dE;\n statedot[2] = dI;\n statedot[3] = dM;\n statedot[4] = dHrec;\n statedot[5] = dHfat;\n statedot[6] = dF;\n statedot[7] = dRm;\n statedot[8] = dRh;\n },\n state0, 0.0, (double)duration_, dt_,\n [this, &counter, &results](const StateType &s, double t) {\n results[counter] = std::vector(s.begin(), s.end());\n counter++;\n });\n\n // Multiply results by population\n double population = this->population_;\n for (auto &res : results) {\n std::transform(res.begin(), res.end(), res.begin(),\n [population](double &c) { return population * c; });\n }\n return results;\n}\n\n#if 0\nint main(int argc, char *argv[])\n{\n SEIR seir;\n seir.Hc_ = .001;\n seir.R0Table_.clear();\n seir.R0Table_.push_back(R0TableElement(4.5, 0));\n seir.R0Table_.push_back(R0TableElement(1.5, 150));\n\n auto results = seir.compute();\n auto lr = results[results.size() - 1];\n#if 0\n for (int i = 0; i < NSTATES; i++) {\n std::cout << lr[i] << std::endl;\n }\n#endif\n return 0;\n}\n#endif\n", "meta": {"hexsha": "ce2b60b59f731e1d0ba8b2da28f4245eee0a9c31", "size": 5923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/seir.cpp", "max_stars_repo_name": "StevenSamirMichael/SEIR", "max_stars_repo_head_hexsha": "ba4f2e493eee51de7bb366e53696a3f67909a9db", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-09-29T15:43:33.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-29T15:43:33.000Z", "max_issues_repo_path": "src/seir.cpp", "max_issues_repo_name": "StevenSamirMichael/SEIR", "max_issues_repo_head_hexsha": "ba4f2e493eee51de7bb366e53696a3f67909a9db", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2021-12-30T16:55:43.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-30T16:55:44.000Z", "max_forks_repo_path": "src/seir.cpp", "max_forks_repo_name": "StevenSamirMichael/SEIR", "max_forks_repo_head_hexsha": "ba4f2e493eee51de7bb366e53696a3f67909a9db", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.0104712042, "max_line_length": 78, "alphanum_fraction": 0.5461759244, "num_tokens": 1624, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.654760080136677}} {"text": "#include \"k_points_util.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \"../array_math.h\"\n\nint KPointsUtil::get_n_k_points(const double rcut) {\n int count = 0;\n const int n_max = std::floor(static_cast(rcut));\n double rcut_square = rcut * rcut;\n for (int i = -n_max; i <= n_max; i++) {\n for (int j = -n_max; j <= n_max; j++) {\n for (int k = -n_max; k <= n_max; k++) {\n if (i * i + j * j + k * k > rcut_square) continue;\n count++;\n }\n }\n }\n return count;\n}\n\nstd::vector> KPointsUtil::generate_k_points(\n const double rcut) {\n std::vector> k_points;\n const int n_max = std::floor(static_cast(rcut));\n assert(n_max < 127);\n double rcut_square = rcut * rcut;\n for (int i = -n_max; i <= n_max; i++) {\n for (int j = -n_max; j <= n_max; j++) {\n for (int k = -n_max; k <= n_max; k++) {\n if (i * i + j * j + k * k > rcut_square) continue;\n k_points.push_back(std::array({static_cast(i),\n static_cast(j),\n static_cast(k)}));\n }\n }\n }\n std::stable_sort(\n k_points.begin(),\n k_points.end(),\n [](const auto& a, const auto& b) -> bool {\n return squared_norm(a) < squared_norm(b);\n });\n return k_points;\n}\n\nstd::vector> KPointsUtil::get_k_diffs(\n const std::vector>& k_points) {\n // Generate all possible differences between two different k points.\n std::unordered_set, boost::hash>>\n k_diffs_set;\n std::vector> k_diffs;\n const int n_k_points = k_points.size();\n for (int p = 0; p < n_k_points; p++) {\n for (int q = 0; q < n_k_points; q++) {\n if (p == q) continue;\n const auto& diff_pq = k_points[q] - k_points[p];\n if (k_diffs_set.count(diff_pq) == 1) continue;\n k_diffs.push_back(diff_pq);\n k_diffs_set.insert(diff_pq);\n }\n }\n\n // Sort k_diffs into ascending order so that later sorting hci queue will be\n // faster.\n std::stable_sort(\n k_diffs.begin(), k_diffs.end(), [](const auto& a, const auto& b) -> bool {\n return squared_norm(a) < squared_norm(b);\n });\n\n return k_diffs;\n}", "meta": {"hexsha": "25599e29ba8c9a8e3e5daaa6111bc765f4776a21", "size": 2423, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/heg/k_points_util.cc", "max_stars_repo_name": "jl2922/hci", "max_stars_repo_head_hexsha": "2806ad1f2cc0e100632eaaaf491670f928c9feec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-09-23T17:52:52.000Z", "max_stars_repo_stars_event_max_datetime": "2017-11-01T20:15:01.000Z", "max_issues_repo_path": "src/heg/k_points_util.cc", "max_issues_repo_name": "jl2922/hci", "max_issues_repo_head_hexsha": "2806ad1f2cc0e100632eaaaf491670f928c9feec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2017-09-24T14:29:03.000Z", "max_issues_repo_issues_event_max_datetime": "2017-09-24T14:44:12.000Z", "max_forks_repo_path": "src/heg/k_points_util.cc", "max_forks_repo_name": "jl2922/hci", "max_forks_repo_head_hexsha": "2806ad1f2cc0e100632eaaaf491670f928c9feec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.3066666667, "max_line_length": 80, "alphanum_fraction": 0.5827486587, "num_tokens": 726, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6547196418381726}} {"text": "#ifndef COORDINATE_CALCULATION\n#define COORDINATE_CALCULATION\n\n#include \"util/coordinate.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace osrm\n{\nnamespace util\n{\nnamespace coordinate_calculation\n{\n\nnamespace detail\n{\nconst constexpr double DEGREE_TO_RAD = 0.017453292519943295769236907684886;\nconst constexpr double RAD_TO_DEGREE = 1. / DEGREE_TO_RAD;\n\ninline double degToRad(const double degree)\n{\n using namespace boost::math::constants;\n return degree * (pi() / 180.0);\n}\n\ninline double radToDeg(const double radian)\n{\n using namespace boost::math::constants;\n return radian * (180.0 * (1. / pi()));\n}\n}\n\n//! Takes the squared euclidean distance of the input coordinates. Does not return meters!\nstd::uint64_t squaredEuclideanDistance(const Coordinate lhs, const Coordinate rhs);\n\ndouble fccApproximateDistance(const Coordinate first_coordinate,\n const Coordinate second_coordinate);\n\ndouble haversineDistance(const Coordinate first_coordinate, const Coordinate second_coordinate);\n\ndouble greatCircleDistance(const Coordinate first_coordinate, const Coordinate second_coordinate);\n\n// get the length of a full coordinate vector, using one of our basic functions to compute distances\ntemplate \ndouble getLength(iterator_type begin, const iterator_type end, BinaryOperation op);\n\n// Find the closest distance and location between coordinate and the line connecting source and\n// target:\n// coordinate\n// |\n// |\n// source -------- x -------- target.\n// returns x as well as the distance between source and x as ratio ([0,1])\ninline std::pair projectPointOnSegment(const FloatCoordinate &source,\n const FloatCoordinate &target,\n const FloatCoordinate &coordinate);\n\n// find the closest distance between a coordinate and a segment\n// O(1)\ndouble findClosestDistance(const Coordinate coordinate,\n const Coordinate segment_begin,\n const Coordinate segment_end);\n\n// find the closest distance between a coordinate and a set of coordinates\n// O(|coordinates|)\ntemplate \ndouble findClosestDistance(const Coordinate coordinate,\n const iterator_type begin,\n const iterator_type end);\n\n// find the closes distance between two sets of coordinates\n// O(|lhs| * |rhs|)\ntemplate \ndouble findClosestDistance(const iterator_type lhs_begin,\n const iterator_type lhs_end,\n const iterator_type rhs_begin,\n const iterator_type rhs_end);\n\n// checks if two sets of coordinates describe a parallel set of ways\ntemplate \nbool areParallel(const iterator_type lhs_begin,\n const iterator_type lhs_end,\n const iterator_type rhs_begin,\n const iterator_type rhs_end);\n\ndouble perpendicularDistance(const Coordinate segment_source,\n const Coordinate segment_target,\n const Coordinate query_location);\n\ndouble perpendicularDistance(const Coordinate segment_source,\n const Coordinate segment_target,\n const Coordinate query_location,\n Coordinate &nearest_location,\n double &ratio);\n\nCoordinate centroid(const Coordinate lhs, const Coordinate rhs);\n\ndouble bearing(const Coordinate first_coordinate, const Coordinate second_coordinate);\n\n// Get angle of line segment (A,C)->(C,B)\ndouble computeAngle(const Coordinate first, const Coordinate second, const Coordinate third);\n\n// find the center of a circle through three coordinates\nboost::optional circleCenter(const Coordinate first_coordinate,\n const Coordinate second_coordinate,\n const Coordinate third_coordinate);\n\n// find the radius of a circle through three coordinates\ndouble circleRadius(const Coordinate first_coordinate,\n const Coordinate second_coordinate,\n const Coordinate third_coordinate);\n\n// factor in [0,1]. Returns point along the straight line between from and to. 0 returns from, 1\n// returns to\nCoordinate interpolateLinear(double factor, const Coordinate from, const Coordinate to);\n\n// compute the signed area of a triangle\ndouble signedArea(const Coordinate first_coordinate,\n const Coordinate second_coordinate,\n const Coordinate third_coordinate);\n\n// check if a set of three coordinates is given in CCW order\nbool isCCW(const Coordinate first_coordinate,\n const Coordinate second_coordinate,\n const Coordinate third_coordinate);\n\ntemplate \nstd::pair leastSquareRegression(const iterator_type begin,\n const iterator_type end);\n\n// rotates a coordinate around the point (0,0). This function can be used to normalise a few\n// computations around regression vectors\nCoordinate rotateCCWAroundZero(Coordinate coordinate, double angle_in_radians);\n\n// compute the difference vector of two coordinates lhs - rhs\nCoordinate difference(const Coordinate lhs, const Coordinate rhs);\n\n// TEMPLATE/INLINE DEFINITIONS\ninline std::pair 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(slope_vector.lon * rel_coordinate.lon) +\n static_cast(slope_vector.lat * rel_coordinate.lat);\n // squared length of the slope vector\n const auto squared_length = static_cast(slope_vector.lon * slope_vector.lon) +\n static_cast(slope_vector.lat * slope_vector.lat);\n\n if (squared_length < std::numeric_limits::epsilon())\n {\n return {0, source};\n }\n\n const double normed_ratio = unnormed_ratio / squared_length;\n double clamped_ratio = normed_ratio;\n if (clamped_ratio > 1.)\n {\n clamped_ratio = 1.;\n }\n else if (clamped_ratio < 0.)\n {\n clamped_ratio = 0.;\n }\n\n return {clamped_ratio,\n {\n FloatLongitude{1.0 - clamped_ratio} * source.lon +\n target.lon * FloatLongitude{clamped_ratio},\n FloatLatitude{1.0 - clamped_ratio} * source.lat +\n target.lat * FloatLatitude{clamped_ratio},\n }};\n}\n\ntemplate \ndouble getLength(iterator_type begin, const iterator_type end, BinaryOperation op)\n{\n double result = 0;\n const auto functor = [&result, op](const Coordinate lhs, const Coordinate rhs) {\n result += op(lhs, rhs);\n return false;\n };\n // side-effect find adding up distances\n std::adjacent_find(begin, end, functor);\n\n return result;\n}\n\ntemplate \ndouble\nfindClosestDistance(const Coordinate coordinate, const iterator_type begin, const iterator_type end)\n{\n double current_min = std::numeric_limits::max();\n\n // comparator updating current_min without ever finding an element\n const auto compute_minimum_distance = [¤t_min, coordinate](const Coordinate lhs,\n const Coordinate rhs) {\n current_min = std::min(current_min, findClosestDistance(coordinate, lhs, rhs));\n return false;\n };\n\n std::adjacent_find(begin, end, compute_minimum_distance);\n return current_min;\n}\n\ntemplate \ndouble findClosestDistance(const iterator_type lhs_begin,\n const iterator_type lhs_end,\n const iterator_type rhs_begin,\n const iterator_type rhs_end)\n{\n double current_min = std::numeric_limits::max();\n\n const auto compute_minimum_distance_in_rhs = [¤t_min, rhs_begin, rhs_end](\n const Coordinate coordinate) {\n current_min = std::min(current_min, findClosestDistance(coordinate, rhs_begin, rhs_end));\n return false;\n };\n\n std::find_if(lhs_begin, lhs_end, compute_minimum_distance_in_rhs);\n return current_min;\n}\n\ntemplate \nstd::pair leastSquareRegression(const iterator_type begin,\n const iterator_type end)\n{\n // following the formulas of https://faculty.elgin.edu/dkernler/statistics/ch04/4-2.html\n const auto number_of_coordinates = std::distance(begin, end);\n BOOST_ASSERT(number_of_coordinates >= 2);\n const auto extract_lon = [](const Coordinate coordinate) {\n return static_cast(toFloating(coordinate.lon));\n };\n\n const auto extract_lat = [](const Coordinate coordinate) {\n return static_cast(toFloating(coordinate.lat));\n };\n\n double min_lon = extract_lon(*begin);\n double max_lon = extract_lon(*begin);\n double min_lat = extract_lat(*begin);\n double max_lat = extract_lat(*begin);\n\n for (auto coordinate_iterator = begin; coordinate_iterator != end; ++coordinate_iterator)\n {\n const auto c = *coordinate_iterator;\n const auto lon = extract_lon(c);\n min_lon = std::min(min_lon, lon);\n max_lon = std::max(max_lon, lon);\n const auto lat = extract_lat(c);\n min_lat = std::min(min_lat, lat);\n max_lat = std::max(max_lat, lat);\n }\n // very small difference in longitude -> would result in inaccurate calculation, check if lat is\n // better\n if ((max_lat - min_lat) > 2 * (max_lon - min_lon))\n {\n std::vector rotated_coordinates(number_of_coordinates);\n // rotate all coordinates to the right\n std::transform(begin, end, rotated_coordinates.begin(), [](const auto coordinate) {\n return rotateCCWAroundZero(coordinate, detail::degToRad(-90));\n });\n const auto rotated_regression =\n leastSquareRegression(rotated_coordinates.begin(), rotated_coordinates.end());\n return {rotateCCWAroundZero(rotated_regression.first, detail::degToRad(90)),\n rotateCCWAroundZero(rotated_regression.second, detail::degToRad(90))};\n }\n\n const auto make_accumulate = [](const auto extraction_function) {\n return [extraction_function](const double sum_so_far, const Coordinate coordinate) {\n return sum_so_far + extraction_function(coordinate);\n };\n };\n\n const auto accumulated_lon = std::accumulate(begin, end, 0., make_accumulate(extract_lon));\n\n const auto accumulated_lat = std::accumulate(begin, end, 0., make_accumulate(extract_lat));\n\n const auto mean_lon = accumulated_lon / number_of_coordinates;\n const auto mean_lat = accumulated_lat / number_of_coordinates;\n const auto make_variance = [](const auto mean, const auto extraction_function) {\n return [extraction_function, mean](const double sum_so_far, const Coordinate coordinate) {\n const auto difference = extraction_function(coordinate) - mean;\n return sum_so_far + difference * difference;\n };\n };\n\n // using the unbiased version, we divide by num_samples - 1 (see\n // http://mathworld.wolfram.com/SampleVariance.html)\n const auto sample_variance_lon =\n std::sqrt(std::accumulate(begin, end, 0., make_variance(mean_lon, extract_lon)) /\n (number_of_coordinates - 1));\n\n // if we don't change longitude, return the vertical line as is\n if (std::abs(sample_variance_lon) <\n std::numeric_limits::epsilon())\n return {*begin, *(end - 1)};\n\n const auto sample_variance_lat =\n std::sqrt(std::accumulate(begin, end, 0., make_variance(mean_lat, extract_lat)) /\n (number_of_coordinates - 1));\n\n if (std::abs(sample_variance_lat) <\n std::numeric_limits::epsilon())\n return {*begin, *(end - 1)};\n const auto linear_correlation =\n std::accumulate(begin,\n end,\n 0.,\n [&](const auto sum_so_far, const auto current_coordinate) {\n return sum_so_far +\n (extract_lon(current_coordinate) - mean_lon) *\n (extract_lat(current_coordinate) - mean_lat) /\n (sample_variance_lon * sample_variance_lat);\n }) /\n (number_of_coordinates - 1);\n\n const auto slope = linear_correlation * sample_variance_lat / sample_variance_lon;\n const auto intercept = mean_lat - slope * mean_lon;\n\n const auto GetLatAtLon = [intercept,\n slope](const util::FloatLongitude longitude) -> util::FloatLatitude {\n return {intercept + slope * static_cast((longitude))};\n };\n\n const double offset = 0.00001;\n const Coordinate regression_first = {\n toFixed(util::FloatLongitude{min_lon - offset}),\n toFixed(util::FloatLatitude(GetLatAtLon(util::FloatLongitude{min_lon - offset})))};\n const Coordinate regression_end = {\n toFixed(util::FloatLongitude{max_lon + offset}),\n toFixed(util::FloatLatitude(GetLatAtLon(util::FloatLongitude{max_lon + offset})))};\n\n return {regression_first, regression_end};\n}\n\ntemplate \nbool areParallel(const iterator_type lhs_begin,\n const iterator_type lhs_end,\n const iterator_type rhs_begin,\n const iterator_type rhs_end)\n{\n const auto regression_lhs = leastSquareRegression(lhs_begin, lhs_end);\n const auto regression_rhs = leastSquareRegression(rhs_begin, rhs_end);\n\n const auto null_island = Coordinate(FixedLongitude{0}, FixedLatitude{0});\n const auto difference_lhs = difference(regression_lhs.first, regression_lhs.second);\n const auto difference_rhs = difference(regression_rhs.first, regression_rhs.second);\n\n // we normalise the left slope to be zero, so we rotate the coordinates around 0,0 to match 90\n // degrees\n const auto bearing_lhs = bearing(null_island, difference_lhs);\n\n // we rotate to have one of the lines facing horizontally to the right (bearing 90 degree)\n const auto rotation_angle_radians = detail::degToRad(bearing_lhs - 90);\n const auto rotated_difference_rhs = rotateCCWAroundZero(difference_rhs, rotation_angle_radians);\n\n const auto get_slope = [](const Coordinate from, const Coordinate to) {\n const auto diff_lat = static_cast(from.lat) - static_cast(to.lat);\n const auto diff_lon = static_cast(from.lon) - static_cast(to.lon);\n if (diff_lon == 0)\n return std::numeric_limits::max();\n return static_cast(diff_lat) / static_cast(diff_lon);\n };\n\n const auto slope_rhs = get_slope(null_island, rotated_difference_rhs);\n // the left hand side has a slope of `0` after the rotation. We can check the slope of the right\n // hand side to ensure we only considering slight slopes\n return std::abs(slope_rhs) < 0.20; // twenty percent incline at the most\n}\n\ndouble computeArea(const std::vector &polygon);\n\n} // ns coordinate_calculation\n} // ns util\n} // ns osrm\n\n#endif // COORDINATE_CALCULATION\n", "meta": {"hexsha": "884169e4cc338e8b354faa5aaba8b4f398861cf3", "size": 16289, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/util/coordinate_calculation.hpp", "max_stars_repo_name": "curefit/osrm-backend", "max_stars_repo_head_hexsha": "9b779c704f2cfe4e25c3609da7e30e0bc751a633", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/util/coordinate_calculation.hpp", "max_issues_repo_name": "curefit/osrm-backend", "max_issues_repo_head_hexsha": "9b779c704f2cfe4e25c3609da7e30e0bc751a633", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/util/coordinate_calculation.hpp", "max_forks_repo_name": "curefit/osrm-backend", "max_forks_repo_head_hexsha": "9b779c704f2cfe4e25c3609da7e30e0bc751a633", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9819587629, "max_line_length": 100, "alphanum_fraction": 0.6674442876, "num_tokens": 3172, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736693, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6547196319314161}} {"text": "/*=================================================================================\n *\t Copyleft! 2018 William Yu\n * Some rights reserved:CC(creativecommons.org)BY-NC-SA\n * Copyleft! 2018 William Yu\n * 版权部分所有,遵循CC(creativecommons.org)BY-NC-SA协议授权方式使用\n *\n * Filename : \n * Description : 视觉SLAM十四讲/ch4 学习记录\n * 李代数库\n * Reference : \n * Programmer(s) : William Yu, windmillyucong@163.com\n * Company : HUST, DMET国家重点实验室FOCUS团队\n * Modification History\t : ver1.0, 2018.03.26, William Yu\n \n=================================================================================*/\n/// Include files\n#include \n#include \nusing namespace std; \n\n#include \n#include \n\n#include \"sophus/so3.h\"\n#include \"sophus/se3.h\"\n\n\n\n/// Global Variables\n\n\n\n/// Function definitions\n\n\n/**\n * @function main\n * @author William Yu\n * @brief \n * @param None\n * @retval None\n */\nint main( int argc, char** argv )\n{\n //--------------------------------------------------------------------------------------------------\n // 旋转矩阵\n //--------------------------------------------------------------------------------------\n // 沿Z轴转90度的旋转矩阵\n //   角度   轴  罗德里格公式进行转换为旋转矩阵 \n Eigen::Matrix3d R = Eigen::AngleAxisd(M_PI/2, Eigen::Vector3d(0,0,1)).toRotationMatrix();\n \n\n //--------------------------------------------------------------------------------------------------\n // 李群\n //--------------------------------------------------------------------------------------\n Sophus::SO3 SO3_R(R); // Sophus::SO(3)可以直接从旋转矩阵构造\n Sophus::SO3 SO3_v( 0, 0, M_PI/2 ); // 亦可从旋转向量构造\n Eigen::Quaterniond q(R); // 或者四元数\n Sophus::SO3 SO3_q( q );\n // 上述表达方式都是等价的\n // 输出SO(3)时,以so(3)形式输出\n cout<<\"SO(3) from matrix: \"< Vector6d;\n Vector6d se3 = SE3_Rt.log();\n cout<<\"se3 = \"<\n#include \n#include \"PcaSpline.h\"\n#include \"Utils.h\"\n#include \n//#define EIGEN_USE_MKL_ALL 1\n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\n/**\n * Create the basis splines for order requested at a particular value of x.\n * From \"A Practical Guide To Splines - Revised Edition\" by Carl de Boor p 111\n * the algorithm for BSPLVB. The value of the spline coefficients can be calculated\n * based on a cool recursion. This is a simplified and numerically stable algorithm\n * that seems to be the basis of most bspline implementations including gsl, matlab,etc.\n * @param all_knots - Original knots vector augmented with order number of endpoints\n * @param n_knots - Total number of knots.\n * @param order - Order or order of polynomials, 4 for cubic splines.\n * @param i - index of value x in knots such that all_knots[i] <= x && all_knots[i+1] > x\n * @param x - value that we want to evaluate spline at.\n * @param b - memory to write our coefficients into, must be at least order long.\n */\nvoid basis_spline_xi(float *all_knots, int n_knots, int order, int i, float x, float *b) {\n b[0] = 1;\n double kr[order];\n double kl[order];\n double term;\n double saved;\n for (int j = 0; j < order - 1; j++) {\n kr[j] = all_knots[i + j + 1] - x; // k right values\n kl[j] = x - all_knots[i - j]; // k left values\n saved = 0;\n for (int r = 0; r <= j; r++) {\n term = b[r] / (kr[r] + kl[j-r]);\n b[r] = saved + kr[r] * term;\n saved = kl[j-r] * term;\n }\n b[j+1] = saved;\n }\n}\n\n/**\n * Create the augmented knots vector and fill in matrix Xt with the spline basis vectors\n */\nvoid basis_splines_endreps_local(float *knots, int n_knots, int order, int *boundaries, int n_boundaries, MatrixXf &Xt) {\n assert(n_boundaries == 2 && boundaries[0] < boundaries[1]);\n int n_rows = boundaries[1] - boundaries[0]; // this is frames so evaluate at each frame we'll need\n int n_cols = n_knots + order; // number of basis vectors we'll have at end \n Xt.resize(n_cols, n_rows); // swapped to transpose later. This order lets us use it as a scratch space\n Xt.fill(0);\n int n_std_knots = n_knots + 2 * order;\n float std_knots[n_std_knots];\n\n // Repeat the boundary knots on there to ensure linear out side of knots\n for (int i = 0; i < order; i++) {\n std_knots[i] = boundaries[0];\n }\n // Our original boundary knots here\n for (int i = 0; i < n_knots; i++) {\n std_knots[i+order] = knots[i];\n }\n // Repeat the boundary knots on there to ensure linear out side of knots\n for (int i = 0; i < order; i++) {\n std_knots[i+order+n_knots] = boundaries[1];\n }\n // Evaluate our basis splines at each frame.\n for (int i = boundaries[0]; i < boundaries[1]; i++) {\n int idx = -1;\n // find index such that i >= knots[idx] && i < knots[idx+1]\n float *val = std::upper_bound(std_knots, std_knots + n_std_knots - 1, 1.0f * i);\n idx = val - std_knots - 1;\n assert(idx >= 0);\n float *f = Xt.data() + i * n_cols + idx - (order - 1); //column offset\n basis_spline_xi(std_knots, n_std_knots, order, idx, i, f);\n }\n // Put in our conventional format where each column is a basis vector\n Xt.transposeInPlace();\n}\n\n\nvoid PcaSpline::FillInKnots(const std::string &strategy, int n_frame, std::vector &knots) {\n if (strategy != \"no-knots\") {\n if (strategy == \"even4\") {\n float stride = n_frame / 3.0f;\n knots.push_back(stride);\n knots.push_back(stride * 2.0f);\n }\n else if (strategy == \"middle\") {\n float stride = n_frame / 2.0f;\n knots.push_back(stride);\n }\n else if (strategy.find(\"explicit:\") == 0) {\n string spec = strategy.substr(9, strategy.length() - 9);\n knots = char2Vec(spec.c_str(), ',');\n }\n else {\n assert(false);\n }\n }\n}\n\nint PcaSpline::NumBasisVectors(int n_pca, int n_frames, int n_order, const std::string &knot_strategy) {\n std::vector knots;\n FillInKnots(knot_strategy, n_frames, knots);\n int spline_basis = 0;\n if (knots.size() > 0) {\n spline_basis = knots.size() + n_order;\n }\n return spline_basis + n_pca;\n}\n\nvoid PcaSpline::LossyCompress(int n_wells, int n_frame, float *image, \n\t\t\t int n_sample_wells, float *image_sample,\n\t\t\t PcaSplineRegion &compressed) {\n Map Ysub(image_sample, n_sample_wells, n_frame);\n Map Y(image, n_wells, n_frame);\n MatrixXf C = Ysub.transpose() * Ysub;\n SelfAdjointEigenSolver es;\n es.compute(C);\n MatrixXf Pca_Basis = es.eigenvectors();\n MatrixXf Spline_Basis;\n vector knots;\n FillInKnots(m_knot_strategy, n_frame, knots);\n if (!knots.empty()) {\n int boundaries[2];\n boundaries[0] = 0;\n boundaries[1] = n_frame;\n basis_splines_endreps_local(&knots[0], knots.size(), m_order, boundaries, sizeof(boundaries)/sizeof(boundaries[0]), Spline_Basis);\n }\n assert(compressed.n_basis == m_num_pca + Spline_Basis.cols());\n Map Basis(compressed.basis_vectors, compressed.n_frames, compressed.n_basis);\n for(int i = 0; i < m_num_pca; i++) {\n Basis.col(i) = Pca_Basis.col(Pca_Basis.cols() - i - 1);\n }\n for (int i = 0; i < Spline_Basis.cols(); i++) {\n Basis.col(i+m_num_pca) = Spline_Basis.col(i);\n }\n MatrixXf SX;\n if (m_tikhonov_reg > 0) {\n MatrixXf diag(Basis.cols(), Basis.cols());\n diag.fill(0);\n for (int i = 0; i < diag.rows(); i++) {\n diag(i,i) = 1.0f * m_tikhonov_reg;\n }\n SX = ((Basis.transpose() * Basis) + (diag.transpose() * diag)).inverse() * Basis.transpose();\n }\n else { \n SX = (Basis.transpose() * Basis).inverse() * Basis.transpose();\n }\n Map B(compressed.coefficients, n_wells, Basis.cols());\n B = Y * SX.transpose();\n}\n\nvoid PcaSpline::SampleImageMatrix(int n_wells, int n_frames, float * __restrict orig, int *__restrict trcs_state, int target_sample,\n\t\t\t\t int &n_sample, float ** __restrict sample) {\n int good_wells = 0;\n int * __restrict state_begin = trcs_state;\n int * __restrict state_end = trcs_state + n_wells;\n while (state_begin != state_end) {\n if (*state_begin++ >= 0) {\n good_wells++;\n }\n }\n int sample_rate = max(1,good_wells/target_sample);\n int n_sample_rows = (int)(ceil((float)good_wells/sample_rate));\n n_sample = n_sample_rows;\n *sample = (float *) memalign(32, sizeof(float) * n_frames * n_sample_rows);\n for (int i = 0; i < n_frames; i++) {\n float *__restrict col_start = orig + i * n_wells;\n float *__restrict col_end = col_start + n_wells;\n state_begin = trcs_state;\n float *__restrict sample_col_begin = (*sample) + n_sample_rows * i;\n int check_count = 0;\n int good_count = sample_rate - 1;\n while (col_start != col_end) {\n if (*state_begin >= 0 && ++good_count == sample_rate) {\n\t*sample_col_begin++ = *col_start;\n\tgood_count = 0;\n\tcheck_count++;\n }\n col_start++;\n }\n assert(check_count == n_sample_rows); \n }\n}\n\nvoid PcaSpline::LossyUncompress(int n_wells, int n_frame, float *image, \n\t\t\t\tconst PcaSplineRegion &compressed) {\n Map Yh(image, n_wells, compressed.n_frames);\n Map Basis(compressed.basis_vectors, compressed.n_frames, compressed.n_basis);\n Map B(compressed.coefficients, n_wells, compressed.n_basis);\n Yh = B * Basis.transpose();\n}\n", "meta": {"hexsha": "f83f74e6f4630b96e4753f7da0243dbeedcf94c4", "size": 7403, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Analysis/Image/PcaSpline.cpp", "max_stars_repo_name": "konradotto/TS", "max_stars_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 125.0, "max_stars_repo_stars_event_min_datetime": "2015-01-22T05:43:23.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T17:15:59.000Z", "max_issues_repo_path": "Analysis/Image/PcaSpline.cpp", "max_issues_repo_name": "konradotto/TS", "max_issues_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 59.0, "max_issues_repo_issues_event_min_datetime": "2015-02-10T09:13:06.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-11T02:32:38.000Z", "max_forks_repo_path": "Analysis/Image/PcaSpline.cpp", "max_forks_repo_name": "konradotto/TS", "max_forks_repo_head_hexsha": "bf088bd8432b1e3f4b8c8c083650a30d9ef2ae2e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 98.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T01:25:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T17:29:42.000Z", "avg_line_length": 37.2010050251, "max_line_length": 134, "alphanum_fraction": 0.6609482642, "num_tokens": 2270, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970779778824, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6545802004119526}} {"text": "/**\n * @file \n * @author Denise Ratasich\n * @date 14.10.2013\n *\n * @brief Implement sampling from specific distributions.\n *\n * Currently only Gaussian distributions can be choosen for process\n * and covariance noise. Hence only sampling from a Gaussian\n * distribution is implemented.\n */\n\n#include \"probability/sampling.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace probability\n{\n // create the rng only once (otherwise the numbers generated are\n // always the same)\n static boost::mt19937 rng(time(NULL));\n\n VectorXd sampleNormalDistribution(VectorXd mean, MatrixXd covariance)\n {\n // save last covariance (so Cholesky decomposition needs not to\n // be done every time entering this function)\n static MatrixXd cov;\t\t\n static MatrixXd T;\t\t\t// transform matrix when cov is not diagonal\n\n // additionally needed for rng\n boost::normal_distribution<> dist(0,1);\t// mean = 0, standard deviation = 1\n boost::variate_generator > random(rng, dist);\n\n VectorXd sample = VectorXd::Zero(mean.size());\n\n // check if covariance is diagonal (set diagonal to zero and\n // compare with MatrixXD::Zero)\n if (covariance.isDiagonal())\n {\n // sample each variable independently\n for (int i = 0; i < sample.size(); i++)\n\tsample[i] = mean[i] + random() * sqrt(covariance(i,i));\n } \n else\n {\n // x ~ N(0,C^-1)\n // C = L*L^T\n // sample x = L^-T * z, where z ~ N(0,I)\n \n // same covariance as before? (do calculation of L only once!)\n if (cov.rows() != covariance.rows() ||\n\t cov.cols() != covariance.cols() ||\n\t cov != covariance)\n\t{\n\t cov = covariance;\n\n\t // Cholesky decomposition of inverse covariance to get L;\n\t // the covariance must be a symmetric and positive definite\n\t // matrix (a covariance has these features, but the user\n\t // must configure it so)\n\t covariance = covariance.inverse();\n\t MatrixXd L = covariance.llt().matrixL();\n\t \n\t MatrixXd checkLL = L*L.transpose();\n\t for (int r = 0; r < covariance.rows(); r++)\n\t for (int c = 0; c < covariance.cols(); c++)\n\t if (checkLL(r,c) - covariance(r,c) > 0.000001)\n\t\tthrow std::runtime_error(\"sampleNormalDistribution: Cholesky decomposition failed.\");\n\n\t T = L.inverse().transpose();\n\t}\n\n // sample z: z_i ~ N(0,1)\n for (int i = 0; i < sample.size(); i++)\n\tsample[i] = random();\n\n // transform to x (and add mean!)\n sample = mean + T * sample;\n }\n\n return sample;\n }\n\n VectorXd sampleUniformDistribution(VectorXd a, VectorXd b)\n {\n VectorXd sample = VectorXd::Zero(a.size());\n\n if (a.size() != b.size())\n throw std::runtime_error(\"sampleUniformDistribution: Bounds a and b must have equal sizes.\");\n\n // additionally needed for rng\n boost::uniform_real<> dist(0,1);\n boost::variate_generator >\n random(rng, dist);\n\n // sample each variable independently\n for (int i = 0; i < sample.size(); i++)\n sample[i] = a[i] + random() * (b[i]-a[i]);\n\n return sample;\n }\n}\n\n", "meta": {"hexsha": "6a4087b28c08d04c3aee67e62960954c1a213101", "size": 3256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sf_estimation/src/probability/sampling.cpp", "max_stars_repo_name": "tuw-cpsg/sf-pkg", "max_stars_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2015-09-30T09:47:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-12T16:01:11.000Z", "max_issues_repo_path": "sf_estimation/src/probability/sampling.cpp", "max_issues_repo_name": "ros-agriculture/sf-pkg", "max_issues_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-05-13T04:59:08.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-13T14:39:24.000Z", "max_forks_repo_path": "sf_estimation/src/probability/sampling.cpp", "max_forks_repo_name": "tuw-cpsg/sf-pkg", "max_forks_repo_head_hexsha": "267d2ec4b886dee70d53a23b695acfa7f7edbeb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2016-04-17T21:13:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-24T17:00:28.000Z", "avg_line_length": 29.871559633, "max_line_length": 99, "alphanum_fraction": 0.648955774, "num_tokens": 826, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699436, "lm_q2_score": 0.7279754548076478, "lm_q1q2_score": 0.6545382935453659}} {"text": "// written for clarity not efficiency.\n\n#include \nusing std::cout;\nusing std::endl;\n\n#include \n#include \n\nclass Subtractive_generator {\nprivate:\n static const int param_i = 55;\n static const int param_j = 24;\n static const int initial_load = 219;\n static const int mod = 1e9;\n boost::circular_buffer r;\npublic:\n Subtractive_generator(int seed);\n int next();\n int operator()(){return next();}\n};\n\nSubtractive_generator::Subtractive_generator(int seed)\n:r(param_i)\n{\n boost::array s;\n s[0] = seed;\n s[1] = 1;\n for(int n = 2; n < param_i; ++n){\n int t = s[n-2]-s[n-1];\n if (t < 0 ) t+= mod;\n s[n] = t;\n }\n\n for(int n = 0; n < param_i; ++n){\n\tint i = (34 * (n+1)) % param_i;\n r.push_back(s[i]);\n }\n for(int n = param_i; n <= initial_load; ++n) next();\n}\n\nint Subtractive_generator::next()\n{\n int t = r[0]-r[31];\n if (t < 0) t += mod;\n r.push_back(t);\n return r[param_i-1];\n}\n\nint main()\n{\n Subtractive_generator rg(292929);\n\n cout << \"result = \" << rg() << endl;\n cout << \"result = \" << rg() << endl;\n cout << \"result = \" << rg() << endl;\n cout << \"result = \" << rg() << endl;\n cout << \"result = \" << rg() << endl;\n cout << \"result = \" << rg() << endl;\n cout << \"result = \" << rg() << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "8e8150a66e95b024c9986ee6967a36dc226a8a90", "size": 1389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lang/C++/subtractive-generator.cpp", "max_stars_repo_name": "ethansaxenian/RosettaDecode", "max_stars_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-11-09T22:08:38.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-09T22:08:38.000Z", "max_issues_repo_path": "lang/C++/subtractive-generator.cpp", "max_issues_repo_name": "ethansaxenian/RosettaDecode", "max_issues_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "lang/C++/subtractive-generator.cpp", "max_forks_repo_name": "ethansaxenian/RosettaDecode", "max_forks_repo_head_hexsha": "8ea1a42a5f792280b50193ad47545d14ee371fb7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-11-09T22:08:40.000Z", "max_forks_repo_forks_event_max_datetime": "2018-11-09T22:08:40.000Z", "avg_line_length": 21.703125, "max_line_length": 56, "alphanum_fraction": 0.5471562275, "num_tokens": 425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8991213772699435, "lm_q2_score": 0.7279754548076477, "lm_q1q2_score": 0.6545382935453656}} {"text": "\r\n#ifndef LATTICE_HPP\r\n#define LATTICE_HPP\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\n\r\n\r\n/** class representing a general lattice structure\r\n\tparameters\r\n\t\t- lattice basis vectors\r\n\t\t- which lattice sites are coupled\t\r\n*/\r\n\r\nusing namespace Eigen;\r\n\r\n\r\n\r\n//a structure given for making the lattice \r\nstruct basis{\r\n\t//matrix that contains basis indexes\r\n\tstd::vector> pairing;\t\t\r\n};\r\n\r\n\r\n\r\n\r\n\r\nclass Lattice{\r\n\t\r\npublic:\r\n\t\r\n\t//lattice basis vectors\r\n\tMatrixXf basis_vectors;\r\n\t\r\n\t//closest particle vectors \r\n\t// R = r_aa r_ba r_ca\r\n\t//\t\tr_ab r_bb r_cb\r\n\t//\t\tr_ac r_bc r_cc\r\n\tstd::vector> R;\r\n\t\r\n\t\r\n\t//t_matrix << 0, -t,-t,\r\n\t//\t\t\t-t, 0, -t,\r\n\t//\t\t\t-t, -t, 0;\r\n\tMatrixXf t_matrix;\r\n\t\r\n\t//dimensions\r\n\tint bands;\r\n\tint dim;\r\n\t\r\n\t//all the kinetic hamiltonians\r\n\tstd::vector H_kin_matrices;\r\n\t\r\n\t//all the k_values\r\n\tstd::vector k_vectors;\r\n\t\r\n\tconst std::complex IF = std::complex(0.0f, 1.0f); \r\n\t\r\n\t//constructor \r\n\tLattice(const MatrixXf& basis, const std::vector>& r, const MatrixXf& t_mat) : \r\n\t\tbasis_vectors(basis), bands(t_mat.cols()), dim(basis.cols()),\r\n\t\tR(r), t_matrix(t_mat) {}\t\r\n\t\r\n\t//destructor\r\n\t~Lattice() {};\r\n\t\r\n\tint Bands(){\r\n\t\treturn bands;\r\n\t}\r\n\t\r\n\tint Dim(){\r\n\t\treturn dim;\r\n\t}\r\n\t\r\n\t\r\n\t//calculates the kinetic hamiltonian for a given k\r\n\tMatrixXcf KineticHamiltonian(const VectorXf& k){\r\n\t\tMatrixXcf H_kin(bands,bands);\r\n\t\tH_kin = MatrixXcf::Zero(bands,bands);\r\n\t\tfor(int l=0; l es(bands);\r\n\t\t\r\n\t\tes.compute(KineticHamiltonian(k));\t\t\r\n\t\t\r\n\t\treturn es.eigenvalues();\r\n\t\t\r\n\t}\r\n\t\r\n\t//calculates the dispersion over the first brillouin zone\r\n\t//returns a matrix of [kx ky E1 E2 E3]\r\n\tMatrixXf CalculateDispersion(const float& k_min, const float& k_max){\r\n\t\t\r\n\t\tint Nk = 20;\r\n\t\tVectorXf kx = VectorXf::LinSpaced(Nk,k_min,k_max);\r\n\t\tVectorXf ky = VectorXf::LinSpaced(Nk,k_min,k_max);\r\n\t\t\r\n\t\tMatrixXf k_values(Nk*Nk, dim);\r\n\t\t\r\n\t\tMatrixXf Energies(Nk*Nk, bands);\r\n\r\n\t\tfor(int i = 0; i\n#include \n#include \n#include \n#include \n\n#include \"gambit/ScannerBit/cholesky.hpp\"\n#include \"gambit/ScannerBit/priors.hpp\"\n#include \"gambit/Utils/yaml_options.hpp\"\n\n#include \n\nnamespace Gambit\n{\n namespace Priors\n {\n /**\n * @brief Multi-dimensional Gaussian prior\n *\n * Defined by a covariance matrix and mean.\n *\n * If the covariance matrix is diagonal, it may instead be specified by the square-roots of its \n * diagonal entries, denoted \\f$\\sigma\\f$.\n */\n class Gaussian : public BasePrior\n {\n private:\n std::vector mu;\n mutable Cholesky col;\n\n public:\n // Constructor defined in gaussian.cpp\n Gaussian(const std::vector&, const Options&);\n\n /** @brief Transformation from unit interval to the Gaussian */\n void transform(const std::vector &unitpars, std::unordered_map &outputMap) const\n {\n std::vector vec(unitpars.size());\n\n auto v_it = vec.begin();\n for (auto elem_it = unitpars.begin(), elem_end = unitpars.end(); elem_it != elem_end; elem_it++, v_it++)\n {\n *v_it = M_SQRT2 * boost::math::erf_inv(2. * (*elem_it) - 1.);\n }\n\n col.ElMult(vec);\n\n v_it = vec.begin();\n auto m_it = mu.begin();\n for (auto str_it = param_names.begin(), str_end = param_names.end(); str_it != str_end; str_it++)\n {\n outputMap[*str_it] = *(v_it++) + *(m_it++);\n }\n }\n\n std::vector inverse_transform(const std::unordered_map &physical) const override\n {\n // subtract mean\n std::vector central;\n for (int i = 0, n = this->size(); i < n; i++)\n {\n central.push_back(physical.at(param_names[i]) - mu[i]);\n }\n\n // invert rotation by Cholesky matrix\n std::vector rotated = col.invElMult(central);\n\n // now diagonal; invert Gaussian CDF\n std::vector u;\n for (const auto& v : rotated)\n {\n u.push_back(0.5 * (boost::math::erf(v / M_SQRT2) + 1.));\n }\n return u;\n }\n\n double operator()(const std::vector &vec) const\n {\n static double norm = 0.5 * std::log(2. * M_PI * std::pow(col.DetSqrt(), 2));\n return -0.5 * col.Square(vec, mu) - norm;\n }\n };\n\n LOAD_PRIOR(gaussian, Gaussian)\n\n } // namespace Priors\n} // namespace Gambit\n\n#endif // __PRIOR_GAUSSIAN_HPP__\n", "meta": {"hexsha": "c96290642c926773c451e4baa2a9e47934d4b851", "size": 3234, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ScannerBit/include/gambit/ScannerBit/priors/gaussian.hpp", "max_stars_repo_name": "GambitBSM/gambit_2.0", "max_stars_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-09-17T22:53:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-17T22:53:26.000Z", "max_issues_repo_path": "ScannerBit/include/gambit/ScannerBit/priors/gaussian.hpp", "max_issues_repo_name": "GambitBSM/gambit_2.0", "max_issues_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-07-22T11:23:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-22T17:24:41.000Z", "max_forks_repo_path": "ScannerBit/include/gambit/ScannerBit/priors/gaussian.hpp", "max_forks_repo_name": "GambitBSM/gambit_2.0", "max_forks_repo_head_hexsha": "a4742ac94a0352585a3b9dcb9b222048a5959b91", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-14T10:31:41.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-14T10:31:41.000Z", "avg_line_length": 27.641025641, "max_line_length": 116, "alphanum_fraction": 0.573283859, "num_tokens": 843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9230391579526935, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6544524355720398}} {"text": "#include \n#include \n\nnamespace itomp_cio_planner\n{\nnamespace exponential_map\n{\n\nEigen::Vector3d RotationToExponentialMap(const Eigen::Matrix3d& matrix, const Eigen::Vector3d* close_to)\n{\n if (close_to == NULL)\n return QuaternionToExponentialMap(Eigen::Quaterniond(matrix));\n else\n {\n Eigen::Quaterniond q0 = Eigen::Quaterniond(matrix);\n Eigen::Vector3d exp_map0 = QuaternionToExponentialMap(q0);\n\n Eigen::Quaterniond q1 = q0;\n q1.coeffs() = -q0.coeffs();\n Eigen::Vector3d exp_map1 = QuaternionToExponentialMap(q1);\n\n if ((exp_map0 - *close_to).norm() <= (exp_map1 - *close_to).norm())\n return exp_map0;\n else\n return exp_map1;\n }\n}\n\nEigen::Matrix3d ExponentialMapToRotation(const Eigen::Vector3d& exponential_rotation)\n{\n\treturn ExponentialMapToQuaternion(exponential_rotation).toRotationMatrix();\n}\n\nEigen::Vector3d QuaternionToExponentialMap(const Eigen::Quaterniond& quaternion)\n{\n\tEigen::Vector3d vec = quaternion.vec();\n if (vec.norm() < ITOMP_EPS)\n\t\treturn Eigen::Vector3d::Zero();\n\n\tdouble theta = 2.0 * std::acos(quaternion.w());\n\tvec.normalize();\n\treturn theta * vec;\n}\n\nEigen::Quaterniond ExponentialMapToQuaternion(const Eigen::Vector3d& exponential_rotation)\n{\n\tdouble angle = 0.5 * exponential_rotation.norm();\n\tEigen::Quaterniond quaternion;\n\tquaternion.w() = std::cos(angle);\n\tquaternion.vec() = 0.5 * boost::math::sinc_pi(angle) * exponential_rotation;\n\treturn quaternion;\n}\n\n}\n}\n", "meta": {"hexsha": "56764ddd7f2995b7cc66b7eff00bfa28469c9234", "size": 1570, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "itomp_cio_planner/src/util/exponential_map.cpp", "max_stars_repo_name": "Chpark/itomp", "max_stars_repo_head_hexsha": "a11713a14a0b65ede54ab3b1cee2c0060b386d0e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 23.0, "max_stars_repo_stars_event_min_datetime": "2015-02-02T14:46:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-06T02:57:19.000Z", "max_issues_repo_path": "itomp_cio_planner/src/util/exponential_map.cpp", "max_issues_repo_name": "Chpark/itomp", "max_issues_repo_head_hexsha": "a11713a14a0b65ede54ab3b1cee2c0060b386d0e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2016-12-16T14:44:57.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-19T05:49:51.000Z", "max_forks_repo_path": "itomp_cio_planner/src/util/exponential_map.cpp", "max_forks_repo_name": "Chpark/itomp", "max_forks_repo_head_hexsha": "a11713a14a0b65ede54ab3b1cee2c0060b386d0e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 13.0, "max_forks_repo_forks_event_min_datetime": "2015-01-01T04:45:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-23T04:28:53.000Z", "avg_line_length": 28.0357142857, "max_line_length": 104, "alphanum_fraction": 0.7121019108, "num_tokens": 404, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392756357326, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6543432068611125}} {"text": "// Implementing the class that is defined in the header file: Option.hpp\r\n//\r\n// (c) Sudhansh Dua\r\n\r\n\r\n#include \"EuropeanOption.hpp\"\r\n#include \r\n#include \r\n\r\nusing namespace std;\r\nusing namespace boost::math;\r\n\r\n\r\n//\tGaussian functions using boost libraries\r\ndouble EuropeanOption::N(double x) const\r\n{\r\n\tnormal_distribution<> Standard_normal(0.0, 1.0);\r\n\treturn cdf(Standard_normal, x);\r\n}\r\n\r\ndouble EuropeanOption::n(double x) const\r\n{\r\n\tnormal_distribution<> Standard_normal(0.0, 1.0);\r\n\treturn pdf(Standard_normal, x);\r\n}\r\n\r\n//\tKernel functions\r\ndouble EuropeanOption::CallPrice() const\r\n{\r\n\treturn ::CallPrice(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::PutPrice() const\r\n{\r\n\treturn ::PutPrice(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::CallDelta() const\r\n{\r\n\treturn ::CallDelta(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::PutDelta() const\r\n{\r\n\treturn ::PutDelta(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::CallGamma() const\r\n{\r\n\treturn ::CallGamma(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::PutGamma() const\r\n{\r\n\treturn ::PutGamma(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::CallVega() const\r\n{\r\n\treturn ::CallVega(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::PutVega() const\r\n{\r\n\treturn ::PutVega(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::CallTheta() const\r\n{\r\n\treturn ::CallTheta(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::PutTheta() const\r\n{\r\n\treturn ::PutTheta(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::CallRho() const\r\n{\r\n\treturn ::CallRho(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::PutRho() const\r\n{\r\n\treturn ::PutRho(S, K, T, r, sig, b);\r\n}\r\n\r\ndouble EuropeanOption::CallCoc() const\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\treturn T * S * exp((b - r) * T) * N(d1);\r\n}\r\n\r\ndouble EuropeanOption::PutCoc() const\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\treturn -T * S * exp((b - r) * T) * N(-d1);\r\n}\r\n\r\n\r\n//\tInitialising all the default values\r\nvoid EuropeanOption::init()\r\n{\r\n\t//\tDefault values\r\n\tr = 0.03;\r\n\tsig = 0.2;\r\n\tK = 100;\r\n\tS = 95;\t\t\t\t//\tDefault stock price \r\n\tT = 1;\r\n\tb = r;\t\t\t\t//\tBlack - Scholes(1973) stock option model : b = r\r\n\ttype = \"C\";\t\t\t//\tCall option as the default\r\n}\r\n\r\n\r\nvoid EuropeanOption::copy(const EuropeanOption& option)\r\n{\r\n\tS = option.S;\r\n\tK = option.K;\r\n\tT = option.T;\r\n\tr = option.r;\r\n\tsig = option.sig;\r\n\tb = option.b;\r\n\ttype = option.type;\r\n}\r\n\r\n//\tConstructors and destructor\r\nEuropeanOption::EuropeanOption() : Option()\t\t\t\t\t\t//\tDefault constructor\r\n{\r\n\tinit();\r\n}\r\n\r\nEuropeanOption::EuropeanOption(const EuropeanOption& option) : Option(option)\t\t//\tCopy constructor\r\n{\r\n\tcopy(option);\r\n}\r\n\r\n//\tConstructor that accepts values\r\nEuropeanOption::EuropeanOption(const double& S1, const double& K1, const double& T1, const double& r1,\r\n\tconst double& sig1, const double& b1, const string type1) : Option(), S(S1), K(K1), T(T1), r(r1), sig(sig1), b(b1), type(type1) {}\r\n\r\nEuropeanOption::~EuropeanOption() {}\t\t\t\t\t\t\t//\tDestructor\r\n\r\n\r\n//\tAssignment operator\r\nEuropeanOption& EuropeanOption::operator = (const EuropeanOption& option)\r\n{\r\n\tif (this == &option)\r\n\t{\r\n\t\treturn *this;\r\n\t}\r\n\tOption::operator = (option);\r\n\tcopy(option);\r\n\treturn *this;\r\n}\r\n\r\n\r\n//\tFunctions that calculate option price and sensitivities\r\ndouble EuropeanOption::Price() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallPrice();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutPrice();\r\n\t}\r\n}\r\n\r\ndouble EuropeanOption::Delta() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallDelta();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutDelta();\r\n\t}\r\n}\r\n\r\ndouble EuropeanOption::Gamma() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallGamma();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutGamma();\r\n\t}\r\n}\r\n\r\ndouble EuropeanOption::Vega() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallVega();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutVega();\r\n\t}\r\n}\r\n\r\ndouble EuropeanOption::Theta() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallTheta();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutTheta();\r\n\t}\r\n}\r\n\r\ndouble EuropeanOption::Rho() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallRho();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutRho();\r\n\t}\r\n}\r\n\r\n\r\n//\tFunctions that calculates the Cost of carry\r\ndouble EuropeanOption::Coc() const\r\n{\r\n\tif (type == \"C\")\r\n\t{\r\n\t\treturn CallCoc();\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn PutCoc();\r\n\t}\r\n}\r\n\r\n\r\n// Modifier functions\r\nvoid EuropeanOption::toggle()\t\t\t\t//\tChange the option type\r\n{\r\n\ttype = ((type == \"C\") ? \"P\" : \"C\");\r\n}\r\n\r\n\r\n//\tGlobal Functions\r\ndouble CallDelta(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn exp((b - r) * T) * cdf(standard_normal, d1);\r\n\r\n}\r\n\r\ndouble PutDelta(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn exp((b - r) * T) * (cdf(standard_normal, d1) - 1.0);\r\n}\r\n\r\n\r\ndouble CallGamma(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\tdouble d2 = d1 - (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn (pdf(standard_normal, d1) * exp((b - r) * T)) / (S * sig * sqrt(T));\r\n}\r\n\r\ndouble PutGamma(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\treturn CallGamma(S, K, T, r, sig, b);\r\n}\r\n\r\n\r\ndouble CallVega(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\treturn (S * sqrt(T) * exp((b - r) * T) * pdf(standard_normal, d1));\r\n}\r\n\r\n\r\ndouble PutVega(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\treturn CallVega(S, K, T, r, sig, b);\r\n}\r\n\r\n\r\ndouble CallTheta(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\tdouble d2 = d1 - (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\tdouble t1 = (S * sig * exp((b - r) * T) * pdf(standard_normal, d1)) / (2 * sqrt(T));\r\n\tdouble t2 = ((b - r) * S * exp((b - r) * T) * cdf(standard_normal, d1));\r\n\tdouble t3 = (r * K * exp(-r * T) * cdf(standard_normal, d1));\r\n\treturn -(t1 + t2 + t3);\r\n}\r\n\r\ndouble PutTheta(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\tdouble d2 = d1 - (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\tdouble t1 = (S * sig * exp((b - r) * T) * pdf(standard_normal, d1)) / (2 * sqrt(T));\r\n\tdouble t2 = ((b - r) * S * exp((b - r) * T) * cdf(standard_normal, d1));\r\n\tdouble t3 = (r * K * exp(-r * T) * cdf(standard_normal, d1));\r\n\treturn t2 + t3 - t1;\r\n}\r\n\r\n\r\ndouble CallRho(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\tdouble d2 = d1 - (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\tif (b != 0.0)\r\n\t{\r\n\t\treturn T * K * exp(-r * T) * cdf(standard_normal, d2);\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn -T * CallPrice(S, K, T, r, sig, b);\r\n\t}\r\n}\r\n\r\ndouble PutRho(const double S, const double K, const double T, const double r, const double sig, const double b)\r\n{\r\n\tdouble d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));\r\n\tdouble d2 = d1 - (sig * sqrt(T));\r\n\tnormal_distribution<> standard_normal(0.0, 1.0);\r\n\tif (b != 0.0)\r\n\t{\r\n\t\treturn T * K * exp(-r * T) * cdf(standard_normal, -d2);\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn -T * PutPrice(S, K, T, r, sig, b);\r\n\t}\r\n}\r\n", "meta": {"hexsha": "14ee19d3e2ec9317825d6d2f3cc91bbef5c344a0", "size": 8035, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EuropeanOption.cpp", "max_stars_repo_name": "sudhanshdua/Option_Classes", "max_stars_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EuropeanOption.cpp", "max_issues_repo_name": "sudhanshdua/Option_Classes", "max_issues_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EuropeanOption.cpp", "max_forks_repo_name": "sudhanshdua/Option_Classes", "max_forks_repo_head_hexsha": "b483d71ac78cd5cdd3c69205eb0ee37bca3ae668", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8917378917, "max_line_length": 132, "alphanum_fraction": 0.5973864343, "num_tokens": 2508, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391624034103, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6542733176214486}} {"text": "/* vim: set tabstop=4 expandtab shiftwidth=4 softtabstop=4: */\n\n/**\n * \\file boost/numeric/ublasx/operation/trace.hpp\n *\n * \\brief Compute the trace of a matrix.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n *
\n *\n * Copyright (c) 2010, Marco Guazzone\n *\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_TRACE_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_TRACE_HPP\n\n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nnamespace ublas = ::boost::numeric::ublas;\n\n\n/**\n * \\brief Compute the trace of a given matrix.\n *\n * \\tparam MatrixExprT The type of the input matrix expression.\n *\n * \\param A The input matrix expression.\n * \\return The trace of \\a A.\n *\n * The trace of a m-by-n matrix \\f$A\\f$ is defined as\n * \\f[\n * \\operatorname{tr}(A) = \\sum_{i=1}^k a_{ii}\n * \\f]\n * where \\f$k=\\min(m,n)\\f$.\n */\ntemplate \nBOOST_UBLAS_INLINE\ntypename ublas::matrix_traits::value_type trace(ublas::matrix_expression const& A)\n{\n typedef typename ublas::matrix_traits::value_type value_type;\n typedef typename ublas::matrix_traits::size_type size_type;\n\n size_type n = ::std::min(num_rows(A), num_columns(A));\n value_type res = 0;\n\n for (size_type i = 0; i < n; ++i)\n {\n res += A()(i,i);\n }\n\n return res;\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_TRACE_HPP\n", "meta": {"hexsha": "1318471881e0623c131a8de1aaf5e3e5f171d184", "size": 1799, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/trace.hpp", "max_stars_repo_name": "sguazt/boost-ublasx", "max_stars_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-05-14T11:08:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-05T14:22:20.000Z", "max_issues_repo_path": "boost/numeric/ublasx/operation/trace.hpp", "max_issues_repo_name": "sguazt/boost-ublasx", "max_issues_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-12-28T18:36:04.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-06T11:28:51.000Z", "max_forks_repo_path": "boost/numeric/ublasx/operation/trace.hpp", "max_forks_repo_name": "sguazt/boost-ublasx", "max_forks_repo_head_hexsha": "21c9b393d33a6ec2a8071ba8d48680073d766409", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-23T02:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-23T02:53:27.000Z", "avg_line_length": 25.338028169, "max_line_length": 108, "alphanum_fraction": 0.7087270706, "num_tokens": 511, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916134888613, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.6542732954621198}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef CGAL::Triangulation_vertex_base_with_info_2 Vb;\ntypedef CGAL::Triangulation_data_structure_2 Tds;\ntypedef CGAL::Delaunay_triangulation_2 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 MapM3Xd;\ntypedef Eigen::Ref RefM3Xd;\n\nint main(int argc, char *argv[]) {\n\n // We expect three command line arguments:\n // 1. Path to the data file\n // 2. Output directory where output files will be created\n if (argc < 3) {\n std::cout << \"Usage: ./calcVolume \" << std::endl;\n return 0;\n }\n\n clock_t t = clock();\n\n // Open the data file\n std::ifstream inputfile(argv[1]);\n if (!inputfile.is_open()) {\n std::cout << \"Unable to open file \" << argv[1] << std::endl;\n return 0;\n }\n\n //**********************************************************************//\n //\n\n auto outputFile = std::string(argv[2]) + \"/volume.dat\";\n std::ofstream vol_file(outputFile);\n\n if (!vol_file) {\n std::cout << \"Failed to create output file \" << outputFile << std::endl;\n return 0;\n }\n\n //**********************************************************************//\n // Now read the first( or the header ) line of the data file\n // The first line contains N, gamma and beta information\n std::string line, ignore;\n size_t N;\n double_t gamma = 0, beta = 0;\n std::getline(inputfile, line);\n std::istringstream header(line);\n header >> ignore >> N >> ignore >> gamma >> ignore >> beta;\n int lmax = std::floor(std::sqrt(N) - 1);\n\n // Write column names in the output files\n vol_file << \"volume\" << std::endl;\n vol_file.precision(7);\n\n //**********************************************************************//\n // Some useful lambda functions\n //\n\n // A function to read N rows of a 3xN matrix from a stringstream\n auto readMatrix3Xd = [](std::istringstream &ss, RefM3Xd X) {\n auto N = X.cols();\n size_t valCount = 0;\n while (valCount < 3 * N && ss.good()) {\n std::string value;\n std::getline(ss, value, ',');\n X(valCount % 3, valCount / 3) = std::stod(value);\n valCount++;\n }\n };\n //**********************************************************************//\n\n //***************************** MAIN LOOP ******************************//\n // Skip the first row which is just zero temperature data\n std::getline(inputfile, line);\n\n // Now iterate over the remaining rows\n auto rowCount = 1;\n while (std::getline(inputfile, line)) {\n\n std::istringstream rowStream(line);\n\n // We will extract 3*N doubles representing particle positions\n // from the stream and ignore the 3*N rotation vector components\n Matrix3Xd Xt(3, N), X0(3, N);\n readMatrix3Xd(rowStream, Xt);\n\n // Project the points to a unit sphere\n X0 = Xt.colwise().normalized();\n\n // Rotate all points of the shell so that the 0th point is along z-axis\n Vector3d c = X0.col(0);\n double_t cos_t = c(2);\n double_t sin_t = std::sin(std::acos(cos_t));\n Vector3d axis;\n axis << c(1), -c(0), 0.;\n axis.normalize();\n Matrix3d rotMat, axis_cross, outer;\n axis_cross << 0., -axis(2), axis(1), axis(2), 0., -axis(0), -axis(1),\n axis(0), 0.;\n outer.noalias() = axis * axis.transpose();\n rotMat =\n cos_t * Matrix3d::Identity() + sin_t * axis_cross + (1 - cos_t) * outer;\n Matrix3Xd rPts(3, N);\n rPts = rotMat * X0;\n\n // Calculate the stereographic projections\n Vector3d p0;\n p0 << 0, 0, -1.0; // Point on the plane of projection\n c = rPts.col(0); // The point from which we are projecting\n\n MapM3Xd l0(&(rPts(0, 1)), 3, N - 1);\n Matrix3Xd l(3, N - 1), proj(3, N - 1);\n l = (l0.colwise() - c).colwise().normalized(); // dirns of projections\n for (auto j = 0; j < N - 1; ++j) {\n proj.col(j) = ((p0(2) - l0(2, j)) / l(2, j)) * l.col(j) + l0.col(j);\n }\n\n // Insert the projected points in a CGAL vertex_with_info vector\n std::vector> verts;\n for (auto j = 0; j < N - 1; ++j) {\n verts.push_back(std::make_pair(Point(proj(0, j), proj(1, j)), j + 1));\n }\n\n // Triangulate\n Delaunay dt(verts.begin(), verts.end());\n\n // Iterate over the triangles to calculate volume\n auto volume = 0.0;\n for (auto ffi = dt.finite_faces_begin(); ffi != dt.finite_faces_end();\n ++ffi) {\n auto i = ffi->vertex(0)->info();\n auto j = ffi->vertex(2)->info();\n auto k = ffi->vertex(1)->info();\n volume += 0.166666667 * (Xt.col(i).dot(Xt.col(j).cross(Xt.col(k))));\n }\n\n // Iterate over infinite faces\n Face_circulator fc = dt.incident_faces(dt.infinite_vertex()), done(fc);\n if (fc != 0) {\n do {\n auto i = dt.is_infinite(fc->vertex(0)) ? 0 : fc->vertex(0)->info();\n auto j = dt.is_infinite(fc->vertex(2)) ? 0 : fc->vertex(2)->info();\n auto k = dt.is_infinite(fc->vertex(1)) ? 0 : fc->vertex(1)->info();\n volume += 0.166666667 * (Xt.col(i).dot(Xt.col(j).cross(Xt.col(k))));\n } while (++fc != done);\n }\n vol_file << volume << std::endl;\n rowCount++;\n }\n inputfile.close();\n vol_file.close();\n\n std::cout << \"Time elapsed = \" << ((float)(clock() - t)) / CLOCKS_PER_SEC\n << \" seconds.\" << std::endl;\n\n return 1;\n}\n", "meta": {"hexsha": "bca8899401f0c5cff54e7eaf1e448401434ae7c6", "size": 5833, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "src/PostProcess/CalculateVolume.cxx", "max_stars_repo_name": "amit112amit/oriented-particles", "max_stars_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-06-21T08:01:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-21T08:01:15.000Z", "max_issues_repo_path": "src/PostProcess/CalculateVolume.cxx", "max_issues_repo_name": "amit112amit/oriented-particles", "max_issues_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PostProcess/CalculateVolume.cxx", "max_forks_repo_name": "amit112amit/oriented-particles", "max_forks_repo_head_hexsha": "1bb0f01a49d9bf33b88c4748025af756faf26688", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3314285714, "max_line_length": 80, "alphanum_fraction": 0.5880336019, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9585377225508371, "lm_q2_score": 0.6825737473266736, "lm_q1q2_score": 0.6542726852355003}} {"text": "//\n// Created by kazem on 2020-05-18.\n//\n\n\n#include \"includes/sympiler_cholesky.h\"\n#include \n#include \n\n\n namespace sympiler\n {\n // Solving Ax=b\n // Inputs:\n // H n by n sparse Hessian matrix **lower triangle only** (see\n // .triangularView() )\n // q n by 1 vector\n // Outputs:\n // x n by 1 solution vector\n // Returns sympiler exit flag\n //\n int sympiler_spd_linsolve(\n // Pass inputs by copy so we get non-const and casted data\n Eigen::SparseMatrix A,\n Eigen::Matrix b,\n Eigen::Matrix & x){\n assert(A.isApprox(A.triangularView(),0) &&\n \"P should be lower triangular\");\n assert(A.isCompressed());\n assert(A.rows()==A.cols());\n assert(A.rows()==b.rows());\n\n auto *H = new sym_lib::parsy::CSC;\n H->nzmax = A.nonZeros();\n H->ncol= H->nrow=A.rows();\n H->p = A.outerIndexPtr();\n H->i = A.innerIndexPtr();\n H->x = A.valuePtr();\n H->stype=-1;\n H->xtype=SYMPILER_REAL;\n H->packed=TRUE;\n H->nz = NULL;\n H->sorted = TRUE;\n\n auto *sym_chol = new sym_lib::parsy::SolverSettings(H,b.data());\n sym_chol->ldl_variant = 1;\n sym_chol->solver_mode = 0;\n sym_chol->symbolic_analysis();\n sym_chol->numerical_factorization();\n double *sol = sym_chol->solve_only();\n //lbl->compute_norms();\n //std::cout<<\"residual: \"<res_l1<<\"\\n\";\n\n x = Eigen::Map< Eigen::Matrix >(\n sol,A.rows(),1);\n\n // Exitflag TODO\n int exitflag = 0;\n delete sym_chol;\n delete H;\n return exitflag;\n }\n\n\n sym_lib::parsy::CSC* sympiler_csc_format(\n // Pass inputs by copy so we get non-const and casted data\n Eigen::SparseMatrix A) {\n assert(A.isApprox(A.triangularView(), 0) &&\n \"P should be lower triangular\");\n assert(A.isCompressed());\n assert(A.rows() == A.cols());\n\n auto *H = new sym_lib::parsy::CSC;\n H->nzmax = A.nonZeros();\n H->ncol = H->nrow = A.rows();\n H->p = A.outerIndexPtr();\n H->i = A.innerIndexPtr();\n H->x = A.valuePtr();\n H->stype = -1;\n H->xtype = SYMPILER_REAL;\n H->packed = TRUE;\n H->nz = NULL;\n H->sorted = TRUE;\n return H;\n }\n\n sym_lib::parsy::SolverSettings* sympiler_chol_symbolic(\n // Pass inputs by copy so we get non-const and casted data\n sym_lib::parsy::CSC *A){\n\n auto *sym_chol = new sym_lib::parsy::SolverSettings(A);\n sym_chol->ldl_variant = 1;\n sym_chol->solver_mode = 0;\n sym_chol->symbolic_analysis();\n return sym_chol;\n }\n\n\n sym_lib::parsy::SolverSettings* sympiler_chol_symbolic(\n // Pass inputs by copy so we get non-const and casted data\n sym_lib::parsy::CSC *A, int num_threads, sym_lib::parsy::SYM_ORDER so, int mode){\n\n auto *sym_chol = new sym_lib::parsy::SolverSettings(A);\n sym_chol->ldl_variant = mode;\n sym_chol->num_thread = num_threads;\n sym_chol->solver_mode = 0;\n sym_chol->sym_order = so;\n sym_chol->symbolic_analysis();\n return sym_chol;\n }\n\n }\n\n\n\n", "meta": {"hexsha": "e6ec5f32bafcc267a1de5a2ccc34bc25497588b5", "size": 3055, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sympiler_cholesky.cpp", "max_stars_repo_name": "sympiler/sympiler-eigen", "max_stars_repo_head_hexsha": "277cc858c2bafb1056a10b94ff6657bc227bb9a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sympiler_cholesky.cpp", "max_issues_repo_name": "sympiler/sympiler-eigen", "max_issues_repo_head_hexsha": "277cc858c2bafb1056a10b94ff6657bc227bb9a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sympiler_cholesky.cpp", "max_forks_repo_name": "sympiler/sympiler-eigen", "max_forks_repo_head_hexsha": "277cc858c2bafb1056a10b94ff6657bc227bb9a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.3362068966, "max_line_length": 86, "alphanum_fraction": 0.6337152209, "num_tokens": 966, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6541435214152622}} {"text": "//\n// Created by jianping on 17-9-1.\n//\n\n#ifndef DEPTHPROBABILITY_ESTIMATOR_HPP\n#define DEPTHPROBABILITY_ESTIMATOR_HPP\n\n#include \n#include \n#include \n#include \n\nclass DistributionEstimator {\npublic:\n struct distributionCostFunctor {\n\n distributionCostFunctor(double ob_x,double min, double max)\n :_ob_x(ob_x),_min(min),_max(max)\n {\n\n }\n\n template \n bool operator()(const T* const params, T* residual) const {\n T part_normal = T(1.0)/(T(std::sqrt(2.0*M_PI))*params[2])\n *ceres::exp(-(T(_ob_x)-params[1])*(T(_ob_x)-params[1])/(T(2)*params[2]*params[2]))*params[0];\n T part_uniform = T(1)/(_max-_min)*(T(1.0)-params[0]);\n residual[0] = -ceres::log(part_normal+part_uniform);\n if(params[0] < T(0.3) || params[0]>T(1))\n {\n return false;\n }\n return true;\n }\n\n double _ob_x;\n double _min;\n double _max;\n\n };\n\npublic:\n DistributionEstimator(const std::vector& data)\n :_data(data)\n {\n _min = *std::min_element(_data.begin(),_data.end());\n _max = *std::max_element(_data.begin(),_data.end());\n\n\n //init\n params.resize(3);\n params[0] = 1;\n params[1] = std::accumulate(_data.begin(),_data.end(),0.0)/_data.size();\n params[2] = 0;\n for (int i = 0; i < _data.size(); ++i) {\n params[2] += (_data[i]-params[1])*(_data[i]-params[1]);\n }\n params[2]/=_data.size();\n params[2] = std::sqrt(params[2]);\n std::cout<<\" mu:\"< params;//pi mu sigma\nprivate:\n const std::vector& _data;\n double _min;\n double _max;\n\n};\n\n\n#endif //DEPTHPROBABILITY_ESTIMATOR_HPP\n", "meta": {"hexsha": "09af78f3ab1a096274edc603af9bb5e8878f8c80", "size": 1941, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/estimator.hpp", "max_stars_repo_name": "kafeiyin00/DepthProbability", "max_stars_repo_head_hexsha": "15a2f3a710cdf2aaf5dbef263dfdd32f5f53fe6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-09-01T02:10:32.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-01T02:10:32.000Z", "max_issues_repo_path": "src/estimator.hpp", "max_issues_repo_name": "kafeiyin00/DepthProbability", "max_issues_repo_head_hexsha": "15a2f3a710cdf2aaf5dbef263dfdd32f5f53fe6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/estimator.hpp", "max_forks_repo_name": "kafeiyin00/DepthProbability", "max_forks_repo_head_hexsha": "15a2f3a710cdf2aaf5dbef263dfdd32f5f53fe6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-14T05:32:14.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-14T05:32:14.000Z", "avg_line_length": 25.88, "max_line_length": 121, "alphanum_fraction": 0.552807831, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025423, "lm_q2_score": 0.7310585786300049, "lm_q1q2_score": 0.6541435152620255}} {"text": "#include \"mex.h\"\n#include \n#include \n#include \n#include \"drakeMexUtil.h\"\n#include \n\nusing namespace Eigen;\nusing namespace std;\n\n/*\n * c++ version of\n * function [H,C,B] = manipulatorDynamics(obj,q,qd)\n */\n\ntemplate\nvoid manipulatorDynamics(const mxArray *pobj, const MatrixBase& q, const MatrixBase& qd,\n mxArray **plhs)\n{\n // keep it readable:\n double m1 = mxGetScalar(mxGetProperty(pobj, 0, \"m1\"));\n double m2 = mxGetScalar(mxGetProperty(pobj, 0, \"m2\"));\n double l1 = mxGetScalar(mxGetProperty(pobj, 0, \"l1\"));\n double g = mxGetScalar(mxGetProperty(pobj, 0, \"g\"));\n double lc1 = mxGetScalar(mxGetProperty(pobj, 0, \"lc1\"));\n double lc2 = mxGetScalar(mxGetProperty(pobj, 0, \"lc2\"));\n double b1 = mxGetScalar(mxGetProperty(pobj, 0, \"b1\"));\n double b2 = mxGetScalar(mxGetProperty(pobj, 0, \"b2\"));\n double I1 = mxGetScalar(mxGetProperty(pobj, 0, \"Ic1\")) + m1 * lc1 * lc1;\n double I2 = mxGetScalar(mxGetProperty(pobj, 0, \"Ic2\")) + m2 * lc2 * lc2;\n double m2l1lc2 = m2 * l1 * lc2; // occurs often!\n\n auto c2 = cos(q(1));\n auto s1 = sin(q(0)), s2 = sin(q(1));\n auto s12 = sin(q(0) + q(1));\n\n auto h12 = I2 + m2l1lc2 * c2;\n\n typedef typename DerivedQ::Scalar Scalar;\n Matrix H;\n Matrix C;\n Matrix B;\n\n H << I1 + I2 + m2 * l1 * l1 + 2 * m2l1lc2 * c2, h12, h12, I2;\n\n //C = [ -2*m2l1lc2*s(2)*qd(2), -m2l1lc2*s(2)*qd(2); m2l1lc2*s(2)*qd(1), 0 ];\n //G = g*[ m1*lc1*s(1) + m2*(l1*s(1)+lc2*s12); m2*lc2*s12 ];\n\n C << -2 * m2l1lc2 * s2 * qd(1) * qd(0) + -m2l1lc2 * s2 * qd(1) * qd(1), m2l1lc2 * s2 * qd(0) * qd(0);\n\n // add in G terms\n C(0) += g * m1 * lc1 * s1 + g * m2 * (l1 * s1 + lc2 * s12);\n C(1) += g * m2 * lc2 * s12;\n\n // damping terms\n C(0) += b1 * qd(0);\n C(1) += b2 * qd(1);\n\n // input matrix\n // multiplying by q(0) just to get the size of the derivatives vector right; Matlab TaylorVar operations will complain otherwise. We could handle this case on the Matlab side instead.\n B << 0.0 * q(0), 1.0;\n\n plhs[0] = eigenToMatlabGeneral<2, 2>(H);\n plhs[1] = eigenToMatlabGeneral<2, 1>(C);\n plhs[2] = eigenToMatlabGeneral<2, 1>(B);\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n const mxArray *pobj = prhs[0];\n\n if (mxIsDouble(prhs[1]) && mxIsDouble(prhs[2])) {\n auto q = matlabToEigenMap<2, 1>(prhs[1]);\n auto qd = matlabToEigenMap<2, 1>(prhs[2]);\n manipulatorDynamics(pobj, q, qd, plhs);\n } else if (isa(prhs[1], \"TrigPoly\") && isa(prhs[2], \"TrigPoly\")) {\n auto q = trigPolyToEigen(prhs[1]);\n auto qd = trigPolyToEigen(prhs[2]);\n manipulatorDynamics(pobj, q, qd, plhs);\n } else if (isa(prhs[1], \"TaylorVar\") && isa(prhs[2], \"TaylorVar\")) {\n auto q = taylorVarToEigen(prhs[1]);\n auto qd = taylorVarToEigen(prhs[2]);\n manipulatorDynamics(pobj, q, qd, plhs);\n } else {\n mexErrMsgIdAndTxt(\"Drake:AcrobotPLantCpp:UnknownType\",\n \"don't know how to handle the datatypes passed in for q and/or qd (yet)\");\n }\n}\n\n\n", "meta": {"hexsha": "ac7fde878fff5e9744332f789c5eeac373cfbc4b", "size": 3115, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "drake/examples/Acrobot/@AcrobotPlantCpp/manipulatorDynamics.cpp", "max_stars_repo_name": "jhu-asco/drake", "max_stars_repo_head_hexsha": "ae42555eb1ca98240b1aea1fb646b7fb1475303a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-04-16T09:54:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T21:59:27.000Z", "max_issues_repo_path": "drake/examples/Acrobot/@AcrobotPlantCpp/manipulatorDynamics.cpp", "max_issues_repo_name": "jhu-asco/drake", "max_issues_repo_head_hexsha": "ae42555eb1ca98240b1aea1fb646b7fb1475303a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "drake/examples/Acrobot/@AcrobotPlantCpp/manipulatorDynamics.cpp", "max_forks_repo_name": "jhu-asco/drake", "max_forks_repo_head_hexsha": "ae42555eb1ca98240b1aea1fb646b7fb1475303a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-08-24T20:32:03.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-24T20:32:03.000Z", "avg_line_length": 34.2307692308, "max_line_length": 185, "alphanum_fraction": 0.6176565008, "num_tokens": 1197, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.7248702821204019, "lm_q1q2_score": 0.6537754876022699}} {"text": "/*! \\file main.cpp\n \\brief The main file performing the spectral numerical integration.\n\n In this file, we perform the computation from the PDF.\n*/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\n#include \n\n\n#include \"chebyshev_differentiation.h\"\n#include \"spectral_integration_utilities.h\"\n\n#include \"tictoc.h\"\n\n\n// Number od admitted strain fields and number of mode per strain field\nstatic constexpr unsigned int na = 3; // Kirkhoff rod\nstatic constexpr unsigned int ne = 3; // dimesion of qe\n\n// Number of Chebyshev nodes\nstatic constexpr unsigned int number_of_chebyshev_nodes = 11;\n\n\n/*!\n * \\brief getA Compute the matrix A for the system x' = Ax + b\n * \\param t_qe The current generalized strains coordinates\n * \\tparam t_state_dimension The dimension of the state x\n * \\tparam t_number_of_chebyshev_nodes The number of Chebyshev nodes (which also account for the first one)\n * \\tparam t_na The number of allowed strain coordinates\n * \\tparam t_ne The number of modes per strain coordinate\n * \\return\n */\ntemplate\nEigen::MatrixXd getA(const Eigen::Matrix &t_qe)\n{\n\n // Define the Chebyshev points on the unit circle\n const auto x = ComputeChebyshevPoints();\n\n // Definition of the problem dymension\n static constexpr unsigned int problem_dimension = t_state_dimension * t_number_of_chebyshev_nodes;\n\n std::array, t_number_of_chebyshev_nodes> A_stack;\n\n Eigen::Vector3d K;\n Eigen::Matrix A_at_chebyshev_point;\n for(unsigned int i=0; i(x[i])*t_qe;\n\n // Compute the A matrix of Q' = 1/2 A(K) Q\n A_at_chebyshev_point << 0, -K(0), -K(1), -K(2),\n K(0), 0, K(2), -K(1),\n K(1), -K(2), 0, K(0),\n K(2), K(1), -K(0), 0;\n\n\n A_stack[i] = 0.5*A_at_chebyshev_point;\n }\n\n // Declare the matrix for the system Ax = b\n Eigen::Matrix A = Eigen::Matrix::Zero();\n A.setConstant(0);\n\n // Define a vector containing the indexes of the top left corners of the blocks composing the matrix A\n Eigen::VectorXi block_indexes = Eigen::VectorXi::LinSpaced(t_state_dimension, 0, t_number_of_chebyshev_nodes*(t_state_dimension-1));\n\n // Populate this matrix with all the elements in the right order\n for(unsigned int chebyshev_point=0; chebyshev_point &t_qe)\n{\n /* The state dimension and the number of nodes are known. The state dimension will not change\n * (a quaternion will remain a quaternion, a twist will remain a twist ecc..) and the number of\n * nodes are not changed at runtime and neither between runs. Typically, once a satisfactory number\n * of nodes has been found, it is kept for the whole lifetime of the project.\n *\n * Thus, we can enforce this concept with constexpr classifier so that the values are known at\n * compile time and we can use templated function for our matrices and vector, which are a bit faster.\n */\n // Dimension of the state\n constexpr unsigned int state_dimension = 4;\n\n // Problem size is the total number of elements\n constexpr unsigned int prob_dimension = state_dimension * number_of_chebyshev_nodes;\n // The subset of unknows in the problem\n constexpr unsigned int unknow_state_dimension = state_dimension * (number_of_chebyshev_nodes - 1);\n\n\n /* These are a set of type definition in order to have a more neat algorithm in\n * terms of matrix and vector dymensions\n */\n typedef Eigen::Matrix MatrixNpNp;\n typedef Eigen::Matrix VectorNp;\n\n typedef Eigen::Matrix MatrixNpNs;\n\n typedef Eigen::Matrix MatrixNuNu;\n typedef Eigen::Matrix VectorNu;\n\n typedef Eigen::Matrix MatrixNchebNcheb;\n\n typedef Eigen::Matrix MatrixNchebNs;\n\n /* In this first part, we precompute the matrices P and Dn. In fact, once we know the state dimension and the\n * number of nodes, these matrices are constant and thus me can compute them beforehand\n *\n * P.S. As we know the number of nodes, the matrix Phi can be computed at every chebyshev point to be stacked\n * into a vector. As a result, instead of computing the matrices, we directly access their value in the vector position.\n * This can actually be something more than 200 times faster.\n *\n */\n\n const MatrixNpNp P = getP();\n\n const MatrixNchebNcheb Dn = getDn();\n const MatrixNpNp D = Eigen::KroneckerProduct(Eigen::MatrixXd::Identity(state_dimension, state_dimension), Dn);\n\n /* In this part we compute the matrix A and the vector b.\n * In this case, the elements of the matrix A depends on the strain. As we change the strains during\n * simulation, we have to compute the components of A at runtime.\n *\n * Similarly, the vector b contains the values not related to the derivating variable, but that depends on other parameters.\n * For example when computing r' = R(Q)*Γ it does not depend on r but only on Q and Γ.\n *\n * We can interpret everything before this point as the setup and everything after as the actual run-time operations.\n *\n * In the following there are some matrices and operation that could be moved in the setup. However I choose to left them\n * there for clarity, but feel free to move where you thing it's better.\n *\n * The following is the translation into C++ of the equations presented in the PDF\n *\n */\n //tictoc.tic();\n const MatrixNpNp A = getA(t_qe);\n //tictoc.toc(\"Time to compute A : \");\n\n\n const VectorNp b = Eigen::Matrix::Zero();\n\n\n // Apply transformation of initial condition onto ODE's matrices\n\n const MatrixNpNp Ap = P.transpose() * A * P;\n const MatrixNpNp Dp = P.transpose() * D * P; // Can be moved in setup\n const VectorNp bp = P * b;\n\n\n\n // Compute the ivp\n const MatrixNpNs D_IT = Dp.block(0, 0); // Can be moved in setup\n const MatrixNpNs A_IT = Ap.block(0, 0);\n const VectorNp b_IT = ( D_IT - A_IT ) * t_initial_state;\n\n\n // Obtain the section related to the unknows of the problem\n const MatrixNuNu D_NN = Dp.block(state_dimension, state_dimension);\n const MatrixNuNu A_NN = Ap.block(state_dimension, state_dimension);\n const VectorNu ivp = b_IT.block(state_dimension, 0);\n const VectorNu b_NN = bp.block(state_dimension, 0);\n\n // Finally compute the states at the unknows Chebyshev points\n const VectorNu X_NN = (D_NN - A_NN).inverse() * (b_NN - ivp);\n\n // We now stack together the initial state on top of the other we just compute\n // Then we need to map back to a more readable stack of states\n const VectorNp X_tilde = P * (VectorNp() << t_initial_state, X_NN).finished();\n\n // Then we write the element row-wise\n const MatrixNchebNs X_stack = Eigen::Map(X_tilde.data());\n\n return X_stack;\n\n}\n\n\n\n\nEigen::MatrixXd IntegratePositions(const Eigen::Vector3d &t_initial_state,\n const Eigen::Matrix &t_qe,\n const Eigen::MatrixXd &t_quaternions_stack)\n{\n /* The state dimension and the number of nodes are known. The state dimension will not change\n * (a quaternion will remain a quaternion, a twist will remain a twist ecc..) and the number of\n * nodes are not changed at runtime and neither between runs. Typically, once a satisfactory number\n * of nodes has been found, it is kept for the whole lifetime of the project.\n *\n * Thus, we can enforce this concept with constexpr classifier so that the values are known at\n * compile time and we can use templated function for our matrices and vector, which are a bit faster.\n */\n // Dimension of the state\n constexpr unsigned int state_dimension = 3;\n\n // Problem size is the total number of elements\n constexpr unsigned int prob_dimension = state_dimension * number_of_chebyshev_nodes;\n // The subset of unknows in the problem\n constexpr unsigned int unknow_state_dimension = state_dimension * (number_of_chebyshev_nodes - 1);\n\n\n /* These are a set of type definition in order to have a more neat algorithm in\n * terms of matrix and vector dymensions\n */\n typedef Eigen::Matrix MatrixNpNp;\n typedef Eigen::Matrix VectorNp;\n\n typedef Eigen::Matrix MatrixNpNs;\n\n typedef Eigen::Matrix MatrixNuNu;\n typedef Eigen::Matrix VectorNu;\n\n typedef Eigen::Matrix MatrixNchebNcheb;\n\n typedef Eigen::Matrix MatrixNchebNs;\n\n MatrixNchebNs positions_stack;\n\n return positions_stack;\n}\n\n\nint main()\n{\n tictoc tictoc;\n\n // Const curvature strain field\n Eigen::Matrix qe;\n // Here we give some value for the strain\n qe << 0,\n 0,\n 0,\n 1.2877691307032,\n -1.63807499160786,\n 0.437406679142598,\n 0,\n 0,\n 0;\n\n// Let's deal with quaternion\n\n // Define the initial state\n const Eigen::Vector4d initial_state(1, 0, 0, 0); // Quaternion case\n const auto ruaternions_stack = GetQuaternions(initial_state, qe);\n\n\n// Let's deal with positions\n const Eigen::Vector3d initial_position(0, 0, 0);\n const auto positions_stack = IntegratePositions(initial_position, qe, ruaternions_stack);\n\n Eigen::Quaterniond q;\n Eigen::Matrix3d R = q.toRotationMatrix();\n\n\n std::cout<< \"X_stack = \" << std::endl << ruaternions_stack <\nusing namespace Eigen;\n\n#include \n#include \nusing namespace autodiff;\n\n#include \n\nnamespace samson::se3\n{\n\n using Vector6dual = Matrix;\n using Matrix4dual = Matrix;\n\n auto se3(const Vector6dual &v) -> Matrix4dual\n {\n Matrix4dual X;\n X << 0.0, -v(2), v(1), v(3),\n v(2), 0.0, -v(0), v(4),\n -v(1), v(0), 0.0, v(5),\n 0.0, 0.0, 0.0, 0.0;\n return X;\n }\n\n auto se3(const Matrix4dual &X) -> Vector6dual\n {\n Vector6dual v;\n v << X(2, 1), X(0, 2), X(1, 0), X(0, 3), X(1, 3), X(2, 3);\n return v;\n }\n\n auto exp(Vector6dual &x) -> Matrix4dual\n {\n using samson::so3::from_axis_angle;\n using samson::so3::so3;\n\n Vector3dual w = x.head<3>();\n Vector3dual v = x.tail<3>();\n\n dual theta = w.norm();\n Matrix4dual ret = Matrix4dual::Identity();\n if (theta == 0.0)\n {\n ret = Matrix4dual::Identity();\n ret.block<3, 1>(0, 3) = v;\n return ret;\n }\n\n Vector3dual k = w.normalized();\n dual sin_theta = sin(theta);\n dual one_minus_cos_theta = 1.0 - cos(theta);\n Matrix3dual K = so3(k);\n Matrix3dual KK = K * K;\n\n Matrix3dual I = Matrix3dual::Identity();\n\n ret.block<3, 3>(0, 0) = from_axis_angle(k, theta);\n ret.block<3, 1>(0, 3) = (I * theta + one_minus_cos_theta * K + (theta - sin_theta) * KK) * (v / theta);\n\n return ret;\n }\n\n auto exp(Matrix4dual &X) -> Matrix4dual\n {\n Vector6dual x = se3(X);\n return exp(x);\n }\n} // namespace samson::se3", "meta": {"hexsha": "cd2ef1226efa69871d7dba41ad5f9cbff56db706", "size": 1750, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/samson/se3.hpp", "max_stars_repo_name": "tingelst/samson", "max_stars_repo_head_hexsha": "a34717d40d61868cb87560b94f422859d59d8bde", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/samson/se3.hpp", "max_issues_repo_name": "tingelst/samson", "max_issues_repo_head_hexsha": "a34717d40d61868cb87560b94f422859d59d8bde", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/samson/se3.hpp", "max_forks_repo_name": "tingelst/samson", "max_forks_repo_head_hexsha": "a34717d40d61868cb87560b94f422859d59d8bde", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.6478873239, "max_line_length": 111, "alphanum_fraction": 0.5188571429, "num_tokens": 612, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6537754807029603}} {"text": "#include \n\n#include \n\n#include \n#include \n\nusing namespace QuantLib;\nusing namespace boost::assign;\n\n\nvoid bdkSmile() {\n\n std::ofstream out;\n out.open(\"bdk.dat\");\n\n Real forward = 0.03;\n Real expiryTime = 20.0;\n\n std::vector sabrParams;\n sabrParams.push_back(0.15); // alpha\n sabrParams.push_back(0.8); // beta\n sabrParams.push_back(0.50); // nu\n sabrParams.push_back(-0.48); // rho\n\n boost::shared_ptr sabr(\n new SabrSmileSection(expiryTime, forward, sabrParams));\n\n boost::shared_ptr bdk(new BdkSmileSection(sabr, 1.0, 1.0, 0.025, 0.06));\n\n Real strike = 0.0001;\n while (strike <= 0.10) {\n out << strike << \" \" << sabr->optionPrice(strike) << \" \"\n << bdk->optionPrice(strike) << \" \"\n << sabr->digitalOptionPrice(strike) << \" \"\n << bdk->digitalOptionPrice(strike) << \" \" << sabr->density(strike)\n << \" \" << bdk->density(strike) << \" \" << sabr->volatility(strike) << \" \" <<\n bdk->volatility(strike) << std::endl;\n strike += 0.0001;\n }\n\n out.close();\n\n}\n\nvoid zabrExamples() {\n\n Real forward = 0.03;\n Real expiryTime = 15;\n\n Real alpha = 0.10;\n Real beta = 0.7;\n Real nu = 0.20;\n Real rho = -0.4;\n Real gamma = 1.0;\n\n std::vector sabrParams, zabrParams;\n\n sabrParams += alpha, beta, nu, rho;\n zabrParams += alpha, beta, nu, rho, gamma;\n\n boost::shared_ptr sabr = boost::make_shared(expiryTime, forward, sabrParams);\n\n boost::shared_ptr zabrln =\n boost::make_shared(\n expiryTime, forward, zabrParams,\n ZabrSmileSection::ShortMaturityLognormal);\n\n boost::shared_ptr zabrfull =\n boost::make_shared(\n expiryTime, forward, zabrParams,\n ZabrSmileSection::FullFd, std::vector(), 2);\n\n boost::shared_ptr zabrfd =\n boost::make_shared(\n expiryTime, forward, zabrParams,\n ZabrSmileSection::LocalVolatility, std::vector(), 2);\n\n // only for debug\n boost::shared_ptr tmpZabrFull = boost::make_shared(\n expiryTime, forward, alpha, beta, nu, rho, gamma);\n\n std::ofstream out;\n out.open(\"smiles.dat\");\n\n // debug full fd\n std::vector tmpFullFd(100);\n Size tmpIdx = 0;\n#pragma omp parallel for\n for(Size i=0;i<100;++i)\n tmpFullFd[i] = 0.0;//tmpZabrFull->fullFdPrice(0.0001+i*0.0010);\n // end debug full fd\n\n Real strike = 0.0001;\n while (strike <= 1.00) {\n // 1 strike\n out << strike << \" \";\n // 2, 3, 4, 5 sabr\n out << sabr->volatility(strike) << \" \"\n << sabr->optionPrice(strike) << \" \"\n << sabr->digitalOptionPrice(strike) << \" \"\n << sabr->density(strike) << \" \";\n // 6, 7, 8, 9 zabr (lognormal short mat)\n out << zabrln->volatility(strike) << \" \"\n << zabrln->optionPrice(strike) << \" \"\n << zabrln->digitalOptionPrice(strike) << \" \"\n << zabrln->density(strike) << \" \";\n // 10, 11, 12, 13 zabr (full fd)\n out <volatility(strike) << \" \"\n << zabrfull->optionPrice(strike) << \" \"\n << zabrfull->digitalOptionPrice(strike) << \" \"\n << zabrfull->density(strike) << \" \";\n // 14, 15, 16, 17 zabr (fd)\n out <volatility(strike) << \" \"\n << zabrfd->optionPrice(strike) << \" \"\n << zabrfd->digitalOptionPrice(strike) << \" \"\n << zabrfd->density(strike) << \" \";\n // 14 zabr price full fd (debug)\n out << tmpFullFd[tmpIdx++];\n strike += 0.0010;\n out << std::endl;\n }\n\n out.close();\n\n}\n\nvoid zabrPaper() {\n\n // compare different SABR formulas\n\n std::ofstream out;\n out.open(\"smiles.dat\");\n\n // this is an example from the paper, forward is a guess (since not\n // mentioned there)\n\n Real forward = 0.0325;\n Real expiryTime = 10.0;\n\n std::vector sabrParams, zabrParams;\n\n sabrParams.push_back(0.0873); // alpha\n sabrParams.push_back(0.7); // beta\n sabrParams.push_back(0.47); // nu\n sabrParams.push_back(-0.48); // rho\n\n // Black Scholes with 20%\n // sabrParams.push_back(0.20); // alpha\n // Sabrparams.push_back(1.0); // beta\n // sabrParams.push_back(0.0001); // nu\n // sabrParams.push_back(0.0); // rho\n\n // BS beta = 0.7\n // sabrParams.push_back(0.08); // alpha\n // sabrParams.push_back(0.7); // beta\n // sabrParams.push_back(0.0001); // nu\n // sabrParams.push_back(0.0); // rho\n\n // BScholes nu = 0.50\n // sabrParams.push_back(0.20); // alpha\n // sabrParams.push_back(1.0); // beta\n // sabrParams.push_back(0.50); // nu\n // sabrParams.push_back(0.0); // rho\n\n zabrParams.push_back(sabrParams[0]);\n zabrParams.push_back(sabrParams[1]);\n zabrParams.push_back(sabrParams[2]);\n zabrParams.push_back(sabrParams[3]);\n zabrParams.push_back(1.0); // gamma\n\n std::vector zabrParamsg0(zabrParams);\n zabrParamsg0[4] = 0.0;\n std::vector zabrParamsg05(zabrParams);\n zabrParamsg05[4] = 0.5;\n std::vector zabrParamsg15(zabrParams);\n zabrParamsg15[4] = 1.5;\n std::vector zabrParamsg17(zabrParams);\n zabrParamsg17[4] = 1.7;\n\n boost::shared_ptr sabr(\n new SabrSmileSection(expiryTime, forward, sabrParams));\n\n boost::shared_ptr zabrln(\n new ZabrSmileSection(expiryTime, forward, zabrParams,\n ZabrSmileSection::ShortMaturityLognormal));\n\n boost::shared_ptr zabrnm(\n new ZabrSmileSection(expiryTime, forward, zabrParams,\n ZabrSmileSection::ShortMaturityNormal));\n\n boost::shared_ptr zabrlv(new ZabrSmileSection(\n expiryTime, forward, zabrParams, ZabrSmileSection::LocalVolatility));\n\n boost::shared_ptr zabrnmg0(\n new ZabrSmileSection(expiryTime, forward, zabrParamsg0,\n ZabrSmileSection::ShortMaturityNormal));\n boost::shared_ptr zabrnmg05(\n new ZabrSmileSection(expiryTime, forward, zabrParamsg05,\n ZabrSmileSection::ShortMaturityNormal));\n boost::shared_ptr zabrnmg15(\n new ZabrSmileSection(expiryTime, forward, zabrParamsg15,\n ZabrSmileSection::ShortMaturityNormal));\n boost::shared_ptr zabrnmg17(\n new ZabrSmileSection(expiryTime, forward, zabrParamsg17,\n ZabrSmileSection::ShortMaturityNormal));\n\n // boost::shared_ptr zabrfd(new ZabrSmileSection(\n // expiryTime, forward, zabrParams, ZabrSmileSection::FullFd));\n\n boost::shared_ptr zabrmodel = zabrln->model();\n\n Real strike = 0.0001; // we start at 1bp ...\n\n while (strike <= 0.50) { // ... and go to 50% ...\n\n // debug: localvol function for sabr hardcoded\n Real ytmp = strike >= 0.0\n ? 1.0 / (sabrParams[0] * (1.0 - sabrParams[1])) *\n (pow(forward, 1.0 - sabrParams[1]) -\n pow(strike, 1.0 - sabrParams[1]))\n : 1.0 / (sabrParams[0] * (1.0 - sabrParams[1])) *\n (pow(-strike, 1.0 - sabrParams[1]) +\n pow(forward, 1.0 - sabrParams[1]));\n Real Jtmp = sqrt(1.0 + sabrParams[2] * sabrParams[2] * ytmp * ytmp -\n 2.0 * sabrParams[3] * sabrParams[2] * ytmp);\n Real localVol =\n Jtmp * pow(std::fabs(strike), sabrParams[1]) * sabrParams[0];\n // end debug\n\n out << strike << \" \" // 1 SABR hagan\n << sabr->volatility(strike) << \" \" // 2\n << sabr->optionPrice(strike) << \" \" // 3\n << sabr->digitalOptionPrice(strike) << \" \" // 4\n << sabr->density(strike) << \" \" // 5\n << zabrln->volatility(strike)\n << \" \" // 6 ZABR short maturity lognormal\n << zabrln->optionPrice(strike) << \" \" // 7\n << zabrln->digitalOptionPrice(strike) << \" \" // 8\n << zabrln->density(strike) << \" \" // 9\n << zabrnm->volatility(strike)\n << \" \" // 10 ZABR short maturity normal\n << zabrnm->optionPrice(strike) << \" \" // 11\n << zabrnm->digitalOptionPrice(strike) << \" \" // 12\n << zabrnm->density(strike) << \" \" // 13\n << zabrmodel->localVolatility(strike)\n << \" \" // 14 *** Equivalent deterministic volatility\n << localVol\n << \" \" // 15 *** same as 14, but hardcoded for SABR (debug)\n << zabrlv->volatility(strike) << \" \" // 16 ZABR local vol\n << zabrlv->optionPrice(strike) << \" \" // 17\n << zabrlv->digitalOptionPrice(strike, Option::Call, 1.0, 1E-4)\n << \" \" // 18\n << zabrlv->density(strike, Option::Call, 1E-4) << \" \" // 19\n // << zabrfd->volatility(strike) << \" \" // 20 ZABR fd\n // << zabrfd->optionPrice(strike) << \" \" // 21\n // << zabrfd->digitalOptionPrice(strike) << \" \" // 22\n // << zabrfd->density(strike) << \" \" // 23\n << zabrnmg0->volatility(strike)\n << \" \" // 20 ZABR short maturity normal gamma=0.0\n << zabrnmg05->volatility(strike)\n << \" \" // 21 ZABR short maturity normal gamma=0.5\n << zabrnmg15->volatility(strike)\n << \" \" // 22 ZABR short maturity normal gamma=1.5\n << zabrnmg17->volatility(strike)\n << \" \" // 23 ZABR short maturity normal gamma=1.7\n << std::endl;\n\n strike += 0.0001; // ... in steps of 5bp\n }\n\n out.close();\n}\n\nvoid splineSmiles() {\n\n std::ofstream out;\n out.open(\"smiles2.dat\");\n\n // same example as in zabrPaper\n\n Real forward = 0.0325;\n Real expiryTime = 10.0;\n\n std::vector sabrParams;\n\n sabrParams.push_back(0.0873); // alphacd\n sabrParams.push_back(0.7); // beta\n sabrParams.push_back(0.47); // nu\n sabrParams.push_back(-0.48); // rho\n\n std::vector money;\n for(Size i=0;i<40;i++) {\n money.push_back(i/40.0);\n }\n for(Size i=10;i<=100;i++) {\n money.push_back(i*0.1);\n }\n for(Size i=11;i<=100;i++) {\n money.push_back(i*1.0);\n }\n\n boost::shared_ptr sabr(\n new SabrSmileSection(expiryTime, forward, sabrParams));\n\n boost::shared_ptr flatSmileSection(new FlatSmileSection(expiryTime,0.10,Actual365Fixed(),forward));\n\n boost::shared_ptr spline(\n new SplineDensitySmileSection(flatSmileSection, forward, 0.0, 1.00,\n false, money));\n\n std::cout << \"arbitrage free region is \" << spline->leftCoreStrike()\n << \" ... \" << spline->rightCoreStrike() << std::endl;\n\n Real strike = 0.00001;\n\n while (strike <= 3.0) {\n\n Real vol = 0.10;\n Real mu = std::log(forward) + vol*vol*expiryTime/2.0;\n Real referencePrice = blackFormula(Option::Call,strike,forward,vol*sqrt(expiryTime));\n Real referenceDigital = blackFormulaCashItmProbability(Option::Call,strike,forward,vol*sqrt(expiryTime));\n NormalDistribution norm(mu,vol*sqrt(expiryTime));\n Real referenceDensity = norm(std::log(strike))/strike;\n\n out << strike << \" \" // 1\n // << sabr->volatility(strike) << \" \" // 2\n // << sabr->optionPrice(strike) << \" \" // 3\n // << sabr->digitalOptionPrice(strike) << \" \" // 4\n // << sabr->density(strike) << \" \" // 5\n << flatSmileSection->volatility(strike) << \" \" // 2\n << flatSmileSection->optionPrice(strike) << \" \" // 3\n << flatSmileSection->digitalOptionPrice(strike) << \" \" // 4\n << flatSmileSection->density(strike) << \" \" // 5\n << spline->volatility(strike) << \" \" // 6\n << spline->optionPrice(strike) << \" \" // 7\n << spline->digitalOptionPrice(strike) << \" \" // 8\n << spline->density(strike) << \" \" // 9\n // << referencePrice << \" \" // 5\n // << referenceDigital << \" \" //6\n // << referenceDensity << \" \" //7\n // << referenceDigital - spline->digitalOptionPrice(strike) << \" \" // 8\n << std::endl;\n strike += 0.0010;\n }\n\n out.close();\n}\n\nvoid sbSmiles() {\n\n std::ofstream out;\n out.open(\"smiles3.dat\");\n\n Real forward = 0.0325;\n Real expiryTime = 10.0;\n\n\n boost::shared_ptr sb(new SbSmileSection(expiryTime,forward,\n 0.0,0.50,1.0,1.0));\n\n Real strike = -1.0;\n\n while (strike <= 1.0) {\n\n out << strike << \" \" // 1\n //<< sb->volatility(strike) << \" \" // 2\n << sb->optionPrice(strike) << \" \" // 3\n << sb->digitalOptionPrice(strike) << \" \" // 4\n << sb->density(strike) << \" \" // 5\n << std::endl;\n strike += 0.0010;\n }\n\n out.close();\n\n}\n\nvoid interpolation() {\n\n std::ofstream out;\n out.open(\"sample.dat\");\n\n Real x[] = { 0.0, 0.5, 1.0, 1.5, 2.0 };\n Real y1[] = { 0.0, 0.5, 1.0, 0.5, 0.0 };\n Real y2[] = { 0.0, 0.5, 0.2, 0.5, 0.0 };\n\n std::vector xv(x,x+5);\n std::vector yv1(y1,y1+5);\n std::vector yv2(y2,y2+5);\n\n CubicInterpolation i1(xv.begin(), xv.end(), yv1.begin(), CubicInterpolation::Parabolic, false,\n CubicInterpolation::FirstDerivative, 0.0, CubicInterpolation::FirstDerivative, 0.0);\n\n CubicInterpolation i2(xv.begin(), xv.end(), yv2.begin(), CubicInterpolation::Parabolic, false,\n CubicInterpolation::FirstDerivative, 0.0, CubicInterpolation::FirstDerivative, 0.0);\n\n Real h = 0.0;\n while(h <= 2.01) {\n out << h << \" \" << i1(h) << \" \" << i2(h) << std::endl;\n h+=0.01;\n }\n\n out.close();\n\n}\n\nint main(int, char * []) {\n zabrExamples();\n // splineSmiles();\n}\n", "meta": {"hexsha": "5216bd0eb0d3d78238bc16511d6493f0fe61f626", "size": 14901, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/InterestRateSmiles/InterestRateSmiles.cpp", "max_stars_repo_name": "universe1987/QuantLib", "max_stars_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-03-28T15:05:23.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-17T23:05:57.000Z", "max_issues_repo_path": "Examples/InterestRateSmiles/InterestRateSmiles.cpp", "max_issues_repo_name": "universe1987/QuantLib", "max_issues_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-02T20:32:43.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-02T20:32:43.000Z", "max_forks_repo_path": "Examples/InterestRateSmiles/InterestRateSmiles.cpp", "max_forks_repo_name": "pcaspers/quantlib", "max_forks_repo_head_hexsha": "bbb0145aff285853755b9f6ed013f53a41163acb", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2015-01-26T14:50:24.000Z", "max_forks_repo_forks_event_max_datetime": "2015-10-23T07:41:30.000Z", "avg_line_length": 36.1674757282, "max_line_length": 117, "alphanum_fraction": 0.5345949936, "num_tokens": 4441, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206712569267, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6537754753423252}} {"text": "#include \n#include \n#include \n#include \n#include \n\nusing namespace boost::numeric::odeint;\n\nusing state_t = std::vector;\n\nint mod_subtract(int a, int b, int bound){\n\t//computes a - b mod bound\n\tint res = a - b;\n\tif(res < 0){\n\t\twhile(res < 0){\n\t\t\tres += bound;\n\t\t}\n\t}\n\telse if(res >= bound){\n\t\tres -= bound;\n\t}\n\treturn res;\n}\n\nvoid time_differentiate(const state_t& x, state_t& dxdt, const double /* type param */)\n{\n\tauto J = x.size();\n\n\t//precondition: x and dx/dt have the same length\n\tassert(J == dxdt.size());\n\t\n\tauto bound = static_cast(J);\n\n\tdouble F = 8;\n\n\tfor(int i = 0; i < bound; i++){\n\t\tdxdt[i] = ( x[(i+1) % bound] - x[mod_subtract(i, 2, bound)] ) * x[mod_subtract(i,1,bound)] - x[i] + F;\n\t}\n}\n\nvoid apply_initial_conditions(state_t& x){\n\t//apply initial conditions from the HW\n\tfor(auto& val : x){\n\t\tval = 0;\n\t}\n\tx[1] = 1.0;\n}\n\nstruct state_storage\n{\n\tstd::vector& m_states;\n\n\tstd::vector& m_times;\n\n\tstate_storage(std::vector& states, std::vector& times) :\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tm_states(states),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tm_times(times) {};\n\n\tvoid operator()(const state_t& x, double t){\n\t\tm_states.push_back(x);\n\t\tm_times.push_back(t);\n\t}\n\n};\n\nint main(int argc, char** argv){\n\n\tstate_t x(10);\n\n\tstd::vector x_stored;\n\tstd::vector times;\n\n\tapply_initial_conditions(x);\n\n\tdouble time_length = 10.0;\n\n\tdouble init_step_size = 0.05;\n\n\tstd::cout << \"Integrating ODE over 10 second total time length.\\n\";\n\t\n\t//solve with runge_kutta54_cash_karp stepper\n\tsize_t steps = integrate(time_differentiate, x, 0.0,\n\t\t\t\t\t\t \t time_length, init_step_size, \n\t\t\t\t\t\t\t state_storage(x_stored, times) );\n\n\tstd::cout << \"Solved ODE in \" << steps << \" timesteps.\\n\";\n\n\tstd::ofstream filewriter;\n\tfilewriter.open(\"hw1.csv\");\n\tfor(const auto& x : x_stored){\n\t\tfor(const auto& val : x){\n\t\t\tfilewriter << val << \", \";\n\t\t}\n\t\tfilewriter << \"\\n\";\n\t}\n\n\tfilewriter.close();\n\t\n\treturn 0;\n}\n", "meta": {"hexsha": "c83fabc644c73a79f1b4775eddab43ba424ad292", "size": 1995, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "HW-Code/HW1/hw1.cpp", "max_stars_repo_name": "DiffeoInvariant/Data-Assimilation", "max_stars_repo_head_hexsha": "7afe25b1efb87a6988bea6df34e17650d9eb86fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "HW-Code/HW1/hw1.cpp", "max_issues_repo_name": "DiffeoInvariant/Data-Assimilation", "max_issues_repo_head_hexsha": "7afe25b1efb87a6988bea6df34e17650d9eb86fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "HW-Code/HW1/hw1.cpp", "max_forks_repo_name": "DiffeoInvariant/Data-Assimilation", "max_forks_repo_head_hexsha": "7afe25b1efb87a6988bea6df34e17650d9eb86fa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.7524752475, "max_line_length": 104, "alphanum_fraction": 0.6365914787, "num_tokens": 586, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951182587158, "lm_q2_score": 0.7745833737577158, "lm_q1q2_score": 0.6536671277985026}} {"text": "/*\n * Copyright 2022 Sean McBane under the terms of the MIT license.\n * This file contains validation via method of manufactured solution for the\n * linear elasticity code. The analytical solution for displacement is given\n * by\n *\n * u_x = (-3.0/2.0*pow(x, 3) + (23.0/4.0)*pow(x, 2) - 5*x)*sin(M_PI*y) +\n * ((3.0/2.0)*pow(x, 3) - 13.0/4.0*pow(x, 2) + 1)*cos(M_PI*y);\n *\n * u_y = -2*x*y + x + 2*y - 1;\n *\n * Young's modulus: E = 1 + sin(M_PI * x) * cos(M_PI * y) / 4;\n * Poisson's ratio: nu = 3 / 10;\n *\n * The functions below are all derived symbolically from these solutions.\n */\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"convert_to_eigen.hpp\"\n#include \"elasticity.hpp\"\n#include \"get_triangles.hpp\"\n#include \"mesh_tools.hpp\"\n#include \"read_mesh.hpp\"\n\nusing namespace Elasticity;\nusing namespace std::chrono;\n\ndouble manufactured_ux(double x, double y)\n{\n return (-3.0 / 2.0 * pow(x, 3) + (23.0 / 4.0) * pow(x, 2) - 5 * x) * sin(M_PI * y) +\n ((3.0 / 2.0) * pow(x, 3) - 13.0 / 4.0 * pow(x, 2) + 1) * cos(M_PI * y);\n}\n\ndouble manufactured_uy(double x, double y) { return -2 * x * y + x + 2 * y - 1; }\n\nEigen::Vector2d u_true(std::array coord)\n{\n const auto [x, y] = coord;\n return Eigen::Vector2d(manufactured_ux(x, y), manufactured_uy(x, y));\n}\n\nEigen::Vector2d u_right(std::array coord) { return u_true(coord); }\n\nEigen::Vector2d u_left(std::array coord) { return u_true(coord); }\n\nEigen::Vector2d u_upper(std::array coord) { return u_true(coord); }\n\nEigen::Vector2d u_lower(std::array coord) { return u_true(coord); }\n\n/*\n * Definitions of the Lame parameters for the manufactured solution.\n */\ndouble manufactured_lambda(std::array coord)\n{\n auto [x, y] = coord;\n return (15.0 / 182.0) * sin(M_PI * x) * cos(M_PI * y) + 30.0 / 91.0;\n}\n\ndouble manufactured_mu(std::array coord)\n{\n auto [x, y] = coord;\n return (5.0 / 52.0) * sin(M_PI * x) * cos(M_PI * y) + 5.0 / 13.0;\n}\n\n/*\n * Manufactured solution traction boundary condition for the lower boundary.\n */\ndouble traction_lower_x(double x, [[maybe_unused]] double y) noexcept\n{\n return (5.0 / 208.0) * (M_PI * x * (6 * pow(x, 2) - 23 * x + 20) - 4) * (sin(M_PI * x) + 4);\n}\n\ndouble traction_lower_y(double x, [[maybe_unused]] double y) noexcept\n{\n return (5.0 / 364.0) * (sin(M_PI * x) + 4) * (-27 * pow(x, 2) + 79 * x - 40);\n}\n\nEigen::Vector2d traction_lower(std::array coord) noexcept\n{\n auto [x, y] = coord;\n return Eigen::Vector2d(traction_lower_x(x, y), traction_lower_y(x, y));\n}\n\n/*\n * Manufactured solution traction boundary condition for the upper boundary.\n */\ndouble traction_upper_x(double x, [[maybe_unused]] double y) noexcept\n{\n return (5.0 / 208.0) * (-M_PI * x * (6 * pow(x, 2) - 23 * x + 20) + 4) * (sin(M_PI * x) - 4);\n}\n\ndouble traction_upper_y(double x, [[maybe_unused]] double y) noexcept\n{\n return (5.0 / 364.0) * (sin(M_PI * x) - 4) * (27 * pow(x, 2) + x - 40);\n}\n\nEigen::Vector2d traction_upper(std::array coord) noexcept\n{\n auto [x, y] = coord;\n return Eigen::Vector2d(traction_upper_x(x, y), traction_upper_y(x, y));\n}\n\n/*\n * Manufactured solution forcing term on \\Omega\n */\ndouble forcing_x(double x, double y) noexcept\n{\n return (5.0 / 52.0) * ((13 - 18 * x) * cos(M_PI * y) + (18 * x - 23) * sin(M_PI * y)) *\n (sin(M_PI * x) * cos(M_PI * y) + 4) +\n (15.0 / 364.0) * (sin(M_PI * x) * cos(M_PI * y) + 4) *\n ((13 - 18 * x) * cos(M_PI * y) + (18 * x - 23) * sin(M_PI * y) + 4) +\n (5.0 / 208.0) * (sin(M_PI * x) * cos(M_PI * y) + 4) *\n (-pow(M_PI, 2) * x * (6 * pow(x, 2) - 23 * x + 20) * sin(M_PI * y) +\n pow(M_PI, 2) * (6 * pow(x, 3) - 13 * pow(x, 2) + 4) * cos(M_PI * y) + 8) -\n 5.0 / 52.0 * M_PI *\n (x * (9 * x - 13) * cos(M_PI * y) +\n (-9 * pow(x, 2) + 23 * x - 10) * sin(M_PI * y)) *\n cos(M_PI * x) * cos(M_PI * y) +\n (15.0 / 364.0) * M_PI *\n (-x * (9 * x - 13) * cos(M_PI * y) + 4 * x +\n (9 * pow(x, 2) - 23 * x + 10) * sin(M_PI * y) - 4) *\n cos(M_PI * x) * cos(M_PI * y) -\n 5.0 / 208.0 * M_PI *\n (M_PI * x * (6 * pow(x, 2) - 23 * x + 20) * cos(M_PI * y) + 8 * y +\n M_PI * (6 * pow(x, 3) - 13 * pow(x, 2) + 4) * sin(M_PI * y) - 4) *\n sin(M_PI * x) * sin(M_PI * y);\n}\n\ndouble forcing_y(double x, double y) noexcept\n{\n return (5.0 / 1456.0) * M_PI *\n ((112 - 112 * x) * sin(M_PI * x) * sin(M_PI * y) +\n 26 * (sin(M_PI * x) * cos(M_PI * y) + 4) *\n (x * (9 * x - 13) * sin(M_PI * y) +\n (9 * pow(x, 2) - 23 * x + 10) * cos(M_PI * y)) -\n 12 *\n (-x * (9 * x - 13) * cos(M_PI * y) + 4 * x +\n (9 * pow(x, 2) - 23 * x + 10) * sin(M_PI * y) - 4) *\n sin(M_PI * x) * sin(M_PI * y) +\n 7 *\n (M_PI * x * (6 * pow(x, 2) - 23 * x + 20) * cos(M_PI * y) + 8 * y +\n M_PI * (6 * pow(x, 3) - 13 * pow(x, 2) + 4) * sin(M_PI * y) - 4) *\n cos(M_PI * x) * cos(M_PI * y));\n}\n\nEigen::Vector2d forcing(std::array coord) noexcept\n{\n auto [x, y] = coord;\n return Eigen::Vector2d(forcing_x(x, y), forcing_y(x, y));\n}\n\nauto compute_parameter_functions(const MeshVariant &mv)\n{\n Eigen::VectorXd lambda = evaluate_on_mesh(mv, manufactured_lambda);\n Eigen::VectorXd mu = evaluate_on_mesh(mv, manufactured_mu);\n return std::pair(lambda, mu);\n}\n\nauto get_boundary_conditions(const MeshVariant &mv, size_t right_bound, size_t left_bound)\n{\n Eigen::Matrix2Xd uright = evaluate_on_boundary(mv, right_bound, u_right);\n Eigen::Matrix2Xd uleft = evaluate_on_boundary(mv, left_bound, u_left);\n\n return std::pair(uright, uleft);\n}\n\nnamespace\n{\n\nEigen::Matrix2Xd solve(const MeshVariant &mv)\n{\n size_t right_bound = find_boundary_with_tag(mv, \"RIGHT\").value();\n size_t left_bound = find_boundary_with_tag(mv, \"LEFT\").value();\n size_t upper_bound = find_boundary_with_tag(mv, \"UPPER\").value();\n size_t lower_bound = find_boundary_with_tag(mv, \"LOWER\").value();\n\n auto tp_start = steady_clock::now();\n Eigen::Matrix2Xd force_coefficients = evaluate_on_mesh(mv, forcing);\n Eigen::Matrix2Xd nodal_forcing = Elasticity::integrate_volume_force(mv, force_coefficients);\n\n Eigen::Matrix2Xd traction_upper_coefficients =\n evaluate_on_boundary(mv, upper_bound, traction_upper);\n Eigen::Matrix2Xd traction_lower_coefficients =\n evaluate_on_boundary(mv, lower_bound, traction_lower);\n\n Eigen::Matrix2Xd traction_upper =\n integrate_traction_force(mv, upper_bound, traction_upper_coefficients);\n Eigen::Matrix2Xd traction_lower =\n integrate_traction_force(mv, lower_bound, traction_lower_coefficients);\n\n add_traction_force(mv, nodal_forcing, upper_bound, traction_upper);\n add_traction_force(mv, nodal_forcing, lower_bound, traction_lower);\n\n auto tp_end = steady_clock::now();\n\n size_t us = duration_cast(tp_end - tp_start).count();\n printf(\"Assembling forcing took %ld us\\n\", us);\n\n Eigen::VectorXd lambda, mu;\n std::tie(lambda, mu) = compute_parameter_functions(mv);\n\n Eigen::Matrix2Xd uright, uleft;\n std::tie(uright, uleft) = get_boundary_conditions(mv, right_bound, left_bound);\n\n tp_start = steady_clock::now();\n auto K_unassembled = Elasticity::assemble_stiffness(mv, lambda, mu);\n\n auto flat_forcing = nodal_forcing.reshaped();\n Elasticity::impose_dirichlet_condition(mv, K_unassembled, flat_forcing, right_bound, uright);\n Elasticity::impose_dirichlet_condition(mv, K_unassembled, flat_forcing, left_bound, uleft);\n\n auto K = convert_to_eigen(K_unassembled);\n tp_end = steady_clock::now();\n us = duration_cast(tp_end - tp_start).count();\n printf(\"Assembling stiffness took %ld us\\n\", us);\n\n tp_start = steady_clock::now();\n Eigen::Matrix2Xd u(2, nodal_forcing.cols());\n u.reshaped() = Eigen::SimplicialLDLT, Eigen::Upper>(K).solve(\n nodal_forcing.reshaped());\n tp_end = steady_clock::now();\n us = duration_cast(tp_end - tp_start).count();\n printf(\"Linear system solve took %ld us\\n\", us);\n\n return u;\n}\n\n} // namespace\n\nint main(int argc, char *argv[])\n{\n if (!(argc > 1))\n {\n fprintf(stderr, \"Usage: ./manufactured [mesh order] [mesh files...]\\n\");\n return 1;\n }\n\n int order = atoi(argv[1]);\n if (!(order >= 1 && order <= 4))\n {\n fprintf(stderr, \"Got mesh order %d; order should be 1-4\\n\", order);\n return 2;\n }\n\n for (int fi = 2; fi < argc; ++fi)\n {\n FILE *infile = fopen(argv[fi], \"r\");\n if (!infile)\n {\n fprintf(stderr, \"Skipping mesh file %s (couldn't be opened)\\n\", argv[fi]);\n continue;\n }\n fclose(infile);\n auto mesh = read_mesh(argv[fi], order);\n FILE *outfile = fopen(\"mesh_elements.dat\", \"wb\");\n if (!outfile)\n {\n fprintf(stderr, \"Skipping output, couldn't open file\\n\");\n }\n else\n {\n get_triangle_info(mesh).serialize(outfile);\n fclose(outfile);\n }\n Eigen::Matrix2Xd u = solve(mesh);\n outfile = fopen(\"u.dat\", \"wb\");\n int64_t dims[] = {u.rows(), u.cols()};\n fwrite(dims, sizeof(int64_t), 2, outfile);\n fwrite(u.data(), sizeof(double), u.size(), outfile);\n fclose(outfile);\n\n auto [l2_error, u_norm] = Elasticity::integrate_error(mesh, u, u_true);\n\n printf(\n \"Error for input file %s: %E (L^2 error) %E (L^2 u)\\n\", argv[fi], l2_error, u_norm);\n }\n\n return 0;\n}\n\n", "meta": {"hexsha": "3846639175384e640b0f30c864deadac1c023b1f", "size": 9871, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "validation/manufactured.cpp", "max_stars_repo_name": "slmcbane/Elasticity", "max_stars_repo_head_hexsha": "bf3ae6c27659d803b81fc69121a96af797616f3b", "max_stars_repo_licenses": ["MIT", "Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "validation/manufactured.cpp", "max_issues_repo_name": "slmcbane/Elasticity", "max_issues_repo_head_hexsha": "bf3ae6c27659d803b81fc69121a96af797616f3b", "max_issues_repo_licenses": ["MIT", "Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "validation/manufactured.cpp", "max_forks_repo_name": "slmcbane/Elasticity", "max_forks_repo_head_hexsha": "bf3ae6c27659d803b81fc69121a96af797616f3b", "max_forks_repo_licenses": ["MIT", "Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.513986014, "max_line_length": 98, "alphanum_fraction": 0.5858575626, "num_tokens": 3134, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6536661147779619}} {"text": "#include \"clustering/spectral_cluster.h\"\n#include \"clustering/kmeans.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"util/timer.h\"\n\nnamespace GraphSfM {\n\nstd::unordered_map SpectralCluster::ComputeCluster(\n const std::vector>& edges,\n const std::vector& weights,\n const int num_partitions)\n{\n if (num_partitions == 1) {\n for (auto node : nodes_) {\n labels_[node] = 0;\n }\n return labels_;\n }\n\n colmap::Timer timer;\n std::vector> s_triplets;\n std::unordered_map degrees;\n const int k = num_partitions;\n cluster_num_ = num_partitions;\n\n for (uint i = 0; i < edges.size(); i++) {\n auto edge = edges[i];\n nodes_.push_back(edge.first);\n nodes_.push_back(edge.second);\n }\n\n std::sort(nodes_.begin(), nodes_.end());\n nodes_.erase(std::unique(nodes_.begin(), nodes_.end()), nodes_.end());\n\n // 1. Compute similarity graph.\n for (uint i = 0; i < nodes_.size(); i++) {\n node_mapper_[nodes_[i]] = i;\n }\n\n timer.Start();\n const int N = nodes_.size();\n Eigen::SparseMatrix S(N, N);\n for (uint i = 0; i < edges.size(); i++) {\n int src = edges[i].first, dst = edges[i].second;\n s_triplets.push_back(Eigen::Triplet(src, dst, weights[i]));\n s_triplets.push_back(Eigen::Triplet(dst, src, weights[i]));\n degrees[src] += 2;\n }\n\n S.setFromTriplets(s_triplets.begin(), s_triplets.end());\n S.makeCompressed();\n timer.Pause();\n LOG(INFO) << \"1. Similarity Graph Computation Time: \" << timer.ElapsedSeconds();\n\n // 2. Compute Laplacian matrix.\n timer.Start();\n Eigen::SparseMatrix L = ComputeLaplacian(S, degrees);\n L.makeCompressed();\n timer.Pause();\n LOG(INFO) << \"2. Laplacian Matrix Computation Time: \" << timer.ElapsedSeconds();\n\n // 3. Compute the top-k smallest eigen values and corresponding eigen vectors.\n timer.Start();\n Spectra::SparseSymMatProd op(L);\n Spectra::SymEigsSolver> eigs(&op, \n k,\n std::min(2 * k, N));\n eigs.init();\n int nconv = eigs.compute();\n\n Eigen::VectorXd eigen_values;\n Eigen::MatrixXd eigen_vectors;\n if (eigs.info() == Spectra::SUCCESSFUL) {\n eigen_values = eigs.eigenvalues();\n eigen_vectors = eigs.eigenvectors();\n }\n\n timer.Pause();\n LOG(INFO) << \"3. EigenValue Computation Time: \" << timer.ElapsedSeconds();\n\n // 4. Reverse original eigen vectors(as it stored in descending order)\n timer.Start();\n uint i = 0, j = k - 1;\n while (i < j) {\n const Eigen::VectorXd tmp = eigen_vectors.col(i);\n eigen_vectors.col(i) = eigen_vectors.col(j);\n eigen_vectors.col(j) = tmp;\n i++; j--;\n }\n\n std::vector source_data;\n source_data.reserve(eigen_vectors.rows());\n for (uint i = 0; i < eigen_vectors.rows(); i++) {\n source_data.push_back(eigen_vectors.row(i));\n }\n timer.Pause();\n LOG(INFO) << \"4. Eigen Vectors Reverse Time: \" << timer.ElapsedSeconds();\n\n // 5. Invert K-Means for clustering.\n timer.Start();\n std::vector cluster_assignment;\n std::vector centers;\n KMeans(source_data, cluster_assignment, centers, k);\n timer.Pause();\n LOG(INFO) << \"5. KMeans Time: \" << timer.ElapsedSeconds();\n\n for (uint i = 0; i < cluster_assignment.size(); i++) {\n labels_[nodes_[i]] = cluster_assignment[i];\n }\n return labels_;\n}\n\nEigen::SparseMatrix SpectralCluster::ComputeLaplacian(\n const Eigen::SparseMatrix& S,\n const std::unordered_map& degrees) const\n{\n // Compute degree matrix.\n const int N = degrees.size();\n Eigen::SparseMatrix D(N, N);\n // Eigen::SparseMatrix D_inv(N, N);\n // Eigen::SparseMatrix D_sqrt(N, N);\n for (auto it = degrees.begin(); it != degrees.end(); ++it) {\n int id = it->first;\n D.insert(node_mapper_.at(id), node_mapper_.at(id)) = it->second;\n // D_inv.insert(node_mapper_.at(id), node_mapper_.at(id)) = 1.0 / it->second;\n // D_sqrt.insert(node_mapper_.at(id), node_mapper_.at(id)) = -1.0 / sqrt(it->second);\n }\n D.makeCompressed();\n // D_inv.makeCompressed();\n // D_sqrt.makeCompressed();\n\n // Compute Laplacian matrix.\n Eigen::SparseMatrix L = D - S;\n // Eigen::MatrixXd L_random = D_inv * L;\n // Eigen::MatrixXd L_sym = D_sqrt * L * D_sqrt;\n\n return L;\n}\n\n} // namespace GraphSfM", "meta": {"hexsha": "d77b298fe3b54dfe2def1889aaf5fab374e637c7", "size": 4953, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/clustering/spectral_cluster.cpp", "max_stars_repo_name": "longchao343/GraphSfM", "max_stars_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-01-17T04:16:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T04:16:29.000Z", "max_issues_repo_path": "src/clustering/spectral_cluster.cpp", "max_issues_repo_name": "longchao343/GraphSfM", "max_issues_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/clustering/spectral_cluster.cpp", "max_forks_repo_name": "longchao343/GraphSfM", "max_forks_repo_head_hexsha": "c4cac7885f1ee383d9d0031a390bd1dbf3ee0104", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.02, "max_line_length": 93, "alphanum_fraction": 0.6036745407, "num_tokens": 1279, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.653582385535319}} {"text": "#include \"stats/rmsd.h\"\n#include \n#include \n#include \n\nnamespace xmd {\n void compute_rmsd::operator()() const {\n using matrix_t = Eigen::Matrix;\n matrix_t P = matrix_t::Zero(num_particles, 3);\n matrix_t Q = matrix_t::Zero(num_particles, 3);\n\n for (int idx = 0; idx < num_particles; ++idx) {\n P.row(idx) = convert(r[idx]);\n Q.row(idx) = convert(ref_r[idx]);\n }\n\n Eigen::Matrix H = P.transpose() * Q;\n auto svd = Eigen::JacobiSVD(H,\n Eigen::ComputeFullU & Eigen::ComputeFullV);\n\n auto U = svd.matrixU();\n auto V = svd.matrixV();\n auto d = (V * U.transpose()).determinant() > 0 ? 1 : -1;\n auto R = V * Eigen::DiagonalMatrix(1, 1, d) * U.transpose();\n\n auto D = (P - Q) * R;\n real rmsd_ = 0.0;\n for (int idx = 0; idx < num_particles; ++idx) {\n rmsd_ += D.row(idx).squaredNorm();\n }\n *rmsd = sqrt(rmsd_ / num_particles);\n }\n}", "meta": {"hexsha": "283de0673639a630e8ce753ff4fa4e711681e00c", "size": 1097, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "xmd/src/stats/rmsd.cpp", "max_stars_repo_name": "vitreusx/xmd", "max_stars_repo_head_hexsha": "09f7df4b398f41f0e59abdced25998b53470f0a4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-16T02:26:30.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-16T02:26:30.000Z", "max_issues_repo_path": "xmd/src/stats/rmsd.cpp", "max_issues_repo_name": "vitreusx/xmd", "max_issues_repo_head_hexsha": "09f7df4b398f41f0e59abdced25998b53470f0a4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xmd/src/stats/rmsd.cpp", "max_forks_repo_name": "vitreusx/xmd", "max_forks_repo_head_hexsha": "09f7df4b398f41f0e59abdced25998b53470f0a4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2424242424, "max_line_length": 77, "alphanum_fraction": 0.5414767548, "num_tokens": 333, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9481545362802363, "lm_q2_score": 0.6893056167854461, "lm_q1q2_score": 0.6535682474385669}} {"text": "// =========================================================================\n// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co)\n// =========================================================================\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// -- Some typedefs\nusing TScalar = double;\nusing TMatrix = Eigen::Matrix< TScalar, Eigen::Dynamic, Eigen::Dynamic >;\n\n// -- Helper functions\nvoid read_file( TMatrix& X, const std::string& filename );\n\n// -- Main function\nint main( int argc, char** argv )\n{\n // Check inputs and get them\n if( argc < 2 )\n {\n std::cerr\n << \"Usage: \" << argv[ 0 ] << \" input.bin\"\n << std::endl;\n return( 1 );\n } // end if\n std::string input = argv[ 1 ];\n\n // Read data\n TMatrix X;\n std::cout << \"Read... \" << std::flush;\n read_file( X, input );\n std::cout << \"done! \" << X.rows( ) << \" \" << X.cols( ) << std::endl;\n\n // Compute PCA\n std::cout << \"Mean... \" << std::flush;\n auto m = X.colwise( ).mean( );\n std::cout << \"done! \" << m.rows( ) << \" \" << m.cols( ) << std::endl;\n std::cout << \"Centering... \" << std::flush;\n auto c = X.rowwise( ) - m;\n std::cout << \"done! \" << c.rows( ) << \" \" << c.cols( ) << std::endl;\n std::cout << \"Covariance... \" << std::flush;\n auto S = ( c.transpose( ) * c ) / TScalar( X.cols( ) );\n std::cout << \"done! \" << S.rows( ) << \" \" << S.cols( ) << std::endl;\n std::cout << \"Eigen analysis... \" << std::flush;\n auto svd = S.bdcSvd( Eigen::ComputeFullU | Eigen::ComputeFullV );\n std::cout << \"done!\" << std::endl;\n TMatrix eR = svd.matrixU( );\n TMatrix ev = svd.singularValues( );\n TScalar sv = ev.sum( );\n\n unsigned long i = 0;\n double s = ev( i, 0 ) / sv;\n while( i < ev.rows( ) && s <= 0.95 )\n {\n i++;\n s += ev( i, 0 ) / sv;\n } // end while\n TMatrix Xp = ( X * eR ).block( 0, 0, X.rows( ), i );\n std::cout << i << \" \" << Xp.rows( ) << \" \" << Xp.cols( ) << std::endl;\n\n unsigned long xrows, xcols;\n xrows = Xp.rows( );\n xcols = Xp.cols( );\n\n std::ofstream out = std::ofstream( \"out.bin\", std::ios::binary );\n out.write( ( char* )( &xrows ), sizeof( unsigned long ) );\n out.write( ( char* )( &xcols ), sizeof( unsigned long ) );\n out.write( ( char* )( Xp.data( ) ), sizeof( TScalar ) * xrows * xcols );\n out.close( );\n\n /* TODO\n this->m_EigenValues.SetSize( ps );\n for( unsigned int d = 0; d < ps; ++d )\n this->m_EigenValues[ d ] = ev( d, 0 );\n */\n\n return( 0 );\n}\n\n// -------------------------------------------------------------------------\nvoid read_file( TMatrix& X, const std::string& filename )\n{\n std::ifstream Xreader = std::ifstream( filename, std::ios::binary );\n unsigned long xrows, xcols;\n Xreader.read( ( char* )( &xrows ), sizeof( unsigned long ) );\n Xreader.read( ( char* )( &xcols ), sizeof( unsigned long ) );\n X = TMatrix::Zero( xrows, xcols );\n Xreader.read( ( char* )( X.data( ) ), sizeof( TScalar ) * xrows * xcols );\n Xreader.close( );\n}\n\n// eof - pca.cxx\n", "meta": {"hexsha": "2193c4fd979d3e75d597b2c3acf1e1bf045a114d", "size": 3051, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "examples/pca/pca.cxx", "max_stars_repo_name": "DanteCely/PUJ_ML", "max_stars_repo_head_hexsha": "7cb592bb51a9c7b5a5d330754d410377cc34911b", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-09-01T09:20:00.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T23:16:37.000Z", "max_issues_repo_path": "examples/pca/pca.cxx", "max_issues_repo_name": "DanteCely/PUJ_ML", "max_issues_repo_head_hexsha": "7cb592bb51a9c7b5a5d330754d410377cc34911b", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/pca/pca.cxx", "max_forks_repo_name": "DanteCely/PUJ_ML", "max_forks_repo_head_hexsha": "7cb592bb51a9c7b5a5d330754d410377cc34911b", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-09-10T21:38:45.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T23:17:44.000Z", "avg_line_length": 30.8181818182, "max_line_length": 76, "alphanum_fraction": 0.5093411996, "num_tokens": 950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953030553434, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6535001412225011}} {"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"../../data/FluidIndex.hpp\"\n#include \n\nnamespace fluid {\nnamespace algorithm {\n\ntemplate \nEigen::Matrix\ntoeplitz(const Eigen::Matrix& vec)\n{\n index size = vec.size();\n\n Eigen::Matrix mat(size, size);\n\n for (auto i = 0; i < size; i++)\n {\n for (auto j = 0; j < i; j++) mat(j, i) = vec(i - j);\n for (auto j = i; j < size; j++) mat(j, i) = vec(j - i);\n }\n\n return mat;\n}\n\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "e9f26c1cc304301b7eab260c46244c8d04a87a8e", "size": 994, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/Toeplitz.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/util/Toeplitz.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/util/Toeplitz.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 26.1578947368, "max_line_length": 74, "alphanum_fraction": 0.6941649899, "num_tokens": 260, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7461389873857265, "lm_q1q2_score": 0.6534588191137906}} {"text": "/*\n * recon.cpp\n *\n * Created on: Jul 25, 2019\n * Author: dmarce1\n */\n#include \"../../octotiger/print.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nauto band_filter(double t, double Ps, double Pc) {\n\tconst auto x = 2.0 * M_PI * t / Pc;\n\tconst auto y = 2.0 * M_PI * (t / Ps + 0.5);\n\tconst auto sinc = x == 0 ? 1.0 : sin(x) / x;\n\tconstexpr auto a0 = 7938.0 / 18608.0;\n\tconstexpr auto a1 = 9240.0 / 18608.0;\n\tconstexpr auto a2 = 1430.0 / 18608.0;\n\tconst auto blackman = (a0 - a1 * cos(y) + a2 * cos(2 * y));\n\tif (blackman > 0.0) {\n\t\treturn sinc * blackman;\n\t} else {\n\t\treturn 0.0;\n\t}\n}\n\nvoid output_spectrogram(double Ps, double Pc) {\n\tdouble pmin = Pc / 100.0;\n\tdouble pmax = 2.0 * Ps;\n\tdouble dp = (pmax - pmin) / 1000.0;\n\tconst auto dt = Ps / 100000.0;\n\tFILE *fp = fopen(\"filter.dat\", \"wt\");\n\tfor (auto p = pmin; p <= pmax; p += dp) {\n\t\tdouble w = 0.0;\n\t\tconst auto omega = 2.0 * M_PI / p;\n\t\tdouble sum = 0.0;\n\t\tconstexpr std::complex I(0, 1);\n\t\tfor (double t = dt / 2.0; t < Ps / 2.0; t += dt) {\n\t\t\tconst auto bf = band_filter(t, Ps, Pc);\n\t\t\tw += 2.0 * bf * dt;\n\t\t\tsum += 2.0 * bf * cos(omega * t) * dt;\n\t\t}\n\t\tsum /= w;\n\t\tfprintf(fp, \"%.12e %.12e\\n\", p, sum);\n\t}\n\tfclose(fp);\n\n}\n\nauto derivative(const std::vector> &f, double omega) {\n\tstd::vector> g;\n\tstd::vector u(f[0].size());\n\tconst auto P = 2.0 * M_PI / omega;\n\tfor (int n = 1; n < f.size() - 1; n++) {\n\t\tconst auto nm = n - 1;\n\t\tconst auto np = n + 1;\n\t\tconst auto h1 = (f[n][0] - f[nm][0]);\n\t\tconst auto h2 = (f[np][0] - f[n][0]);\n\t\tfor (int i = 0; i < u.size(); i++) {\n\t\t\tu[i] = P * (f[np][i] * h1 * h1 + f[n][i] * (h2 * h2 - h1 * h1) - f[nm][i] * h2 * h2) / (f[0][i] * h1 * h2 * (h1 + h2));\n\t\t}\n\t\tu[0] = f[n][0];\n\t\tg.push_back(u);\n\t}\n\n\treturn g;\n\n}\n\nauto filter(const std::vector> &f, double omega, double Pc, double Ps) {\n\tstd::vector> g;\n\tstd::vector u(f[0].size());\n\n\tconst auto tmin = f[0][0];\n\tconst auto tmax = f[f.size() - 1][0];\n\tconst auto P = 2.0 * M_PI / omega;\n\tdouble rt = tmin / P;\n\tPc *= P;\n\tPs *= P;\n\tfor (int n = 1; n < f.size() - 1; n++) {\n\t\tdouble t0 = f[n][0];\n\t\tdouble dt;\n\t\tdouble weight = 0.0;\n\n\t\tif (Pc / 2.0 + tmin < t0 && t0 < tmax - Pc / 2.0) {\n\t\t\tstd::fill(u.begin(), u.end(), 0.0);\n\t\t\tfor (int m = 1; m < f.size() - 1; m++) {\n\t\t\t\tdouble t = f[m][0];\n\t\t\t\tif (t0 - Pc / 2.0 < t && t < t0 + Pc / 2.0) {\n\t\t\t\t\tdt = (f[m + 1][0] - f[m - 1][0]) / 2.0;\n\t\t\t\t\tconst auto h1 = f[m][0] - f[m - 1][0];\n\t\t\t\t\tconst auto h2 = f[m + 1][0] - f[m][0];\n\t\t\t\t\tconst auto w1 = (h1 + h2) * (2 * h1 - h2) / h1 / 6.0;\n\t\t\t\t\tconst auto w2 = std::pow(h1 + h2, 3) / h2 / h1 / 6.0;\n\t\t\t\t\tconst auto w3 = (h1 + h2) * (2 * h2 - h1) / h2 / 6.0;\n\t\t\t\t\tdouble y1 = band_filter(f[m - 1][0] - t0, Ps, Pc);\n\t\t\t\t\tdouble y2 = band_filter(f[m][0] - t0, Ps, Pc);\n\t\t\t\t\tdouble y3 = band_filter(f[m + 1][0] - t0, Ps, Pc);\n\t\t\t\t\tfor (int i = 0; i < u.size(); i++) {\n\t\t\t\t\t\tu[i] += w1 * f[m - 1][i] * y1 * dt;\n\t\t\t\t\t\tu[i] += w2 * f[m][i] * y2 * dt;\n\t\t\t\t\t\tu[i] += w3 * f[m + 1][i] * y3 * dt;\n\t\t\t\t\t}\n\t\t\t\t\tweight += w1 * y1 * dt;\n\t\t\t\t\tweight += w2 * y2 * dt;\n\t\t\t\t\tweight += w3 * y3 * dt;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (int i = 0; i < u.size(); i++) {\n\t\t\t\tu[i] /= weight;\n\t\t\t}\n\t\t\tu[0] = rt;\n\t\t\tg.push_back(u);\n\t\t}\n\t\tdt = (f[n + 1][0] - f[n - 1][0]) / 2.0;\n\t\trt += dt / P;\n\t}\n\treturn g;\n}\n\nstruct options {\n\tdouble pmin;\n\tdouble pmax;\n\tbool help;\n\tbool normalize;\n\tstd::string input;\n\n\tint read_options(int argc, char *argv[]) {\n\t\tnamespace po = boost::program_options;\n\n\n\t\tpo::options_description command_opts(\"options\");\n\n\t\tcommand_opts.add_options() //\n\t\t(\"input\", po::value(&input)->default_value(\"binary.dat\"), \"input filename\") //\n\t\t(\"pmin\", po::value(&pmin)->default_value(1.25), \"minimum period to allow through filter\") //\n\t\t(\"pmax\", po::value(&pmax)->default_value(5), \"period where filter allows 100%\") //\n\t\t(\"normalize\", po::value(&normalize)->default_value(true), \"normalize averages to t=0 value\") //\n\t\t(\"help\", po::value(&help)->default_value(false), \"show the help page\") //\n\t\t\t\t;\n\t\tboost::program_options::variables_map vm;\n\t\tpo::store(po::parse_command_line(argc, argv, command_opts), vm);\n\t\tpo::notify(vm);\n\n\t\tif (help) {\n\t\t\tstd::cout << command_opts << \"\\n\";\n\t\t\treturn -1;\n\t\t}\n\t\tFILE *fp = fopen(input.c_str(), \"rb\");\n\t\tif (fp == NULL) {\n\t\t\tprint(\"Unable to open %s\\n\", input.c_str());\n\t\t\treturn -1;\n\t\t} else {\n\t\t\tfclose(fp);\n\t\t}\n\n\t\treturn 0;\n\t}\n};\nint main(int argc, char *argv[]) {\n\toptions opts;\n\tif (opts.read_options(argc, argv) == 0) {\n\n\t\tFILE *fp = fopen(opts.input.c_str(), \"rt\");\n\t\tstatic char buffer[100000];\n\t\tstd::map> values;\n\n\t\twhile (!feof(fp)) {\n\t\t\tconst char* b = fgets(buffer, 100000, fp);\n\t\t\tbool done = false;\n\t\t\tchar *ptr = buffer;\n\t\t\tdouble t;\n\t\t\tint col = 0;\n\t\t\tstd::vector these_values;\n\t\t\tdo {\n\t\t\t\twhile (isspace(*ptr)) {\n\t\t\t\t\tif (*ptr == '\\n') {\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tptr++;\n\t\t\t\t}\n\t\t\t\tif (!done) {\n\t\t\t\t\tdouble number = atof(ptr);\n\t\t\t\t\tif (col == 0) {\n\t\t\t\t\t\tt = number;\n\t\t\t\t\t}\n\t\t\t\t\tthese_values.push_back(number);\n\t\t\t\t\tcol++;\n\t\t\t\t}\n\t\t\t\twhile (!isspace(*ptr)) {\n\t\t\t\t\tptr++;\n\t\t\t\t}\n\t\t\t} while (!done);\n\t\t\tif (values.find(t) == values.end()) {\n\t\t\t\tvalues.insert(std::make_pair(t, std::move(these_values)));\n\t\t\t}\n\t\t}\n\n\t\tstd::vector> v1;\n\t\tfor (auto &v : values) {\n\t\t\tv1.push_back(std::move(v.second));\n\t\t}\n\n\t\tauto Pc = 2.0 * opts.pmax * opts.pmin / (opts.pmax + opts.pmin);\n\t\tauto Ps = 4.0 * opts.pmax * opts.pmin / (opts.pmax - opts.pmin);\n\t\tprint(\"sinc period = %e\\n\", Pc);\n\t\tprint(\"Blackmann period = %e\\n\", Ps);\n\t\tconst auto P = 2.0 * M_PI / v1[0][2];\n\n\t\tprint(\"Window is +/- %.12e orbits\\n\", Pc / 2.0);\n\n\t\tauto v2 = filter(v1, v1[0][2], Pc, Ps);\n\t\tif (v2.size() == 0) {\n\t\t\tprint(\"Not enough data to produce output\\n\");\n\t\t} else {\n\t\t\tif (opts.normalize) {\n\t\t\t\tfor (auto &line : v2) {\n\t\t\t\t\tfor (int i = 1; i < line.size(); i++) {\n\t\t\t\t\t\tline[i] /= v1[0][i];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst auto v4 = derivative(v1, v1[0][2]);\n\t\t\tconst auto v3 = filter(v4, v1[0][2], Pc, Ps);\n\t\t\tFILE *fp1 = fopen(\"avg.dat\", \"wt\");\n\t\t\tFILE *fp2 = fopen(\"drv.dat\", \"wt\");\n\t\t\tfor (const auto &i : v2) {\n\t\t\t\tfor (const auto &j : i) {\n\t\t\t\t\tfprintf(fp1, \" %.12e \", j);\n\t\t\t\t}\n\t\t\t\tfprintf(fp1, \"\\n\");\n\t\t\t}\n\t\t\tfor (const auto &i : v3) {\n\t\t\t\tfor (const auto &j : i) {\n\t\t\t\t\tfprintf(fp2, \" %.12e \", j);\n\t\t\t\t}\n\t\t\t\tfprintf(fp2, \"\\n\");\n\t\t\t}\n\t\t\tfclose(fp1);\n\t\t\tfclose(fp2);\n\t\t\tfclose(fp);\n\t\t}\n\n\t\toutput_spectrogram(Ps, Pc);\n\t}\n\treturn 0;\n}\n\n", "meta": {"hexsha": "2094bef1468bfbf89905fbe89fe8de8908a0a1f7", "size": 6694, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tools/bfilter/bfilter.cpp", "max_stars_repo_name": "srinivasyadav18/octotiger", "max_stars_repo_head_hexsha": "4d93c50fe345a081b7985ecb4cb698d16c121565", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 35.0, "max_stars_repo_stars_event_min_datetime": "2016-11-17T22:35:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T19:07:36.000Z", "max_issues_repo_path": "tools/bfilter/bfilter.cpp", "max_issues_repo_name": "srinivasyadav18/octotiger", "max_issues_repo_head_hexsha": "4d93c50fe345a081b7985ecb4cb698d16c121565", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 123.0, "max_issues_repo_issues_event_min_datetime": "2016-11-17T21:29:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-03T21:40:04.000Z", "max_forks_repo_path": "tools/bfilter/bfilter.cpp", "max_forks_repo_name": "srinivasyadav18/octotiger", "max_forks_repo_head_hexsha": "4d93c50fe345a081b7985ecb4cb698d16c121565", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2018-11-28T18:17:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T12:52:37.000Z", "avg_line_length": 26.1484375, "max_line_length": 122, "alphanum_fraction": 0.5261428145, "num_tokens": 2468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869916479466, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6534588141699512}} {"text": "// Copyright (c) 2021 fortiss GmbH\n//\n// Authors: Klemens Esterle and Tobias Kessler\n//\n// This work is licensed under the terms of the MIT license.\n// For a copy, see .\n\n#ifndef MIQP_COMMON_MATH_HPP_\n#define MIQP_COMMON_MATH_HPP_\n\n#include \n\nnamespace miqp {\nnamespace common {\nnamespace math {\n\ninline void WrapRadiantTo2Pi(double& x) {\n x = fmod(x, 2 * boost::math::constants::pi());\n if (x < 0) {\n x += 2 * boost::math::constants::pi();\n }\n assert(x >= 0);\n assert(x <= 2 * boost::math::constants::pi());\n}\n\ninline void SwapIfNeeded(float& maxval, float& minval) {\n if (maxval < minval) {\n float tmp = maxval;\n maxval = minval;\n minval = tmp;\n }\n}\n\ninline double InterpolateWithBounds(const double x0, const double y0,\n const double x1, const double y1,\n const double xInterp) {\n double yInterp;\n if (xInterp > x1) {\n yInterp = y1;\n } else if (xInterp < x0) {\n yInterp = y0;\n } else {\n yInterp = (y1 - y0) / (x1 - x0) * (xInterp - x0) + y0;\n }\n return yInterp;\n};\n\n} // namespace math\n} // namespace common\n} // namespace miqp\n\n#endif // MIQP_COMMON_MATH_HPP_\n", "meta": {"hexsha": "9d88d82bea2b46ef0cbedfc830f76d11f0d4de27", "size": 1269, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "common/math/math.hpp", "max_stars_repo_name": "bark-simulator/planner-miqp", "max_stars_repo_head_hexsha": "aef044d03febadeb62c9634eed9830133d4c8b7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2021-12-23T08:52:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T21:33:02.000Z", "max_issues_repo_path": "common/math/math.hpp", "max_issues_repo_name": "bark-simulator/planner-miqp", "max_issues_repo_head_hexsha": "aef044d03febadeb62c9634eed9830133d4c8b7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "common/math/math.hpp", "max_forks_repo_name": "bark-simulator/planner-miqp", "max_forks_repo_head_hexsha": "aef044d03febadeb62c9634eed9830133d4c8b7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.9433962264, "max_line_length": 69, "alphanum_fraction": 0.6170212766, "num_tokens": 372, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511469672594, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.653428454728821}} {"text": "/**\n * @file\n * @brief NPDE homework ElementMatrixComputation code\n * @author Janik Schüttler, edited by Oliver Rietmann\n * @date 03.03.2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"mylinearfeelementmatrix.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace ElementMatrixComputation {\n\n/* SAM_LISTING_BEGIN_1 */\nEigen::Matrix MyLinearFEElementMatrix::Eval(\n const lf::mesh::Entity &cell) {\n // Topological type of the cell\n const lf::base::RefEl ref_el{cell.RefEl()};\n\n // Obtain the vertex coordinates of the cell, which completely\n // describe its shape.\n const lf::geometry::Geometry *geo_ptr = cell.Geometry();\n // Matrix storing corner coordinates in its columns\n auto vertices = geo_ptr->Global(ref_el.NodeCoords());\n // Matrix for returning element matrix\n\n auto lapl_mat = lf::uscalfe::LinearFELaplaceElementMatrix().Eval(cell);\n\n if (ref_el == lf::base::RefElType::kQuad) {\n Eigen::Matrix elem_mat;\n elem_mat << 4,2,1,2,\n 2,4,2,1,\n 1,2,4,2,\n 2,1,2,4;\n\n double x0 = vertices.row(0).minCoeff();\n double x1 = vertices.row(0).maxCoeff();\n double y0 = vertices.row(1).minCoeff();\n double y1 = vertices.row(1).maxCoeff();\n\n double area = (x1 - x0) * (y1 - y0);\n\n return area * elem_mat / 36. + lapl_mat;\n }\n\n else if(ref_el == lf::base::RefElType::kTria) {\n Eigen::Matrix elem_mat;\n elem_mat << 2,1,1,0,\n 1,2,1,0,\n 1,1,2,0,\n 0,0,0,0;\n\n Eigen::Matrix2d side_lengths;\n\n side_lengths.col(0) = vertices.col(1) - vertices.col(0);\n side_lengths.col(1) = vertices.col(2) - vertices.col(0);\n\n double area = 0.5 * side_lengths.determinant();\n\n return area * elem_mat / 12. + lapl_mat;\n\n }\n else {\n assert(0 && \"unsupported cell type\");\n }\n\n}\n/* SAM_LISTING_END_1 */\n} // namespace ElementMatrixComputation\n", "meta": {"hexsha": "0efd010f349537dbb314719d735a243b64b136a8", "size": 2035, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/ElementMatrixComputation/mysolution/mylinearfeelementmatrix.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7763157895, "max_line_length": 73, "alphanum_fraction": 0.6319410319, "num_tokens": 613, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8558511396138365, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6534284491146021}} {"text": "//\n// Created by TAADEJOM on 15.05.2021.\n//\n\n#include \"DataSet.hpp\"\n#include \n\nusing namespace Eigen;\n\n/**\n * Concatenates two matrices vertically. A at the top and B at the bottom\n */\nMatrixXd vConcat(const MatrixXd& A, const MatrixXd& B) {\n MatrixXd D(A.rows()+B.rows(), A.cols()); // <-- D(A.rows() + B.rows(), ...)\n D << A, B;\n return D;\n}\n\n/**\n * See: https://gist.github.com/gocarlos/c91237b02c120c6319612e42fa196d77\n * Note: matrix index starts at 1 in matlab and at 0 in eigen -> never forget -1!\n */\nQVector DataSet::regression(int degree) const {\n QSharedPointer data = graph->data();\n int m = data->size(); // rows\n int n = degree; // columns\n // xPoints = data(:,1); %x -> A\n // yPoints = data(:,2); %y -> b\n MatrixXd xPoints(m, 1); // n rows, 1 column\n MatrixXd yPoints(m, 1); // n rows, 1 column\n for (int i = 0; i < m; ++i) {\n xPoints(i, 0) = data->at(i)->key;\n yPoints(i, 0) = data->at(i)->value;\n }\n\n // x0 = ones(m,1).*80.3e3;\n MatrixXd x1 = xPoints;\n MatrixXd x0 = Eigen::MatrixXd::Ones(m, 1) * 80300;\n\n MatrixXd z1 = (x1 - x0).array() / 50;\n\n // Set up vector A\n MatrixXd A(m, n);\n for (int i = 1; i <= n; ++i) {\n if (i == n) {\n // A(1:m, degree) = ones(m,1);\n A.col(i - 1) = Eigen::MatrixXd::Ones(m, 1);\n } else {\n // A(1:m, degree) = xPoints.^(n - degree);\n A.col(i - 1) = xPoints.array().pow(n - i);\n }\n }\n\n MatrixXd Im = Eigen::MatrixXd::Identity(m, m); // m*m identity matrix\n\n // QR-Zerlegung von A\n MatrixXd R = A;\n MatrixXd Q = Im;\n for (int k = 1; k <= n; ++k) {\n MatrixXd x = R.col(k - 1).bottomRows(R.rows() - k + 1); // we wanna show R.rows - k rows from the bottom // fixme: ErrorRowIndexOutOfBounds with 5 data points and degree 10\n\n // x is a matrix with 1 column and however many rows\n double lambda = x.coeff(k - 1, 0) < 0 ? x.norm() : -x.norm();\n\n MatrixXd e = Im.col(k - 1).bottomRows(R.rows() - k + 1);\n MatrixXd v = (x - lambda * e) / (x - lambda * e).norm(); // use normalize()\n MatrixXd z = Eigen::MatrixXd::Zero(k - 1, 1);\n\n // H = eye(m)-2.*[z;v]*[z;v]';\n MatrixXd H = Eigen::MatrixXd::Identity(m, m) - (2 * (vConcat(z, v) * vConcat(z, v).transpose()));\n\n Q = Q * H; // mXm * mXm matrix mul => VERY SLOW\n R = H * R;\n }\n // Rückwärtseinsetzen\n MatrixXd y = Q.transpose() * yPoints;\n\n MatrixXd x = Eigen::MatrixXd::Zero(1, n);\n // x(n) = y(n)/R(n,n);\n x.coeffRef(0, n - 1) = y.coeff(n - 1, 0) / R.coeff(n - 1, n - 1);\n\n for (int i = (n - 1); i >= 1; --i) {\n double s = 0;\n for (int j = i + 1; j <= n; ++j) {\n // s = s + x(j)*R(i,j);\n s += x.coeff(0, j - 1) * R.coeff(i - 1, j - 1);\n }\n // x(i) = (y(i) - s)/R(i,i);\n x.coeffRef(0, i - 1) = (y.coeff(i - 1, 0) - s) / R.coeff(i - 1, i - 1);\n }\n\n return QVector(x.data(), x.data() + x.rows() * x.cols());\n}\n\n/**\n * Makes a function string out of a list of coeffs\n */\nQString DataSet::getFunctionString(const QVector& coeffs) {\n QString regression = \"\";\n for (int i = 0; i < coeffs.size(); ++i) {\n regression += QString(\"%1*x^%2+\").arg(QString::number(coeffs.at(i), 'E', 16)).arg(coeffs.length() - i - 1);\n }\n regression.truncate(regression.lastIndexOf('+'));\n return regression;\n}\n\nQDataStream &operator<<(QDataStream &out, const DataSet &dataSet) {\n out << dataSet.displayName << dataSet.functionString << dataSet.color << quint32(dataSet.graphWidth) << quint32(dataSet.pointDensity);\n return out;\n}\n\nQDataStream &operator>>(QDataStream &in, DataSet &dataSet) {\n QString displayName;\n QString functionString;\n QColor color;\n quint32 graphWidth;\n quint32 pointDensity;\n in >> displayName >> functionString >> color >> graphWidth >> pointDensity;\n dataSet.displayName = displayName;\n dataSet.functionString = functionString;\n dataSet.color = color;\n dataSet.graphWidth = graphWidth;\n dataSet.pointDensity = pointDensity;\n return in;\n}", "meta": {"hexsha": "99a54b9b1fdd15738fdc33b8ff2baf0eeca0f7fd", "size": 4156, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QDataVis/Sources/DataSet.cpp", "max_stars_repo_name": "bolo1221/Cpp_Qt_Plotter", "max_stars_repo_head_hexsha": "0b4022cc9cc1f48cd379389213bbd36864ccbeb6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T21:19:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T03:39:19.000Z", "max_issues_repo_path": "QDataVis/Sources/DataSet.cpp", "max_issues_repo_name": "bolo1221/Cpp_Qt_Plotter", "max_issues_repo_head_hexsha": "0b4022cc9cc1f48cd379389213bbd36864ccbeb6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-05-13T22:42:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-16T11:33:06.000Z", "max_forks_repo_path": "QDataVis/Sources/DataSet.cpp", "max_forks_repo_name": "bolo1221/Cpp_Qt_Plotter", "max_forks_repo_head_hexsha": "0b4022cc9cc1f48cd379389213bbd36864ccbeb6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-11-09T20:51:29.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-09T20:51:29.000Z", "avg_line_length": 33.248, "max_line_length": 180, "alphanum_fraction": 0.5543792108, "num_tokens": 1319, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6533686652586891}} {"text": "#pragma once\r\n\r\n\r\n#include \r\n#include \r\n\r\nclass CubicKernel\r\n{\r\npublic:\r\n\t Discregrid::Real getRadius() { return m_radius; }\r\n\t void setRadius(Discregrid::Real val)\r\n\t{\r\n\t\tm_radius = val;\r\n\t\tconst Discregrid::Real pi = static_cast(M_PI);\r\n\r\n\t\tconst Discregrid::Real h3 = m_radius*m_radius*m_radius;\r\n\t\tm_k = 8.0 / (pi*h3);\r\n\t\tm_l = 48.0 / (pi*h3);\r\n\t\tm_W_zero = W(Discregrid::Vector3r::Zero());\r\n\t}\r\n\r\npublic:\r\n\tDiscregrid::Real W(Discregrid::Vector3r const& r)\r\n\t{\r\n\t\tDiscregrid::Real res = 0.0;\r\n\t\tconst Discregrid::Real rl = r.norm();\r\n\t\tconst Discregrid::Real q = rl/m_radius;\r\n\t\tif (q <= 1.0)\r\n\t\t{\r\n\t\t\tif (q <= 0.5)\r\n\t\t\t{\r\n\t\t\t\tconst Discregrid::Real q2 = q*q;\r\n\t\t\t\tconst Discregrid::Real q3 = q2*q;\r\n\t\t\t\tres = m_k * (6.0*q3-6.0*q2+1.0);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tauto _1mq = 1.0 - q;\r\n\t\t\t\tres = m_k * (2.0*_1mq*_1mq*_1mq);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn res;\r\n\t}\r\n\r\n\tDiscregrid::Vector3r gradW(const Discregrid::Vector3r &r)\r\n\t{\r\n\t\tusing namespace Eigen;\r\n\t\tDiscregrid::Vector3r res;\r\n\t\tconst Discregrid::Real rl = r.norm();\r\n\t\tconst Discregrid::Real q = rl / m_radius;\r\n\t\tif (q <= 1.0)\r\n\t\t{\r\n\t\t\tif (rl > 1.0e-6)\r\n\t\t\t{\r\n\t\t\t\tconst Discregrid::Vector3r gradq = r * ((Discregrid::Real) 1.0 / (rl*m_radius));\r\n\t\t\t\tif (q <= 0.5)\r\n\t\t\t\t{\r\n\t\t\t\t\tres = m_l*q*((Discregrid::Real) 3.0*q - (Discregrid::Real) 2.0)*gradq;\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tconst Discregrid::Real factor = 1.0 - q;\r\n\t\t\t\t\tres = m_l*(-factor*factor)*gradq;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t\tres.setZero();\r\n\r\n\t\treturn res;\r\n\t}\r\n\r\n\tDiscregrid::Real W_zero()\r\n\t{\r\n\t\treturn m_W_zero;\r\n\t}\r\n\r\nprivate:\r\n\tDiscregrid::Real m_radius;\r\n\tDiscregrid::Real m_k;\r\n\tDiscregrid::Real m_l;\r\n\tDiscregrid::Real m_W_zero;\r\n};\r\n", "meta": {"hexsha": "be8520565e3cc5bfd20e55bd9483f33a797026bc", "size": 1715, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmd/generate_density_map/sph_kernel.hpp", "max_stars_repo_name": "kennychufk/Discregrid", "max_stars_repo_head_hexsha": "c0a84f8e61e70f702cfcbf4cbff746b33164e346", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmd/generate_density_map/sph_kernel.hpp", "max_issues_repo_name": "kennychufk/Discregrid", "max_issues_repo_head_hexsha": "c0a84f8e61e70f702cfcbf4cbff746b33164e346", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmd/generate_density_map/sph_kernel.hpp", "max_forks_repo_name": "kennychufk/Discregrid", "max_forks_repo_head_hexsha": "c0a84f8e61e70f702cfcbf4cbff746b33164e346", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 20.4166666667, "max_line_length": 85, "alphanum_fraction": 0.5790087464, "num_tokens": 629, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7520125737597972, "lm_q1q2_score": 0.6533686652586891}} {"text": "#include \"IntrinsicGeometry.h\"\n#include \"MeshConnectivity.h\"\n#include \n\nIntrinsicGeometry::IntrinsicGeometry(const MeshConnectivity &mesh, const std::vector &abars) : abars(abars)\n{\n int nedges = mesh.nEdges();\n int nfaces = mesh.nFaces();\n\n Js.resize(2 * nfaces, 2);\n for (int i = 0; i < nfaces; i++)\n {\n Eigen::Matrix2d Jeuclid;\n Jeuclid << 0, -1,\n 1, 0;\n Js.block<2, 2>(2 * i, 0) = std::sqrt(abars[i].determinant()) * abars[i].inverse() * Jeuclid;\n }\n\n Ts.resize(2 * nedges, 4);\n Ts.setZero();\n for (int i = 0; i < nedges; i++)\n {\n int face1 = mesh.edgeFace(i, 0);\n int face2 = mesh.edgeFace(i, 1);\n if (face1 == -1 || face2 == -1)\n continue;\n\n int vert1 = mesh.edgeVertex(i, 0);\n int vert2 = mesh.edgeVertex(i, 1);\n\n // write edge vert1->vert2 in barycentric coordinates on each face\n Eigen::Vector2d barys[3] = { {0,0}, {1,0}, {0,1} };\n Eigen::Vector2d face1e(0, 0);\n Eigen::Vector2d face2e(0, 0);\n for (int j = 0; j < 3; j++)\n {\n if (vert1 == mesh.faceVertex(face1, j))\n face1e -= barys[j];\n else if (vert2 == mesh.faceVertex(face1, j))\n face1e += barys[j];\n if (vert1 == mesh.faceVertex(face2, j))\n face2e -= barys[j];\n else if (vert2 == mesh.faceVertex(face2, j))\n face2e += barys[j];\n }\n\n Eigen::Vector2d face1eperp = Js.block<2, 2>(2 * face1, 0) * face1e;\n Eigen::Vector2d face2eperp = Js.block<2, 2>(2 * face2, 0) * face2e;\n Eigen::Matrix2d face1basis;\n face1basis.col(0) = face1e;\n face1basis.col(1) = face1eperp;\n Eigen::Matrix2d face2basis;\n face2basis.col(0) = face2e;\n face2basis.col(1) = face2eperp;\n Ts.block<2, 2>(2 * i, 0) = face2basis * face1basis.inverse();\n Ts.block<2, 2>(2 * i, 2) = face1basis * face2basis.inverse();\n }\n}\n", "meta": {"hexsha": "ba587fabf838b76f77394f7ac435ecc453bd51cd", "size": 2012, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "IntrinsicGeometry.cpp", "max_stars_repo_name": "csyzzkdcz/effective-garbanzo", "max_stars_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IntrinsicGeometry.cpp", "max_issues_repo_name": "csyzzkdcz/effective-garbanzo", "max_issues_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IntrinsicGeometry.cpp", "max_forks_repo_name": "csyzzkdcz/effective-garbanzo", "max_forks_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1016949153, "max_line_length": 124, "alphanum_fraction": 0.5347912525, "num_tokens": 669, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267762381844, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6533686649790916}} {"text": "#include \n#include \n\nBZ_USING_NAMESPACE(blitz)\n\nvoid setupInitialConditions(Array& P1, Array& P2,\n Array& P3, Array& c, int N);\n\nBZ_DECLARE_STENCIL4(acoustic3D, P1, P2, P3, c)\n P3 = 2 * P2 + c * Laplacian3D_stencilop(P2) - P1;\nBZ_END_STENCIL\n\nfloat acoustic3D_BlitzStencil(int N, int niters)\n{\n Array P1, P2, P3, c;\n allocateArrays(shape(N,N,N), P1, P2, P3, c);\n\n setupInitialConditions(P1, P2, P3, c, N);\n\n for (int iter=0; iter < niters; ++iter)\n {\n applyStencil(acoustic3D(), P1, P2, P3, c);\n cycleArrays(P1, P2, P3);\n }\n\n return P1(N/2,N/2,N/2);\n}\n\n", "meta": {"hexsha": "6fe464442867b6f0ddd3d058ecaf895879906d98", "size": 680, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "depspawn-blitz-0.10/benchmarks/acou3db4.cpp", "max_stars_repo_name": "fraguela/depspawn", "max_stars_repo_head_hexsha": "b5760f4c0d38a1b245ee5274e2ccc5c5fe2d3d45", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2017-04-12T11:05:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T11:10:27.000Z", "max_issues_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/acou3db4.cpp", "max_issues_repo_name": "MSV-Project/IBAMR", "max_issues_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ibtk/third_party/blitz-0.10/benchmarks/acou3db4.cpp", "max_forks_repo_name": "MSV-Project/IBAMR", "max_forks_repo_head_hexsha": "3cf614c31bb3c94e2620f165ba967cba719c45ea", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.4482758621, "max_line_length": 67, "alphanum_fraction": 0.6367647059, "num_tokens": 251, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.7431680086124812, "lm_q1q2_score": 0.6533537454285903}} {"text": "#include \"space_vector_modulation.h\"\n#include \"global_debug.h\"\n#include \"util/clarke_transform.h\"\n#include \"util/conversions.h\"\n#include \"util/math_constants.h\"\n#include \n\nconst std::array, 6> kSvmVectors = []() {\n std::array, 6> result;\n result[0] = {1, 0};\n for (int i = 0; i < 6; ++i) {\n result[i] = {std::cos(i * 2 * kPI / 6), std::sin(i * 2 * kPI / 6)};\n }\n return result;\n}();\n\nint get_sector(const std::complex& voltage_ab) {\n const std::complex rot_60_deg = std::conj(kSvmVectors[1]);\n\n std::complex curr = voltage_ab;\n std::complex next = voltage_ab * rot_60_deg;\n int sector;\n for (sector = 0; sector < 5; ++sector) {\n if (curr.imag() >= 0 && next.imag() < 0) {\n // found it\n break;\n }\n // rotate\n curr = next;\n next *= rot_60_deg;\n }\n\n return sector;\n}\n\nstd::array get_pwm_duties(const Scalar bus_voltage,\n const std::complex& voltage_ab) {\n const int sector_x = get_sector(voltage_ab);\n const int sector_y = (sector_x + 1) % 6;\n\n const std::complex boundary_x =\n kSvmVectors[sector_x] * kClarkeScale * bus_voltage;\n const std::complex boundary_y =\n kSvmVectors[sector_y] * kClarkeScale * bus_voltage;\n\n Eigen::Matrix boundaries;\n boundaries <<\n // clang-format off\n\tboundary_x.real(), boundary_y.real(),\n\tboundary_x.imag(), boundary_y.imag()\n // clang-format on\n ;\n Eigen::Matrix v_ab;\n v_ab << voltage_ab.real(), voltage_ab.imag();\n\n Eigen::Matrix coeffs = boundaries.inverse() * v_ab;\n Scalar cx = coeffs(0);\n Scalar cy = coeffs(1);\n Scalar cx_p_cy = cx + cy;\n Scalar c0 = 1.0 - cx_p_cy;\n if (cx_p_cy > 1) {\n c0 = 0;\n cx /= cx_p_cy;\n cy /= cx_p_cy;\n }\n\n const auto& gx = kSvmStates[sector_x];\n const auto& gy = kSvmStates[sector_y];\n\n std::array duties;\n for (int i = 0; i < 3; ++i) {\n duties[i] = c0 / 2 + gx[i] * cx + gy[i] * cy;\n }\n return duties;\n}\n\nstd::complex get_avg_voltage_ab(const Scalar bus_voltage,\n const std::array& duties) {\n // optimal sort 3 elements\n int first_gate_on = 0;\n int second_gate_on = 1;\n int third_gate_on = 2;\n if (duties[second_gate_on] > duties[first_gate_on]) {\n std::swap(first_gate_on, second_gate_on);\n }\n if (duties[third_gate_on] > duties[second_gate_on]) {\n std::swap(third_gate_on, second_gate_on);\n }\n // after these two swaps, duties[third_gate_on] is minimal\n if (duties[second_gate_on] > duties[first_gate_on]) {\n std::swap(first_gate_on, second_gate_on);\n }\n // duties[first_gate_on] is maximum\n\n Eigen::Matrix pole_voltages_x =\n Eigen::Matrix::Zero();\n pole_voltages_x(first_gate_on) = bus_voltage;\n\n Eigen::Matrix pole_voltages_y = pole_voltages_x;\n pole_voltages_y(second_gate_on) = bus_voltage;\n\n Eigen::Matrix pole_voltages_avg =\n pole_voltages_x * (duties[first_gate_on] - duties[second_gate_on]) +\n pole_voltages_y * (duties[second_gate_on] - duties[third_gate_on]);\n\n return to_complex(kClarkeTransform2x3 * pole_voltages_avg);\n}\n", "meta": {"hexsha": "839f37b0fed0bf78c66cd92077f031b56a2c12d4", "size": 3454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "controls/space_vector_modulation.cpp", "max_stars_repo_name": "mark-berobot/motor_sim", "max_stars_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 16.0, "max_stars_repo_stars_event_min_datetime": "2020-08-17T00:20:36.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-08T01:33:11.000Z", "max_issues_repo_path": "controls/space_vector_modulation.cpp", "max_issues_repo_name": "INKSureIT/motor_sim", "max_issues_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "controls/space_vector_modulation.cpp", "max_forks_repo_name": "INKSureIT/motor_sim", "max_forks_repo_head_hexsha": "62e3d5555e06b84bbc638b348595150e47fe751b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-10-10T01:15:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-19T13:35:23.000Z", "avg_line_length": 31.9814814815, "max_line_length": 78, "alphanum_fraction": 0.6132020845, "num_tokens": 1016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467611766711, "lm_q2_score": 0.743167997235783, "lm_q1q2_score": 0.6533537377799918}} {"text": "/********************************************************************************\n * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute,\n * Faculty of Engineering, University of Southern Denmark\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n ********************************************************************************/\n\n#ifndef RW_MATH_ROTATION2D_HPP\n#define RW_MATH_ROTATION2D_HPP\n\n/**\n * @file Rotation2D.hpp\n */\n\n#if !defined(SWIG)\n#include \"Vector2D.hpp\"\n\n#include \n\n#include \n#endif\n\nnamespace rw { namespace math {\n\n template< class T > class Rotation2DVector;\n\n /** @addtogroup math */\n /* @{*/\n\n#if !defined(SWIGJAVA)\n\n /**\n * @brief A 2x2 rotation matrix \\f$ \\mathbf{R}\\in SO(2) \\f$\n *\n * @f$\n * \\mathbf{R}=\n * \\left[\n * \\begin{array}{cc}\n * {}^A\\hat{X}_B & {}^A\\hat{Y}_B\n * \\end{array}\n * \\right]\n * =\n * \\left[\n * \\begin{array}{cc}\n * r_{11} & r_{12} \\\\\n * r_{21} & r_{22}\n * \\end{array}\n * \\right]\n * @f$\n */\n#endif\n template< class T = double > class Rotation2D\n {\n public:\n //! Value type.\n typedef T value_type;\n\n //! The type of the internal Boost matrix implementation.\n typedef Eigen::Matrix< T, 2, 2 > EigenMatrix2x2;\n\n /**\n @brief A rotation matrix with uninitialized storage.\n */\n Rotation2D () {}\n\n#if !defined(SWIGJAVA)\n\n /**\n * @brief Constructs an initialized 2x2 rotation matrix\n *\n * @param r11 \\f$ r_{11} \\f$\n * @param r12 \\f$ r_{12} \\f$\n * @param r21 \\f$ r_{21} \\f$\n * @param r22 \\f$ r_{22} \\f$\n *\n * @f$\n * \\mathbf{R} =\n * \\left[\n * \\begin{array}{cc}\n * r_{11} & r_{12} \\\\\n * r_{21} & r_{22}\n * \\end{array}\n * \\right]\n * @f$\n */\n\n#endif\n Rotation2D (T r11, T r12, T r21, T r22)\n {\n _m[0][0] = r11;\n _m[0][1] = r12;\n _m[1][0] = r21;\n _m[1][1] = r22;\n }\n\n#if !defined(SWIGJAVA)\n /**\n * @brief Constructs an initialized 2x2 rotation matrix\n * @f$ \\robabx{a}{b}{\\mathbf{R}} =\n * \\left[\n * \\begin{array}{cc}\n * \\robabx{a}{b}{\\mathbf{i}} & \\robabx{a}{b}{\\mathbf{j}}\n * \\end{array}\n * \\right]\n * @f$\n *\n * @param i @f$ \\robabx{a}{b}{\\mathbf{i}} @f$\n * @param j @f$ \\robabx{a}{b}{\\mathbf{j}} @f$\n */\n\n#endif\n Rotation2D (const rw::math::Vector2D< T >& i, const rw::math::Vector2D< T >& j)\n {\n _m[0][0] = i[0];\n _m[0][1] = j[0];\n _m[1][0] = i[1];\n _m[1][1] = j[1];\n }\n\n#if !defined(SWIGJAVA)\n /**\n * @brief Constructs an initialized 2x2 rotation matrix\n * @f$ \\robabx{a}{b}{\\mathbf{R}} =\n * \\left[\n * \\begin{array}{cc}\n * \\robabx{a}{b}{\\mathbf{i}} & \\robabx{a}{b}{\\mathbf{j}}\n * \\end{array}\n * \\right]\n * @f$\n *\n * @param theta\n */\n\n#endif\n Rotation2D (const T theta)\n {\n _m[0][0] = cos (theta);\n _m[0][1] = -sin (theta);\n _m[1][0] = sin (theta);\n _m[1][1] = cos (theta);\n }\n\n /**\n @brief Construct an initialized 2x2 rotation matrix.\n\n The second of column of the matrix is deduced from the first column.\n\n @param i [in] The first column of the rotation matrix.\n */\n Rotation2D (const rw::math::Vector2D< T >& i)\n {\n _m[0][0] = i[0];\n _m[0][1] = -i[1];\n _m[1][0] = i[1];\n _m[1][1] = i[0];\n }\n\n /**\n @brief Construct a rotation matrix from an Eigen matrix.\n */\n template< class R > explicit Rotation2D (const EigenMatrix2x2& m)\n {\n _m[0][0] = m (0, 0);\n _m[0][1] = m (0, 1);\n _m[1][0] = m (1, 0);\n _m[1][1] = m (1, 1);\n }\n\n#if !defined(SWIGJAVA)\n /**\n * @brief Constructs a 2x2 rotation matrix set to identity\n * @return a 2x2 identity rotation matrix\n *\n * @f$\n * \\mathbf{R} =\n * \\left[\n * \\begin{array}{cc}\n * 1 & 0\\\\\n * 0 & 1\n * \\end{array}\n * \\right]\n * @f$\n */\n\n#endif\n static const Rotation2D& identity ()\n {\n static Rotation2D id (1, 0, 0, 1);\n return id;\n }\n \n#if !defined(SWIG)\n /**\n * @brief Returns reference to matrix element\n * @param row [in] row\n * @param column [in] column\n * @return reference to the element\n */\n T& operator() (size_t row, size_t column) { return _m[row][column]; }\n\n /**\n * @brief Returns reference to matrix element\n * @param row [in] row\n * @param column [in] column\n * @return reference to the element\n */\n const T& operator() (size_t row, size_t column) const { return _m[row][column]; }\n#else\n MATRIXOPERATOR (T);\n#endif\n /**\n * @brief Comparison operator.\n *\n * The comparison operator makes a element wise comparison.\n * Returns true only if all elements are equal.\n *\n * @param rhs [in] Rotation2D to compare with\n * @return True if equal.\n */\n bool operator== (const Rotation2D< T >& rhs) const\n {\n for (int i = 0; i < 2; ++i) {\n for (int j = 0; j < 2; ++j) {\n if (!(_m[i][j] == rhs (i, j))) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * @brief Comparison operator.\n *\n * The comparison operator makes a element wise comparison.\n * Returns true if any of the elements are different.\n *\n * @param rhs [in] Rotation2D to compare with\n * @return True if not equal.\n */\n bool operator!= (const Rotation2D< T >& rhs) const { return !(*this == rhs); }\n\n /**\n * @brief Returns a boost 2x2 matrix @f$ \\mathbf{M}\\in SO(2)\n * @f$ that represents this rotation\n *\n * @return @f$ \\mathbf{M}\\in SO(2) @f$\n */\n EigenMatrix2x2 e ()\n {\n EigenMatrix2x2 matrix;\n matrix (0, 0) = _m[0][0];\n matrix (0, 1) = _m[0][1];\n matrix (1, 0) = _m[1][0];\n matrix (1, 1) = _m[1][1];\n return matrix;\n }\n\n /**\n * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{R}} =\n * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{R}} \\f$\n *\n * @param aRb [in] \\f$ \\robabx{a}{b}{\\mathbf{R}} \\f$\n *\n * @param bRc [in] \\f$ \\robabx{b}{c}{\\mathbf{R}} \\f$\n *\n * @return \\f$ \\robabx{a}{c}{\\mathbf{R}} \\f$\n */\n const Rotation2D operator* (const Rotation2D& bRc) const\n {\n return Rotation2D ((*this) (0, 0) * bRc (0, 0) + (*this) (0, 1) * bRc (1, 0),\n (*this) (0, 0) * bRc (0, 1) + (*this) (0, 1) * bRc (1, 1),\n (*this) (1, 0) * bRc (0, 0) + (*this) (1, 1) * bRc (1, 0),\n (*this) (1, 0) * bRc (0, 1) + (*this) (1, 1) * bRc (1, 1));\n }\n\n /**\n * @brief Calculates \\f$ \\robabx{a}{c}{\\mathbf{v}} =\n * \\robabx{a}{b}{\\mathbf{R}} \\robabx{b}{c}{\\mathbf{v}} \\f$\n *\n * @param aRb [in] \\f$ \\robabx{a}{b}{\\mathbf{R}} \\f$\n * @param bVc [in] \\f$ \\robabx{b}{c}{\\mathbf{v}} \\f$\n * @return \\f$ \\robabx{a}{c}{\\mathbf{v}} \\f$\n */\n const rw::math::Vector2D< T > operator* (const rw::math::Vector2D< T >& bVc) const\n {\n return rw::math::Vector2D< T > ((*this) (0, 0) * bVc (0) + (*this) (0, 1) * bVc (1),\n (*this) (1, 0) * bVc (0) + (*this) (1, 1) * bVc (1));\n }\n#if !defined(SWIG)\n /**\n * @brief Writes rotation matrix to stream\n * @param os [in/out] output stream to use\n * @param r [in] rotation matrix to print\n * @return the updated output stream\n */\n friend std::ostream& operator<< (std::ostream& os, const Rotation2D& r)\n {\n return os << \"Rotation2D {\" << r (0, 0) << \", \" << r (0, 1) << \", \" << r (1, 0) << \", \"\n << r (1, 1) << \"}\";\n }\n#else\n TOSTRING (rw::math::Rotation2D< T >);\n#endif\n\n private:\n T _m[2][2];\n // Base _atrix;\n };\n\n /**\n * @brief Casts Rotation2D to Rotation2D\n * @param rot [in] Rotation2D with type T\n * @return Rotation2D with type R\n */\n template< class R, class T > const Rotation2D< R > cast (const Rotation2D< T >& rot)\n {\n Rotation2D< R > res (Rotation2D< R >::identity ());\n for (size_t i = 0; i < 2; i++)\n for (size_t j = 0; j < 2; j++)\n res (i, j) = static_cast< R > (rot (i, j));\n return res;\n }\n\n /**\n * @brief The inverse @f$ \\robabx{b}{a}{\\mathbf{R}} =\n * \\robabx{a}{b}{\\mathbf{R}}^{-1} @f$ of a rotation matrix\n *\n * @relates Rotation2D\n *\n * @param aRb [in] the rotation matrix @f$ \\robabx{a}{b}{\\mathbf{R}} @f$\n *\n * @return the matrix inverse @f$ \\robabx{b}{a}{\\mathbf{R}} =\n * \\robabx{a}{b}{\\mathbf{R}}^{-1} @f$\n *\n * @f$ \\robabx{b}{a}{\\mathbf{R}} = \\robabx{a}{b}{\\mathbf{R}}^{-1} =\n * \\robabx{a}{b}{\\mathbf{R}}^T @f$\n */\n template< class T > const Rotation2D< T > inverse (const Rotation2D< T >& aRb)\n {\n return Rotation2D< T > (aRb (0, 0), aRb (1, 0), aRb (0, 1), aRb (1, 1));\n }\n\n /**\n * @brief Find the transpose of \\b aRb.\n *\n * The transpose of a rotation matrix is the same as the inverse.\n */\n template< class T > const Rotation2D< T > transpose (const Rotation2D< T >& aRb)\n {\n return Rotation2D< T > (aRb (0, 0), aRb (1, 0), aRb (0, 1), aRb (1, 1));\n }\n#if !defined(SWIG)\n extern template class rw::math::Rotation2D< double >;\n extern template class rw::math::Rotation2D< float >;\n#else\n SWIG_DECLARE_TEMPLATE (Rotation2Dd, rw::math::Rotation2D< double >);\n SWIG_DECLARE_TEMPLATE (Rotation2Df, rw::math::Rotation2D< float >);\n#endif\n /**@}*/\n}} // namespace rw::math\n\nnamespace rw { namespace common {\n class OutputArchive;\n class InputArchive;\n namespace serialization {\n /**\n * @copydoc rw::common::serialization::write\n * @relatedalso rw::math::Rotation2D\n */\n template<>\n void write (const rw::math::Rotation2D< double >& sobject,\n rw::common::OutputArchive& oarchive, const std::string& id);\n\n /**\n * @copydoc rw::common::serialization::write\n * @relatedalso rw::math::Rotation2D\n */\n template<>\n void write (const rw::math::Rotation2D< float >& sobject,\n rw::common::OutputArchive& oarchive, const std::string& id);\n\n /**\n * @copydoc rw::common::serialization::read\n * @relatedalso rw::math::Rotation2D\n */\n template<>\n void read (rw::math::Rotation2D< double >& sobject, rw::common::InputArchive& iarchive,\n const std::string& id);\n\n /**\n * @copydoc rw::common::serialization::read\n * @relatedalso rw::math::Rotation2D\n */\n template<>\n void read (rw::math::Rotation2D< float >& sobject, rw::common::InputArchive& iarchive,\n const std::string& id);\n\n } // namespace serialization\n}} // namespace rw::common\n\n#endif // end include guard\n", "meta": {"hexsha": "516d82e1fa26171f83615b317063ece412b3afb8", "size": 12445, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "RobWork/src/rw/math/Rotation2D.hpp", "max_stars_repo_name": "ZLW07/RobWork", "max_stars_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-12-29T14:16:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T14:16:27.000Z", "max_issues_repo_path": "RobWork/src/rw/math/Rotation2D.hpp", "max_issues_repo_name": "ZLW07/RobWork", "max_issues_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RobWork/src/rw/math/Rotation2D.hpp", "max_forks_repo_name": "ZLW07/RobWork", "max_forks_repo_head_hexsha": "e713881f809d866b9a0749eeb15f6763e64044b3", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.1331719128, "max_line_length": 99, "alphanum_fraction": 0.4697468863, "num_tokens": 3843, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.837619979547273, "lm_q2_score": 0.7799928900257126, "lm_q1q2_score": 0.6533376285903557}} {"text": "#include \n#include \n\n#include \n#include \n\n/***********************************************************************************************/\n\n// Generic functor\n// See http://eigen.tuxfamily.org/index.php?title=Functors\n// C++ version of a function pointer that stores meta-data about the function\ntemplate\nstruct Functor\n{\n\n // Information that tells the caller the numeric type (eg. double) and size (input / output dim)\n typedef _Scalar Scalar;\n enum { // Required by numerical differentiation module\n InputsAtCompileTime = NX,\n ValuesAtCompileTime = NY\n };\n\n // Tell the caller the matrix sizes associated with the input, output, and jacobian\n typedef Eigen::Matrix InputType;\n typedef Eigen::Matrix ValueType;\n typedef Eigen::Matrix JacobianType;\n\n // Local copy of the number of inputs\n int m_inputs, m_values;\n\n // Two constructors:\n Functor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n Functor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n // Get methods for users to determine function input and output dimensions\n int inputs() const { return m_inputs; }\n int values() const { return m_values; }\n\n};\n\n/***********************************************************************************************/\n\n// https://en.wikipedia.org/wiki/Test_functions_for_optimization\n// Booth Function\n// Implement f(x,y) = (x + 2*y -7)^2 + (2*x + y - 5)^2\nstruct BoothFunctor : Functor\n{\n // Simple constructor\n BoothFunctor(): Functor(2,3) {}\n\n // Implementation of the objective function\n int operator()(const Eigen::VectorXd &z, Eigen::VectorXd &fvec) const {\n double a = z(0);\n\t double b = z(1);\n\t double c = z(2);\n\t/*\n * Evaluate the Booth function.\n * Important: LevenbergMarquardt is designed to work with objective functions that are a sum\n * of squared terms. The algorithm takes this into account: do not do it yourself.\n * In other words: objFun = sum(fvec(i)^2)\n */\n fvec(0) = 3*a -cos(b*c) -0.5;\n fvec(1) = pow(a,2.0) -81*pow((b+0.1),2.0)+sin(c)+1.06;\n\t fvec(2) = exp(-a*b)+20*c+(10*M_PI-3.0)/3.0;\n return 0;\n }\n};\n\n/***********************************************************************************************/\n\n// https://en.wikipedia.org/wiki/Test_functions_for_optimization\n// Himmelblau's Function\n// Implement f(x,y) = (x^2 + y - 11)^2 + (x + y^2 - 7)^2\nstruct HimmelblauFunctor : Functor\n{\n // Simple constructor\n HimmelblauFunctor(): Functor(2,2) {}\n // Implementation of the objective function\n int operator()(const Eigen::VectorXd &z, Eigen::VectorXd &fvec) const {\n double x = z(0); double y = z(1);\n /*\n * Evaluate Himmelblau's function.\n * Important: LevenbergMarquardt is designed to work with objective functions that are a sum\n * of squared terms. The algorithm takes this into account: do not do it yourself.\n * In other words: objFun = sum(fvec(i)^2)\n */\n fvec(0) = x * x + y - 11;\n fvec(1) = x + y * y - 7;\n return 0;\n }\n};\n\n/***********************************************************************************************/\n\nvoid testBoothFun() {\n std::cout << \"Testing the Booth function...\" << std::endl;\n Eigen::VectorXd zInit(3); zInit << 0.1, 0.1, -0.1;\n std::cout << \"zInit: \" << zInit.transpose() << std::endl;\n\n BoothFunctor functor;\n Eigen::NumericalDiff numDiff(functor);\n Eigen::LevenbergMarquardt,double> lm(numDiff);\n lm.parameters.maxfev = 1000;\n lm.parameters.xtol = 1.0e-10;\n std::cout << \"max fun eval: \" << lm.parameters.maxfev << std::endl;\n std::cout << \"x tol: \" << lm.parameters.xtol << std::endl;\n\n Eigen::VectorXd z = zInit;\n int ret = lm.minimize(z);\n std::cout << \"iter count: \" << lm.iter << std::endl;\n std::cout << \"return status: \" << ret << std::endl;\n std::cout << \"zSolver: \" << z.transpose() << std::endl;\n std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n}\n\n/***********************************************************************************************/\n\nvoid testHimmelblauFun() {\n std::cout << \"Testing the Himmelblau function...\" << std::endl;\n // Eigen::VectorXd zInit(2); zInit << 0.0, 0.0; // soln 1\n // Eigen::VectorXd zInit(2); zInit << -1, 1; // soln 2\n // Eigen::VectorXd zInit(2); zInit << -1, -1; // soln 3\n Eigen::VectorXd zInit(2); zInit << 1, -1; // soln 4\n std::cout << \"zInit: \" << zInit.transpose() << std::endl;\n std::cout << \"soln 1: [3.0, 2.0]\" << std::endl;\n std::cout << \"soln 2: [-2.805118, 3.131312]\" << std::endl;\n std::cout << \"soln 3: [-3.77931, -3.28316]\" << std::endl;\n std::cout << \"soln 4: [3.584428, -1.848126]\" << std::endl;\n\n HimmelblauFunctor functor;\n Eigen::NumericalDiff numDiff(functor);\n Eigen::LevenbergMarquardt,double> lm(numDiff);\n lm.parameters.maxfev = 1000;\n lm.parameters.xtol = 1.0e-10;\n std::cout << \"max fun eval: \" << lm.parameters.maxfev << std::endl;\n std::cout << \"x tol: \" << lm.parameters.xtol << std::endl;\n\n Eigen::VectorXd z = zInit;\n int ret = lm.minimize(z);\n std::cout << \"iter count: \" << lm.iter << std::endl;\n std::cout << \"return status: \" << ret << std::endl;\n std::cout << \"zSolver: \" << z.transpose() << std::endl;\n std::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n}\n\n/***********************************************************************************************/\n\nint main(int argc, char *argv[])\n{\n\n\tstd::cout << \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\" << std::endl;\n\ttestBoothFun();\n\ttestHimmelblauFun();\n\treturn 0;\n}", "meta": {"hexsha": "7c472a9258f2e51524d10af24419efc79bb29d69", "size": 5981, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/test_matrix_solve.cpp", "max_stars_repo_name": "neeldug/404CircuitSim", "max_stars_repo_head_hexsha": "cc402770ec4e8c5d1914bfd93696fb59d519fdb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/test_matrix_solve.cpp", "max_issues_repo_name": "neeldug/404CircuitSim", "max_issues_repo_head_hexsha": "cc402770ec4e8c5d1914bfd93696fb59d519fdb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/test_matrix_solve.cpp", "max_forks_repo_name": "neeldug/404CircuitSim", "max_forks_repo_head_hexsha": "cc402770ec4e8c5d1914bfd93696fb59d519fdb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-06T20:27:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-06T20:27:56.000Z", "avg_line_length": 38.5870967742, "max_line_length": 98, "alphanum_fraction": 0.5664604581, "num_tokens": 1657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199714402812, "lm_q2_score": 0.7799928951399098, "lm_q1q2_score": 0.6533376265507135}} {"text": "#ifndef RSVD_STANDARD_NORMAL_RANDOM_HPP_\n#define RSVD_STANDARD_NORMAL_RANDOM_HPP_\n\n#include \n#include \n#include \n#include \n\nnamespace Rsvd {\n\nnamespace Internal {\n\nnamespace {\n/// \\brief Shortcut for the underlying \\a real type used in the matrix.\n///\n/// \\long E.g. if the matrix is of type \\c std::complex, this typedef equals to \\c double.\ntemplate \nusing RealType = typename Eigen::NumTraits::Real;\n} // namespace\n\n/// \\brief Helper struct to do partial specialization in the matrix scalar type\n///\n/// \\tparam MatrixType Eigen matrix type.\n///\n/// \\tparam ScalarType Underlying scalar type used in \\c MatrixType, can be complex or real.\n///\n/// \\tparam RandomEngineType Type of the random engine, e.g. \\c std::default_random_engine or \\c\n/// std::mt19937_64.\ntemplate \nstruct StandardNormalRandomHelper {\n static inline MatrixType generate(Eigen::Index numRows, Eigen::Index numCols,\n RandomEngineType &engine);\n};\n\n/// \\brief Partial specialization for real matrices.\ntemplate \nstruct StandardNormalRandomHelper, RandomEngineType> {\n static inline MatrixType generate(const Eigen::Index numRows, const Eigen::Index numCols,\n RandomEngineType &engine) {\n // Create a standard normal distribution with zero mean (mu = 0) and unity variance (sigma^2 =\n // 1)\n std::normal_distribution> distribution{0, 1};\n const auto normal{[&](typename MatrixType::Scalar) { return distribution(engine); }};\n return MatrixType::NullaryExpr(numRows, numCols, normal);\n }\n};\n\n/// \\brief Partial specialization for complex matrices.\ntemplate \nstruct StandardNormalRandomHelper>,\n RandomEngineType> {\n static inline MatrixType generate(const Eigen::Index numRows, const Eigen::Index numCols,\n RandomEngineType &engine) {\n // A complex standard normal distribution has half of its variance in the real variable and\n // half in the complex. Hence, the each variance is 1/2 and each standard deviation is\n // 1/sqrt(2)\n constexpr RealType stdDev{0.707106781186547};\n std::normal_distribution> distribution{0, stdDev};\n const auto complexNormal{[&](typename MatrixType::Scalar) {\n return std::complex>(distribution(engine), distribution(engine));\n }};\n return MatrixType::NullaryExpr(numRows, numCols, complexNormal);\n }\n};\n\n/// \\brief Generate a matrix with iid elements from standard normal\n/// distribution.\n///\n/// \\long The matrix elements are drawn from the standard normal distribution (zero mean and unit\n/// variance), i.e. \\f$ [ \\Omega ]_{i,j} \\sim \\mathcal{N}(0, 1) \\f$ for the real case and \\f$ [\n/// \\Omega ]_{i,j} \\sim \\mathcal{N}\\left(0, \\frac{1}{2} \\right) + \\mathcal{N}\\left(0, \\frac{1}{2}\n/// \\right) \\cdot \\mathrm{i}\\f$ for the complex case.\n///\n/// \\tparam MatrixType Eigen matrix type.\n/// \\tparam RandomEngineType Type of the random engine, e.g. \\c std::default_random_engine or \\c\n/// std::mt19937_64.\n///\n/// \\param numRows Number of matrix rows \\f$ m \\f$.\n/// \\param numCols Number of matrix columns \\f$ n \\f$.\n/// \\param engine Reference to the random engine.\n///\n/// \\return Matrix \\f$ \\Omega \\in \\mathbb{F}^{m \\times n} \\f$ with \\f$\\mathbb{F} \\in \\{ \\mathbb{R},\n/// \\mathbb{C} \\} \\f$ with normally distributed elements.\ntemplate \ninline MatrixType standardNormalRandom(const Eigen::Index numRows, const Eigen::Index numCols,\n RandomEngineType &engine) {\n return StandardNormalRandomHelper::generate(numRows, numCols, engine);\n}\n\n} // namespace Internal\n\n} // namespace Rsvd\n\n#endif\n", "meta": {"hexsha": "1453a7baaf61579e600b5882c879bbad72adc08a", "size": 4173, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/rsvd/StandardNormalRandom.hpp", "max_stars_repo_name": "mooreryan/coda", "max_stars_repo_head_hexsha": "e6c92d035e4d6cfb0cb7ab3cccc9150e60bd97c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-09-16T09:12:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-03T15:40:04.000Z", "max_issues_repo_path": "include/rsvd/StandardNormalRandom.hpp", "max_issues_repo_name": "mooreryan/coda", "max_issues_repo_head_hexsha": "e6c92d035e4d6cfb0cb7ab3cccc9150e60bd97c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/rsvd/StandardNormalRandom.hpp", "max_forks_repo_name": "mooreryan/coda", "max_forks_repo_head_hexsha": "e6c92d035e4d6cfb0cb7ab3cccc9150e60bd97c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-08T18:45:56.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-08T18:45:56.000Z", "avg_line_length": 43.46875, "max_line_length": 99, "alphanum_fraction": 0.6999760364, "num_tokens": 990, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199592797929, "lm_q2_score": 0.7799929053683038, "lm_q1q2_score": 0.653337625633126}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n MatrixXd X = MatrixXd::Random(5,5);\nMatrixXd A = X * X.transpose();\nX = MatrixXd::Random(5,5);\nMatrixXd B = X * X.transpose();\n\nGeneralizedSelfAdjointEigenSolver es(A,B,EigenvaluesOnly);\ncout << \"The eigenvalues of the pencil (A,B) are:\" << endl << es.eigenvalues() << endl;\nes.compute(B,A,false);\ncout << \"The eigenvalues of the pencil (B,A) are:\" << endl << es.eigenvalues() << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "a79b03f63a62b5f439322d1e051616413dd4f39a", "size": 547, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_SelfAdjointEigenSolver_compute_MatrixType2.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_SelfAdjointEigenSolver_compute_MatrixType2.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_SelfAdjointEigenSolver_compute_MatrixType2.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.8636363636, "max_line_length": 87, "alphanum_fraction": 0.6782449726, "num_tokens": 155, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278602705731, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6531504835788359}} {"text": "#pragma once\n\n#include \n#include \n\n#include \n#include \n\nusing std::vector;\nusing std::map;\n\n\nnamespace mcl_cpp\n{\n\tclass mcl\n\t{\n\tpublic:\n\t\t//! @brief MCL ctor. Register a callback function to return the cluster results\n\t\tmcl(const Eigen::MatrixXd& Min, std::function< void(size_t cluster_j, size_t member_i) > f) : M(Min), ClusterResultCallback(f) {}\n\n\t\t/*! @brief Apply Markov clustering algorithm with specified parameters and return clusters\n\t\t\tFor each cluster, returns the list of node-ids that belong to that cluster\n\t\t\t*/\n\t\tEigen::MatrixXd cluster_mcl(double expand_factor = 2, double inflate_factor = 2, double max_loop = 10, double mult_factor = 1)\n\t\t{\n\t\t\tEigen::MatrixXd M_selfloop = M + mult_factor * Eigen::MatrixXd::Identity(M.cols(), M.rows());\n\t\t\tEigen::MatrixXd M_normalized = normalize(M_selfloop);\n\t\t\tint i;\n\t\t\tfor (i = 0; i < max_loop && !stop(M_normalized, i); i++)\n\t\t\t{\n\t\t\t\tinflate(M_normalized, inflate_factor);\n\t\t\t\texpand(M_normalized, expand_factor);\n\t\t\t}\n\t\t\tfor (auto row = 0; row 0)\n\t\t\t\t{\n\t\t\t\t\tfor (auto col = 0; col < M_normalized.cols(); col++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (M_normalized.coeff(row, col) > 0)\n\t\t\t\t\t\t\tClusterResultCallback(row, col);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn std::move(M_normalized);\n\t\t}\n\n\tprivate:\n\t\tbool stop(const Eigen::MatrixXd& in, int i)\n\t\t{\n\t\t\tEigen::MatrixXd m = in*in;\n\t\t\tEigen::MatrixXd diff = (m - in);\n\t\t\tdouble mx = diff.maxCoeff(), mn = diff.minCoeff();\n\t\t\treturn (diff.maxCoeff() == diff.minCoeff());\n\t\t}\n\n\t\tEigen::MatrixXd normalize(Eigen::MatrixXd& in)\n\t\t{\n\t\t\tEigen::MatrixXd one_over_col_sum = in.colwise().sum().cwiseInverse();\n\t\t\tEigen::MatrixXd M_normalized = in * one_over_col_sum.asDiagonal();\n\t\t\treturn std::move(M_normalized);\n\t\t}\n\n\t\tvoid expand(Eigen::MatrixXd& in, double expand_factor)\n\t\t{\n\t\t\tEigen::MatrixPower Apow(in);\n\t\t\tin = Apow(expand_factor);\n\t\t}\n\n\t\tvoid inflate(Eigen::MatrixXd& in, double inflate_factor)\n\t\t{\n\t\t\tauto lam = [inflate_factor](double x) -> double { return std::pow(x, inflate_factor); };\n\t\t\tin = in.unaryExpr(lam);\n\t\t\tin = normalize(in);\n\t\t}\n\n\t\tconst Eigen::MatrixXd & M;\n\t\tstd::function< void(size_t cls_i, size_t mem_j) > ClusterResultCallback;\n\t};\n\n\n\n\n\n\n}", "meta": {"hexsha": "e7327bc9422f437b117ce29a830bd12e928b9bda", "size": 2286, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "mcl/mcl.hpp", "max_stars_repo_name": "kgopalak/mcl_cpp", "max_stars_repo_head_hexsha": "9ba11713ab9d6b4f1d31552f8b1736a6016aee29", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-04-26T01:15:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-17T18:01:57.000Z", "max_issues_repo_path": "mcl/mcl.hpp", "max_issues_repo_name": "kgopalak/mcl_cpp", "max_issues_repo_head_hexsha": "9ba11713ab9d6b4f1d31552f8b1736a6016aee29", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mcl/mcl.hpp", "max_forks_repo_name": "kgopalak/mcl_cpp", "max_forks_repo_head_hexsha": "9ba11713ab9d6b4f1d31552f8b1736a6016aee29", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.5813953488, "max_line_length": 131, "alphanum_fraction": 0.6688538933, "num_tokens": 644, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278540866548, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6531504790016581}} {"text": "#include \n#include \n#include \n\nvoid buildSystem(Eigen::MatrixXd& A, Eigen::VectorXd& b, const unsigned int dim) {\n A = Eigen::MatrixXd::Random(dim, dim);\n A.diagonal() += (dim + 1) * Eigen::VectorXd::Ones(dim);\n \n b = Eigen::VectorXd::Random(dim);\n assert(b.norm() > DBL_EPSILON);\n}\n\nEigen::VectorXd GS(const Eigen::MatrixXd& A, const Eigen::VectorXd& b, const unsigned int nbIter) {\n auto x = b;\n for (size_t iter = 0; iter < nbIter; ++iter) {\n for (size_t i = 0; i < A.rows(); i++) {\n double sum = 0.0;\n for (size_t j = 0; j < A.cols(); j++) {\n if (j != i) {\n sum += A(i, j) * x(j);\n }\n x(i) = (b(i) - sum) / A(i, i);\n }\n }\n }\n return x;\n}\n\nint main(int argc, char const *argv[]) {\n const unsigned int arraySize = 5;\n Eigen::MatrixXd A = Eigen::MatrixXd::Random(arraySize, arraySize);\n Eigen::VectorXd b = Eigen::VectorXd::Random(arraySize);\n buildSystem(A, b, A.size());\n\n TP_CPP_IMAC2::Chrono chrono;\n\n // Jacobi\n chrono.start();\n Eigen::VectorXd x = GS(A, b, 28);\n chrono.stop();\n std::cout << \"Jacobi : \" << chrono.timeSpan() << std::endl;\n\n // Lu\n chrono.start();\n Eigen::PartialPivLU lu(A);\n x = A * lu.solve(b);\n chrono.stop();\n std::cout << \"Lu : \" << chrono.timeSpan() << std::endl;\n\n // QR\n chrono.start();\n Eigen::ColPivHouseholderQR qr(A);\n x = A * qr.solve(b);\n chrono.stop();\n std::cout << \"QR : \" << chrono.timeSpan() << std::endl;\n\n // SVD\n chrono.start();\n Eigen::JacobiSVD svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV);\n x = A * svd.solve(b);\n chrono.stop();\n std::cout << \"SVD : \" << chrono.timeSpan() << std::endl;\n\n return 0;\n}\n\n", "meta": {"hexsha": "4dbb8771562a76c78d4d6c99296282bd768600e3", "size": 1865, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/semestre-3/maths-3/ex5/main.cpp", "max_stars_repo_name": "guillaume-haerinck/imac-c", "max_stars_repo_head_hexsha": "2d88de90acdb546479c4e310528e786358e66bd7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/semestre-3/maths-3/ex5/main.cpp", "max_issues_repo_name": "guillaume-haerinck/imac-c", "max_issues_repo_head_hexsha": "2d88de90acdb546479c4e310528e786358e66bd7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/semestre-3/maths-3/ex5/main.cpp", "max_forks_repo_name": "guillaume-haerinck/imac-c", "max_forks_repo_head_hexsha": "2d88de90acdb546479c4e310528e786358e66bd7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8358208955, "max_line_length": 99, "alphanum_fraction": 0.5378016086, "num_tokens": 548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093975331752, "lm_q2_score": 0.731058584489497, "lm_q1q2_score": 0.6530615036717684}} {"text": "#include \n#include \n#include \n\nusing namespace std;\n\nstruct Vertex {\n double x, y, z;\n};\n \nint main()\n{\n Vertex v1, v2, v3;\n cin >> v1.x >> v1.y >> v1.z\n >> v2.x >> v2.y >> v2.z\n >> v3.x >> v3.y >> v3.z;\n \n Eigen::Vector3d vec12(v2.x-v1.x, v2.y-v1.y, v2.z-v1.z);\n Eigen::Vector3d vec23(v3.x-v2.x, v3.y-v2.y, v3.z-v2.z);\n\n Eigen::Vector3d veccross = vec12.cross(vec23);\n // veccross /= sqrt(veccross.array().pow(2).sum());\n veccross.normalize();\n\n Eigen::Vector4d faceEqn;\n faceEqn << veccross, -veccross[0]*v1.x -veccross[1]*v1.y -veccross[2]*v1.z;\n\n cout << veccross << endl << faceEqn << endl;\n \n}", "meta": {"hexsha": "d9b4fa8f496f4406c9c6e3e246e708872403180e", "size": 686, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "QmatrixTest.cpp", "max_stars_repo_name": "CalaW/Mesh-Simplification", "max_stars_repo_head_hexsha": "0bd0a4bf2cfd6b8cc4ea839937829ad8462eba63", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-02-26T04:37:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T04:37:27.000Z", "max_issues_repo_path": "QmatrixTest.cpp", "max_issues_repo_name": "CalaW/Mesh-Simplification", "max_issues_repo_head_hexsha": "0bd0a4bf2cfd6b8cc4ea839937829ad8462eba63", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QmatrixTest.cpp", "max_forks_repo_name": "CalaW/Mesh-Simplification", "max_forks_repo_head_hexsha": "0bd0a4bf2cfd6b8cc4ea839937829ad8462eba63", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.8666666667, "max_line_length": 79, "alphanum_fraction": 0.5626822157, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229948845201, "lm_q2_score": 0.7057850278370111, "lm_q1q2_score": 0.6530134452013466}} {"text": "#include \n#include \n#include \n#include \n\nEigen::Matrix3d OthMatrix(const Eigen::Matrix3d& input) {\n Eigen::Quaterniond q(input);\n q.normalize();\n return q.toRotationMatrix();\n}\n\n// 解决如下问题\n// 1. Affine3d, Isomtry3d, Matrix4d表示同一个欧式变换时,求逆是否不同\n// 从输出可以看出来结果一致\nint main(int argv, char** argc) {\n double theta_z = M_PI * 60 / 180;\n double theta_y = M_PI * 30 / 180;\n double theta_x = M_PI * 40 / 180;\n Eigen::Matrix3d rz =\n Eigen::AngleAxisd(theta_z, Eigen::Vector3d::UnitZ()).toRotationMatrix();\n Eigen::Matrix3d ry =\n Eigen::AngleAxisd(theta_y, Eigen::Vector3d::UnitY()).toRotationMatrix();\n Eigen::Matrix3d rx =\n Eigen::AngleAxisd(theta_x, Eigen::Vector3d::UnitX()).toRotationMatrix();\n\n Eigen::Quaterniond rotation(rz * ry * rx);\n std::cout << rotation.matrix() << std::endl;\n Eigen::Translation3d t(1, 2, 3);\n Eigen::Affine3d matrix_affine = t * rotation;\n std::cout <<\"matrix_affine : \\n\" << matrix_affine.matrix() << std::endl;\n\n Eigen::Isometry3d isometry3d(t * rotation);\n std::cout << \"isometry3 : \\n\" << isometry3d.matrix() << std::endl;\n\n Eigen::Matrix4d m4d = matrix_affine.matrix();\n std::cout << \"matrix4d : \\n\" << m4d.matrix() << std::endl;\n\n std::cout <<\"matrix_affine inverse: \\n\" << matrix_affine.inverse().matrix() << std::endl;\n std::cout << \"matrix4d inverse : \\n\" << m4d.inverse() << std::endl;\n std::cout << \"isometry3 inverse : \\n\" << isometry3d.inverse().matrix() << std::endl;\n\n}", "meta": {"hexsha": "e08123586f801230358c4938fce51a49da20d8cd", "size": 1538, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/space_transform/matrix_representation.cpp", "max_stars_repo_name": "sliding-window/algorithm-practice", "max_stars_repo_head_hexsha": "c70fd954423372cebbfd9dee368058a85e43a292", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/space_transform/matrix_representation.cpp", "max_issues_repo_name": "sliding-window/algorithm-practice", "max_issues_repo_head_hexsha": "c70fd954423372cebbfd9dee368058a85e43a292", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/space_transform/matrix_representation.cpp", "max_forks_repo_name": "sliding-window/algorithm-practice", "max_forks_repo_head_hexsha": "c70fd954423372cebbfd9dee368058a85e43a292", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.619047619, "max_line_length": 94, "alphanum_fraction": 0.6417425228, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.925229948845201, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6530134394755358}} {"text": "/*\n * two_dimensional_phase_lattice.cpp\n *\n * This example show how one can use matrices as state types in odeint.\n *\n * Copyright 2009-2012 Karsten Ahnert and Mario Mulansky.\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n */\n\n#include \n#include \n#include \n#include \n\n#ifndef M_PI //not there on windows\n#define M_PI 3.1415927 //...\n#endif\n\n#include \n\nusing namespace std;\nusing namespace boost::numeric::odeint;\n\n//[ two_dimensional_phase_lattice_definition\ntypedef boost::numeric::ublas::matrix< double > state_type;\n\nstruct two_dimensional_phase_lattice\n{\n two_dimensional_phase_lattice( double gamma = 0.5 )\n : m_gamma( gamma ) { }\n\n void operator()( const state_type &x , state_type &dxdt , double /* t */ ) const\n {\n size_t size1 = x.size1() , size2 = x.size2();\n\n for( size_t i=1 ; i map_type;\n\n write_snapshots( void ) : m_count( 0 ) { }\n\n void operator()( const state_type &x , double t )\n {\n map< size_t , string >::const_iterator it = m_snapshots.find( m_count );\n if( it != m_snapshots.end() )\n {\n ofstream fout( it->second.c_str() );\n for( size_t i=0 ; i( rand() ) / RAND_MAX * 2.0 * M_PI;\n\n write_snapshots snapshots;\n snapshots.snapshots().insert( make_pair( size_t( 0 ) , string( \"lat_0000.dat\" ) ) );\n snapshots.snapshots().insert( make_pair( size_t( 100 ) , string( \"lat_0100.dat\" ) ) );\n snapshots.snapshots().insert( make_pair( size_t( 1000 ) , string( \"lat_1000.dat\" ) ) );\n observer_collection< state_type , double > obs;\n obs.observers().push_back( write_for_gnuplot( 10 ) );\n obs.observers().push_back( snapshots );\n\n cout << \"set term x11\" << endl;\n cout << \"set pm3d map\" << endl;\n\n integrate_const( runge_kutta4() , two_dimensional_phase_lattice( 1.2 ) ,\n x , 0.0 , 1001.0 , 0.1 , boost::ref( obs ) );\n\n // controlled steppers work only after ublas bugfix\n //integrate_const( make_dense_output< runge_kutta_dopri5< state_type > >( 1E-6 , 1E-6 ) , two_dimensional_phase_lattice( 1.2 ) ,\n // x , 0.0 , 1001.0 , 0.1 , boost::ref( obs ) );\n\n\n return 0;\n}\n", "meta": {"hexsha": "db5bbebfeb0a7d61d38d61ac46f794a3969aa622", "size": 4592, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/two_dimensional_phase_lattice.cpp", "max_stars_repo_name": "Drona-Org/Drona-DMR", "max_stars_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2019-05-14T14:49:09.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T06:53:28.000Z", "max_issues_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/two_dimensional_phase_lattice.cpp", "max_issues_repo_name": "Dronacharya-Org/Dronacharya", "max_issues_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/ros_simulator/src/quadrotor_simulator/include/odeint-v2/libs/numeric/odeint/examples/two_dimensional_phase_lattice.cpp", "max_forks_repo_name": "Dronacharya-Org/Dronacharya", "max_forks_repo_head_hexsha": "ecc756ec137aee90ab5ac9ea97f09b6e030066f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2018-12-15T20:18:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-31T19:26:57.000Z", "avg_line_length": 29.0632911392, "max_line_length": 132, "alphanum_fraction": 0.5158972125, "num_tokens": 1401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406087, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6529351593474146}} {"text": "\n/**\n\\file quintic_spline.cpp\n\\brief quintic_spline parameterization\n *\n\\author Mahmoud Ali\n\\date 21/6/2019\n*/\n\n\n#include\n#include\n#include \"ros/ros.h\"\n#include \"std_msgs/Float64MultiArray.h\"\n\n//#include\n#include\n#include \n#include \n\n#include \n#include \"matplotlibcpp.h\"\nnamespace plt = matplotlibcpp;\nusing namespace Eigen;\nusing namespace std;\nusing Eigen::MatrixXd;\n\nconst double sm=180, vm= 130, am=250, jm=1000; // pos, vel, acc, jrk max limits\n\n\n// finds in which segment time instant tg belons to\nint find_seg_number (double tg, std::vector T_vec){\n // segment changes from 0 to n-2 which mean n-1 seg\n int seg = 0;\n if(tg<= T_vec[0]) //less than tstart\n return seg;\n else if(tg>= T_vec[T_vec.size() -2 ] ) //if tg is greater than the starting time of the last segment\n return T_vec.size() - 2;\n else {\n for (int i=0; i< T_vec.size()-2 ; i++) { // between tstart and tend\n if(tg>= T_vec[i] && tg< T_vec[i+1])\n seg = i;\n }\n return seg;\n }\n}\n\n\n// to sample trajectory, find state(pos, vel, acc, jrk) at a given time tg, T_vec is time vector of waypoints, cof is coef matrix of quintic spline\nvoid sample (const std::vector& T_vec, const double& tg, const std::vector> &cof, std::vector & state){//, bool pos_plt=true, bool vel_plt=true, bool acc_plt=true, bool jrk_plt=true ){\n std::vector a=cof[0], b=cof[1], c=cof[2], d=cof[3], e=cof[4], f=cof[5];\n double pos=0, vel=0, acc=0, jrk=0;\n int n = T_vec.size(), seg=0; // n:number of points\n double t=0; // to represent tg-tseg\n //check for vector sizes\n // std::cout<<\"\\nsize of a= \"<< a.size() << \" size of T= \"<< T_vec.size();\n if( a.size() != T_vec.size()-1 )\n std::cout<<\"error: coef and time have different size\\n\";\n\n\n // check for tg inside T_vec or not, if yes find corrresponding segment\n if(tg < T_vec[0]){\n std::cout<<\"Warn: request time instant is before start time of trajectory\\n\";\n pos= a[0];\n vel= b[0];\n acc= 2*c[0];\n jrk= 6*d[0];\n }\n else if(tg > T_vec[n-1] ){\n std::cout<<\"Warn: request time instant is after the end time of trajectory\\n \";\n t = tg - T_vec[n-1];\n pos= a[n-2] + b[n-2]*t + c[n-2]*pow( t, 2) + d[n-2]*pow( t, 3) + e[n-2]*pow( t, 4) + f[n-2]* pow( t, 5) ;\n vel= b[n-2] + 2*c[n-2]*t + 3*d[n-2]*pow( t, 2) + 4*e[n-2]*pow( t, 3) + 5*f[n-2]* pow( t, 4) ;\n acc= 2*c[n-2] + 6*d[n-2]*t + 12*e[n-2]*pow( t, 2) + 20*f[n-2]* pow( t, 3) ;\n jrk= 6*d[n-2] + 24*e[n-2]*t + 60*f[n-2]* pow( t, 2) ;\n }\n else{\n seg= find_seg_number(tg, T_vec);\n t = tg - T_vec[seg];\n // std::cout<<\" tg= \" < > P_jt_wpt;\n P_jt_wpt.resize( n_jts);\n for(int jt=0; jt stp_pts_idx;\n for (int i=1; i 0 && (pos(i) - pos(i-1))> 0 ) || ( (pos(i+1) - pos(i))< 0 && (pos(i) - pos(i-1))< 0 ) )\n continue;\n stp_pts_idx.push_back( i );\n }\n // ROS_INFO_STREAM(\"stp_pts_idx\"); //check\n // for (int i=0; i< stp_pts_idx.size(); i++)\n // ROS_INFO_STREAM(\" \"<< stp_pts_idx[i] );\n\n\n\n //from pos vector: generate initial time for way points. t: time vector of waypoinys times, h is vector for segments times\n VectorXd t(n), h(n-1); //t0 ==> tn-1 ... h0 ==> hn-2 (#n of t and #n-1 of h)\n for (int i = 0; i < n-1; ++i) {\n h(i) = abs( (abs(pos(i+1)) - abs(pos(i))) ) /vm;\n }\n // ROS_INFO_STREAM(\"h vector: \\n\"<>>>>>>>>>>step_1: 3 boundary conditions for first point (pos0, vel0, acc0), 3 rows\n A(0,0) = 1;\n A(1,1) = 1;\n A(2,2) = 1; // 3 rows are filled so far, so next r=3\n\n\n //>>>>>>>>>>> step_2: pos condition for all waypoints except first and last, (n-2) rows\n int col_idx= 6;\n for (int r = 3; r < 3+(n-2); ++r) { //start filling from 4th row, #rows= n-2\n A(r,col_idx) = 1;\n col_idx+=6;\n } // n-2 rows are filled so far, so total rows are n-2+3= n+1\n\n\n int count =0; // count no of iteration\n std::vector seg_idx; //store segments indices that violate jerk\n bool update_all_seg_time= false; // select: true=> updates times of all segments, false: update time for segments that voilate jerk\n //================================================= loop: update time till the jerk become within the limit ================================\n // bif while loop\n bool lmtd_jrk = false; //will be set to true when all jrk values are in the limits\n while (!lmtd_jrk){\n if(count>0){ //no update in the first loop\n if(update_all_seg_time) // update all segment time\n for (int idx = 0; idx < n-1; ++idx)\n h(idx)=h(idx)+0.01;\n\n else{ // only update the time of segment that violate jerk limit\n for (int idx = 0; idx < seg_idx.size(); ++idx){\n ROS_INFO_STREAM(\"seg_idx[\"<>>>>>>>>>>step_3: boundary conditions for last point (posn, veln, accn), 3 rows (depends on time so it is inside the loop)\n // ROS_INFO(\"3 boundary conditions for last poit\");\n for (int r = n+1 ; r < 3+(n+1); ++r) {// for 3 row\n for (int c = n_eqs-6 ; c < n_eqs; ++c) { // last 6 columns\n generate_coef_matrix_c1( n-2, h, C1);\n A(r, c) = C1(r-(n+1), c-(n_eqs-6)); // last h ==> hn-2\n }\n }//3+(n-2)+3 = n+4 rows are filled so far, so next row to fill is (n+5)th row [its is index= n+4]\n //>>>>>>>>>>>step_4: 5(n-2) coninuity conditions for each waypoints except first and last, 5(n-2) rows (depend on time so it is inside the loop)\n // ROS_INFO(\" 5(n-2) continuity conditions for midle poits\");\n int row_idx = n+4; col_idx=0; //start filling from (n+2)th row [its is index= n+1],\n for (int blk=0; blk< n-2; blk++) { // n-2 blks, each blk is 5 equations with 6 coef\n // ROS_INFO_STREAM(\"row_idx: \"<< row_idx <<\" col_idx:\"<< col_idx);\n for (int r = 0 ; r < 5 ; ++r) { // 5(n-2) rows\n for (int c = 0 ; c < 6; ++c) { // last 6 columns\n // ROS_INFO_STREAM(\"r: \"<< r <<\" c:\"<< c);\n generate_coef_matrix_c1( blk, h, C1);\n A(row_idx+r, col_idx+c) = C1(r,c); // last h ==> hn-2\n A(row_idx+r, col_idx+c+6) = C2(r,c);\n }\n }\n col_idx += 6;\n row_idx += 5;\n } //all row s are filled\n\n\n //====================================check for stop points:==================================\n\n\n //>>>>>>>>>>>step_5: fill B vector B\n B(0) = pos(0);\n B(1) = vel0;\n B(2) = acc0; // 3 rows so far\n for (int i=1; i< n-1; i++) // all pos from pos1 to pos(n-1)= (n-2) rows\n B(i+2)= pos(i); // so far 3+n-2 = n+1\n\n for (int i=n+4; i< n_eqs; i++) // last 5(n-2) ros\n B(i)= 0; // so far 3+n-2 = n+1\n\n B(n+1) = pos(n-1);\n B(n+2) = veln;\n B(n+3) = accn;\n ROS_INFO_STREAM(\"B vector: \\n\"< qr(A);\n X = qr.solve(B); // computes A^-1 * b\n ROS_INFO_STREAM(\"X vector: \\n\"< a, b, c, d, e, f;\n for (int i = 0; i < n_eqs; i+=6) {\n a.push_back( X(i) );\n b.push_back( X(i+1) );\n c.push_back( X(i+2) );\n d.push_back( X(i+3) );\n e.push_back( X(i+4) );\n f.push_back( X(i+5) );\n }\n\n\n // sample trajectory using sample func: create variables, sampling T_vec, Coef_mtrx\n std::vector T_vec;\n T_vec.resize(n);\n for (int i=0; i< n; i++) {\n T_vec[i] = t(i);\n }\n std::vector POS, VEL, ACC, JRK, T;\n std::vector> cof_mtrx;\n cof_mtrx.push_back(a);\n cof_mtrx.push_back(b);\n cof_mtrx.push_back(c);\n cof_mtrx.push_back(d);\n cof_mtrx.push_back(e);\n cof_mtrx.push_back(f);\n std::vector state;\n state.resize(4);\n // states at each intermdiate times\n double frq =125, tg=0;\n while (tg< T_vec[n-1]) {\n sample(T_vec, tg, cof_mtrx, state);\n // std::cout<< \"state:\"<< \"p= \"<< state[0]<<\" v= \"<< state[1]<<\" a= \"<< state[2]<<\" j= \"<< state[3] ;\n T.push_back(tg);\n POS.push_back( state[0]);\n VEL.push_back( state[1]);\n ACC.push_back( state[2]);\n JRK.push_back( state[3]);\n tg += 1/frq;\n }\n\n\n // states at waypoints and check limit conditions\n lmtd_jrk = true;\n std::vector> wpt_states;\n wpt_states.resize(4);\n for (int pt = 0; pt < n; ++pt) {\n tg= T_vec[pt];\n sample(T_vec, tg, cof_mtrx, state);\n wpt_states[0].push_back( state[0] );\n wpt_states[1].push_back( state[1] );\n wpt_states[2].push_back( state[2] );\n wpt_states[3].push_back( state[3] );\n std::cout<< \"jrk[\"< 1000 || state[3] < -1000 ){\n seg_idx.push_back( pt);\n lmtd_jrk = false;\n }\n }\n // ROS_INFO( \"waypoints times: \");\n // for (int i=0; i< n; i++ )\n // ROS_INFO_STREAM( \" \"<< T_vec[i] );\n // ROS_INFO( \"segment peroids: \");\n // for (int i=0; i< n-1; i++ )\n // ROS_INFO_STREAM( \" \"<< h[i] );\n\n // plot section =================================\n count++;\n int plot_per_loop = 3; //to plot 9 iteration to fit on sbplts number\n int sbplt_rows= 3, sbplt_cols= 3;\n bool pos_plt=false, vel_plt=true, acc_plt=true, jrk_plt = false;// select states to plot\n pos_plt=false, vel_plt=false, acc_plt=false, jrk_plt = true;\n std::string sbplt_name;\n\n // here choose few iterations, plot them in subplot\n if( (count)%plot_per_loop == 0 ){\n plt::figure(1);\n plt::subplot( sbplt_rows, sbplt_cols,count/plot_per_loop );\n plt::plot( T, POS);\n plt::plot( T_vec, wpt_states[0],\"r*\");\n sbplt_name= \"pos_iter_\" + std::to_string(count);\n plt::title( sbplt_name);\n plt::grid(true);\n plt::figure(2);\n plt::subplot( sbplt_rows, sbplt_cols,count/plot_per_loop );\n plt::plot( T, VEL);\n plt::plot( T_vec, wpt_states[1],\"r*\");\n sbplt_name= \"vel_iter_\" + std::to_string(count);\n plt::title( sbplt_name);\n plt::grid(true);\n plt::figure(3);\n plt::subplot( sbplt_rows, sbplt_cols,count/plot_per_loop );\n plt::plot( T, ACC);\n plt::plot( T_vec, wpt_states[2],\"r*\");\n sbplt_name= \"acc_iter_\" + std::to_string(count);\n plt::title( sbplt_name);\n plt::grid(true);\n plt::figure(4);\n plt::subplot( sbplt_rows, sbplt_cols,count/plot_per_loop );\n plt::plot( T, JRK);\n plt::plot( T_vec, wpt_states[3],\"r*\");\n sbplt_name= \"jrk_iter_\" + std::to_string(count);\n plt::title( sbplt_name);\n plt::grid(true);\n // plt::legend(); // Enable legend.\n\n }\n if(lmtd_jrk){ // to plot last iteration\n plt::figure(1);\n plt::subplot( sbplt_rows, sbplt_cols,count/plot_per_loop +1);\n plt::plot( T, POS);\n plt::plot( T_vec, wpt_states[0],\"r*\");\n sbplt_name= \"pos_last_iter_\" + std::to_string(count);\n plt::title( sbplt_name);\n plt::grid(true);\n\n plt::figure(2);\n plt::subplot( sbplt_rows, sbplt_cols,count/plot_per_loop +1);\n plt::plot( T, VEL);\n plt::plot( T_vec, wpt_states[1],\"r*\");\n sbplt_name= \"vel_last_iter_\" + std::to_string(count);\n plt::title( sbplt_name);\n plt::grid(true);\n\n plt::figure(3);\n plt::subplot( sbplt_rows, sbplt_cols,count/plot_per_loop +1);\n plt::plot( T, ACC);\n plt::plot( T_vec, wpt_states[2],\"r*\");\n sbplt_name= \"acc_last_iter_\" + std::to_string(count);\n plt::title( sbplt_name);\n plt::grid(true);\n\n plt::figure(4);\n plt::subplot( sbplt_rows, sbplt_cols,count/plot_per_loop +1);\n plt::plot( T, JRK);\n plt::plot( T_vec, wpt_states[3],\"r*\");\n sbplt_name= \"jrk_last_iter_\" + std::to_string(count);\n plt::title( sbplt_name);\n plt::grid(true);\n\n // plt::legend(); // Enable legend.\n }\n ROS_INFO_STREAM(\"#iteration= \"<\n#include \n#include \n#include \n#include \n#include \n#include \"Simulation.h\"\n\nHestonOption::HestonOption(std::string type_option_, double tn_, int n_processes_, int n_steps_, double strike_) {\n sim = Simulation();\n type_option = type_option_;\n tn = tn_;\n n_processes = n_processes_;\n n_steps = n_steps_;\n strike = strike_;\n}\n\nvoid HestonOption::set_params_stock_process(double stock_price_start_, double mu_) {\n stock_price_start = stock_price_start_;\n mu = mu_;\n}\n\nvoid HestonOption::set_prams_variance_process(double variance_start_, double kappa_, double theta_, double sigma_,\n double rho_) {\n variance_start = variance_start_;\n kappa = kappa_;\n theta = theta_;\n sigma = sigma_;\n rho = rho_;\n}\n\ndouble HestonOption::compute_price() {\n auto [stocks, _] = sim.generate_heston_process(n_processes, tn, stock_price_start, mu, variance_start, kappa, theta, sigma, rho, n_steps);\n Eigen::Index stocks_cols = stocks.cols();\n double total_payoffs = 0;\n for (int row = 0; row < stocks.rows(); ++row) {\n if (type_option == \"Call\"){\n total_payoffs += std::max(stocks(row,stocks_cols - 1) - strike, 0.0);\n }\n if (type_option == \"Put\"){\n total_payoffs += std::max(strike - stocks(row,stocks_cols), 0.0);\n }\n }\n return exp(- mu * tn) * total_payoffs / n_processes;\n}\n", "meta": {"hexsha": "077381559446dc03e8f14f5ecd3ec86d5189cabc", "size": 1546, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/HestonOption.cpp", "max_stars_repo_name": "vladargunov/QuantKit", "max_stars_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/HestonOption.cpp", "max_issues_repo_name": "vladargunov/QuantKit", "max_issues_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/HestonOption.cpp", "max_forks_repo_name": "vladargunov/QuantKit", "max_forks_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.7307692308, "max_line_length": 142, "alphanum_fraction": 0.6520051746, "num_tokens": 390, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.721743200312399, "lm_q1q2_score": 0.6529253723680409}} {"text": "#include \"blas.h\"\n#include \"mlfe/device_context/cpu_context.h\"\n#include \n\nnamespace mlfe{ namespace math{\n\ntemplate<>\nvoid gemm(const bool trans_a,\n const bool trans_b,\n const int m,\n const int n,\n const int k,\n const float alpha,\n const float *a_ptr,\n const int lda,\n const float *b_ptr,\n const int ldb,\n const float beta,\n float *c_ptr,\n const int ldc,\n CPUContext *context\n )\n{\n using ConstMapMatXf = Eigen::Map;\n Eigen::Map c(c_ptr, n, m);\n if(beta == 0.f){\n c.setZero();\n }\n else{\n c *= beta;\n }\n if(!trans_a && !trans_b){\n c.noalias() += alpha * (ConstMapMatXf(b_ptr, n, k) *\n ConstMapMatXf(a_ptr, k, m)\n );\n }\n else if(trans_a && !trans_b){\n c.noalias() += alpha * (ConstMapMatXf(b_ptr, n, k) *\n ConstMapMatXf(a_ptr, m, k).transpose()\n );\n }\n else if(!trans_a && trans_b){\n c.noalias() += alpha * (ConstMapMatXf(b_ptr, k, n).transpose() *\n ConstMapMatXf(a_ptr, k, m)\n );\n }\n else{\n c.noalias() += alpha * (ConstMapMatXf(b_ptr, k, n).transpose() *\n ConstMapMatXf(a_ptr, m, k).transpose()\n );\n }\n}\n\ntemplate<>\nvoid gemm(const bool trans_a,\n const bool trans_b,\n const int m,\n const int n,\n const int k,\n const double alpha,\n const double *a_ptr,\n const int lda,\n const double *b_ptr,\n const int ldb,\n const double beta,\n double *c_ptr,\n const int ldc,\n CPUContext *context\n )\n{\n using ConstMapMatXf = Eigen::Map;\n Eigen::Map c(c_ptr, n, m);\n if(beta == 0.){\n c.setZero();\n }\n else{\n c *= beta;\n }\n if(!trans_a && !trans_b){\n c.noalias() += alpha * (ConstMapMatXf(b_ptr, n, k) *\n ConstMapMatXf(a_ptr, k, m)\n );\n }\n else if(trans_a && !trans_b){\n c.noalias() += alpha * (ConstMapMatXf(b_ptr, n, k) *\n ConstMapMatXf(a_ptr, m, k).transpose()\n );\n }\n else if(!trans_a && trans_b){\n c.noalias() += alpha * (ConstMapMatXf(b_ptr, k, n).transpose() *\n ConstMapMatXf(a_ptr, k, m)\n );\n }\n else{\n c.noalias() += alpha * (ConstMapMatXf(b_ptr, k, n).transpose() *\n ConstMapMatXf(a_ptr, m, k).transpose()\n );\n }\n}\n\ntemplate <>\nvoid gemv(const bool trans_a,\n const int m,\n const int n,\n const float alpha,\n const float *a_ptr,\n const int lda,\n const float *b_ptr,\n const float beta,\n float *c_ptr,\n const int ldc,\n CPUContext *context\n )\n{\n using ConstMapMatXf = Eigen::Map;\n using ConstMapVecXf = Eigen::Map;\n Eigen::Map c(c_ptr, !trans_a ? m : n);\n if(beta == 0.f){\n c.setZero();\n }\n else{\n c *= beta;\n }\n\n if(!trans_a){\n c.noalias() += alpha * (ConstMapMatXf(a_ptr, n, m).transpose() *\n ConstMapVecXf(b_ptr, n)\n );\n }\n else{\n c.noalias() += alpha * (ConstMapMatXf(a_ptr, n, m) *\n ConstMapVecXf(b_ptr, m)\n );\n }\n}\n\ntemplate <>\nvoid gemv(const bool trans_a,\n const int m,\n const int n,\n const double alpha,\n const double *a_ptr,\n const int lda,\n const double *b_ptr,\n const double beta,\n double *c_ptr,\n const int ldc,\n CPUContext *context\n )\n{\n using ConstMapMatXf = Eigen::Map;\n using ConstMapVecXf = Eigen::Map;\n Eigen::Map c(c_ptr, !trans_a ? m : n);\n if(beta == 0.){\n c.setZero();\n }\n else{\n c *= beta;\n }\n\n if(!trans_a){\n c.noalias() += alpha * (\n ConstMapMatXf(a_ptr, n, m).transpose() *\n ConstMapVecXf(b_ptr, n)\n );\n }\n else{\n c.noalias() += alpha * (\n ConstMapMatXf(a_ptr, n, m) *\n ConstMapVecXf(b_ptr, m)\n );\n }\n}\n\n} // end namespace math\n} // end namespace mlfe\n", "meta": {"hexsha": "6b991ea42792f9d67575745759b9f115ec7d7336", "size": 5969, "ext": "cc", "lang": "C++", "max_stars_repo_path": "mlfe/math/blas.cc", "max_stars_repo_name": "shi510/mlfe", "max_stars_repo_head_hexsha": "aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 13.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T11:21:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-20T18:25:11.000Z", "max_issues_repo_path": "mlfe/math/blas.cc", "max_issues_repo_name": "shi510/mlfe", "max_issues_repo_head_hexsha": "aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "mlfe/math/blas.cc", "max_forks_repo_name": "shi510/mlfe", "max_forks_repo_head_hexsha": "aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2018-01-08T12:40:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-02T05:23:36.000Z", "avg_line_length": 33.7231638418, "max_line_length": 72, "alphanum_fraction": 0.3786228849, "num_tokens": 1221, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240160063031, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.6528952306853628}} {"text": "// Simple Kalman Filter implementation for one-dimensional processes\n// Author: Marcell Missura \n// Modified for Eigen by Max Schwarz \n\n#include \n#include \n\nnamespace rc_utils\n{\n\nKalmanFilter::KalmanFilter()\n : m_smoothing(0.3)\n , m_timeStep(DefaultTimeStep)\n , m_lastZ(0)\n , m_px(0)\n , m_pv(0)\n{\n\tinit();\n}\n\nKalmanFilter::~KalmanFilter()\n{\n}\n\nvoid KalmanFilter::init()\n{\n\t// Process noise\n\tm_Q = Eigen::Matrix2d::Identity();\n\n\t// Measurement noise\n\tm_R << 0.001 + m_smoothing*100.0, 0.0,\n\t 0.0, 0.001 + m_smoothing*100.0;\n\n\t// Passive linear system dynamics matrix A\n\tm_A << 1.0, m_timeStep,\n\t 0.0, 1.0;\n\n\t// State and measurement vectors\n\tm_X << 0.0, 0.0;\n\n\tm_H = m_I = m_K = m_P = Eigen::Matrix2d::Identity();\n}\n\nvoid KalmanFilter::reset()\n{\n\tm_K = Eigen::Matrix2d::Identity();\n\tm_P = Eigen::Matrix2d::Zero();\n}\n\nvoid KalmanFilter::update(double z)\n{\n\tm_Z << z, (z - m_lastZ) / m_timeStep;\n\n\tm_X = m_A * m_X;\n\tm_P = m_A * m_P * m_A.transpose() + m_Q;\n\tm_K = m_P * m_H.transpose() * (m_H * m_P * m_H.transpose() + m_R).inverse();\n\tm_X = m_X + m_K * (m_Z - m_H * m_X);\n\tm_P = (m_I - m_K * m_H) * m_P;\n\n\tm_lastZ = z;\n\n\tm_px = m_P(0,0);\n\tm_pv = m_P(1,1);\n}\n\nvoid KalmanFilter::setState(double pos, double vel)\n{\n\tm_X << pos, vel;\n\tm_lastZ = pos;\n}\n\n}\n\n", "meta": {"hexsha": "ef6c97bb06fac1500243d85994b415d733c8a6a2", "size": 1370, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/kalmanfilter.cpp", "max_stars_repo_name": "nvtienanh/UXA_OP", "max_stars_repo_head_hexsha": "a06a3f1113721627e7d384f89718369036e8028e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-11-22T08:15:43.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-22T07:18:50.000Z", "max_issues_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/kalmanfilter.cpp", "max_issues_repo_name": "nvtienanh/UXA_OP", "max_issues_repo_head_hexsha": "a06a3f1113721627e7d384f89718369036e8028e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-11-22T08:34:34.000Z", "max_issues_repo_issues_event_max_datetime": "2018-11-22T08:34:34.000Z", "max_forks_repo_path": "src/nimbro_robotcontrol/util/rc_utils/src/kalmanfilter.cpp", "max_forks_repo_name": "nvtienanh/UXA_OP", "max_forks_repo_head_hexsha": "a06a3f1113721627e7d384f89718369036e8028e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.5135135135, "max_line_length": 77, "alphanum_fraction": 0.6291970803, "num_tokens": 471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9381240108164657, "lm_q2_score": 0.6959583187272712, "lm_q1q2_score": 0.6528952093255118}} {"text": "// combination_iterator.hpp\n//\n// Produces all k-combinations of the universe {0,...,n-1} in\n// lexicographical order. The algorithm is a tuned-up version\n// of a simple generation method (\"Algorithm T\") described in:\n//\n// Knuth, Donald E. \n// The Art of Computer Programming, Volume 4A: Combinatorial Algorithms, Part 1. \n// Pearson Education Inc., 2011.\n\n#ifndef COMBINATION_ITERATOR_HPP\n#define COMBINATION_ITERATOR_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n\ntemplate \nclass combination_iterator\n\t: public boost::iterator_facade<\n\tcombination_iterator,\n\tconst std::vector&,\n\tboost::forward_traversal_tag\n\t>\n{\npublic:\n\tcombination_iterator() : end_(true), n_(0), size_(0), comb_() { }\n\n\texplicit combination_iterator(T n, T k) : end_(false), n_(n), size_(k), comb_(k)\n\t{\n\t\tassert(k != 0 && n_ > k);\n\t\tstd::iota(comb_.begin(), comb_.end(), 0);\n\t\tassert(!end_);\n\t}\n\nprivate:\n\tfriend class boost::iterator_core_access;\n\n\tvoid increment()\n\t{\n\t\tstd::int64_t j = size_ - 1;\n\n\t\tfor (const T end = n_ - size_; j >= 0 && comb_[j] >= end + j; --j) { }\n\n\t\tif (j < 0)\n\t\t{\n\t\t\tassert(comb_.front() == n_ - size_);\n\t\t\tend_ = true;\n\t\t\treturn;\n\t\t}\n\n\t\t++comb_[j];\n\n\t\tfor (const std::int64_t end = size_ - 1; j < end; ++j)\n\t\t{\n\t\t\tcomb_[j + 1] = comb_[j] + 1;\n\t\t}\n\n\t\treturn;\n\t}\n\n\tbool equal(const combination_iterator& other) const\n\t{\n\t\treturn end_ == other.end_;\n\t}\n\n\tconst std::vector& dereference() const\n\t{\n\t\treturn comb_;\n\t}\n\n\tbool end_;\n\tconst int n_;\n\tconst int size_;\n\tstd::vector comb_;\n};\n\n#endif\n", "meta": {"hexsha": "347795c538ff6300d9b698a56aed3368d5fcfb18", "size": 1605, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "combination_iterator.hpp", "max_stars_repo_name": "euler314/combinatorics", "max_stars_repo_head_hexsha": "cef5632e4a820762372df5c3ded8aa58290a9020", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-07-12T22:24:44.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-21T13:16:09.000Z", "max_issues_repo_path": "combination_iterator.hpp", "max_issues_repo_name": "euler314/combinatorics", "max_issues_repo_head_hexsha": "cef5632e4a820762372df5c3ded8aa58290a9020", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "combination_iterator.hpp", "max_forks_repo_name": "euler314/combinatorics", "max_forks_repo_head_hexsha": "cef5632e4a820762372df5c3ded8aa58290a9020", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2017-12-06T18:32:14.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-06T18:32:14.000Z", "avg_line_length": 19.5731707317, "max_line_length": 83, "alphanum_fraction": 0.6554517134, "num_tokens": 483, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.803173791645582, "lm_q1q2_score": 0.6528737403366549}} {"text": "#include \"ukf.hpp\"\n#include \"house.hpp\"\n#include \"eigen_csv.hpp\"\n#include \"timer.hpp\"\n\n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\n// One degree (in radians)\nconst double deg = M_PI / 180;\n\n// Dynamical model\nVectorXd ct_prop(double ti, double tf, const VectorXd& x, const VectorXd& w) {\n VectorXd xf(5);\n double W = x(4);\n double T = tf - ti;\n /*if (fabs(W) < 1E-9) {\n xf = x;\n xf(0) += T * xf(1);\n xf(2) += T * xf(3);\n } else {*/\n double sinWT = sin(W*T);\n double cosWT = cos(W*T);\n MatrixXd F(5,5);\n F << 1, sinWT/W, 0, -(1-cosWT)/W, 0,\n 0, cosWT, 0, -sinWT, 0,\n 0, (1-cosWT)/W, 1, sinWT/W, 0,\n 0, sinWT, 0, cosWT, 0,\n 0, 0, 0, 0, 1;\n xf = F * x;\n //}\n return xf + w;\n}\n\n// Measurement model\nVector2d ct_meas(double t, const VectorXd& x) {\n\n Vector2d z;\n\n double xi = x(0);\n double eta = x(2);\n\n z << sqrt(xi*xi + eta*eta), atan2(eta, xi);\n\n return z;\n\n}\n\n// True state as function of time\nVectorXd ct_tru(double t) {\n\n const double v = 120;\n const double w1 = 1 * deg;\n const double w2 = -3 * deg;\n const double r1 = fabs(v / w1);\n const double r2 = fabs(v / w2);\n const double t1 = 90;\n const double t2 = 30;\n const double tl = 125;\n const double l = v * tl;\n const double x0 = 25000;\n const double y0 = 10000;\n\n VectorXd x(5);\n double dt, xc, yc;\n\n if (t <= tl) {\n x(0) = x0 - v * t;\n x(2) = y0;\n x(1) = -v;\n x(3) = 0;\n x(4) = 0;\n } else if (t <= tl + t1) {\n dt = t - tl;\n xc = x0 - l;\n yc = y0 - r1;\n x(0) = xc + r1 * cos(w1 * dt + M_PI/2);\n x(2) = yc + r1 * sin(w1 * dt + M_PI/2);\n x(1) = -w1 * r1 * sin(w1 * dt + M_PI/2);\n x(3) = w1 * r1 * cos(w1 * dt + M_PI/2);\n x(4) = w1;\n } else if (t <= 2*tl + t1) {\n dt = t - tl - t1;\n x(0) = x0 - l - r1;\n x(2) = y0 - r1 - v * dt;\n x(1) = 0;\n x(3) = -v;\n x(4) = 0;\n } else if (t <= 2*tl + t1 + t2) {\n dt = t - 2*tl - t1;\n xc = x0 - l - r1 - r2;\n yc = y0 - l - r1;\n x(0) = xc + r2 * cos(w2 * dt);\n x(2) = yc + r2 * sin(w2 * dt);\n x(1) = -w2 * r2 * sin(w2 * dt);\n x(3) = w2 * r2 * cos(w2 * dt);\n x(4) = w2;\n } else {\n dt = t - 2*tl - t1 - t2;\n x(0) = x0 - l - r1 - r2 - v*dt;\n x(2) = y0 - r1 - r2 - l;\n x(1) = -v;\n x(3) = 0;\n x(4) = 0;\n }\n\n return x;\n\n}\n\n// Generate filename for state estimates\nstd::string est_filename(const std::string& filter, int i, int j) {\n std::string f = \"out/ct_est_\";\n f += filter;\n f += \"_\";\n f += std::to_string(i+1);\n f += \"_\";\n f += std::to_string(j+1);\n f += \".csv\";\n return f;\n}\n\nint main() {\n\n // CUT directory\n UKF::cut_dir = \"../CUT/\";\n\n // UKF state & measurement models\n UKF::dyn_model f = ct_prop;\n UKF::meas_model h = ct_meas;\n\n // HOUSE measurement model\n HOUSE::meas_model hh = [] (double t, const VectorXd& x, const VectorXd& n)\n -> VectorXd {\n return ct_meas(t, x) + n;\n };\n\n // Constants\n double sr, sth, l1, l2;\n sr = 100;\n sth = 1 * deg;\n l1 = 0.16;\n l2 = 0.01;\n\n // Measurement noise covariance\n Matrix2d R;\n R << sr*sr, 0,\n 0, sth*sth;\n\n // Prior mean & covariance\n VectorXd mxi(5), cxx(5);\n cxx << 1000, 10, 1000, 10, 1*deg;\n mxi << 25000, -120, 10000, 0, 0.000001;\n MatrixXd Pxxi = cxx.cwiseAbs2().asDiagonal();\n\n // HOUSE distributions\n HOUSE::Dist distXi(Pxxi), distn(R);\n distXi.mean = mxi;\n\n // Normal noise generator\n mt19937_64 mt;\n normal_distribution nd;\n\n // Time step lengths\n const int Ntimes = 4;\n VectorXd Ts(Ntimes);\n Ts << 1, 2.5, 3.9, 5;\n //Ts.setLinSpaced(Ntimes, 1, 5);\n\n // Save time step lengths\n EigenCSV::write(Ts, \"out/times.csv\");\n\n // Number of tests\n const int Ntest = 100;\n\n // Timer\n Timer timer;\n\n // Average runtime table\n MatrixXd runtime_table(Ntimes, 6);\n runtime_table.col(0) = Ts;\n\n // Run tests for various time step lengths\n for (int i = 0; i < Ntimes; i++) {\n\n // Time step\n double T = Ts(i);\n\n //cout << \"-------------------------------------------\" << endl;\n cout << \"Running T = \" << T << \" s\" << endl;\n //cout << \"-------------------------------------------\" << endl;\n\n // Times\n double Ttot = 125 + 90 + 125 + 30 + 125;\n int steps = (int) ceil(Ttot / T);\n VectorXd t(steps);\n t.setLinSpaced(steps, 0, T*(steps-1));\n\n // True states\n vector Xtru;\n for (int k = 0; k < steps; k++)\n Xtru.push_back(ct_tru(t(k)));\n\n // Save true states\n MatrixXd xtru_table(steps, 6);\n xtru_table.col(0) = t;\n for (int k = 0; k < steps; k++)\n xtru_table.row(k).tail(5) = Xtru[k];\n string filename = \"out/ct_true_\";\n filename += to_string(i+1);\n filename += \".csv\";\n vector header(6);\n header[0] = \"Time (s)\";\n header[1] = \"x (m)\";\n header[2] = \"xd (m/s)\";\n header[3] = \"y (m)\";\n header[4] = \"yd (m/s)\";\n header[5] = \"Omega (rad/s)\";\n EigenCSV::write(xtru_table, header, filename);\n\n // Process noise covariance\n double t22 = T * T / 2;\n double t33 = T * T * T / 3;\n MatrixXd Q(5,5);\n Q << t33, t22, 0, 0, 0,\n t22, T, 0, 0, 0,\n 0, 0, t33, t22, 0,\n 0, 0, t22, T, 0,\n 0, 0, 0, 0, (l2/l1)*T;\n Q *= l1;\n\n // HOUSE process noise distributions\n HOUSE::Dist distw(Q);\n\n // Initialize UKF & CUT filters\n UKF ukf (f, h, true, 0, mxi, Pxxi, Q, R, UKF::sig_type::JU, 1);\n UKF cut4(f, h, true, 0, mxi, Pxxi, Q, R, UKF::sig_type::CUT4, 1);\n UKF cut6(f, h, true, 0, mxi, Pxxi, Q, R, UKF::sig_type::CUT6, 1);\n UKF cut8(f, h, true, 0, mxi, Pxxi, Q, R, UKF::sig_type::CUT8, 1);\n\n // Initialize HOUSE\n HOUSE house(f, hh, 2, 0, distXi, distw, distn, 0.1);\n\n // Runtimes\n MatrixXd runtime(5, Ntest);\n\n // Run multiple tests\n for (int j = 0; j < Ntest; j++) {\n\n //cout << \"Running Trial \" << j+1 << endl;\n\n // Reset filters\n ukf.reset(0, mxi, Pxxi);\n cut4.reset(0, mxi, Pxxi);\n cut6.reset(0, mxi, Pxxi);\n cut8.reset(0, mxi, Pxxi);\n house.reset(0, distXi);\n\n // Measurements\n MatrixXd Ztru(2,steps);\n for (int k = 0; k < steps; k++) {\n Ztru.col(k) = ct_meas(t(k), Xtru[k]);\n Ztru(0,k) += sr * nd(mt);\n Ztru(1,k) += sth * nd(mt);\n }\n\n // Run UKF\n //cout << \" UKF\" << endl;\n timer.tick();\n ukf.run(t, Ztru);\n runtime(0, j) = timer.tock();\n ukf.save(est_filename(\"ukf\", i, j));\n\n // Run CUT-4\n //cout << \" CUT-4\" << endl;\n timer.tick();\n cut4.run(t, Ztru);\n runtime(1, j) = timer.tock();\n cut4.save(est_filename(\"cut4\", i, j));\n\n // Run CUT-6\n //cout << \" CUT-6\" << endl;\n timer.tick();\n cut6.run(t, Ztru);\n runtime(2, j) = timer.tock();\n cut6.save(est_filename(\"cut6\", i, j));\n\n // Run CUT-8\n //cout << \" CUT-8\" << endl;\n timer.tick();\n cut8.run(t, Ztru);\n runtime(3, j) = timer.tock();\n cut8.save(est_filename(\"cut8\", i, j));\n\n // Run HOUSE\n //cout << \" HOUSE\" << endl;\n timer.tick();\n house.run(t, Ztru);\n runtime(4, j) = timer.tock();\n house.save(est_filename(\"house\", i, j));\n\n }\n\n // Average runtimes\n runtime_table.row(i).tail(5) = runtime.rowwise().mean();\n\n }\n\n // Save average runtimes\n vector rth(6);\n rth[0] = \"STEP\";\n rth[1] = \"UKF\";\n rth[2] = \"CUT-4\";\n rth[3] = \"CUT-6\";\n rth[4] = \"CUT-8\";\n rth[5] = \"HOUSE\";\n EigenCSV::write(runtime_table, rth, \"out/runtimes.csv\");\n\n return 0;\n\n}\n", "meta": {"hexsha": "988cabb2a47ed3e418925f3beee94b497a29035f", "size": 8515, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CT_Gauss/CT.cpp", "max_stars_repo_name": "SIOSlab/HOUSE", "max_stars_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CT_Gauss/CT.cpp", "max_issues_repo_name": "SIOSlab/HOUSE", "max_issues_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CT_Gauss/CT.cpp", "max_forks_repo_name": "SIOSlab/HOUSE", "max_forks_repo_head_hexsha": "81381a2384bd84be1afc49cace288c0606ee480f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8814589666, "max_line_length": 78, "alphanum_fraction": 0.4488549618, "num_tokens": 2902, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382023207901, "lm_q2_score": 0.7577943712746406, "lm_q1q2_score": 0.6528688003567672}} {"text": "#include \n#include \n#include \n#include \n#include \"NN3Layer.hpp\"\nusing namespace std;\nusing namespace arma;\n\nmat gen_and_example(int randNum){\n mat A(1,3);\n switch (randNum)\n {\n case 1:\n A={{0,0,0}};\n break;\n case 2:\n A={{0,1,0}};\n break;\n case 3:\n A={{1,0,0}};\n break;\n case 4:\n A={{1,1,1}};\n break;\n default:\n A={{1,1,1}};\n break;\n }\n return A;\n}\nmat gen_or_example(int randNum){\n mat A(1,3);\n switch (randNum)\n {\n case 1:\n A={{0,0,0}};\n break;\n case 2:\n A={{0,1,1}};\n break;\n case 3:\n A={{1,0,1}};\n break;\n case 4:\n A={{1,1,1}};\n break;\n default:\n A={{1,1,1}};\n break;\n }\n return A;\n}\nmat gen_xor_example(int randNum){\n mat A(1,3);\n switch (randNum)\n {\n case 1:\n A={{0,0,0}};\n break;\n case 2:\n A={{0,1,1}};\n break;\n case 3:\n A={{1,0,1}};\n break;\n case 4:\n A={{1,1,0}};\n break;\n default:\n A={{1,1,0}};\n break;\n }\n return A;\n}\n\n\nint main(int argc, char** argv){\n /* 隨機設備 */\n std::random_device rd;\n\n /* 亂數產生器 梅森旋轉演算法*/\n std::mt19937 generator( rd() );\n\n /* 亂數的機率分布 */\n std::uniform_real_distribution unif(0.0, 5.0);\n NN3Layer nn3Layer(2,2,1,0.1);\n //train\n for( int a = 0; a < 100000; a++){\n /* 產生亂數 */\n float x = unif(generator);\n mat data = gen_xor_example((int)x);\n //data.print(\"data:\");\n nn3Layer.train_step_sgd({data(0,0),data(0,1)},{data(0,2)});\n }\n //test\n while(true){\n cout << \"Test Neural Net \\n\";\n cout << \"Input X1:\";\n double x1=0;\n cin >> x1;\n cout << \"Input X2:\";\n double x2=0;\n cin >> x2;\n mat o = nn3Layer.only_forward({x1,x2});\n o.print(\"o:\");\n cout << \"\\n result:\";\n if(o(0,0)>0.5){\n cout << 1<<\"\\n\";\n }else{\n cout << 0<<\"\\n\";\n };\n cout << \"Enter 0 to end ,1 to keep testing.\\n\";\n int c=0;\n cin>>c;\n if(!c){\n break;\n }\n }\n}", "meta": {"hexsha": "4ced000cbbe64bb246722d080b6454d994fa338e", "size": 2191, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "ShangHong-CAI/NN3Layer", "max_stars_repo_head_hexsha": "61b75f44d65b7036e2689567b261fd668a4166ca", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-12-26T06:50:35.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T10:42:13.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "ShangHong-CAI/NN3Layer", "max_issues_repo_head_hexsha": "61b75f44d65b7036e2689567b261fd668a4166ca", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "ShangHong-CAI/NN3Layer", "max_forks_repo_head_hexsha": "61b75f44d65b7036e2689567b261fd668a4166ca", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-12-25T16:13:00.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-27T07:37:19.000Z", "avg_line_length": 18.4117647059, "max_line_length": 65, "alphanum_fraction": 0.4345047923, "num_tokens": 746, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6528504582163561}} {"text": "/**\n * @ file avgvalboundary.cc\n * @ brief NPDE homework AvgValBoundary code\n * @ author Simon Meierhans, edited by Oliver Rietmann\n * @ date 11.03.2019\n * @ copyright Developed at ETH Zurich\n */\n\n#include \"avgvalboundary.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace AvgValBoundary {\n\n/**\n * @brief computes H1 seminorm over the computational domain\n * @param dofh DofHandler of FEspace.\n * u coefficient vector\n */\n/* SAM_LISTING_BEGIN_1 */\ndouble compH1seminorm(const lf::assemble::DofHandler &dofh,\n const Eigen::VectorXd &u) {\n double result = 0.0;\n\n // Compute Stiffness matrix with alpha := 1, beta := 0, gamma := 0\n auto const_one = [](Eigen::Vector2d x) -> double { return 1.0; };\n auto const_zero = [](Eigen::Vector2d x) -> double { return 0.0; };\n auto A = compGalerkinMatrix(dofh, const_one, const_zero, const_zero);\n\n // Compute seminorm using the Stiffness matrix\n result = u.transpose() * A * u;\n result = std::sqrt(result);\n return result;\n}\n/* SAM_LISTING_END_1 */\n\n/**\n * @brief solves pde for some simple test problem with\n * alpha = beta = gamma := 1.0 and load f := 1.0\n * @param dofh DofHandler of FEspace.\n */\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd solveTestProblem(const lf::assemble::DofHandler &dofh) {\n // Obtain Galerkin matrix for alpha = beta = gamma := 1.0\n auto const_one = [](Eigen::Vector2d x) -> double { return 1.0; };\n auto A = compGalerkinMatrix(dofh, const_one, const_one, const_one);\n\n // Set up load vector\n auto fe_space =\n std::make_shared>(dofh.Mesh());\n lf::mesh::utils::MeshFunctionConstant mf_identity{1.0};\n lf::uscalfe::ScalarLoadElementVectorProvider elvec_builder(fe_space,\n mf_identity);\n Eigen::VectorXd phi(dofh.NumDofs());\n phi.setZero();\n AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n // Solve system of linear equations\n Eigen::SparseLU> solver;\n solver.compute(A);\n Eigen::VectorXd mu = solver.solve(phi);\n\n return mu;\n}\n/* SAM_LISTING_END_2 */\n\n/** @brief generate sequence of nested triangular meshes with L+1 levels */\n/* SAM_LISTING_BEGIN_3 */\nstd::shared_ptr generateTestMeshSequence(\n unsigned int L) {\n auto mesh = lf::mesh::test_utils::GenerateHybrid2DTestMesh(3, 1.0 / 3.0);\n std::shared_ptr meshes =\n lf::refinement::GenerateMeshHierarchyByUniformRefinemnt(mesh, L);\n return meshes;\n}\n/* SAM_LISTING_END_3 */\n\n/**\n * @brief Compute the boundary functional values for a sequence of L meshes\n * @param L The number of meshes in the sequence\n * @returns A vector of pairs containing the number of DOFs and value of the\n *\t boundary functional for each level\n */\n/* SAM_LISTING_BEGIN_5 */\nstd::vector> approxBoundaryFunctionalValues(\n unsigned int L) {\n std::vector> result;\n auto meshes = generateTestMeshSequence(L - 1);\n int num_meshes = meshes->NumLevels();\n for (int level = 0; level < num_meshes; ++level) {\n auto mesh_p = meshes->getMesh(level);\n\n // Set up global FE space; lowest order Lagrangian finite elements\n auto fe_space =\n std::make_shared>(mesh_p);\n\n // Obtain local->global index mapping for current finite element space\n const lf::assemble::DofHandler &dofh{fe_space->LocGlobMap()};\n const lf::base::size_type N_dofs(dofh.NumDofs());\n\n // compute galerkin matrix with alpha = 1.0, gamma = 1.0, beta = 0.0\n auto const_one = [](Eigen::Vector2d x) -> double { return 1.0; };\n auto const_zero = [](Eigen::Vector2d x) -> double { return 0.0; };\n auto A = compGalerkinMatrix(dofh, const_one, const_one, const_zero);\n\n // compute load vector for f(x) = x.norm()\n auto f = [](Eigen::Vector2d x) -> double { return x.norm(); };\n lf::mesh::utils::MeshFunctionGlobal mf_f{f};\n lf::uscalfe::ScalarLoadElementVectorProvider elvec_builder(fe_space, mf_f);\n Eigen::VectorXd phi(N_dofs);\n phi.setZero();\n AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n // solve system of equations\n Eigen::SparseLU> solver;\n solver.compute(A);\n Eigen::VectorXd u = solver.solve(phi);\n\n // set up weight function\n auto w = [](Eigen::Vector2d x) -> double { return 1.0; };\n double functional_value = compBoundaryFunctional(dofh, u, w);\n\n result.push_back({N_dofs, functional_value});\n }\n return result;\n}\n/* SAM_LISTING_END_5 */\n\n} // namespace AvgValBoundary\n", "meta": {"hexsha": "8fe3cbe201a4efc72c4b9076c8b65633a7d7b68e", "size": 4888, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/AvgValBoundary/mastersolution/avgvalboundary.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/AvgValBoundary/mastersolution/avgvalboundary.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/AvgValBoundary/mastersolution/avgvalboundary.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 34.6666666667, "max_line_length": 79, "alphanum_fraction": 0.6876022913, "num_tokens": 1354, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7662936484231889, "lm_q1q2_score": 0.6528460209046553}} {"text": "#include \"NeuralNetwork.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n\n\nNeuralNetwork NeuralNetwork::from_stream(std::istream &is)\n{\n\tfloat learning_factor;\n int num_layers;\n \n is.read((char *)&learning_factor, sizeof(learning_factor));\n is.read((char *)&num_layers, sizeof(num_layers));\n\n\tstd::vector sizes;\n\n\tstd::cout << \"reading size: \";\n\n\tfor (int i = 0; i < num_layers; i++)\n\t{\n\t\tint size;\n\t\tis.read((char *)&size, sizeof(size));\n\t\tsizes.push_back(size);\n\t\tstd::cout << size << \" \";\n\t}\n \n\tstd::cout << std::endl;\n\n NeuralNetwork nn(sizes, learning_factor);\n\n\tstd::cout << \"Sizes: \" << std::endl;\n\tfor (int size : nn.m_sizes)\n\t{\n\t\tstd::cout << size << \" \";\n\t}\n\tstd::cout << std::endl;\n\n\tfor (auto & weight_matrix : nn.m_weights)\n\t{\n\t\tfor (int r = 0; r < weight_matrix.rows(); r++)\n\t\t{\n\t\t\tfor (int c = 0; c < weight_matrix.cols(); c++)\n\t\t\t{\n\t\t\t\tis.read((char *)&weight_matrix(r, c), sizeof(float));\n\t\t\t}\n\t\t}\n\t}\n \n return nn;\n}\n\n\nNeuralNetwork::NeuralNetwork(std::vector layer_sizes, float learning_factor)\n\t: m_num_layers(layer_sizes.size())\n\t, m_sizes(layer_sizes)\n\t, m_layers()\n\t, m_deltas()\n\t, m_weights()\n\t, m_learning_factor(learning_factor)\n{\n\tif (m_num_layers == 0)\n\t{\n\t\tthrow std::invalid_argument(\"The number of layers must be at least one!\");\n\t}\n\n\tfor (int i = 0; i < m_num_layers - 1; i++)\n\t{\n\t\tm_layers.push_back(Eigen::VectorXf::Ones(m_sizes[i] + 1)); // extra for the bias\n\t}\n\n\tm_layers.push_back(Eigen::VectorXf::Ones(m_sizes[m_num_layers - 1])); // output doesn't get bias\n\n\tfor (int i = 1; i < m_num_layers; i++)\n\t{\n\t\tm_deltas.push_back(Eigen::VectorXf::Ones(m_sizes[i]));\n\t\tm_weights.push_back(Eigen::MatrixXf::Random(m_sizes[i], m_sizes[i - 1] + 1)); // extra for the bias\n\t}\n\n\tstd::cout << m_layers.size() << std::endl;\n}\n\nvoid NeuralNetwork::forward_propagate(const Eigen::VectorXf& input)\n{\n if (input.size() != m_sizes[0])\n throw std::invalid_argument(\"The input vector must be of size <\" + std::to_string(m_sizes[0]) + \">\");\n\n\tm_layers[0].head(m_sizes[0]) = input;\n\n\tfor (size_t i = 1; i < m_layers.size(); ++i)\n\t{\n\t\tm_layers[i].head(m_sizes[i]) = (m_weights[i - 1] * m_layers[i - 1]).unaryExpr(&sigmoid);\n\t}\n}\n\nvoid NeuralNetwork::back_propagate(const Eigen::VectorXf& output)\n{\n if (output.size() != m_sizes[m_num_layers-1])\n throw std::invalid_argument(\"The output vector must be of size <\" + std::to_string(m_sizes[m_num_layers - 1]) + \">\");\n\n Eigen::VectorXf error = output - m_layers[m_num_layers - 1];\n\tEigen::VectorXf delta_o = error.array() * (m_layers[m_num_layers - 1].unaryExpr(&sigmoid_prime)).array();\n\tm_deltas[m_deltas.size() - 1] = delta_o;\n\n\tint delta_size = m_deltas.size();\n\tfor (int delta_index = delta_size - 2; delta_index >= 0; delta_index--)\n\t{\n\t\tint layer_index = delta_index + 1;\n\t\tEigen::VectorXf derivative = m_layers[layer_index].head(m_sizes[layer_index]).unaryExpr(&sigmoid_prime);\n\t\tEigen::VectorXf err = (m_weights[delta_index + 1].transpose() * m_deltas[delta_index + 1]).head(m_sizes[layer_index]);\n\n\t\tEigen::VectorXf delta = derivative.array() * err.array();\n\t\t\n\t\tm_deltas[delta_index] = delta;\n\t}\n\n\tint weights_size = m_weights.size();\n\tfor (int i = 0; i < weights_size; ++i)\n\t{\n\t\tm_weights[i] += m_learning_factor * (m_deltas[i] * m_layers[i].transpose());\n\t}\n}\n\nEigen::VectorXf NeuralNetwork::test(const Eigen::VectorXf& input, const Eigen::VectorXf& output)\n{\n forward_propagate(input);\n return output - m_layers[m_num_layers - 1];\n}\n\nint NeuralNetwork::classify(const Eigen::VectorXf& input)\n{\n float max_val = -1;\n int max_index = -1;\n\n forward_propagate(input);\n\n for (int i = 0; i < m_sizes[m_num_layers - 1]; ++i)\n {\n if (max_val < m_layers[m_num_layers - 1][i])\n {\n max_val = m_layers[m_num_layers - 1][i];\n max_index = i;\n }\n }\n\n return max_index;\n}\n\nstd::vector> NeuralNetwork::classification(const Eigen::VectorXf& input)\n{\n\tstd::vector> classification_vector(m_sizes[m_num_layers - 1]);\n\n\tforward_propagate(input);\n\n\tfor (int i = 0; i < m_sizes[m_num_layers - 1]; i++)\n\t{\n\t\tclassification_vector.push_back({ i, m_layers[m_num_layers - 1][i] });\n\t}\n\n\tstd::sort\n\t(\n\t\tclassification_vector.begin(), classification_vector.end(), \n\t\t[](std::pair lhs, std::pair rhs) \n\t\t{\n\t\t\treturn lhs.second > rhs.second; \n\t\t}\n\t);\n\n\treturn classification_vector;\n}\n\nvoid NeuralNetwork::serialize(std::ostream &os) const\n{\n\tos.write((char*)&m_learning_factor, sizeof(m_learning_factor));\n\n\tos.write((char *)&m_num_layers, sizeof(m_num_layers));\n\n\tfor (int size : m_sizes)\n\t{\n\t\tos.write((char *)&size, sizeof(size));\n\t}\n\t\n\tfor (const auto & weight_matrix : m_weights)\n\t{\n\t\tfor (int r = 0; r < weight_matrix.rows(); r++)\n\t\t{\n\t\t\tfor (int c = 0; c < weight_matrix.cols(); c++)\n\t\t\t{\n\t\t\t\tos.write((char *)&weight_matrix(r, c), sizeof(float));\n\t\t\t}\n\t\t}\n\t}\n}\n\nint NeuralNetwork::get_num_inputs() const\n{\n return m_sizes[0];\n}\n\nint NeuralNetwork::get_num_outputs() const\n{\n return m_sizes[m_num_layers - 1];\n}\n\nvoid NeuralNetwork::set_learning_factor(float learning_factor)\n{\n\tm_learning_factor = learning_factor;\n}\n\nEigen::VectorXf NeuralNetwork::get_output() const\n{\n\treturn m_layers[m_num_layers - 1];\n}\n\nconst Eigen::MatrixXf& NeuralNetwork::get_weights_ih() const\n{\n return m_weights[0];\n}\n\nconst Eigen::MatrixXf& NeuralNetwork::get_weights_ho() const\n{\n return m_weights[m_weights.size() - 1];\n}\n", "meta": {"hexsha": "b509b68c570ace6de74cd709005d77f210cfe31f", "size": 5516, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/NeuralNetwork.cpp", "max_stars_repo_name": "tdriggs/TetrisAI", "max_stars_repo_head_hexsha": "467d2974c8e5375b6b61e681ce899d74f4728bca", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/NeuralNetwork.cpp", "max_issues_repo_name": "tdriggs/TetrisAI", "max_issues_repo_head_hexsha": "467d2974c8e5375b6b61e681ce899d74f4728bca", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/NeuralNetwork.cpp", "max_forks_repo_name": "tdriggs/TetrisAI", "max_forks_repo_head_hexsha": "467d2974c8e5375b6b61e681ce899d74f4728bca", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.2995594714, "max_line_length": 125, "alphanum_fraction": 0.6593546048, "num_tokens": 1604, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436153333645, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6527787297877244}} {"text": "#ifndef TRIUMF_SUPERCONDUCTIVITY_PIPPARD_HPP\n#define TRIUMF_SUPERCONDUCTIVITY_PIPPARD_HPP\n\n#include \n\n// #include \n\n#include \n#include \n#include \n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n//\nnamespace superconductivity {\n\n// Pippard's phenomenological theory of superconductivity\nnamespace pippard {\n\n///\ntemplate \nT J_0(T temperature, T critical_temperature, T gap_meV, T exponent) {\n // Boltzmann constant (meV / K)\n constexpr T k_B_meV_per_K =\n 1e3 *\n triumf::constants::codata_2018::Boltzmann_constant_in_eV_K::value();\n //\n // T reduced_temperature = temperature / critical_temperature;\n //\n return std::pow(phenomenology::reduced_penetration_depth(\n temperature, critical_temperature, exponent),\n 2) *\n bcs::reduced_gap(temperature, critical_temperature) *\n std::tanh(bcs::gap(temperature, critical_temperature, gap_meV) /\n (2.0 * k_B_meV_per_K * temperature));\n}\n\n/// temperature dependence of the Pippard coherence length,\n/// \"borrowed\" from BCS theory\ntemplate \nT coherence_length(T temperature, T critical_temperature, T gap_meV, T exponent,\n T xi_0, T mean_free_path) {\n T fraction_1 =\n J_0(temperature, critical_temperature, gap_meV, exponent) / xi_0;\n T fraction_2 = 1.0 / mean_free_path;\n T fraction = fraction_1 + fraction_2;\n // handle a some edge cases for very big/small args\n if (std::isinf(fraction)) {\n return 0.0;\n } else if (fraction == 0.0) {\n return std::numeric_limits::infinity();\n } else {\n return 1.0 / fraction;\n }\n}\n\n/// temperature dependence of the (reduced) Pippard coherence length,\n/// \"borrowed\" from BCS theory\ntemplate \nT reduced_coherence_length(T temperature, T critical_temperature, T gap_meV,\n T exponent, T xi_0, T mean_free_path) {\n return coherence_length(temperature, critical_temperature, gap_meV,\n exponent, xi_0, mean_free_path) /\n coherence_length(0.0, critical_temperature, gap_meV, exponent, xi_0,\n mean_free_path);\n}\n\n/// helper function for the Pippard Kernel\ntemplate T g(T x) {\n /*\n boost::multiprecision::cpp_dec_float_100 value =\n (3.0 / 2.0) * ((1.0 + x * x) * std::atan(x) - x) / (x * x * x);\n return value;\n */\n // return correct result when x ~ 0.\n if (x < 1.0e-4) {\n return 1.0;\n } else {\n return (3.0 / 2.0) * ((1.0 + x * x) * std::atan(x) - x) / (x * x * x);\n }\n}\n\n/// Pippard Kernel\ntemplate \nT kernel(T q, T temperature, T critical_temperature, T gap_meV, T xi_0,\n T mean_free_path, T lambda_0, T exponent) {\n T x = q * coherence_length(temperature, critical_temperature, gap_meV,\n exponent, xi_0, mean_free_path);\n return std::pow(phenomenology::penetration_depth(\n temperature, critical_temperature, exponent, lambda_0),\n -2) *\n reduced_coherence_length(temperature, critical_temperature, gap_meV,\n exponent, xi_0, mean_free_path) *\n g(x);\n}\n\n/// (reduced) Pippard Kernel\ntemplate \nT reduced_kernel(T q, T temperature, T critical_temperature, T gap_meV, T xi_0,\n T mean_free_path, T lambda_0, T exponent) {\n return kernel(q, temperature, critical_temperature, gap_meV, xi_0,\n mean_free_path, lambda_0, exponent) /\n kernel(0.0, temperature, critical_temperature, gap_meV, xi_0,\n mean_free_path, lambda_0, exponent);\n}\n\n/// (reduced) magnetic field penetration proifile\ntemplate \nT reduced_field_penetration(T z, T temperature, T critical_temperature,\n T gap_meV, T xi_0, T mean_free_path, T lambda_0,\n T exponent) {\n //\n if (z <= 0.0) {\n return 1.0;\n } else {\n //\n auto pippard_integrand = [&](T q) -> T {\n T K = kernel(q, temperature, critical_temperature, gap_meV, xi_0,\n mean_free_path, lambda_0, exponent);\n return q / (q * q + K);\n };\n // create the integrator w/ specific tolerance and evaluation levels\n // (defaults: root_epsilon and eight levels for type double).\n // static T tolerance = std::sqrt(std::numeric_limits::epsilon());\n static T tolerance = std::cbrt(std::numeric_limits::epsilon());\n std::size_t levels = sizeof(T);\n static boost::math::quadrature::ooura_fourier_sin pippard_integrator =\n boost::math::quadrature::ooura_fourier_sin(tolerance, levels);\n // evaluate the integral, which returns a pair\n // (first = integral, second = relative error)\n std::pair result = pippard_integrator.integrate(pippard_integrand, z);\n // return the integral multiplied by the prefactors to get B vs. z\n return boost::math::constants::two_div_pi() * result.first;\n }\n}\n\n/// magnetic field penetration proifile\ntemplate \nT field_penetration(T z, T temperature, T critical_temperature, T gap_meV,\n T xi_0, T mean_free_path, T lambda_0, T exponent,\n T applied_field) {\n return applied_field * reduced_field_penetration(\n z, temperature, critical_temperature, gap_meV,\n xi_0, mean_free_path, lambda_0, exponent);\n}\n\n} // namespace pippard\n\n} // namespace superconductivity\n\n} // namespace triumf\n\n#endif // TRIUMF_SUPERCONDUCTIVITY_PIPPARD_HPP\n", "meta": {"hexsha": "2ce06799d50354a24db443ce3f9a2932ede406d8", "size": 5808, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/superconductivity/pippard.hpp", "max_stars_repo_name": "rmlmcfadden/triumfpp", "max_stars_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/triumf/superconductivity/pippard.hpp", "max_issues_repo_name": "rmlmcfadden/triumfpp", "max_issues_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/triumf/superconductivity/pippard.hpp", "max_forks_repo_name": "rmlmcfadden/triumfpp", "max_forks_repo_head_hexsha": "da3911cdf1b0ee4600d27999d484f9a1bdb89b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.4709677419, "max_line_length": 80, "alphanum_fraction": 0.6504820937, "num_tokens": 1516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.652778728936229}} {"text": "//\n// This program is used to study how to calculate (SS|SS)^{m}\n// for the recursive relation. Basically, it focus on the \n// fmt function:\n// f_{m}(t) = \\int^{1}_{0} u^{2m} e^{-tu^{2}} du \n// it needs the boost library to calcualte fmt\n// fenglai liu\n// Oct. 2013\n//\n// for reference, see Harris paper and the reference cited inside:\n// Harris, Frank E\n// Evaluation of GTO molecular integrals\n// International Journal of Quantum Chemistry, 1983, Vol. 23, Page 1469--1478\n//\n// note:\n// we found that the approximation of (2m-1)!!/R expression is \n// not numerical stable. Combined with down recursive relation,\n// it introduces greater error compared with other methods. \n// Therefore we finally abadon it.\n//\n//\n//\n\n// common C head files used in the program\n#include\n#include\n\n// external math functions \n#include\n\n// common C++ head files may be used in the program\n#include\n#include\n#include\n#include \n#include\n#include\n#include\n#include\n#include\n#include\n\n#include // special functions in math\n#include \n#include \n#include \nusing namespace boost::math;\nusing namespace boost;\nusing namespace std;\n#define PI 3.1415926535897932384626E0 \n\ndouble fm(const double& a, const int& m); \ndouble doubleFac(const int& m, const int& n); \n\ndouble fm(const double& a, const int& m) {\n\tdouble x = 1.0E0;\n\tif (fabs(a)<1.0E-14) return (pow(x,2*m+1)/(2*m+1));\n\tdouble f12 = 1.0E0/2.0E0;\n\tdouble p = 1.0E0/(2.0E0*pow(a,m+f12));\n\tdouble upperLimit = a*pow(x,2.0E0);\n\treturn tgamma_lower(m+f12,upperLimit)*p;\n}\n\ndouble doubleFac(const int& m, const int& n) {\n\t// calculate (2m-1)!!/(2m+2n+1)!!\n\tdouble x = 1.0E0;\n\tfor(int i=0; i<=n; i++) {\n\t\tx *= 1.0E0/(2*m+2*i+1); \n\t}\n\treturn x;\n} \n\nint main() \n{\n\t///////////////////////////////////////////////////\n\t// global settings\n\t// step length and number of claculation for \n\t// time performance\n\t// global error is the error range\n\t// if the difference is less than the error, we \n\t// think the error could be omitted\n\t///////////////////////////////////////////////////\n\tdouble steplength = 0.000001;\n\tdouble globalError = 1.0E-14;\n\tint top_M_limmit = 40;\n\tdouble T_max_limit = 100.0E0;\n\n\t///////////////////////////////////////////////////\n\t// testing the fmt from down recursive relation\n\t///////////////////////////////////////////////////\n\tcout << endl << endl;\n\tcout << \"===========================================================\" << endl;\n\tcout << \"testing the comparison between f_{m}(t) and f_{m+1}(t) for m up to \" << top_M_limmit << endl;\n\tcout << \"step length for T is \" << steplength << endl;\n\tcout << \"T is ranging from 0 \" << \" to \" <=0; i--) {\n\t\t\t\tdouble e = (1.0/(2*i+1.0))*(t2*e0+et);\n\t\t\t\tif (e0>e) {\n\t\t\t\t\tdouble d = fabs(e0-e);\n\t\t\t\t\tif (d>globalError) {\n\t\t\t\t\t\tprintf(\"T is %-16.14f\\n\", T);\n\t\t\t\t\t\tprintf(\"for m=%d difference is %-16.14f\\n\", n, d);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\te0 = e;\n\t\t\t}\n\t\t}\n\t}\n\treturn 0;\n}\n", "meta": {"hexsha": "360ae0b1e6d00408534ea632548161185de62815", "size": 3473, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "util/fmt_test/fmt_test_compare.cpp", "max_stars_repo_name": "murfreesboro/cppints", "max_stars_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "util/fmt_test/fmt_test_compare.cpp", "max_issues_repo_name": "murfreesboro/cppints", "max_issues_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "util/fmt_test/fmt_test_compare.cpp", "max_forks_repo_name": "murfreesboro/cppints", "max_forks_repo_head_hexsha": "a7beaac034e2bfae8e71997b322133906d1afcaf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.9416666667, "max_line_length": 103, "alphanum_fraction": 0.5882522315, "num_tokens": 1016, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361533336451, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6527787242514914}} {"text": "/*\n * fmath.cpp\n *\n * Created on: Jul 17, 2012\n * @author Ralph Schurade\n */\n#include \"fmath.h\"\n\n#include \"math.h\"\n\n#include \"../thirdparty/newmat10/newmatap.h\"\n#include \"../thirdparty/newmat10/newmatio.h\"\n#include \"../thirdparty/newmat10/newmatrm.h\"\n#include \"../thirdparty/newmat10/precisio.h\"\n\n#include \n#include \n\n#include \n\n#include \n\nFMath::FMath() {}\nFMath::~FMath() {}\n\nColumnVector FMath::vlog( ColumnVector v )\n{\n // allocate memory of output object:\n ColumnVector tmp( v.Nrows() );\n\n // for each element of the vector:\n for ( int i( 1 ); i <= v.Nrows(); ++i )\n {\n if ( v( i ) <= 0.0 )\n tmp( i ) = -1.0e+17;\n else\n tmp( i ) = log( v( i ) );\n }\n return tmp;\n}\n\ndouble FMath::legendre_p( int k )\n{\n double z = 1.0;\n double n = 1.0;\n\n for ( int i = 1; i <= k + 1; i += 2 ) z *= i;\n for ( int i = 2; i <= k - 2; i += 2 ) n *= i;\n\n if (( k / 2 ) % 2 == 0)\n {\n return -1.0 / ( 8 * M_PI ) * ( z / n );\n }\n else\n {\n return 1.0 / ( 8 * M_PI ) * ( z / n );\n }\n\n}\n\ndouble FMath::boostLegendre_p( int order, int arg1, double arg2 )\n{\n return boost::math::legendre_p( order, arg1, arg2 );\n}\n\nMatrix FMath::sh_base( Matrix g, int maxOrder )\n{\n //qDebug() << \"start calculating sh base\";\n // allcoate result matrix\n unsigned long sh_dirs( ( maxOrder + 2 ) * ( maxOrder + 1 ) / 2 );\n Matrix out( g.Nrows(), sh_dirs );\n out = 0.0;\n\n // for each direction\n for ( int i = 0; i < g.Nrows(); ++i )\n {\n // transform current direction to polar coordinates\n double theta( acos( g( i + 1, 3 ) ) );\n double phi( atan2( g( i + 1, 2 ), g( i + 1, 1 ) ) );\n\n // calculate spherical harmonic base\n for ( int order = 0, j = 0; order <= maxOrder; order += 2 )\n {\n for ( int degree( -order ); degree <= order; ++degree, ++j )\n {\n out( i + 1, j + 1 ) = sh_base_function( order, degree, theta, phi );\n }\n }\n }\n //qDebug() << \"finished calculating sh base\";\n return out;\n}\n\ndouble FMath::sh_base_function( int order, int degree, double theta, double phi )\n{\n using namespace boost::math;\n#if 0\n double P = legendre_p( order, abs(degree), cos(theta) );\n\n if ( degree > 0 )\n {\n return P * cos( degree * phi );\n }\n else if ( degree < 0 )\n {\n return P * sin( -degree * phi );\n }\n else\n {\n return P;\n }\n#else\n if ( degree > 0 )\n {\n return spherical_harmonic_r( order, abs( degree ), theta, phi );\n }\n else if ( degree < 0 )\n {\n return spherical_harmonic_i( order, abs( degree ), theta, phi );\n }\n else\n {\n return spherical_harmonic_r( order, 0, theta, phi );\n }\n#endif\n}\n\nSymmetricMatrix FMath::moment_of_inertia( const ColumnVector& values, const QVector& points )\n{\n SymmetricMatrix result( 3 );\n result = 0.0;\n\n double sum( 0.0 );\n for ( int i = 0; i < points.size(); ++i )\n {\n double x( points[i]( 1 ) );\n double y( points[i]( 2 ) );\n double z( points[i]( 3 ) );\n double val = fabs( values( i + 1 ) );\n\n result( 1, 1 ) += x * x * val;\n result( 1, 2 ) += x * y * val;\n result( 1, 3 ) += x * z * val;\n result( 2, 2 ) += y * y * val;\n result( 2, 3 ) += y * z * val;\n result( 3, 3 ) += z * z * val;\n\n sum += val * val;\n }\n result = result / sum;\n\n return result;\n}\n\ndouble FMath::iprod( const ColumnVector& v1, const ColumnVector& v2 )\n{\n double result( 0.0 );\n\n if ( v1.Nrows() != v2.Nrows() )\n {\n throw std::range_error( \"Vectors in scalar product need same size!\" );\n }\n\n for ( int i = 1; i < v1.Nrows() + 1; ++i )\n {\n result += v1( i ) * v2( i );\n }\n\n return result;\n}\n\nColumnVector FMath::cprod( const ColumnVector& v1, const ColumnVector& v2 )\n{\n ColumnVector result( 3 );\n\n if ( v1.Nrows() != 3 || v2.Nrows() != 3 )\n throw std::range_error( \"Vectors in cross product both need size 3!\" );\n\n result( 1 ) = v1( 2 ) * v2( 3 ) - v1( 3 ) * v2( 2 );\n result( 2 ) = v1( 3 ) * v2( 1 ) - v1( 1 ) * v2( 3 );\n result( 3 ) = v1( 1 ) * v2( 2 ) - v1( 2 ) * v2( 1 );\n\n result = result / sqrt( FMath::iprod( result, result ) );\n\n return result;\n}\n\n\nvoid FMath::evd3x3( ColumnVector tensor, QVector& vecs, ColumnVector& vals )\n{\n double i1, i2, i3, v, s, phi, l1, l2, l3;\n double ev1_x, ev1_y, ev1_z, ev2_x, ev2_y, ev2_z, ev3_x, ev3_y, ev3_z, vec_norm;\n\n double xx = tensor( 1 );\n double xy = tensor( 2 );\n double xz = tensor( 3 );\n double yy = tensor( 4 );\n double yz = tensor( 5 );\n double zz = tensor( 6 );\n\n // three invariants of D (dt)\n // i1=l1+l2+l3 (trace)\n // i2=l1*l2+l1*l3+l2*l3\n // i3=l1*l2*l3 (determinante)\n i1 = xx + yy + zz;\n i2 = xx * yy + xx * zz + yy * zz - ( pow2( xy ) + pow2( xz ) + pow2( yz ) );\n i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * pow2( xy ) + yy * pow2( xz ) + xx * pow2( yz ) );\n\n v = pow2( i1 / 3 ) - i2 / 3;\n s = pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2;\n\n if ( ( v > 0 ) && ( pow2( s ) < pow3( v ) ) )\n phi = acos( s / v * sqrt( 1. / v ) ) / 3;\n else\n phi = 0;\n\n // eigenvalues\n if ( phi != 0 )\n {\n l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi );\n l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi );\n l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi );\n }\n else\n l1 = l2 = l3 = 0.0;\n\n // eigenvectors\n ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy );\n ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz );\n ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz );\n\n ev2_x = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * yz - ( zz - l2 ) * xy );\n ev2_y = ( xz * yz - ( zz - l2 ) * xy ) * ( xz * xy - ( xx - l2 ) * yz );\n ev2_z = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * xy - ( xx - l2 ) * yz );\n\n ev3_x = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * yz - ( zz - l3 ) * xy );\n ev3_y = ( xz * yz - ( zz - l3 ) * xy ) * ( xz * xy - ( xx - l3 ) * yz );\n ev3_z = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * xy - ( xx - l3 ) * yz );\n\n vec_norm = sqrt( pow2( ev1_x ) + pow2( ev1_y ) + pow2( ev1_z ) );\n\n if ( vec_norm > 0 )\n {\n ev1_x = ev1_x / vec_norm;\n ev1_y = ev1_y / vec_norm;\n ev1_z = ev1_z / vec_norm;\n }\n else\n ev1_x = ev1_y = ev1_z = 0.0;\n\n vec_norm = sqrt( pow2( ev2_x ) + pow2( ev2_y ) + pow2( ev2_z ) );\n\n if ( vec_norm > 0 )\n {\n ev2_x = ev2_x / vec_norm;\n ev2_y = ev2_y / vec_norm;\n ev2_z = ev2_z / vec_norm;\n }\n else\n ev2_x = ev2_y = ev2_z = 0.0;\n\n vec_norm = sqrt( pow2( ev3_x ) + pow2( ev3_y ) + pow2( ev3_z ) );\n\n if ( vec_norm > 0 )\n {\n ev3_x = ev3_x / vec_norm;\n ev3_y = ev3_y / vec_norm;\n ev3_z = ev3_z / vec_norm;\n }\n else\n ev3_x = ev3_y = ev3_z = 0.0;\n\n ColumnVector ev1( 3 );\n ColumnVector ev2( 3 );\n ColumnVector ev3( 3 );\n\n vals(1) = l1;\n vals(2) = l2;\n vals(3) = l3;\n\n ev1( 1 ) = ev1_x;\n ev1( 2 ) = ev1_y;\n ev1( 3 ) = ev1_z;\n ev2( 1 ) = ev2_x;\n ev2( 2 ) = ev2_y;\n ev2( 3 ) = ev2_z;\n ev3( 1 ) = ev3_x;\n ev3( 2 ) = ev3_y;\n ev3( 3 ) = ev1_z;\n vecs.clear();\n vecs.push_back( ev3 );\n vecs.push_back( ev2 );\n vecs.push_back( ev1 );\n}\n\n///* ***************************************************************************\n///* @file math.cpp\n///* @fn Vector cart2sphere(\n///*\n///* const Vector& input )\n///*\n///* @brief Transforms a cartesian-coordinate vector to spherical coordinates.\n///*\n///* For further information view:
\n///* Wikipedia article on cartesian and spherical coordinates.\n///*\n///* @param Vector: a in cartesian-coordinates\n///*\n///* @return Vector: representation of a in spherical coordinates,\n///* order: r, theta, phi.\n///* ***************************************************************************\nColumnVector FMath::cart2sphere( const ColumnVector& input )\n{\n if ( input.Nrows() != 3 )\n throw std::range_error(\"Can only transform 3D-vectors.\");\n\n ColumnVector result( 3 );\n\n result( 1 ) = sqrt( input( 1 ) * input( 1 ) + input( 2 ) * input( 2 ) + input( 3 ) * input( 3 ) );\n result( 2 ) = acos( input( 3 ) / result( 1 ) );\n result( 3 ) = atan2( input( 2 ), input( 1 ) );\n\n return result;\n}\n\n///* ***************************************************************************\n///* @file math.cpp\n///* @fn Vector sphere2cart(\n///*\n///* const Vector& input )\n///*\n///* @brief Transforms a spherical-coordinate vector to cartesian-coordinates.\n///*\n///* For further information view:
\n///* Wikipedia article on cartesian and spherical coordinates.
\n///*\n///* @param Vector: a in spherical-coordinates\n///*\n///* @return Vector: represantation of a in cartesian-coordinates, order: x,y,z.\n///* ***************************************************************************\nColumnVector FMath::sphere2cart( const ColumnVector& input )\n{\n if ( input.Nrows() != 3 )\n throw std::range_error( \"Can only transform 3D-vectors.\" );\n\n ColumnVector result( 3 );\n\n result( 1 ) = input( 1 ) * sin( input( 2 ) ) * cos( input( 3 ) );\n result( 2 ) = input( 1 ) * sin( input( 2 ) ) * sin( input( 3 ) );\n result( 3 ) = input( 1 ) * cos( input( 2 ) );\n\n return result;\n}\n\nColumnVector FMath::SH_opt_max( const ColumnVector& startX, const ColumnVector& coeff )\n{\n ColumnVector newX( startX );\n ColumnVector oldX( 3 );\n\n // set values for computation\n const double precision( 10.e-6 );\n const double eps( 10.e-4 );\n\n double delta( 1.0 );\n int steps( 0 );\n while ( delta > precision && steps < 100 )\n {\n // Update old value\n ++steps;\n oldX = newX;\n double SH_old( sh_eval( oldX, coeff ) );\n\n // define the delta steps\n ColumnVector dt( oldX );\n ColumnVector dp( oldX );\n dt( 2 ) += eps;\n dp( 3 ) += eps;\n\n // calculate Jacobian\n double Jt( ( FMath::sh_eval( dt, coeff ) - SH_old ) );\n double Jp( ( FMath::sh_eval( dp, coeff ) - SH_old ) );\n\n // do iteration\n newX( 2 ) = oldX( 2 ) + Jt;\n newX( 3 ) = oldX( 3 ) + Jp;\n\n delta = fabs( Jt ) + fabs( Jp );\n //std::cout<\n///*\n///* For further information view:
\n///* Cormen, Leiversn, Rivest, and Stein: Introduction to Algorithms
\n///* Wikipedia article on bubble sort.\n///*\n///* @param Vector: values the vector which determies the sorting\n///* @param Vector: indices to be sorted going along\n///*\n///* @return TODO\n///* ***************************************************************************\ndouble FMath::sh_eval( const ColumnVector& position, const ColumnVector& coeff )\n{\n const int max_order( ( -3 + static_cast( sqrt( 8 * coeff.Nrows() ) + 1 ) ) / 2 );\n\n const double radius( position( 1 ) );\n if ( radius == 0.0 )\n {\n return 0.0;\n }\n\n // for easier readability\n const double theta( position( 2 ) );\n const double phi( position( 3 ) );\n\n double result( 0 );\n for ( int order( 0 ), j( 1 ); order <= max_order; order += 2 )\n {\n for ( int degree( -order ); degree <= order; degree++, ++j )\n {\n result += coeff( j ) * FMath::sh_base_function( order, degree, theta, phi );\n }\n }\n return result;\n}\n\n// calculate rotation matrix: http://en.wikipedia.org/wiki/Rotation_matrix\nMatrix FMath::RotationMatrix( const double angle, const ColumnVector& axis )\n{\n double s( sin( angle ) );\n double c( cos( angle ) );\n double d( 1. - c );\n\n Matrix R( 3, 3 );\n R( 1, 1 ) = c + axis( 1 ) * axis( 1 ) * d;\n R( 1, 2 ) = axis( 1 ) * axis( 2 ) * d - axis( 3 ) * s;\n R( 1, 3 ) = axis( 1 ) * axis( 3 ) * d + axis( 2 ) * s;\n R( 2, 1 ) = axis( 1 ) * axis( 2 ) * d + axis( 3 ) * s;\n R( 2, 2 ) = c + axis( 1 ) * axis( 1 ) * d;\n R( 2, 3 ) = axis( 2 ) * axis( 3 ) * d - axis( 1 ) * s;\n R( 3, 1 ) = axis( 1 ) * axis( 3 ) * d - axis( 2 ) * s;\n R( 3, 2 ) = axis( 2 ) * axis( 3 ) * d + axis( 1 ) * s;\n R( 3, 3 ) = c + axis( 3 ) * axis( 3 ) * d;\n\n return R;\n}\n\nvoid FMath::debugColumnVector3( const ColumnVector& v, QString name )\n{\n if ( v.Nrows() != 3 )\n {\n qDebug() << name << \"error not 3 elements in vector\";\n }\n qDebug() << name << v( 1 ) << v( 2 ) << v( 3 );\n}\n\nMatrix FMath::pseudoInverse( const Matrix& A )\n{\n /*\n Matrix U( A.Nrows(), A.Ncols() );\n DiagonalMatrix D( A.Ncols() );\n Matrix V( A.Ncols(), A.Ncols() );\n SVD( A, D, U, V );\n return ( V * ( D.t() * D ) * D.t() * U.t() );\n */\n\n return ( ( A.t() * A ).i() * A.t() );\n}\n\nvoid FMath::fitTensors( QVector& data, QVector& b0Images, QVector& bvecs, QVector& bvals, QVector& out )\n{\n int N = bvecs.size();\n\n Matrix B( N, 6 );\n Matrix U( N, 6 );\n Matrix V( 6, 6 );\n Matrix BI( 6, N );\n DiagonalMatrix D( 6 );\n\n double mult_c;\n\n for ( int i = 0; i < N; ++i )\n {\n mult_c = bvals[i] / (float) ( bvecs[i].x() * bvecs[i].x() + bvecs[i].y() * bvecs[i].y() + bvecs[i].z() * bvecs[i].z() );\n\n B( i + 1, 1 ) = mult_c * bvecs[i].x() * bvecs[i].x();\n B( i + 1, 2 ) = 2 * mult_c * bvecs[i].x() * bvecs[i].y();\n B( i + 1, 3 ) = 2 * mult_c * bvecs[i].x() * bvecs[i].z();\n B( i + 1, 4 ) = mult_c * bvecs[i].y() * bvecs[i].y();\n B( i + 1, 5 ) = 2 * mult_c * bvecs[i].y() * bvecs[i].z();\n B( i + 1, 6 ) = mult_c * bvecs[i].z() * bvecs[i].z();\n }\n\n SVD( B, D, U, V );\n\n for ( int j = 1; j <= 6; ++j )\n {\n D( j ) = 1. / D( j );\n }\n BI = V * D * U.t();\n\n double s0 = 0.0;\n double si = 0.0;\n vector log_s0_si_pixel( N );\n\n out.clear();\n out.reserve( data.size() );\n\n Matrix blank( 3, 3 );\n blank = 0.0;\n\n for ( int i = 0; i < data.size(); ++i )\n {\n s0 = b0Images.at( i );\n\n if ( s0 > 0 )\n {\n // compute log(s0)-log(si)\n s0 = log( s0 );\n for ( int j = 0; j < N; ++j )\n {\n si = data.at( i )( j + 1 ); //dti[j*blockSize+i];\n if ( si > 0 )\n {\n si = log( si );\n }\n else\n {\n si = 0.0;\n }\n log_s0_si_pixel[j] = s0 - si;\n }\n\n double value;\n // compute tensor\n ColumnVector t( 6 );\n for ( int l = 0; l < 6; l++ )\n {\n value = 0;\n for ( int m = 1; m <= N; ++m )\n {\n value += BI( l + 1, m ) * log_s0_si_pixel[m - 1];\n }\n t( l + 1 ) = (float) ( value ); // save the tensor components in a adjacent memory\n }\n Matrix m( 3, 3 );\n m( 1, 1 ) = t( 1 );\n m( 1, 2 ) = t( 2 );\n m( 1, 3 ) = t( 3 );\n m( 2, 1 ) = t( 2 );\n m( 2, 2 ) = t( 4 );\n m( 2, 3 ) = t( 5 );\n m( 3, 1 ) = t( 3 );\n m( 3, 2 ) = t( 5 );\n m( 3, 3 ) = t( 6 );\n\n out.push_back( m );\n } // end if s0 > 0\n else\n {\n out.push_back( blank );\n }\n }\n}\n\nvoid FMath::fa( QVector& tensors, QVector& faOut )\n{\n int blockSize = tensors.size();\n\n faOut.resize( blockSize );\n\n QVector trace( blockSize );\n float value = 0;\n for ( int i = 0; i < blockSize; ++i )\n {\n value = tensors.at( i )( 1, 1 );\n value += tensors.at( i )( 2, 2 );\n value += tensors.at( i )( 3, 3 );\n trace[i] = value / 3.0;\n }\n\n QVector fa( blockSize );\n\n double xx, xy, xz, yy, yz, zz, tr, AA, DD;\n\n for ( int i = 0; i < blockSize; ++i )\n {\n xx = tensors.at( i )( 1, 1 );\n xy = tensors.at( i )( 1, 2 );\n xz = tensors.at( i )( 1, 3 );\n yy = tensors.at( i )( 2, 2 );\n yz = tensors.at( i )( 2, 3 );\n zz = tensors.at( i )( 3, 3 );\n tr = trace[i];\n\n AA = pow2( xx - tr ) + pow2( yy - tr ) + pow2( zz - tr ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz );\n DD = pow2( xx ) + pow2( yy ) + pow2( zz ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz );\n\n if ( DD > 0 )\n {\n faOut[i] = qMin( 1.0f, (float) ( sqrt( AA ) / sqrt( DD ) * sqrt( 1.5 ) ) );\n }\n else\n {\n faOut[i] = 0.0;\n }\n }\n}\n\nfloat FMath::fa( Matrix tensor )\n{\n float trace;\n float value = 0;\n value = tensor( 1, 1 );\n value += tensor( 2, 2 );\n value += tensor( 3, 3 );\n trace = value / 3.0;\n\n float fa;\n\n double xx, xy, xz, yy, yz, zz, tr, AA, DD;\n\n xx = tensor( 1, 1 );\n xy = tensor( 1, 2 );\n xz = tensor( 1, 3 );\n yy = tensor( 2, 2 );\n yz = tensor( 2, 3 );\n zz = tensor( 3, 3 );\n tr = trace;\n\n AA = pow2( xx - tr ) + pow2( yy - tr ) + pow2( zz - tr ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz );\n DD = pow2( xx ) + pow2( yy ) + pow2( zz ) + 2 * pow2( xy ) + 2 * pow2( xz ) + 2 * pow2( yz );\n\n if ( DD > 0 )\n {\n fa = qMin( 1.0f, (float) ( sqrt( AA ) / sqrt( DD ) * sqrt( 1.5 ) ) );\n }\n else\n {\n fa = 0.0;\n }\n return fa;\n}\n\nvoid FMath::evec1( QVector& tensors, QVector& evec1 )\n{\n int blockSize = tensors.size();\n\n evec1.resize( blockSize );\n\n double xx, xy, xz, yy, yz, zz;\n double i1, i2, i3, v, s, phi, l1, l2, l3;\n double vec_norm, ev1_x, ev1_y, ev1_z;\n\n for ( int i = 0; i < blockSize; ++i )\n {\n xx = tensors.at( i )( 1, 1 );\n xy = tensors.at( i )( 1, 2 );\n xz = tensors.at( i )( 1, 3 );\n yy = tensors.at( i )( 2, 2 );\n yz = tensors.at( i )( 2, 3 );\n zz = tensors.at( i )( 3, 3 );\n\n // three invariants of D (dt)\n // i1=l1+l2+l3 (trace)\n // i2=l1*l2+l1*l3+l2*l3\n // i3=l1*l2*l3 (determinante)\n i1 = xx + yy + zz;\n i2 = xx * yy + xx * zz + yy * zz - ( pow2( xy ) + pow2( xz ) + pow2( yz ) );\n i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * pow2( xy ) + yy * pow2( xz ) + xx * pow2( yz ) );\n\n v = pow2( i1 / 3 ) - i2 / 3;\n s = pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2;\n if ( ( v > 0 ) && ( pow2( s ) < pow3( v ) ) )\n phi = acos( s / v * sqrt( 1. / v ) ) / 3;\n else\n phi = 0;\n\n // eigenvalues\n if ( phi != 0 )\n {\n l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi );\n l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi );\n l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi );\n }\n else\n l1 = l2 = l3 = 0.0;\n\n // eigenvectors\n ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy );\n ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz );\n ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz );\n\n vec_norm = sqrt( pow2( ev1_x ) + pow2( ev1_y ) + pow2( ev1_z ) );\n\n if ( vec_norm > 0 )\n {\n ev1_x = ev1_x / vec_norm;\n ev1_y = ev1_y / vec_norm;\n ev1_z = ev1_z / vec_norm;\n }\n else\n ev1_x = ev1_y = ev1_z = 0.0;\n\n evec1[i].setX( ev1_x );\n evec1[i].setY( ev1_y );\n evec1[i].setZ( ev1_z );\n }\n}\n\nvoid FMath::evecs( QVector& tensors, QVector& evec1, QVector& eval1,\n QVector& evec2, QVector& eval2,\n QVector& evec3, QVector& eval3 )\n{\n int blockSize = tensors.size();\n\n evec1.resize( blockSize );\n evec2.resize( blockSize );\n evec3.resize( blockSize );\n eval1.resize( blockSize );\n eval2.resize( blockSize );\n eval3.resize( blockSize );\n\n double xx, xy, xz, yy, yz, zz;\n double i1, i2, i3, v, s, phi, l1, l2, l3;\n double vec_norm, ev1_x, ev1_y, ev1_z, ev2_x, ev2_y, ev2_z, ev3_x, ev3_y, ev3_z;\n\n for ( int i = 0; i < blockSize; ++i )\n {\n xx = tensors.at( i )( 1, 1 );\n xy = tensors.at( i )( 1, 2 );\n xz = tensors.at( i )( 1, 3 );\n yy = tensors.at( i )( 2, 2 );\n yz = tensors.at( i )( 2, 3 );\n zz = tensors.at( i )( 3, 3 );\n\n // three invariants of D (dt)\n // i1=l1+l2+l3 (trace)\n // i2=l1*l2+l1*l3+l2*l3\n // i3=l1*l2*l3 (determinante)\n i1 = xx + yy + zz;\n i2 = xx * yy + xx * zz + yy * zz - ( pow2( xy ) + pow2( xz ) + pow2( yz ) );\n i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * pow2( xy ) + yy * pow2( xz ) + xx * pow2( yz ) );\n\n v = pow2( i1 / 3 ) - i2 / 3;\n s = pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2;\n if ( ( v > 0 ) && ( pow2( s ) < pow3( v ) ) )\n phi = acos( s / v * sqrt( 1. / v ) ) / 3;\n else\n phi = 0;\n\n // eigenvalues\n if ( phi != 0 )\n {\n l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi );\n l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi );\n l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi );\n }\n else\n l1 = l2 = l3 = 0.0;\n\n eval1[i] = l1;\n eval2[i] = l2;\n eval3[i] = l3;\n\n // eigenvectors\n ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy );\n ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz );\n ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz );\n\n ev2_x = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * yz - ( zz - l2 ) * xy );\n ev2_y = ( xz * yz - ( zz - l2 ) * xy ) * ( xz * xy - ( xx - l2 ) * yz );\n ev2_z = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * xy - ( xx - l2 ) * yz );\n\n ev3_x = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * yz - ( zz - l3 ) * xy );\n ev3_y = ( xz * yz - ( zz - l3 ) * xy ) * ( xz * xy - ( xx - l3 ) * yz );\n ev3_z = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * xy - ( xx - l3 ) * yz );\n\n vec_norm = sqrt( pow2( ev1_x ) + pow2( ev1_y ) + pow2( ev1_z ) );\n\n if ( vec_norm > 0 )\n {\n ev1_x = ev1_x / vec_norm;\n ev1_y = ev1_y / vec_norm;\n ev1_z = ev1_z / vec_norm;\n }\n else\n ev1_x = ev1_y = ev1_z = 0.0;\n\n vec_norm = sqrt( pow2( ev2_x ) + pow2( ev2_y ) + pow2( ev2_z ) );\n\n if ( vec_norm > 0 )\n {\n ev2_x = ev2_x / vec_norm;\n ev2_y = ev2_y / vec_norm;\n ev2_z = ev2_z / vec_norm;\n }\n else\n ev2_x = ev2_y = ev2_z = 0.0;\n\n vec_norm = sqrt( pow2( ev3_x ) + pow2( ev3_y ) + pow2( ev3_z ) );\n\n if ( vec_norm > 0 )\n {\n ev3_x = ev3_x / vec_norm;\n ev3_y = ev3_y / vec_norm;\n ev3_z = ev3_z / vec_norm;\n }\n else\n ev3_x = ev3_y = ev3_z = 0.0;\n\n evec1[i].setX( ev1_x );\n evec1[i].setY( ev1_y );\n evec1[i].setZ( ev1_z );\n evec2[i].setX( ev2_x );\n evec2[i].setY( ev2_y );\n evec2[i].setZ( ev2_z );\n evec3[i].setX( ev3_x );\n evec3[i].setY( ev3_y );\n evec3[i].setZ( ev3_z );\n }\n}\n\nMatrix FMath::expT( Matrix& t )\n{\n double xx, xy, xz, yy, yz, zz;\n double i1, i2, i3, v, s, phi, l1, l2, l3;\n double ev1_x, ev1_y, ev1_z, ev2_x, ev2_y, ev2_z, ev3_x, ev3_y, ev3_z, vec_norm;\n\n xx = t( 1, 1 );\n xy = t( 1, 2 );\n xz = t( 1, 3 );\n yy = t( 2, 2 );\n yz = t( 2, 3 );\n zz = t( 3, 3 );\n\n // three invariants of D (dt)\n // i1=l1+l2+l3 (trace)\n // i2=l1*l2+l1*l3+l2*l3\n // i3=l1*l2*l3 (determinante)\n i1 = xx + yy + zz;\n i2 = xx * yy + xx * zz + yy * zz - ( FMath::pow2( xy ) + FMath::pow2( xz ) + FMath::pow2( yz ) );\n i3 = xx * yy * zz + 2. * xy * xz * yz - ( zz * FMath::pow2( xy ) + yy * FMath::pow2( xz ) + xx * FMath::pow2( yz ) );\n\n v = FMath::pow2( i1 / 3 ) - i2 / 3;\n s = FMath::pow3( i1 / 3 ) - i1 * i2 / 6 + i3 / 2;\n if ( ( v > 0 ) && ( FMath::pow2( s ) < FMath::pow3( v ) ) )\n phi = acos( s / v * sqrt( 1. / v ) ) / 3;\n else\n phi = 0;\n\n // eigenvalues\n if ( phi != 0 )\n {\n l1 = i1 / 3 + 2 * sqrt( v ) * cos( phi );\n l2 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. + phi );\n l3 = i1 / 3 - 2 * sqrt( v ) * cos( M_PI / 3. - phi );\n }\n else\n l1 = l2 = l3 = 0.0;\n /*\n eval1[i] = l1;\n eval2[i] = l2;\n eval3[i] = l3;\n */\n // eigenvectors\n ev1_x = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * yz - ( zz - l1 ) * xy );\n ev1_y = ( xz * yz - ( zz - l1 ) * xy ) * ( xz * xy - ( xx - l1 ) * yz );\n ev1_z = ( xy * yz - ( yy - l1 ) * xz ) * ( xz * xy - ( xx - l1 ) * yz );\n\n ev2_x = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * yz - ( zz - l2 ) * xy );\n ev2_y = ( xz * yz - ( zz - l2 ) * xy ) * ( xz * xy - ( xx - l2 ) * yz );\n ev2_z = ( xy * yz - ( yy - l2 ) * xz ) * ( xz * xy - ( xx - l2 ) * yz );\n\n ev3_x = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * yz - ( zz - l3 ) * xy );\n ev3_y = ( xz * yz - ( zz - l3 ) * xy ) * ( xz * xy - ( xx - l3 ) * yz );\n ev3_z = ( xy * yz - ( yy - l3 ) * xz ) * ( xz * xy - ( xx - l3 ) * yz );\n\n vec_norm = sqrt( FMath::pow2( ev1_x ) + FMath::pow2( ev1_y ) + FMath::pow2( ev1_z ) );\n\n if ( vec_norm > 0 )\n {\n ev1_x = ev1_x / vec_norm;\n ev1_y = ev1_y / vec_norm;\n ev1_z = ev1_z / vec_norm;\n }\n else\n ev1_x = ev1_y = ev1_z = 0.0;\n\n vec_norm = sqrt( FMath::pow2( ev2_x ) + FMath::pow2( ev2_y ) + FMath::pow2( ev2_z ) );\n\n if ( vec_norm > 0 )\n {\n ev2_x = ev2_x / vec_norm;\n ev2_y = ev2_y / vec_norm;\n ev2_z = ev2_z / vec_norm;\n }\n else\n ev2_x = ev2_y = ev2_z = 0.0;\n\n vec_norm = sqrt( FMath::pow2( ev3_x ) + FMath::pow2( ev3_y ) + FMath::pow2( ev3_z ) );\n\n if ( vec_norm > 0 )\n {\n ev3_x = ev3_x / vec_norm;\n ev3_y = ev3_y / vec_norm;\n ev3_z = ev3_z / vec_norm;\n }\n else\n ev3_x = ev3_y = ev3_z = 0.0;\n\n Matrix U( 3, 3 );\n DiagonalMatrix D( 3 );\n\n U( 1, 1 ) = ev1_x;\n U( 2, 1 ) = ev1_y;\n U( 3, 1 ) = ev1_z;\n U( 1, 2 ) = ev2_x;\n U( 2, 2 ) = ev2_y;\n U( 3, 2 ) = ev2_z;\n U( 1, 3 ) = ev3_x;\n U( 2, 3 ) = ev3_y;\n U( 3, 3 ) = ev3_z;\n D( 1 ) = exp( l1 );\n D( 2 ) = exp( l2 );\n D( 3 ) = exp( l3 );\n Matrix expM(3,3);\n expM = U * D * U.t();\n\n return expM;\n}\n//void evd3x3_2( ColumnVector tensor, QVector& vecs, ColumnVector& vals );\nvoid FMath::evd3x3_2( ColumnVector &d, QVector& vec, ColumnVector& val )\n{\n if ( d.Nrows() != 6 )\n throw std::invalid_argument( \"Tensor (6-component vector) expected!\" );\n\n // calculate the eigenvalues:\n val = ColumnVector( 3 );\n vec.reserve( 3 );\n std::vector index( 3 );\n\n ColumnVector e( 3 );\n // Create work variables:\n Matrix A( 3, 3 ), Q( 3, 3 );\n A( 1, 1 ) = d( 1 );\n A( 2, 1 ) = A( 1, 2 ) = d( 2 );\n A( 3, 1 ) = A( 1, 3 ) = d( 3 );\n A( 2, 2 ) = d( 4 );\n A( 3, 2 ) = A( 2, 3 ) = d( 5 );\n A( 3, 3 ) = d( 6 );\n\n double m, c1, c0;\n\n // Determine coefficients of characteristic poynomial. We write\n // | a d f |\n // A = | d* b e |\n // | f* e* c |\n double de = A( 1, 2 ) * A( 2, 3 ); // d * e\n double dd = A( 1, 2 ) * A( 1, 2 ); // d^2\n double ee = A( 2, 3 ) * A( 2, 3 ); // e^2\n double ff = A( 1, 3 ) * A( 1, 3 ); // f^2\n m = A( 1, 1 ) + A( 2, 2 ) + A( 3, 3 );\n c1 = ( A( 1, 1 ) * A( 2, 2 ) + A( 1, 1 ) * A( 3, 3 ) + A( 2, 2 ) * A( 3, 3 ) ) // a*b + a*c + b*c - d^2 - e^2 - f^2\n - ( dd + ee + ff );\n c0 = A( 3, 3 ) * dd + A( 1, 1 ) * ee + A( 2, 2 ) * ff - A( 1, 1 ) * A( 2, 2 ) * A( 3, 3 ) - 2.0 * A( 1, 3 ) * de; // c*d^2 + a*e^2 + b*f^2 - a*b*c - 2*f*d*e)\n\n double p, sqrt_p, q, c, s, phi;\n p = m * m - 3.0 * c1;\n q = m * ( p - ( 3.0 / 2.0 ) * c1 ) - ( 27.0 / 2.0 ) * c0;\n sqrt_p = sqrt( fabs( p ) );\n\n phi = 27.0 * ( 0.25 * c1 * c1 * ( p - c1 ) + c0 * ( q + 27.0 / 4.0 * c0 ) );\n phi = ( 1.0 / 3.0 ) * atan2( sqrt( fabs( phi ) ), q );\n\n c = sqrt_p * cos( phi );\n s = ( 1.0 / sqrt( 3.0 ) ) * sqrt_p * sin( phi );\n\n e( 2 ) = ( 1.0 / 3.0 ) * ( m - c );\n e( 3 ) = e( 2 ) + s;\n e( 1 ) = e( 2 ) + c;\n e( 2 ) -= s;\n\n if ( e( 1 ) > e( 2 ) )\n {\n if ( e( 1 ) > e( 3 ) )\n {\n if ( e( 2 ) > e( 3 ) )\n {\n index = { 0,1,2};\n }\n else\n {\n index = {0,2,1};\n }\n }\n else\n {\n index = { 2,0,1};\n }\n }\n else\n {\n if( e(2) > e(3) )\n {\n if( e(1) > e(3) )\n {\n index = { 1,0,2};\n }\n else\n {\n index = { 1,2,0};\n }\n }\n else\n {\n index = {2,1,0};\n }\n }\n\n for ( unsigned long i( 1 ); i < 4; ++i )\n val( i ) = e( index[i-1]+1 );\n\n double wmax = ( fabs( val( 1 ) ) > fabs( val( 3 ) ) ) ? val( 1 ) : val( 3 );\n double thresh = ( 8.0 * DBL_EPSILON * wmax ) * ( 8.0 * DBL_EPSILON * wmax );\n\n // Prepare calculation of eigenvectors:\n double n0tmp = A( 1, 2 ) * A( 1, 2 ) + A( 1, 3 ) * A( 1, 3 );\n double n1tmp = A( 1, 2 ) * A( 1, 2 ) + A( 2, 3 ) * A( 2, 3 );\n Q( 1, 2 ) = A( 1, 2 ) * A( 2, 3 ) - A( 1, 3 ) * A( 2, 2 );\n Q( 2, 2 ) = A( 1, 3 ) * A( 2, 1 ) - A( 2, 3 ) * A( 1, 1 );\n Q( 3, 2 ) = A( 1, 2 ) * A( 1, 2 );\n\n // Calculate first eigenvector by the formula\n // v(0) = (A - w(0)).e1 x (A - w(0)).e2\n A( 1, 1 ) -= val( 1 );\n A( 2, 2 ) -= val( 1 );\n Q( 1, 1 ) = Q( 1, 2 ) + A( 1, 3 ) * val( 1 );\n Q( 2, 1 ) = Q( 2, 2 ) + A( 2, 3 ) * val( 1 );\n Q( 3, 1 ) = A( 1, 1 ) * A( 2, 2 ) - Q( 3, 2 );\n double norm = Q( 1, 1 ) * Q( 1, 1 ) + Q( 2, 1 ) * Q( 2, 1 ) + Q( 3, 1 ) * Q( 3, 1 );\n double n0 = n0tmp + A( 1, 1 ) * A( 1, 1 );\n double n1 = n1tmp + A( 2, 2 ) * A( 2, 2 );\n double error = n0 * n1;\n double t( 0 ), f( 0 );\n unsigned long i( 0 ), j( 0 );\n\n if ( n0 <= thresh ) // If the first column is zero, then (1,0,0) is an eigenvector\n {\n Q( 1, 1 ) = 1.0;\n Q( 2, 1 ) = 0.0;\n Q( 3, 1 ) = 0.0;\n }\n else if ( n1 <= thresh ) // If the second column is zero, then (0,1,0) is an eigenvector\n {\n Q( 1, 1 ) = 0.0;\n Q( 2, 1 ) = 1.0;\n Q( 3, 1 ) = 0.0;\n }\n else if ( norm < 64.0 * 64.0 * DBL_EPSILON * DBL_EPSILON * error )\n { // If angle between A(0) and A(1) is too small, don't use\n t = A( 1, 2 ) * A( 1, 2 ); // cross product, but calculate v ~ (1, -A0/A1, 0)\n f = -A( 1, 1 ) / A( 1, 2 );\n if ( A( 2, 2 ) * A( 2, 2 ) > t )\n {\n t = A( 2, 2 ) * A( 2, 2 );\n f = -A( 1, 2 ) / A( 2, 2 );\n }\n if ( A( 2, 3 ) * A( 2, 3 ) > t )\n f = -A( 1, 3 ) / A( 2, 3 );\n norm = 1.0 / sqrt( 1 + f * f );\n Q( 1, 1 ) = norm;\n Q( 2, 1 ) = f * norm;\n Q( 3, 1 ) = 0.0;\n }\n else // This is the standard branch\n {\n norm = sqrt( 1.0 / norm );\n for ( j = 1; j < 4; ++j )\n Q( j, 1 ) = Q( j, 1 ) * norm;\n }\n\n // Prepare calculation of second eigenvector\n t = val( 1 ) - val( 2 );\n if ( fabs( t ) > 8.0 * DBL_EPSILON * wmax )\n {\n // For non-degenerate eigenvalue, calculate second eigenvector by the formula\n // v(1) = (A - w(1)).e1 x (A - w(1)).e2\n A( 1, 1 ) += t;\n A( 2, 2 ) += t;\n Q( 1, 2 ) = Q( 1, 2 ) + A( 1, 3 ) * val( 1 );\n Q( 2, 2 ) = Q( 2, 2 ) + A( 2, 3 ) * val( 1 );\n Q( 3, 2 ) = A( 1, 1 ) * A( 2, 2 ) - Q( 3, 2 );\n norm = Q( 1, 2 ) * Q( 1, 2 ) + Q( 2, 2 ) * Q( 2, 2 ) + Q( 3, 2 ) * Q( 3, 2 );\n n0 = n0tmp + A( 1, 1 ) * A( 1, 1 );\n n1 = n1tmp + A( 2, 2 ) * A( 2, 2 );\n error = n0 * n1;\n\n if ( n0 <= thresh ) // If the first column is zero, then (1,0,0) is an eigenvector\n {\n Q( 1, 2 ) = 1.0;\n Q( 2, 2 ) = 0.0;\n Q( 3, 2 ) = 0.0;\n }\n else if ( n1 <= thresh ) // If the second column is zero, then (0,1,0) is an eigenvector\n {\n Q( 1, 2 ) = 0.0;\n Q( 2, 2 ) = 1.0;\n Q( 3, 2 ) = 0.0;\n }\n else if ( norm < 64.0 * DBL_EPSILON * 64.0 * DBL_EPSILON * error )\n { // If angle between A(0) and A(1) is too small, don't use\n t = A( 1, 2 ) * A( 1, 2 ); // cross product, but calculate v ~ (1, -A0/A1, 0)\n f = -A( 1, 1 ) / A( 1, 2 );\n if ( A( 2, 2 ) * A( 2, 2 ) > t )\n {\n t = A( 2, 2 ) * A( 2, 2 );\n f = -A( 1, 2 ) / A( 2, 2 );\n }\n if ( A( 2, 3 ) * A( 2, 3 ) > t )\n f = -A( 1, 3 ) / A( 2, 3 );\n norm = 1.0 / sqrt( 1 + f * f );\n Q( 1, 2 ) = norm;\n Q( 2, 2 ) = f * norm;\n Q( 3, 2 ) = 0.0;\n }\n else\n {\n norm = sqrt( 1.0 / norm );\n for ( j = 1; j < 4; ++j )\n Q( j, 2 ) = Q( j, 2 ) * norm;\n }\n }\n else\n {\n // For degenerate eigenvalue, calculate second eigenvector according to\n // v(1) = v(0) x (A - w(1)).e(i)\n //\n // This would really get to complicated if we could not assume all of A to\n // contain meaningful values.\n A( 2, 1 ) = A( 1, 2 );\n A( 3, 1 ) = A( 1, 3 );\n A( 3, 2 ) = A( 2, 3 );\n A( 1, 1 ) += val( 1 );\n A( 2, 2 ) += val( 1 );\n for ( i = 1; i < 4; ++i )\n {\n A( i, i ) -= val( 2 );\n n0 = A( 1, i ) * A( 1, i ) + A( 2, i ) * A( 2, i ) + A( 3, i ) * A( 3, i );\n if ( n0 > thresh )\n {\n Q( 1, 2 ) = Q( 2, 1 ) * A( 3, i ) - Q( 3, 1 ) * A( 2, i );\n Q( 2, 2 ) = Q( 3, 1 ) * A( 1, i ) - Q( 1, 1 ) * A( 3, i );\n Q( 3, 2 ) = Q( 1, 1 ) * A( 2, i ) - Q( 2, 1 ) * A( 1, i );\n norm = Q( 1, 2 ) * Q( 1, 2 ) + Q( 2, 2 ) * Q( 2, 2 ) + Q( 3, 2 ) * Q( 3, 2 );\n if ( norm > 256.0 * DBL_EPSILON * 256.0 * DBL_EPSILON * n0 ) // Accept cross product only if the angle between\n { // the two vectors was not too small\n norm = sqrt( 1.0 / norm );\n for ( j = 1; j < 4; ++j )\n Q( j, 2 ) = Q( j, 2 ) * norm;\n break;\n }\n }\n }\n\n if ( i == 4 ) // This means that any vector orthogonal to v(0) is an EV.\n {\n for ( j = 1; j < 4; ++j )\n if ( Q( j, 1 ) != 0.0 ) // Find nonzero element of v(0) ...\n { // ... and swap it with the next one\n norm = 1.0 / sqrt( Q( j, 1 ) * Q( j, 1 ) + Q( ( j + 2 ) % 3 + 1, 1 ) * Q( ( j + 1 ) % 3 + 1, 1 ) );\n Q( j, 2 ) = Q( ( j + 1 ) % 3 + 1, 1 ) * norm;\n Q( ( j + 1 ) % 3 + 1, 2 ) = -Q( j, 1 ) * norm;\n Q( ( j + 2 ) % 3 + 1, 2 ) = 0.0;\n break;\n }\n }\n }\n\n // Calculate third eigenvector according to\n // v(2) = v(0) x v(1)\n Q( 1, 3 ) = Q( 2, 1 ) * Q( 3, 2 ) - Q( 3, 1 ) * Q( 2, 2 );\n Q( 2, 3 ) = Q( 3, 1 ) * Q( 1, 2 ) - Q( 1, 1 ) * Q( 3, 2 );\n Q( 3, 3 ) = Q( 1, 1 ) * Q( 2, 2 ) - Q( 2, 1 ) * Q( 1, 2 );\n\n vec.clear();\n for ( int ii( 1 ); ii < 4; ++ii )\n {\n ColumnVector tmp( 3 );\n\n tmp( 1 ) = Q( 1, ii );\n tmp( 2 ) = Q( 2, ii );\n tmp( 3 ) = Q( 3, ii );\n\n vec.push_back( tmp );\n }\n\n}\n\nbool FMath::linePlaneIntersection( QVector3D& contact, QVector3D ray, QVector3D rayOrigin, QVector3D normal, QVector3D coord )\n{\n // calculate plane\n float d = QVector3D::dotProduct( normal, coord );\n\n if ( QVector3D::dotProduct( normal, ray ) == 0 )\n {\n return false; // avoid divide by zero\n }\n\n // Compute the t value for the directed line ray intersecting the plane\n float t = ( d - QVector3D::dotProduct( normal, rayOrigin ) ) / QVector3D::dotProduct( normal, ray );\n\n // scale the ray by t\n QVector3D newRay = ray * t;\n\n // calc contact point\n contact = rayOrigin + newRay;\n\n if ( t >= 0.0f && t <= 1.0f )\n {\n return true; // line intersects plane\n }\n return false; // line does not\n}\n", "meta": {"hexsha": "5eca1173bcd8decc94a75037514d66d74e9ecacd", "size": 37582, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algos/fmath.cpp", "max_stars_repo_name": "rdmenezes/fibernavigator2", "max_stars_repo_head_hexsha": "bbb8bc8ff16790580d5b03fce7e1fad45fae1b91", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algos/fmath.cpp", "max_issues_repo_name": "rdmenezes/fibernavigator2", "max_issues_repo_head_hexsha": "bbb8bc8ff16790580d5b03fce7e1fad45fae1b91", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algos/fmath.cpp", "max_forks_repo_name": "rdmenezes/fibernavigator2", "max_forks_repo_head_hexsha": "bbb8bc8ff16790580d5b03fce7e1fad45fae1b91", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3570274637, "max_line_length": 161, "alphanum_fraction": 0.4148794636, "num_tokens": 14266, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.912436167620237, "lm_q2_score": 0.7154239897159438, "lm_q1q2_score": 0.6527787233999957}} {"text": "#include \n\n#include \n#include \n\n#include \"decode.hpp\"\n\nusing namespace std;\nusing namespace boost::numeric;\nusing boost::dynamic_bitset;\n\n\nstatic const auto parity_mat = [] {\n ublas::matrix parity_m(3, 7);\n vector parity_init = {\n 1, 0, 1, 0, 1, 0, 1,\n 0, 1, 1, 0, 0, 1, 1,\n 0, 0, 0, 1, 1, 1, 1\n };\n\n copy(parity_init.begin(),\n parity_init.end(),\n parity_m.data().begin()\n );\n\n return parity_m;\n}();\n\nstatic const auto decode_mat = [] {\n ublas::matrix decode_m(4, 7);\n vector decode_init = {\n 0, 0, 1, 0, 0, 0, 0,\n 0, 0, 0, 0, 1, 0, 0,\n 0, 0, 0, 0, 0, 1, 0,\n 0, 0, 0, 0, 0, 0, 1\n };\n\n copy(decode_init.begin(),\n decode_init.end(),\n decode_m.data().begin()\n );\n\n return decode_m;\n}();\n\n\noptional parity_check(const ublas::matrix &code_mat) {\n auto syndrome = ublas::prod(parity_mat, code_mat);\n\n dynamic_bitset error_bs;\n for_each(syndrome.begin1(), syndrome.end1(), [&error_bs](auto v) {\n error_bs.push_back(v % 2);\n });\n\n auto error = error_bs.to_ulong();\n\n if (error == 0) { return {}; }\n else { return error - 1; }\n}\n\n\nvector decode(const vector &bytes) {\n dynamic_bitset data;\n data.init_from_block_range(bytes.begin(), bytes.end());\n\n bool back = data[data.size() - 1]; data.pop_back();\n while (!back) {\n back = data[data.size() - 1]; data.pop_back();\n }\n\n dynamic_bitset result;\n\n for (auto p = 0u; p < data.size(); p += 7) {\n ublas::matrix code_mat(7, 1);\n vector code_init;\n\n for (auto i = 0u; i < 7; ++i) {\n code_init.push_back(data[p+i]);\n }\n \n copy(code_init.begin(),\n code_init.end(),\n code_mat.data().begin()\n );\n\n if (auto error = parity_check(code_mat); error) {\n code_mat(error.value(), 0) ^= true;\n }\n\n auto prod = ublas::prod(decode_mat, code_mat);\n\n for_each(prod.begin1(), prod.end1(), [&result] (auto v) {\n result.push_back(v % 2);\n });\n }\n\n vector blocks(result.num_blocks());\n to_block_range(result, blocks.begin());\n\n return blocks;\n}", "meta": {"hexsha": "bfd512c1dd665a0471e15d069f36018b1234c5b5", "size": 2357, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "decode.cpp", "max_stars_repo_name": "Learko/Hamming", "max_stars_repo_head_hexsha": "2241feae7c25f8d4c3475c8b3d6080621ac6106f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "decode.cpp", "max_issues_repo_name": "Learko/Hamming", "max_issues_repo_head_hexsha": "2241feae7c25f8d4c3475c8b3d6080621ac6106f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "decode.cpp", "max_forks_repo_name": "Learko/Hamming", "max_forks_repo_head_hexsha": "2241feae7c25f8d4c3475c8b3d6080621ac6106f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.3366336634, "max_line_length": 70, "alphanum_fraction": 0.5549427238, "num_tokens": 715, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147438, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6527787204187534}} {"text": "//\n// Created by Hamza El-Kebir on 4/17/21.\n//\n\n#ifndef LODESTAR_STATESPACE_HPP\n#define LODESTAR_STATESPACE_HPP\n\n#include \"SystemStateless.hpp\"\n#include \n#include \"Lodestar/aux/CompileTimeQualifiers.hpp\"\n\nnamespace ls {\n namespace systems {\n template\n class StateSpace : public SystemStateless {\n public:\n typedef Eigen::Matrix TDStateMatrix;\n typedef Eigen::Matrix TDInputMatrix;\n typedef Eigen::Matrix TDOutputMatrix;\n typedef Eigen::Matrix TDFeedforwardMatrix;\n\n /**\n * @brief Default constructor.\n */\n StateSpace() : A_(new TDStateMatrix),\n B_(new TDInputMatrix),\n C_(new TDOutputMatrix),\n D_(new TDFeedforwardMatrix),\n dt_(-1), isDiscrete_(false)\n {\n A_->setIdentity();\n B_->setIdentity();\n C_->setIdentity();\n D_->setZero();\n };\n\n /**\n * @brief Construct a state space system with the given matrices.\n *\n * @note TState space systems are assumed to be in continuous time by\n * default.\n *\n * @param A Pointer to state matrix.\n * @param B Pointer to input matrix.\n * @param C Pointer to output matrix.\n * @param D Pointer to feedforward matrix.\n */\n StateSpace(TDStateMatrix *A, TDInputMatrix *B,\n TDOutputMatrix *C, TDOutputMatrix *D);\n\n // /**\n // * @brief Construct a state space system with the given matrices.\n // *\n // * @note TState space systems are assumed to be in continuous time by\n // * default.\n // *\n // * @param A TState matrix.\n // * @param B Input matrix.\n // * @param C Output matrix.\n // * @param D Feedforward matrix.\n // */\n // StateSpace(const TDStateMatrix &A, const TDInputMatrix &B,\n // const TDOutputMatrix &C, const TDOutputMatrix &D);\n\n template\n StateSpace(const Eigen::EigenBase &A, const Eigen::EigenBase &B,\n const Eigen::EigenBase &C, const Eigen::EigenBase &D);\n\n /**\n * @brief Copy constructor.\n *\n * @param other TState space object to copy.\n */\n StateSpace(const StateSpace &other);\n\n /**\n * @brief Gets the state matrix.\n *\n * @return TState matrix.\n */\n const TDStateMatrix &getA() const;\n\n /**\n * @brief Sets the state matrix.\n *\n * @param A Pointer to state matrix.\n */\n void setA(TDStateMatrix *A);\n\n template\n void setA(Eigen::EigenBase *A);\n\n /**\n * @brief Sets the state matrix.\n *\n * @param A TState matrix.\n */\n void setA(const TDStateMatrix &A);\n\n template\n void setA(const Eigen::EigenBase &A);\n\n /**\n * @brief Gets the input matrix.\n *\n * @return Input matrix.\n */\n const TDInputMatrix &getB() const;\n\n /**\n * @brief Sets the input matrix.\n *\n * @param B Pointer to input matrix.\n */\n void setB(TDInputMatrix *B);\n\n template\n void setB(Eigen::EigenBase *B);\n\n /**\n * @brief Sets the input matrix.\n *\n * @param B Input matrix.\n */\n void setB(const TDInputMatrix &B);\n\n template\n void setB(const Eigen::EigenBase &B);\n\n /**\n * @brief Gets the output matrix.\n *\n * @return Output matrix.\n */\n const TDOutputMatrix &getC() const;\n\n /**\n * @brief Sets the output matrix.\n *\n * @param C Pointer to output matrix.\n */\n void setC(TDOutputMatrix *C);\n\n template\n void setC(Eigen::EigenBase *C);\n\n /**\n * @brief Sets the output matrix.\n *\n * @param C Output matrix.\n */\n void setC(const TDOutputMatrix &C);\n\n template\n void setC(const Eigen::EigenBase &C);\n\n /**\n * @brief Gets the feedforward matrix.\n *\n * @return Feedforward matrix.\n */\n const TDFeedforwardMatrix &getD() const;\n\n /**\n * @brief Sets the feedforward matrix.\n *\n * @param D Feedforward matrix.\n */\n void setD(TDFeedforwardMatrix *D);\n\n template\n void setD(Eigen::EigenBase *D);\n\n /**\n * @brief Sets the feedforward matrix.\n *\n * @param D Pointer to feedforward matrix.\n */\n void setD(const TDFeedforwardMatrix &D);\n\n template\n void setD(const Eigen::EigenBase &D);\n\n /**\n * @brief Copies matrices from one state space object to the current\n * instance.\n *\n * @param ss TState space object to copy matrices from.\n */\n void copyMatrices(const StateSpace &other);\n\n /**\n * @brief Sets the discrete time system parameters.\n *\n * @param dt Sampling period.\n */\n void setDiscreteParams(double dt);\n\n /**\n * @brief Sets the discrete time system parameters.\n *\n * @param dt Sampling period.\n * @param discrete If true, the system is treated as a discrete time\n * system.\n */\n void setDiscreteParams(double dt, bool discrete);\n\n /**\n * @brief Returns a bool that tells if the system is discrete.\n *\n * @return True if the system is discrete.\n */\n inline bool isDiscrete() const;\n\n /**\n * @brief Returns the sampling period.\n *\n * @return Sampling period.\n */\n inline double getSamplingPeriod() const;\n\n /**\n * @brief Sets the sampling period.\n *\n * @param dt Sampling period.\n */\n void setSamplingPeriod(double dt);\n\n /**\n * @brief Returns the state dimension.\n *\n * @return TState dimension.\n */\n IF_DYNAMIC_RETURN(TStateDim, TInputDim, TOutputDim, long)\n inline stateDim() const\n {\n return stateDimDynamic();\n }\n\n long inline stateDimDynamic() const\n {\n return A_->rows();\n }\n\n IF_STATIC_RETURN(TStateDim, TInputDim, TOutputDim, long)\n inline stateDim() const\n {\n return stateDimStatic();\n }\n\n long inline stateDimStatic() const\n {\n return TStateDim;\n }\n\n /**\n * @brief Returns the input dimension.\n *\n * @return Input dimension.\n */\n IF_DYNAMIC_RETURN(TStateDim, TInputDim, TOutputDim, long)\n inline inputDim() const\n {\n return inputDimDynamic();\n }\n\n long inline inputDimDynamic() const\n {\n return B_->cols();\n }\n\n IF_STATIC_RETURN(TStateDim, TInputDim, TOutputDim, long)\n inline inputDim() const\n {\n return inputDimStatic();\n }\n\n long inline inputDimStatic() const\n {\n return TInputDim;\n }\n\n /**\n * @brief Returns the output dimension.\n *\n * @return Output dimension\n */\n IF_DYNAMIC_RETURN(TStateDim, TInputDim, TOutputDim, long)\n inline outputDim() const\n {\n return outputDimDynamic();\n }\n\n long inline outputDimDynamic() const\n {\n return C_->rows();\n }\n\n IF_STATIC_RETURN(TStateDim, TInputDim, TOutputDim, long)\n inline outputDim() const\n {\n return outputDimStatic();\n }\n\n long inline outputDimStatic() const\n {\n return TOutputDim;\n }\n\n /**\n * @brief Appends to state space systems.\n *\n * If the discrete time parameters do not match the current system,\n * the input system is altered to match the current system.\n *\n * @param ss TState space system to append.\n */\n template\n void append(const StateSpace &ss);\n\n /**\n * @brief Determines if the system is stable based on its\n * eigenvalues.\n *\n * \\p tolerance sets the stability margin that is taken into\n * account during computation.\n *\n * @param tolerance Eigenvalue tolerance.\n * @return True if system is stable.\n */\n inline bool isStable(double tolerance = 0) const;\n\n /**\n * @brief Returns a state space representation that adds integral action to the original system.\n *\n * @details For details on the discrete time case, see [1].\n *\n * @sa D. D. Ruscio, “Discrete LQ optimal control with integral action: A simple controller on incremental\n * form for MIMO systems,” MIC, vol. 33, no. 2, pp. 35–44, 2012, doi:\n * 10.4173/mic.2012.2.1.\n *\n * @note This particular function gets called when the state space system is dynamic.\n *\n * @tparam T_TScalar Copy of \\c TScalar.\n * @tparam T_TStateDim Copy of \\c TStateDim.\n * @tparam T_TInputDim Copy of \\c TInputDim.\n * @tparam T_TOutputDim Copy of \\c TOutputDim.\n *\n * @return State space system augmented with integral action.\n */\n template\n ls::systems::StateSpace\n addIntegralAction(LS_IS_DYNAMIC_DEFAULT(T_TStateDim, T_TInputDim, T_TOutputDim)) const;\n\n /**\n * @brief Returns a state space representation that adds integral action to the original system.\n *\n * @details For details on the discrete time case, see [1].\n *\n * @sa [1] D. D. Ruscio, “Discrete LQ optimal control with integral action: A simple controller on\n * incremental form for MIMO systems,” MIC, vol. 33, no. 2, pp. 35–44, 2012, doi:\n * 10.4173/mic.2012.2.1.\n *\n * @note This particular function gets called when the state space system is static.\n *\n * @tparam T_TScalar Copy of \\c TScalar.\n * @tparam T_TStateDim Copy of \\c TStateDim.\n * @tparam T_TInputDim Copy of \\c TInputDim.\n * @tparam T_TOutputDim Copy of \\c TOutputDim.\n *\n * @return State space system augmented with integral action.\n */\n template\n ls::systems::StateSpace\n addIntegralAction(LS_IS_STATIC_DEFAULT(T_TStateDim, T_TInputDim, T_TOutputDim)) const;\n\n protected:\n TDStateMatrix *A_; //! TState matrix.\n TDInputMatrix *B_; //! Input matrix.\n TDOutputMatrix *C_; //! Output matrix.\n TDFeedforwardMatrix *D_; //! Feedforward matrix.\n double dt_; //! Sampling period.\n bool isDiscrete_; //! Discrete flag.\n };\n }\n}\n\ntemplate\nls::systems::StateSpace::StateSpace(\n const StateSpace &other):\n A_(new TDStateMatrix(other.getA())),\n B_(new TDInputMatrix(other.getB())),\n C_(new TDOutputMatrix(other.getC())),\n D_(new TDFeedforwardMatrix(other.getD())),\n dt_(other.getSamplingPeriod()),\n isDiscrete_(other.isDiscrete())\n{}\n\n// TODO: Replace constructors by Eigen::EigenBase<*>\ntemplate\nls::systems::StateSpace::StateSpace(\n TDStateMatrix *A, TDInputMatrix *B,\n TDOutputMatrix *C, TDOutputMatrix *D):\n A_(new TDStateMatrix(*A)),\n B_(new TDInputMatrix(*B)),\n C_(new TDOutputMatrix(*C)),\n D_(new TDFeedforwardMatrix(*D))\n{\n // *A_ = *A;\n // *B_ = *B;\n // *C_ = *C;\n // *D_ = *D;\n dt_ = -1;\n isDiscrete_ = false;\n}\n\n//template\n//ls::systems::StateSpace::StateSpace(\n// const TDStateMatrix &A, const TDInputMatrix &B,\n// const TDOutputMatrix &C, const TDOutputMatrix &D) : A_(new TDStateMatrix(A)), B_(new TDInputMatrix(B)),\n// C_(new TDOutputMatrix(C)), D_(new TDFeedforwardMatrix(D))\n//{\n//// *A_ = A;\n//// *B_ = B;\n//// *C_ = C;\n//// *D_ = D;\n// dt_ = -1;\n// isDiscrete_ = false;\n//}\n\ntemplate\ntemplate\nls::systems::StateSpace::StateSpace(const Eigen::EigenBase &A,\n const Eigen::EigenBase &B,\n const Eigen::EigenBase &C,\n const Eigen::EigenBase &D):\n A_(new TDStateMatrix(A)),\n B_(new TDInputMatrix(B)),\n C_(new TDOutputMatrix(C)),\n D_(new TDFeedforwardMatrix(D))\n{\n *A_ = A;\n *B_ = B;\n *C_ = C;\n *D_ = D;\n dt_ = -1;\n isDiscrete_ = false;\n}\n\ntemplate\nconst typename ls::systems::StateSpace::TDStateMatrix &\nls::systems::StateSpace::getA() const\n{\n return *A_;\n}\n\ntemplate\nvoid ls::systems::StateSpace::setA(TDStateMatrix *A)\n{\n *A_ = *A;\n}\n\ntemplate\ntemplate\nvoid ls::systems::StateSpace::setA(Eigen::EigenBase *A)\n{\n *A_ = *A;\n}\n\ntemplate\nvoid ls::systems::StateSpace::setA(\n const TDStateMatrix &A)\n{\n *A_ = A;\n}\n\ntemplate\ntemplate\nvoid ls::systems::StateSpace::setA(const Eigen::EigenBase &A)\n{\n *A_ = A;\n}\n\ntemplate\nconst typename ls::systems::StateSpace::TDInputMatrix &\nls::systems::StateSpace::getB() const\n{\n return *B_;\n}\n\ntemplate\nvoid ls::systems::StateSpace::setB(TDInputMatrix *B)\n{\n *B_ = *B;\n}\n\ntemplate\ntemplate\nvoid ls::systems::StateSpace::setB(Eigen::EigenBase *B)\n{\n *B_ = *B;\n}\n\ntemplate\nvoid ls::systems::StateSpace::setB(\n const TDInputMatrix &B)\n{\n *B_ = B;\n}\n\ntemplate\ntemplate\nvoid ls::systems::StateSpace::setB(const Eigen::EigenBase &B)\n{\n *B_ = B;\n}\n\ntemplate\nconst typename ls::systems::StateSpace::TDOutputMatrix &\nls::systems::StateSpace::getC() const\n{\n return *C_;\n}\n\ntemplate\nvoid\nls::systems::StateSpace::setC(TDOutputMatrix *C)\n{\n *C_ = *C;\n}\n\ntemplate\ntemplate\nvoid ls::systems::StateSpace::setC(Eigen::EigenBase *C)\n{\n *C_ = *C;\n}\n\ntemplate\nvoid ls::systems::StateSpace::setC(\n const TDOutputMatrix &C)\n{\n *C_ = C;\n}\n\ntemplate\ntemplate\nvoid ls::systems::StateSpace::setC(const Eigen::EigenBase &C)\n{\n *C_ = C;\n}\n\ntemplate\nconst typename ls::systems::StateSpace::TDFeedforwardMatrix &\nls::systems::StateSpace::getD() const\n{\n return *D_;\n}\n\ntemplate\nvoid ls::systems::StateSpace::setD(\n TDFeedforwardMatrix *D)\n{\n *D_ = *D;\n}\n\ntemplate\ntemplate\nvoid ls::systems::StateSpace::setD(Eigen::EigenBase *D)\n{\n *D_ = *D;\n}\n\ntemplate\nvoid ls::systems::StateSpace::setD(\n const TDFeedforwardMatrix &D)\n{\n *D_ = D;\n}\n\ntemplate\ntemplate\nvoid ls::systems::StateSpace::setD(const Eigen::EigenBase &D)\n{\n *D_ = D;\n}\n\ntemplate\nbool ls::systems::StateSpace::isDiscrete() const\n{\n return isDiscrete_;\n}\n\ntemplate\ndouble ls::systems::StateSpace::getSamplingPeriod() const\n{\n return dt_;\n}\n\ntemplate\nvoid ls::systems::StateSpace::setSamplingPeriod(double dt)\n{\n dt_ = dt;\n}\n\ntemplate\nvoid ls::systems::StateSpace::setDiscreteParams(double dt)\n{\n dt_ = dt;\n isDiscrete_ = true;\n}\n\ntemplate\nvoid ls::systems::StateSpace::setDiscreteParams(double dt, bool discrete)\n{\n dt_ = dt;\n isDiscrete_ = discrete;\n}\n\ntemplate\ntemplate\nvoid ls::systems::StateSpace::append(\n const ls::systems::StateSpace &ss)\n{\n // TODO: Implement state space append function.\n}\n\ntemplate\nbool ls::systems::StateSpace::isStable(const double tolerance) const\n{\n auto eig = A_->eigenvalues();\n\n if (isDiscrete()) {\n double tol = (tolerance < 0 ? -tolerance * tolerance : tolerance * tolerance);\n\n for (int i = 0; i < eig.size(); i++) {\n if (eig(i).real() * eig(i).real() + eig(i).imag() * eig(i).imag() > 1 + tol)\n return false;\n }\n } else {\n for (int i = 0; i < eig.size(); i++) {\n if (eig(i).real() > -tolerance)\n return false;\n }\n }\n\n return true;\n}\n\ntemplate\nvoid ls::systems::StateSpace::copyMatrices(\n const ls::systems::StateSpace &other)\n{\n setA(other.getA());\n setB(other.getB());\n setC(other.getC());\n setD(other.getD());\n\n}\n\ntemplate\ntemplate\nls::systems::StateSpace\nls::systems::StateSpace::addIntegralAction(\n LS_IS_DYNAMIC(T_TStateDim, T_TInputDim, T_TOutputDim)) const\n{\n Eigen::Matrix A(stateDim() + outputDim(), stateDim() + outputDim());\n A.setZero();\n A.topLeftCorner(stateDim(), stateDim()) = getA();\n A.bottomLeftCorner(outputDim(), stateDim()) = getC();\n A.bottomRightCorner(outputDim(), outputDim()).setIdentity();\n\n Eigen::Matrix B(stateDim() + outputDim(), inputDim());\n B.setZero();\n B.topRows(stateDim()) = getB();\n\n Eigen::Matrix C(outputDim(), stateDim() + outputDim());\n C.setZero();\n C.leftCols(stateDim()) = getC();\n C.rightCols(outputDim()).setIdentity();\n\n Eigen::Matrix D(outputDim(), inputDim());\n D = getD();\n\n ls::systems::StateSpace ssi{A, B, C, D};\n\n return ssi;\n}\n\ntemplate\ntemplate\nls::systems::StateSpace\nls::systems::StateSpace::addIntegralAction(\n LS_IS_STATIC(T_TStateDim, T_TInputDim, T_TOutputDim)) const\n{\n Eigen::Matrix A{};\n A.setZero();\n A.template topLeftCorner() = getA();\n A.template bottomLeftCorner() = getC();\n A.template bottomRightCorner().setIdentity();\n\n Eigen::Matrix B{};\n B.setZero();\n B.template topRows() = getB();\n\n Eigen::Matrix C{};\n C.setZero();\n C.template leftCols() = getC();\n C.template rightCols().setIdentity();\n\n Eigen::Matrix D{};\n D = getD();\n\n ls::systems::StateSpace ssi{A, B, C, D};\n\n return ssi;\n}\n\n#endif //LODESTAR_STATESPACE_HPP", "meta": {"hexsha": "849949f530b85a2be95a6f3c3d0376039ca32174", "size": 26022, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Lodestar/systems/StateSpace.hpp", "max_stars_repo_name": "helkebir/Lodestar", "max_stars_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2020-06-05T14:08:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-26T22:15:31.000Z", "max_issues_repo_path": "Lodestar/systems/StateSpace.hpp", "max_issues_repo_name": "helkebir/Lodestar", "max_issues_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-06-25T15:14:01.000Z", "max_issues_repo_issues_event_max_datetime": "2021-07-01T17:43:20.000Z", "max_forks_repo_path": "Lodestar/systems/StateSpace.hpp", "max_forks_repo_name": "helkebir/Lodestar", "max_forks_repo_head_hexsha": "6b325d3e7a388676ed31d44eac1146630ee4bb2c", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-16T03:15:23.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-16T03:15:23.000Z", "avg_line_length": 35.9917012448, "max_line_length": 158, "alphanum_fraction": 0.5929982323, "num_tokens": 6349, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396142, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6527672616759989}} {"text": "#include \n#include \n#include \n\n#include \n\n#include \"timer.h\"\n\n//! \\brief Structure holding a triplet in format (row, col, value)\n//! For convenience, we provide a void constructor and a init constructor. All members are public\n//! Used in the TripletMatrix class to provide a nice wrapper for a triplet\n//! \\tparam scalar represents the type of the triplet (e.g. double)\ntemplate \nstruct Triplet {\n Triplet(void)\n : i(0), j(0), v(0) { }\n \n Triplet(std::size_t i_, std::size_t j_, scalar v_)\n : i(i_), j(j_), v(v_) { }\n \n std::size_t i, j; //< row and col\n scalar v; //< value @ (row,col)\n};\n\n//! \\brief Defines a matrix stored in triplet format (using the Triplet class.\n//! Triplets may be duplicated and in *any* order. If there is a multiple triplet for (row,col) pair, we assume\n//! that the values are intended to be added together\n//! Also stores dimension\n//! \\tparam scalar represents the scalar type of the matrix (and of the triplet) (e.g. double)\ntemplate \nstruct TripletMatrix {\n std::size_t rows, cols; //< Sizes: nrows and ncols\n std::vector< Triplet > triplets;\n \n //! \\brief Converts *this to an eigen (dense) function, used for visualization\n //! Loops over all triplets and add value to Zero matrix (read-only)\n //! WARNING: just for debug, may fill-in a lot of nonzeros if n,m >> 1\n //! \\return Eigen::Matrix of Dynamic size and scalar type\n Eigen::Matrix densify() const {\n Eigen::Matrix M = Eigen::Matrix::Zero(rows, cols);\n for(auto it = triplets.begin(); it != triplets.end(); ++it) {\n M(it->i, it->j) += it->v;\n }\n return M;\n }\n};\n\n// const TripletMatrix;\n\n//! \\brief Structure holding a pair column index-value to be used in CRS format\n//! Provides handy constructor and comparison operators.\n//! \\tparam scalar represents the scalar type of the value stored (e.g. double)\ntemplate \nstruct ColValPair {\n ColValPair(std::size_t col_, scalar v_)\n : col(col_), v(v_) { }\n \n //! \\brief Comparison operator for std::sort and std::lower_bound\n //! Basic sorting operator < for use with std:: functions (i.e. for ordering according to first component (col)\n //! We keep the column values sorted, either by sorting after insertion of by sorted insertion\n //! \\return true if this->col < other.col\n bool operator<(const ColValPair & other) const {\n return this->col < other.col;\n }\n \n std::size_t col; //< col index\n scalar v; //< scalar value at col\n};\n\n//! \\brief Defines a matrix stored in CRS format (using the ColValPair struct.\n//! The row_pt contains the data, indexed by row and column position\n//! Also stores dimension\n//! \\tparam scalar represents the scalar type of the matrix (and of the ColValPair) (e.g. double)\ntemplate \nstruct CRSMatrix {\n std::size_t rows, cols; //< Size of the matrix rows, cols\n std::vector< std::vector< ColValPair > > row_pt; //< Vector containing, for each row, al vector of (col, value) pairs (CRS format)\n \n //! \\brief Converts *this to an eigen (dense) function, used for visualization\n //! Loops over all rows and add value at col (in ColValPair) to Zero matrix (read-only)\n //! WARNING: just for debug, may fill-in a lot of nonzeros if n,m >> 1\n //! \\return Eigen::Matrix of Dynamic size and scalar type\n Eigen::Matrix densify() const {\n Eigen::Matrix M = Eigen::Matrix::Zero(rows, cols);\n std::size_t i = 0;\n for(auto it = row_pt.begin(); it != row_pt.end(); ++it) {\n for(auto it2 = it->begin(); it2 != it->end(); ++it2) {\n M(i, it2->col) = it2->v;\n }\n ++i;\n }\n return M;\n }\n};\n\n//! \\brief Converts a matrix given as triplet matrix to a matrix in CRS format\n//! No assumption is made on the triplets, may be unsorted and/or duplicated\n//! In case of duplicated triplets, values are added toghether\n//! The output CRS matrix may be empty (in that case T = C) or may be already filled with values (in which case C += T)\n//! This version inserts the ColValParis already sorted in the list\n//! Complexity: loops over all triplets (lets say k) and look up over all columns of the row (say n_i), performing a\n//! linear search and an insertion (complexity O(n_i))\n//! Assuming n_i is bounded by n small, complexity is k*n, otherwise k^2\ntemplate \nvoid tripletToCRS(const TripletMatrix & T, CRSMatrix & C) {\n // Copy sizes and reserve memory for rows\n C.rows = T.rows;\n C.cols = T.cols;\n C.row_pt.resize(C.rows);\n \n // Loop over all triplets\n for(auto triplet_it = T.triplets.begin(); triplet_it != T.triplets.end(); ++triplet_it) {\n // Store row (containing the ColValPairs for this row) inside the row_pt vector\n auto & row = C.row_pt.at(triplet_it->i);\n // Create a ColVal pair that must be inserted somewhere\n ColValPair col_val(triplet_it->j, triplet_it->v);\n // Find the place (as iterator) where to insert col_val, i.e. the first place where col_val < C.row_pt.at(i)\n // WARNING: Costly call (loops over all of row (worts case scenario))\n auto lb_it = std::lower_bound(row.begin(), row.end(), col_val);\n // If lower bound has already a col (and is not end()) with some value, just add the value to the column, othervise insert it\n if(lb_it != row.end() && lb_it->col == triplet_it->j) {\n lb_it->v += triplet_it->v;\n } else {\n // WARNING: Costly call (loops over all of row (worts case scenario))\n row.insert(lb_it, col_val);\n }\n }\n}\n\n//! \\brief Converts a matrix given as triplet matrix to a matrix in CRS format\n//! No assumption is made on the triplets, may be unsorted and/or duplicated\n//! In case of duplicated triplets, values are added toghether\n//! The output CRS matrix may be empty (in that case T = C) or may be already filled with values (in which case C += T)\n//! This version inserts all the triplets (push_back) then sorts eatch row and cumsum al the duplicated col values\n//! *** Complexity: loops over all triplets (lets say k) and do a cheap (amortized) o(1) push back (complexity k*1). Then sorts an array\n//! of rows (ith quicksort complexity k * log(k))\ntemplate \nvoid tripletToCRS_sortafter(const TripletMatrix & T, CRSMatrix & C) {\n // Copy dimensions and reserve known space\n C.rows = T.rows;\n C.cols = T.cols;\n C.row_pt.resize(C.rows);\n \n // Loops over all triplets and push them at the ritgh place (cheap)\n for(auto triplets_it = T.triplets.begin(); triplets_it != T.triplets.end(); ++triplets_it) {\n ColValPair cp(triplets_it->j, triplets_it->v);\n C.row_pt.at(triplets_it->i).push_back(cp);\n }\n // Loops over all rows , sort them (according to col) and sum duplicated values\n for(auto row_it = C.row_pt.begin(); row_it != C.row_pt.end(); ++row_it) {\n // WARNING: costly call in this case\n std::sort(row_it->begin(), row_it->end());\n // Sum duplicated cols\n // NOTE: iterating backwards should be faster\n for(auto col_it = row_it->begin(); col_it != row_it->end(); ++col_it) {\n // Check that next col is not at the end and that has same col value\n if((col_it + 1) != row_it->end() && (col_it + 1)->col == col_it->col) {\n // Last col with same value (starting from next col)\n auto last_col_it = col_it + 1;\n while(last_col_it != row_it->end() && last_col_it->col == col_it->col) {\n col_it->v += last_col_it->v;\n ++last_col_it;\n }\n // Remove range from next col to last col with same value\n // WARNING: std::vector keeps the data as c-array, so mildly costly call (from col_it to end() (at most M)\n row_it->erase(col_it+1, last_col_it);\n }\n }\n }\n}\n\n//! \\brief overload of operator << for output of Triplet Matrix (debug).\n//! WARNING: uses densify() so there may be a lot of fill-in\n//! \\param o standard output stream\n//! \\param S matrix in Triplet matrix format\n//! \\return a ostream o, s.t. you can write o << A << B;\nstd::ostream & operator<<(std::ostream & o, const TripletMatrix & S) {\n return o << S.densify();\n}\n\n//! \\brief overload of operator << for output of CRS Matrix (debug).\n//! WARNING: uses densify() so there may be a lot of fill-in\n//! \\param o standard output stream\n//! \\param S matrix in CRS matrix format\n//! \\return a ostream o, s.t. you can write o << A << B;\nstd::ostream & operator<<(std::ostream & o, const CRSMatrix & S) {\n return o << S.densify();\n}\n\nint main() {\n //// Correctness test\n std::size_t nrows = 7, ncols = 5, ntriplets = 9;\n \n TripletMatrix T;\n CRSMatrix C,D;\n \n T.rows = nrows;\n T.cols = ncols;\n T.triplets.reserve(ntriplets); // Always reserve space if you can\n for(auto i = 0u; i < ntriplets; ++i) {\n // Test unordered triplets, random and maybe repeated triplets\n T.triplets.push_back(Triplet(rand() % nrows, rand() % ncols, rand() % 1000));\n }\n \n std::cout << \"***Test conversion with random matrices***\" << std::endl;\n tripletToCRS(T, C);\n std::cout << \"--> Frobenius norm of T - C: \" << (T.densify()-C.densify()).norm() << std::endl;\n std::cout << \"T = \" << std::endl << T << std::endl;\n std::cout << \"C = \" << std::endl << C << std::endl;\n \n tripletToCRS_sortafter(T, D);\n std::cout << \"--> Frobenius norm of T - D: \" << (T.densify()-D.densify()).norm() << std::endl;\n std::cout << \"D = \" << D << std::endl;\n \n // Big benefit of how we defined our functions: can add new triplets to the old ones:\n std::cout << \"***Test addition with random matrices***\" << std::endl;\n TripletMatrix T2;\n T2.rows = nrows;\n T2.cols = ncols;\n T2.triplets.reserve(ntriplets); // Always reserve space if you can\n for(auto i = 0u; i < ntriplets; ++i) {\n // Test unordered triplets, random and maybe repeated triplets\n T2.triplets.push_back(Triplet(rand() % nrows, rand() % ncols, rand() % 1000));\n }\n tripletToCRS(T2, C);\n tripletToCRS_sortafter(T2, D);\n std::cout << \"T = \" << std::endl << T << std::endl;\n std::cout << \"T2 = \" << std::endl << T2 << std::endl;\n std::cout << \"C = \" << std::endl << C << std::endl;\n std::cout << \"D = \" << std::endl << D << std::endl;\n \n //// Runtime test\n bool noruntime = false; // Skip runtime measurments\n bool noaddition = true; // Do not test addition of new triplets\n \n if(noruntime) {\n return 0;\n }\n std::cout << \"***Runtime test***\" << std::endl;\n \n // Play around with this parameters (also introducing lambda functions)\n auto frows = [](std::size_t M) { return 2*M; };\n auto fcols = [](std::size_t M) { return M; };\n auto ftriplets = [](std::size_t M) { return M*5; };\n \n // Do some timings\n timer<> sortafter_timer, insertsort_timer;\n for(std::size_t M = 2u; M < 1024u; M *= 2u) {\n sortafter_timer.reset();\n insertsort_timer.reset();\n std::cout << \"Runtime for \" << M << \"x\" << M/2 << \" matrix (with nnz(A) <= \" << M << \"):\" << std::endl;\n for(int r = 0; r < 4; ++r) {\n \n TripletMatrix A;\n CRSMatrix B, E;\n \n A.rows = frows(M); // nrows\n A.cols = fcols(M); //ncols\n A.triplets.reserve(ftriplets(M));\n for(auto i = 0u; i < ftriplets(M); ++i) {\n A.triplets.push_back(Triplet(rand() % A.rows, rand() % A.cols, rand() % 1000));\n }\n \n insertsort_timer.start();\n tripletToCRS(A, B);\n if(!noaddition) tripletToCRS(A, B);\n insertsort_timer.stop();\n \n sortafter_timer.start();\n tripletToCRS_sortafter(A, E);\n if(!noaddition) tripletToCRS_sortafter(A, E);\n sortafter_timer.stop();\n }\n std::cout << \"Insertsort took: \" << insertsort_timer.min().count() / 1000. << \" ms.\" << std::endl;\n std::cout << \"Sortafter took: \" << sortafter_timer.min().count() / 1000. << \" ms.\" << std::endl;\n }\n}\n", "meta": {"hexsha": "0b96a41d4912a1b489a9b271c001904ecc50cb24", "size": 12548, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS3/solutions_ps3/tripletToCRS_solution.cpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS3/tripletToCRS_solution.cpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS3/tripletToCRS_solution.cpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.1366906475, "max_line_length": 142, "alphanum_fraction": 0.6119700351, "num_tokens": 3391, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998714925403, "lm_q2_score": 0.8397339616560072, "lm_q1q2_score": 0.6527251004831361}} {"text": "/*=============================================================================\n Copyright (c) 2010-2016 Bolero MURAKAMI\n https://github.com/bolero-MURAKAMI/Sprig\n\n Distributed under the Boost Software License, Version 1.0. (See accompanying\n file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n=============================================================================*/\n#ifndef SPRIG_UBLAS_MATRIX_HPP\n#define SPRIG_UBLAS_MATRIX_HPP\n\n#include \n\n#ifdef SPRIG_USING_PRAGMA_ONCE\n#\tpragma once\n#endif\t// #ifdef SPRIG_USING_PRAGMA_ONCE\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace sprig {\n\tnamespace ublas {\n\t\t//\n\t\t// make_scaling_matrix_2d\n\t\t//\n\t\ttemplate\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix make_scaling_matrix_2d(T const sx, T const sy) {\n\t\t\tboost::numeric::ublas::matrix mat = boost::numeric::ublas::identity_matrix(3);\n\t\t\tmat(0, 0) = sx;\n\t\t\tmat(1, 1) = sy;\n\t\t\treturn mat;\n\t\t}\n\t\t//\n\t\t// make_rotation_matrix_2d\n\t\t//\n\t\ttemplate\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix make_rotation_matrix_2d(T const a) {\n\t\t\tboost::numeric::ublas::matrix mat = boost::numeric::ublas::identity_matrix(3);\n\t\t\tmat(0, 0) = std::cos(a);\n\t\t\tmat(0, 1) = std::sin(a);\n\t\t\tmat(1, 0) = -mat(0, 1);\n\t\t\tmat(1, 1) = mat(0, 0);\n\t\t\treturn mat;\n\t\t}\n\t\t//\n\t\t// make_translation_matrix_2d\n\t\t//\n\t\ttemplate\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix make_translation_matrix_2d(T const tx, T const ty) {\n\t\t\tboost::numeric::ublas::matrix mat = boost::numeric::ublas::identity_matrix(3);\n\t\t\tmat(2, 0) = tx;\n\t\t\tmat(2, 1) = ty;\n\t\t\treturn mat;\n\t\t}\n\t\t//\n\t\t// matrix_prod\n\t\t//\n\t\ttemplate\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix matrix_prod(\n\t\t\tboost::numeric::ublas::matrix const& m1,\n\t\t\tboost::numeric::ublas::matrix const& m2\n\t\t\t)\n\t\t{\n\t\t\treturn boost::numeric::ublas::prod(m1, m2);\n\t\t}\n\t\ttemplate\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix matrix_prod(\n\t\t\tboost::numeric::ublas::matrix const& m1,\n\t\t\tboost::numeric::ublas::matrix const& m2,\n\t\t\tboost::numeric::ublas::matrix const& m3\n\t\t\t)\n\t\t{\n\t\t\treturn boost::numeric::ublas::prod(matrix_prod(m1, m2), m3);\n\t\t}\n\t\ttemplate\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix matrix_prod(\n\t\t\tboost::numeric::ublas::matrix const& m1,\n\t\t\tboost::numeric::ublas::matrix const& m2,\n\t\t\tboost::numeric::ublas::matrix const& m3,\n\t\t\tboost::numeric::ublas::matrix const& m4\n\t\t\t)\n\t\t{\n\t\t\treturn boost::numeric::ublas::prod(matrix_prod(m1, m2, m3), m4);\n\t\t}\n\t\ttemplate\n\t\tSPRIG_INLINE boost::numeric::ublas::matrix matrix_prod(\n\t\t\tboost::numeric::ublas::matrix const& m1,\n\t\t\tboost::numeric::ublas::matrix const& m2,\n\t\t\tboost::numeric::ublas::matrix const& m3,\n\t\t\tboost::numeric::ublas::matrix const& m4,\n\t\t\tboost::numeric::ublas::matrix const& m5\n\t\t\t)\n\t\t{\n\t\t\treturn boost::numeric::ublas::prod(matrix_prod(m1, m2, m3, m4), m5);\n\t\t}\n\t\t//\n\t\t// scaling_2d\n\t\t//\n\t\ttemplate\n\t\tclass scaling_2d {\n\t\tpublic:\n\t\t\ttypedef T value_type;\n\t\t\ttypedef boost::numeric::ublas::matrix matrix_type;\n\t\tprivate:\n\t\t\tboost::array elems_;\n\t\tpublic:\n\t\t\tscaling_2d() {\n\t\t\t\telems_[0] = value_type();\n\t\t\t\telems_[1] = value_type();\n\t\t\t}\n\t\t\tscaling_2d(\n\t\t\t\ttypename boost::call_traits::param_type v1,\n\t\t\t\ttypename boost::call_traits::param_type v2\n\t\t\t\t)\n\t\t\t{\n\t\t\t\telems_[0] = v1;\n\t\t\t\telems_[1] = v2;\n\t\t\t}\n\t\t\tmatrix_type matrix() const{\n\t\t\t\treturn make_scaling_matrix_2d(elems_[0], elems_[1]);\n\t\t\t}\n\t\t\ttemplate\n\t\t\tvalue_type const& get() const {\n\t\t\t\treturn elems_[N];\n\t\t\t}\n\t\t\ttemplate\n\t\t\tvalue_type& get() {\n\t\t\t\treturn elems_[N];\n\t\t\t}\n\t\t};\n\t\t//\n\t\t// rotation_2d\n\t\t//\n\t\ttemplate\n\t\tclass rotation_2d {\n\t\tpublic:\n\t\t\ttypedef T value_type;\n\t\t\ttypedef boost::numeric::ublas::matrix matrix_type;\n\t\tprivate:\n\t\t\tboost::array elems_;\n\t\tpublic:\n\t\t\trotation_2d() {\n\t\t\t\telems_[0] = value_type();\n\t\t\t}\n\t\t\trotation_2d(\n\t\t\t\ttypename boost::call_traits::param_type v1\n\t\t\t\t)\n\t\t\t{\n\t\t\t\telems_[0] = v1;\n\t\t\t}\n\t\t\tmatrix_type matrix() const{\n\t\t\t\treturn make_rotation_matrix_2d(elems_[0]);\n\t\t\t}\n\t\t\ttemplate\n\t\t\tvalue_type const& get() const {\n\t\t\t\treturn elems_[N];\n\t\t\t}\n\t\t\ttemplate\n\t\t\tvalue_type& get() {\n\t\t\t\treturn elems_[N];\n\t\t\t}\n\t\t};\n\t\t//\n\t\t// translation_2d\n\t\t//\n\t\ttemplate\n\t\tclass translation_2d {\n\t\tpublic:\n\t\t\ttypedef T value_type;\n\t\t\ttypedef boost::numeric::ublas::matrix matrix_type;\n\t\tprivate:\n\t\t\tboost::array elems_;\n\t\tpublic:\n\t\t\ttranslation_2d() {\n\t\t\t\telems_[0] = value_type();\n\t\t\t\telems_[1] = value_type();\n\t\t\t}\n\t\t\ttranslation_2d(\n\t\t\t\ttypename boost::call_traits::param_type v1,\n\t\t\t\ttypename boost::call_traits::param_type v2\n\t\t\t\t)\n\t\t\t{\n\t\t\t\telems_[0] = v1;\n\t\t\t\telems_[1] = v2;\n\t\t\t}\n\t\t\tmatrix_type matrix() const{\n\t\t\t\treturn make_translation_matrix_2d(elems_[0], elems_[1]);\n\t\t\t}\n\t\t\ttemplate\n\t\t\tvalue_type const& get() const {\n\t\t\t\treturn elems_[N];\n\t\t\t}\n\t\t\ttemplate\n\t\t\tvalue_type& get() {\n\t\t\t\treturn elems_[N];\n\t\t\t}\n\t\t};\n\t}\t// namespace ublas\n}\t// namespace sprig\n\n#endif\t// #ifndef SPRIG_UBLAS_MATRIX_HPP\n", "meta": {"hexsha": "c386800b92d4e4430e0c4d282d8091135918cb07", "size": 5349, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "sprig/ublas/matrix.hpp", "max_stars_repo_name": "bolero-MURAKAMI/Sprig", "max_stars_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2017-10-24T13:56:24.000Z", "max_stars_repo_stars_event_max_datetime": "2018-09-28T13:21:22.000Z", "max_issues_repo_path": "sprig/ublas/matrix.hpp", "max_issues_repo_name": "bolero-MURAKAMI/Sprig", "max_issues_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sprig/ublas/matrix.hpp", "max_forks_repo_name": "bolero-MURAKAMI/Sprig", "max_forks_repo_head_hexsha": "51ce4db4f4d093dee659a136f47249e4fe91fc7a", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2016-04-12T03:26:06.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-28T13:21:22.000Z", "avg_line_length": 26.2205882353, "max_line_length": 100, "alphanum_fraction": 0.6389979435, "num_tokens": 1719, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339636614181, "lm_q2_score": 0.7772998560157665, "lm_q1q2_score": 0.6527250890455691}} {"text": "#include \n#include \n#include \n#include \n\n#include \n\nusing namespace boost::geometry;\n\ntemplate\n<\n typename Point\n>\nstruct triangle {\n Point p1,p2,p3;\n std::vector adjacent_indices;\n};\n\ntemplate\n<\n typename Area,\n typename Point\n>\nArea triangle_double_area(const Point& p1, const Point& p2, const Point& p3) {\n return std::abs(boost::numeric_cast(get<0>(p1))*boost::numeric_cast(get<1>(p2))-boost::numeric_cast(get<0>(p1))*boost::numeric_cast(get<1>(p3))+boost::numeric_cast(get<0>(p2))*boost::numeric_cast(get<1>(p3))-boost::numeric_cast(get<0>(p2))*boost::numeric_cast(get<1>(p1))+boost::numeric_cast(get<0>(p3))*boost::numeric_cast(get<1>(p1))-boost::numeric_cast(get<0>(p3))*boost::numeric_cast(get<1>(p2)));\n}\n\ntemplate\n<\n typename Point\n>\ndouble circumcircle_diameter(const Point& p1, const Point& p2, const Point& p3)\n{\n return distance(p1,p2)*distance(p1,p3)*distance(p2,p3)/triangle_double_area(p1,p2,p3);\n}\n\n\ntemplate\n<\n typename Point\n>\nPoint circumcircle_center(const Point& p1, const Point& p2, const Point& p3)\n{\n auto ax = get<0>(p1);\n auto ay = get<1>(p1);\n auto bx = get<0>(p2);\n auto by = get<1>(p2);\n auto cx = get<0>(p3);\n auto cy = get<1>(p3);\n auto d = 2*(ax*(by-cy)+bx*(cy-ay)+cx*(ay-by));\n auto x = ((ax*ax+ay*ay)*(by-cy)+(bx*bx+by*by)*(cy-ay)+(cx*cx+cy*cy)*(ay-by))/d;\n auto y = ((ax*ax+ay*ay)*(cx-bx)+(bx*bx+by*by)*(ax-cx)+(cx*cx+cy*cy)*(bx-ax))/d;\n return make(x,y);\n}\n\ntemplate\n<\n typename Segment\n>\ndouble angle(const Segment& s)\n{\n return std::atan2(get<1,1>(s)-get<0,1>(s),get<1,0>(s)-get<0,0>(s));\n}\n\ntemplate\n<\n typename Point,\n typename Segment\n>\nbool is_left_of(const Point& p, const Segment& s)\n{\n return (get<0>(p)-get<0,0>(s))*(get<1,1>(s)-get<0,1>(s))-(get<1>(p)-get<0,1>(s))*(get<1,0>(s)-get<0,0>(s))<0;\n}\n\ntemplate\n<\n typename Point\n>\nbool adjacent_at_edge(const triangle& t1, const triangle& t2, const Point& p1, const Point& p2)\n{\n //Very naive check, not necessary with proper triangulation data structure\n return (equals(p1,t1.p1) || equals(p1,t1.p2) || equals(p1,t1.p3)) \n && (equals(p2,t1.p1) || equals(p2,t1.p2) || equals(p2,t1.p3))\n && (equals(p1,t2.p1) || equals(p1,t2.p2) || equals(p1,t2.p3))\n && (equals(p2,t2.p1) || equals(p2,t2.p2) || equals(p2,t2.p3));\n}\n\ntemplate\n<\n typename Point\n>\nstd::vector> flip_if_not_locally_delaunay(std::vector>& triangles, std::size_t ti1, std::size_t ti2)\n{\n triangle& t1 = triangles[ti1];\n if(std::find(t1.adjacent_indices.begin(),t1.adjacent_indices.end(),ti2)==t1.adjacent_indices.end())\n return {};\n triangle& t2 = triangles[ti2];\n Point *p1, *p2, *p3, *p4;\n if(!equals(t1.p1,t2.p1) && !equals(t1.p1,t2.p2) && !equals(t1.p1, t2.p3)) {\n p4 = &t1.p1;\n p1 = &t1.p2;\n p3 = &t1.p3;\n }\n else if(!equals(t1.p2,t2.p1) && !equals(t1.p2,t2.p2) && !equals(t1.p2, t2.p3)) {\n p4 = &t1.p2;\n p1 = &t1.p3;\n p3 = &t1.p1;\n }\n else {\n p4 = &t1.p3;\n p1 = &t1.p1;\n p3 = &t1.p2;\n }\n if(!equals(t2.p1,*p1) && !equals(t2.p1,*p3))\n p2 = &t2.p1;\n else if(!equals(t2.p2,*p1) && !equals(t2.p2,*p3))\n p2 = &t2.p2;\n else\n p2 = &t2.p3;\n bool loc_delaunay = distance(circumcircle_center(*p1,*p2,*p3),*p4)>circumcircle_diameter(*p1,*p2,*p3)/2;\n if(loc_delaunay)\n return {};\n std::size_t t1a1=-1, t2a1=-1;\n for(const auto& i : t1.adjacent_indices) {\n if(i!=ti2)\n if(adjacent_at_edge(t1, triangles[i], *p3, *p4))\n t1a1 = i;\n }\n for(const auto& i : t2.adjacent_indices) {\n if(i!=ti1)\n if(adjacent_at_edge(t2, triangles[i], *p1, *p2))\n t2a1 = i;\n }\n Point temp;\n assign(temp,*p3);\n assign(*p3,*p2);\n if(equals(t2.p1,temp))\n assign(t2.p2,*p4);\n else if(equals(t2.p2,temp))\n assign(t2.p3,*p4);\n else\n assign(t2.p1,*p4);\n if(t1a1!=-1 && t2a1!=-1) {\n std::replace(triangles[t1a1].adjacent_indices.begin(),triangles[t1a1].adjacent_indices.end(),ti1,ti2);\n std::replace(t1.adjacent_indices.begin(),t1.adjacent_indices.end(),t1a1,t2a1);\n std::replace(triangles[t2a1].adjacent_indices.begin(),triangles[t2a1].adjacent_indices.end(),ti2,ti1);\n std::replace(t2.adjacent_indices.begin(),t2.adjacent_indices.end(),t2a1,t1a1);\n }\n else if(t1a1!=-1) {\n std::replace(triangles[t1a1].adjacent_indices.begin(),triangles[t1a1].adjacent_indices.end(),ti1,ti2);\n t1.adjacent_indices.erase(std::find(t1.adjacent_indices.begin(),t1.adjacent_indices.end(),t1a1));\n t2.adjacent_indices.push_back(t1a1);\n }\n else if(t2a1!=-1) {\n std::replace(triangles[t2a1].adjacent_indices.begin(),triangles[t2a1].adjacent_indices.end(),ti2,ti1);\n t2.adjacent_indices.erase(std::find(t2.adjacent_indices.begin(),t2.adjacent_indices.end(),t2a1));\n t1.adjacent_indices.push_back(t2a1);\n }\n std::vector> outer_edges;\n for(const auto& t : {ti1,ti2}) {\n for(const auto& ta : triangles[t].adjacent_indices)\n if(ta != ti1 && ta != ti2)\n outer_edges.push_back(std::pair(t,ta));\n }\n return outer_edges;\n}\n\ntemplate\n<\n typename MultiPoint\n>\nstd::pair::type>>,std::vector::type>>> shull(const MultiPoint& input, bool skip_delaunay = false, double eps=0.0001)\n{\n typedef typename boost::range_value::type Point;\n typedef triangle Triangle;\n std::vector points;\n points.reserve(boost::size(input));\n for(const auto& in : input)\n points.push_back(in);\n //Step 2\n std::sort(points.begin()+1, points.end(), [&points](const Point& p1, const Point& p2) {\n auto d1 = comparable_distance(points[0],p1);\n auto d2 = comparable_distance(points[0],p2);\n if(d1(p1)(p2) || (get<0>(p1)==get<0>(p2) && get<1>(p1)(p2) ))\n return true;\n return false;});\n for(auto it=points.end()-1;it!=points.begin();--it) //remove almost-duplicates\n if(distance(*it,*(it-1))<=eps)\n it = points.erase(it);\n //Step 4\n double min_circumcircle_diameter = circumcircle_diameter(points[0],points[1],points[2]);\n std::size_t mcd_index = 2;\n for(std::size_t i=3;imin_circumcircle_diameter)\n break;\n }\n std::swap(points[2],points[mcd_index]);\n Point C = circumcircle_center(points[0], points[1], points[2]);\n\n //Step 5\n typedef typename model::segment Segment;\n typedef typename std::pair indexed_segment;\n if(!is_left_of(points[2], Segment{points[0],points[1]}))\n std::swap(points[1],points[2]);\n std::sort(points.begin()+2, points.end(), [&C](const Point& p1, const Point& p2) {\n return comparable_distance(C,p1) < comparable_distance(C,p2);\n });\n\n std::vector outer_hull = {indexed_segment(Segment{points[0],points[1]},0),indexed_segment(Segment{points[1],points[2]},0),indexed_segment(Segment{points[2],points[0]},0)};\n std::vector triangles = {Triangle{points[0],points[1],points[2],{}}};\n\n auto outer_hull_pred = [](const indexed_segment& s1, const indexed_segment& s2) { return angle(s1.first)first.first, p, it->first.second,{it->second}});\n triangles[it->second].adjacent_indices.push_back(triangles.size()-1);\n if(it!=begin) {\n triangles[triangles.size()-1].adjacent_indices.push_back(triangles.size()-2);\n triangles[triangles.size()-2].adjacent_indices.push_back(triangles.size()-1);\n }\n }\n indexed_segment new_outer1(Segment(begin->first.first,p),end_tri), new_outer2(Segment(p,(end-1)->first.second),triangles.size()-1);\n if(begin==outer_hull.begin()) {\n auto begin2 = std::find_if(end, outer_hull.end(), [&p](const indexed_segment& s) {\n return !is_left_of(p,s.first);\n });\n \n if(begin2 != outer_hull.end()) {\n std::size_t end_tri2 = triangles.size();\n for(auto it = begin2; it != outer_hull.end(); ++it) {\n triangles.push_back(Triangle{it->first.first, p, it->first.second,{it->second}});\n triangles[it->second].adjacent_indices.push_back(triangles.size()-1);\n if(it!=begin2) {\n triangles[triangles.size()-1].adjacent_indices.push_back(triangles.size()-2);\n triangles[triangles.size()-2].adjacent_indices.push_back(triangles.size()-1);\n }\n }\n triangles.back().adjacent_indices.push_back(end_tri);\n triangles[end_tri].adjacent_indices.push_back(triangles.size()-1);\n new_outer1 = indexed_segment(Segment(begin2->first.first,p), end_tri2);\n outer_hull.erase(begin2, outer_hull.end());\n }\n }\n outer_hull.erase(begin, end);\n for(const auto& s : {new_outer1, new_outer2})\n outer_hull.insert(std::upper_bound(outer_hull.begin(), outer_hull.end(), s, outer_hull_pred),s);\n }\n\n //Step 9\n if(!skip_delaunay) {\n std::stack> L;\n for(std::size_t i=0; i < triangles.size(); ++i)\n for(const auto& a : triangles[i].adjacent_indices)\n if(i(triangles, edge.first, edge.second);\n for(const auto& ne : new_edges)\n L.push(ne);\n }\n }\n std::vector no_index_hull;\n no_index_hull.reserve(outer_hull.size());\n for(const auto& si : outer_hull)\n no_index_hull.push_back(si.first);\n return std::make_pair(triangles,no_index_hull);\n}\n", "meta": {"hexsha": "0e416cc3c7364eaedd79bfee68abac175e422b38", "size": 11391, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "shull.hpp", "max_stars_repo_name": "tinko92/boost_geometry_GSoC_2019_project_3_4_test", "max_stars_repo_head_hexsha": "3dc8d6e5282fa2f7cc501b3f5025ef2ccfec4637", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "shull.hpp", "max_issues_repo_name": "tinko92/boost_geometry_GSoC_2019_project_3_4_test", "max_issues_repo_head_hexsha": "3dc8d6e5282fa2f7cc501b3f5025ef2ccfec4637", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "shull.hpp", "max_forks_repo_name": "tinko92/boost_geometry_GSoC_2019_project_3_4_test", "max_forks_repo_head_hexsha": "3dc8d6e5282fa2f7cc501b3f5025ef2ccfec4637", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0102739726, "max_line_length": 477, "alphanum_fraction": 0.6055657976, "num_tokens": 3459, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9334308036221031, "lm_q2_score": 0.6992544335934766, "lm_q1q2_score": 0.6527056278854774}} {"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n// Modified Jonker-Volgenant Algorithm\n// DF Crouse. On implementing 2D rectangular assignment algorithms.\n// IEEE Transactions on Aerospace and Electronic Systems, 52(4):1679-1696, August 2016,\n\n#pragma once\n\n#include \"AlgorithmUtils.hpp\"\n#include \"FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \n#include \n#include \n\nnamespace fluid {\nnamespace algorithm {\n\nclass Assign2D\n{\npublic:\n using ArrayXd = Eigen::ArrayXd;\n using ArrayXXd = Eigen::ArrayXXd;\n using ArrayXi = Eigen::ArrayXi;\n static const index UNASSIGNED = -1;\n bool process(Eigen::Ref costMatrix,\n Eigen::Ref result)\n {\n using namespace std;\n using namespace Eigen;\n double minCost = costMatrix.minCoeff();\n if(minCost > 0) minCost = 0;\n mCost = costMatrix - minCost;\n if(mCost.cols() > mCost.rows()){\n mCost.transposeInPlace();\n mTransposed = true;\n }\n else mTransposed = false;\n\n mRow2Col = ArrayXi::Constant(mCost.rows(), UNASSIGNED);\n mCol2Row = ArrayXi::Constant(mCost.cols(), UNASSIGNED);\n mV = ArrayXd::Zero(mCost.rows());\n mU = ArrayXd::Zero(mCost.cols());\n for (index c = 0; c < mCost.cols(); c++){\n index sink = shortestPath(c);\n if(sink == UNASSIGNED) return false;\n index j = sink;\n index h;\n while(true){\n index i = mPred(j);\n mRow2Col(j) = i;\n h = mCol2Row(i);\n mCol2Row(i) = j;\n j = h;\n if(i == c) break;\n }\n }\n result = mTransposed?mCol2Row:mRow2Col;\n return true;\n }\n\n index shortestPath(index c){\n using namespace std;\n mPred = ArrayXi::Zero(mCost.rows());\n ArrayXi scannedCols = ArrayXi::Zero(mCost.cols());\n ArrayXi scannedRows = ArrayXi::Zero(mCost.rows());\n vector row2Scan(mCost.rows());\n iota(row2Scan.begin(), row2Scan.end(), 0);\n index nRows2Scan = mCost.rows();\n index sink = UNASSIGNED;\n double delta = 0;\n index currentCol = c;\n index currentRow, currentClosestRow, closestRow;\n double minVal, reducedCost;\n ArrayXd shortestPathCost = ArrayXd::Constant(mCost.rows(), infinity);\n while(sink == UNASSIGNED){\n scannedCols(currentCol) = 1;\n minVal = infinity;\n for(index r = 0; r < nRows2Scan; r++){\n currentRow = row2Scan[r];\n reducedCost = delta\n + mCost(currentRow, currentCol)\n - mU(currentCol) - mV(currentRow);\n if(reducedCost < shortestPathCost(currentRow)){\n mPred(currentRow) = currentCol;\n shortestPathCost(currentRow) = reducedCost;\n }\n if(shortestPathCost(currentRow) < minVal){\n minVal = shortestPathCost(currentRow);\n currentClosestRow = r;\n }\n }\n if(isinf(minVal)) return UNASSIGNED;\n closestRow = row2Scan[currentClosestRow];\n scannedRows(closestRow) = 1;\n nRows2Scan--;\n row2Scan.erase(row2Scan.begin() + currentClosestRow);\n delta = shortestPathCost(closestRow);\n if(mRow2Col(closestRow) == UNASSIGNED) sink = closestRow;\n else currentCol = mRow2Col(closestRow);\n }\n mU(c) = mU(c) + delta;\n for(index i = 0; i < mCost.cols(); i++){\n if(i !=c && scannedCols(i) != 0){\n mU(i) = mU(i) + delta - shortestPathCost(mCol2Row(i));\n }\n }\n\n for(index i = 0; i < mCost.rows(); i++){\n if(scannedRows(i) != 0){\n mV(i) = mV(i) - delta + shortestPathCost(i);\n }\n }\n return sink;\n}\nprivate:\n ArrayXXd mCost;\n ArrayXi mRow2Col;\n ArrayXi mCol2Row;\n ArrayXd mU;\n ArrayXd mV;\n ArrayXi mPred;\n bool mTransposed{false};\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "38188c954253d03b3828b650b0639c297c019115", "size": 4100, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/Assign2D.hpp", "max_stars_repo_name": "chriskiefer/flucoma-core", "max_stars_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2020-05-11T15:42:53.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T01:51:36.000Z", "max_issues_repo_path": "include/algorithms/util/Assign2D.hpp", "max_issues_repo_name": "chriskiefer/flucoma-core", "max_issues_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 90.0, "max_issues_repo_issues_event_min_datetime": "2020-05-13T20:25:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-29T18:05:35.000Z", "max_forks_repo_path": "include/algorithms/util/Assign2D.hpp", "max_forks_repo_name": "chriskiefer/flucoma-core", "max_forks_repo_head_hexsha": "81efe4fe2ad812af5a99adc8aa6013d1da23b297", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2020-05-11T15:15:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-15T12:15:36.000Z", "avg_line_length": 30.3703703704, "max_line_length": 87, "alphanum_fraction": 0.636097561, "num_tokens": 1121, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6522454745263344}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n\nusing namespace Eigen;\nusing namespace std;\n\ndouble amips_param;\ndouble c1_param;\ndouble c2_param;\ndouble d1_param;\n\n\nVector2d energy_derivative(int type, Vector2d S)\n{\n \n Vector2d es;\n double J;\n double l1;\n double l2;\n \n switch(type)\n {\n case 0: //arap\n es[0] = 2 * (S[0] - 1);\n es[1] = 2 * (S[1] - 1);\n break;\n \n case 1: // mips\n es[0] = 1.0 / S[1] - S[1] / (S[0] * S[0]);\n es[1] = 1.0 / S[0] - S[0] / (S[1] * S[1]);\n //es[0] *= 100;\n //es[1] *= 100;\n break;\n \n case 2: // iso\n es[0] = 2 * S[0] - 2.0 / (S[0] * S[0] * S[0]);\n es[1] = 2 * S[1] - 2.0 / (S[1] * S[1] * S[1]);\n break;\n \n case 3: // amips\n es[0] = amips_param * exp(amips_param * (S[0] / S[1] + S[1] / S[0])) * (1.0 / S[1] - S[1] / (S[0] * S[0]));\n es[1] = amips_param * exp(amips_param * (S[0] / S[1] + S[1] / S[0])) * (1.0 / S[0] - S[0] / (S[1] * S[1]));\n break;\n \n case 4: // conf\n es[0] = 2 * S[0] / (S[1] * S[1]);\n es[1] = -2 * S[0] * S[0] / (S[1] * S[1] * S[1]);\n break;\n \n case 5: // gmr\n\t\t\t\t\t\t// J = S[0] * S[1];\n\t\t\t\t\t\t// l1 = S[0] * S[0] + S[1] * S[1];\n\t\t\t\t\t\t// l2 = S[0] * S[0] * S[1] * S[1];\n\t\t\t\t\t\t// \n\t\t\t\t\t\t// es[0] = c1_param * (-2.0 / 3.0 * pow(J, -5.0 / 3.0) * S[1] * l1 + pow(J, -2.0 / 3.0) * 2 * S[0]) \n\t\t\t\t\t\t// + c2_param * (-4.0 / 3.0 * pow(J, -7.0 / 3.0) * S[1] * l2 + pow(J, -4.0 / 3.0) * 2 * S[1] * S[1] * S[0]) \n\t\t\t\t\t\t// + d1_param * 2 * (J - 1) * S[1];\n\t\t\t\t\t\t// \n\t\t\t\t\t\t// es[1] = c1_param * (-2.0 / 3.0 * pow(J, -5.0 / 3.0) * S[0] * l1 + pow(J, -2.0 / 3.0) * 2 * S[1]) \n\t\t\t\t\t\t// + c2_param * (-4.0 / 3.0 * pow(J, -7.0 / 3.0) * S[0] * l2 + pow(J, -4.0 / 3.0) * 2 * S[0] * S[0] * S[1]) \n\t\t\t\t\t\t// + d1_param * 2 * (J - 1) * S[0];\n\n\t\t\t\t\t\tes[0] = c1_param * (1.0 / S[1] - S[1] / (S[0] * S[0])) - d1_param *2.*S[1]*(1.0 - S[0]*S[1]);\n\t\t\t\t\t\tes[1] = c1_param * (1.0 / S[0] - S[0] / (S[1] * S[1])) - d1_param *2.*S[0]*(1.0 - S[0]*S[1]);\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\n\t\t\t\t\n case 6: // olg\n \n if(S[0] > 1.0 / S[1])\n {\n es[0] = 1;\n es[1] = 0;\n }else{\n es[0] = 0;\n es[1] = -1.0 / (S[1] * S[1]);\n }\n \n break;\n }\n \n return es;\n\n}\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n \n mxArray *output_mex, *J_value_mex, *JT_value_mex, *wu_mex, *bu_mex;\n const int *dims;\n double *tri_num, *X_g_inv, *tri_areas, *obj_tri, *q_target, *type, *amips_s, *F_dot, *ver_num, *c1_g, *c2_g, *d1_g, *J_index, *JT_index, *JTJ_info, *x2u;\n double *output, *J_value, *JT_value, *wu, *bu;\n \n tri_num = mxGetPr(prhs[0]);\n X_g_inv = mxGetPr(prhs[1]);\n tri_areas = mxGetPr(prhs[2]);\n obj_tri = mxGetPr(prhs[3]);\n q_target = mxGetPr(prhs[4]);\n type = mxGetPr(prhs[5]);\n amips_s = mxGetPr(prhs[6]);\n F_dot = mxGetPr(prhs[7]);\n ver_num = mxGetPr(prhs[8]);\n c1_g = mxGetPr(prhs[9]);\n c2_g = mxGetPr(prhs[10]);\n d1_g = mxGetPr(prhs[11]);\n J_index = mxGetPr(prhs[12]);\n JT_index = mxGetPr(prhs[13]);\n JTJ_info = mxGetPr(prhs[14]);\n x2u = mxGetPr(prhs[15]);\n \n int tri_n = tri_num[0];\n int ver_n = ver_num[0];\n int energy_type = type[0];\n amips_param = amips_s[0];\n c1_param = c1_g[0];\n c2_param = c2_g[0];\n d1_param = d1_g[0];\n int J_rn = JTJ_info[0];\n int J_cn = JTJ_info[1];\n int JT_rn = JTJ_info[2];\n int JT_cn = JTJ_info[3];\n \n output_mex = plhs[0] = mxCreateDoubleMatrix(2 * ver_n, 1, mxREAL);\n J_value_mex = plhs[1] = mxCreateDoubleMatrix(J_rn * J_cn, 1, mxREAL);\n JT_value_mex = plhs[2] = mxCreateDoubleMatrix(JT_rn * JT_cn, 1, mxREAL);\n wu_mex = plhs[3] = mxCreateDoubleMatrix(tri_n, 1, mxREAL);\n bu_mex = plhs[4] = mxCreateDoubleMatrix(tri_n, 1, mxREAL);\n \n output = mxGetPr(output_mex);\n J_value = mxGetPr(J_value_mex);\n JT_value = mxGetPr(JT_value_mex);\n wu = mxGetPr(wu_mex);\n bu = mxGetPr(bu_mex);\n \n memset(J_value, 0, J_rn * J_cn * sizeof(double));\n memset(JT_value, 0, JT_rn * JT_cn * sizeof(double));\n memset(output, 0, 2 * ver_n * sizeof(double));\n\n vector offset;\n \n offset.resize(2 * ver_n, 0);\n \n int tri[3];\n double tri_area;\n \n Matrix2d B, X_f, A, F_d;\n Vector2d S, u0, u1, v0, v1;\n Matrix2d U, V;\n \n Vector2d es;\n Vector2d cs;\n \n double es1, es2;\n double d1, d2;\n double dphi;\n \n \n for(int i = 0; i < tri_n; i++)\n {\n tri[0] = obj_tri[i] - 1; \n tri[1] = obj_tri[i + tri_n] - 1; \n tri[2] = obj_tri[i + 2 * tri_n] - 1; \n tri_area = tri_areas[i];\n \n B(0, 0) = X_g_inv[i];\n B(0, 1) = X_g_inv[i + tri_n * 2];\n B(1, 0) = X_g_inv[i + tri_n];\n B(1, 1) = X_g_inv[i + tri_n * 3];\n \n X_f(0, 0) = q_target[2 * tri[1]] - q_target[2 * tri[0]];\n X_f(1, 0) = q_target[2 * tri[1] + 1] - q_target[2 * tri[0] + 1]; \n X_f(0, 1) = q_target[2 * tri[2]] - q_target[2 * tri[0]];\n X_f(1, 1) = q_target[2 * tri[2] + 1] - q_target[2 * tri[0] + 1];\n \n A = X_f * B;\n \n JacobiSVD svd(A, ComputeFullU | ComputeFullV);\n \n S = svd.singularValues();\n U = svd.matrixU();\n V = svd.matrixV();\n \n if(A.determinant() <= 0)\n {\n //mexPrintf(\"inverted\\n\");\n }\n \n bu[i] = S[0] * S[1];\n \n es = energy_derivative(energy_type, S);\n \n cs = S;\n \n es1 = es[0];\n es2 = es[1];\n \n ////////////////////////////////////////////\n \n wu[i] = 0;\n \n u0 = U.col(0);\n u1 = U.col(1);\n v0 = V.col(0);\n v1 = V.col(1);\n \n for(int j = 0; j < 6; j++)\n {\n \n F_d(0, 0) = F_dot[i + j * tri_n];\n F_d(0, 1) = F_dot[i + j * tri_n + 6 * 2 * tri_n];\n F_d(1, 0) = F_dot[i + j * tri_n + 6 * tri_n];\n F_d(1, 1) = F_dot[i + j * tri_n + 6 * 3 * tri_n];\n \n d1 = u0.transpose() * F_d * v0;\n d2 = u1.transpose() * F_d * v1;\n \n dphi = d1 * es1 + d2 * es2;\n \n int cache_1 = 2 * tri[j / 2] + (j % 2);\n int cache_2 = x2u[cache_1];\n \n output[cache_1] += tri_area * dphi;\n \n if(cache_2 > 0)\n {\n int idx = cache_2 - 1;\n \n double value = d1 * cs[1] + d2 * cs[0];\n \n J_value[idx * J_cn + offset[cache_1]] = value;\n \n offset[cache_1]++;\n \n JT_value[i * JT_cn + j] = value;\n \n wu[i] += value * value;\n }\n } \n }\n \n return;\n \n}", "meta": {"hexsha": "c4b9a3c34d5162e5e31b9d293e843c4af330adf2", "size": 7310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/2D/lib/mex/grad_function_mex.cpp", "max_stars_repo_name": "ErisZhang/BCQN", "max_stars_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-07-23T16:35:22.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-04T11:47:42.000Z", "max_issues_repo_path": "code/2D/lib/mex/grad_function_mex.cpp", "max_issues_repo_name": "ErisZhang/BCQN", "max_issues_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-07-10T12:12:18.000Z", "max_issues_repo_issues_event_max_datetime": "2019-07-10T12:12:18.000Z", "max_forks_repo_path": "code/2D/lib/mex/grad_function_mex.cpp", "max_forks_repo_name": "ErisZhang/BCQN", "max_forks_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-02-21T06:12:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-27T09:58:32.000Z", "avg_line_length": 29.24, "max_line_length": 157, "alphanum_fraction": 0.412995896, "num_tokens": 2762, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418241572634, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.6522454688072575}} {"text": "#include \"Kinematics.h\"\r\n#include \r\n\r\nusing namespace MotionControl;\r\n\r\nMatrix Kinematics::Rodrigues(Matrix a, double q)\r\n{\r\n\treturn AngleAxisd(q,a).toRotationMatrix();\r\n}\r\n\r\nMatrix Kinematics::rot2omega(Matrix R)\r\n{\r\n\tdouble alpha = (R(0,0)+R(1,1)+R(2,2)-1)/2;\r\n\tdouble th;\r\n\tMatrix vector_R(Matrix::Zero());\r\n\r\n\tif(fabs(alpha-1) < eps)\r\n\t\treturn Matrix::Zero();\r\n\r\n\tth = std::cos(alpha);\r\n\tvector_R << R(2,1)-R(1,2), R(0,2)-R(2,0), R(1,0)-R(0,1);\r\n\treturn 0.5*th/std::sin(th)*vector_R;\r\n}\r\n\r\nEigen::Matrix Kinematics::computeMatrixFromAngles(double roll, double pitch, double yaw)\r\n{\r\n\tEigen::Matrix R;\r\n\r\n\tR(0,0) = std::cos(pitch) * std::cos(yaw) - std::sin(roll) * std::sin(pitch) * std::sin(yaw);\r\n\tR(0,1) = -std::cos(roll) * std::sin(yaw);\r\n\tR(0,2) = std::sin(roll) * std::cos(yaw) + std::sin(roll) * std::cos(pitch) * std::sin(yaw);\r\n\tR(1,0) = std::cos(pitch) * std::sin(yaw) + std::sin(roll) * std::sin(pitch) * std::cos(yaw);\r\n\tR(1,1) = std::cos(roll) * std::cos(yaw);\r\n\tR(1,2) = std::sin(pitch) * std::sin(yaw) - std::sin(roll) * std::cos(pitch) * std::cos(yaw);\r\n\tR(2,0) = -std::cos(roll) * std::sin(pitch);\r\n\tR(2,1) = std::sin(roll);\r\n\tR(2,2) = std::cos(roll) * std::cos(pitch);\r\n\r\n\treturn R;\r\n}\r\n\r\nvoid Kinematics::computeAnglesFromMatrix(Eigen::Matrix R, double &roll, double &pitch, double &yaw)\r\n{\r\n\tfloat threshold = 0.001;\r\n\tif(abs(R(2,1) - 1.0) < threshold){ // R(2,1) = std::sin(x) = 1の時\r\n\t\troll \t= M_PI / 2;\r\n\t\tpitch = 0;\r\n\t\tyaw \t= std::atan2(R(1,0), R(0,0));\r\n\t}else if(abs(R(2,1) + 1.0) < threshold){ // R(2,1) = std::sin(x) = -1の時\r\n\t\troll\t= - M_PI / 2;\r\n\t\tpitch = 0;\r\n\t\tyaw\t\t= std::atan2(R(1,0), R(0,0));\r\n\t}else{\r\n\t\troll\t= std::sin(R(2,1));\r\n\t\tpitch\t= std::atan2(-R(2,0), R(2,2));\r\n\t\tyaw\t\t= std::atan2(-R(0,1), R(1,1));\r\n\t}\r\n}\r\n\r\nvector Kinematics::FindRoute(int to)\r\n{\r\n\tvector idx;\r\n\tint link_num = to;\r\n\r\n\twhile(link_num != 0)\r\n\t{\r\n\t\tidx.push_back(link_num);\r\n\t\tlink_num = ulink[link_num].parent;\r\n\t}\r\n\treverse(idx.begin(), idx.end());\r\n\treturn idx;\r\n}\r\n\r\nMatrix Kinematics::calcVWerr(Link Cref, Link Cnow)\r\n{\r\n\tMatrix perr = Cref.p - Cnow.p;\r\n\tMatrix Rerr = Cref.R - Cnow.R;\r\n\tMatrix werr = Cnow.R * rot2omega(Rerr);\r\n\tMatrix err;\r\n\r\n\terr << perr,werr;\r\n\treturn err;\r\n}\r\n\r\nvoid Kinematics::calcForwardKinematics(int rootlink)\r\n{\r\n\tif(rootlink == -1) return;\r\n\tif(rootlink != 0)\r\n\t{\r\n\t\tint parent = ulink[rootlink].parent;\r\n\t\tulink[rootlink].p = ulink[parent].R * ulink[rootlink].b + ulink[parent].p;\r\n\t\tulink[rootlink].R = ulink[parent].R * Rodrigues(ulink[rootlink].a, ulink[rootlink].q);\r\n\t}\r\n\tcalcForwardKinematics(ulink[rootlink].sister);\r\n\tcalcForwardKinematics(ulink[rootlink].child);\r\n}\r\n\r\n// 逆運動学\r\nbool Kinematics::calcInverseKinematics(int to, Link target)\r\n{\r\n\tMatrix J;\r\n\tMatrix dq, err;\r\n\r\n\tColPivHouseholderQR QR; //QR分解?\r\n\tconst double lambda = 0.5;\r\n\tconst int iteration = 100;\r\n\r\n\tcalcForwardKinematics(CC);\r\n\tvector idx = FindRoute(to);\r\n\r\n\tfor(int n=0;n idx, MatrixXd dq )\r\n{\r\n\tfor(int n=0; n idx = FindRoute(to);\r\n\tdouble wn_pos = 1/0.3;\r\n\tdouble wn_ang = 1/(2*pi);\r\n\tdouble lambda, Ek, Ek2;\r\n\tMatrix< double, 6,1 > we, err, gerr;\r\n\twe << wn_pos, wn_pos, wn_pos, wn_ang, wn_ang, wn_ang;\r\n\tMatrix< double, 6,6 >We = we.array().matrix().asDiagonal();\r\n\tMatrixXd Wn = MatrixXd::Identity(idx.size(),idx.size());\r\n\r\n\tcalcForwardKinematics(CC);\r\n\terr = calcVWerr( target, ulink[to]);\r\n\tEk = err.transpose() * We * err;\r\n\r\n\tfor(int i = 0; i < 10; i++)\r\n\t{\r\n\r\n\t\tJ = calcJacobian( ulink, idx );\r\n\t\tlambda = Ek + 0.002;\r\n\t\tJh = J.transpose() * We * J + Wn * lambda; //Hk + wn\r\n\t\tgerr = J.transpose() * We * err; // gk\r\n\r\n\t\tdq = Jh.inverse() * gerr; // new qk\r\n\t\tMoveJoints(idx, dq);\r\n\r\n\t\tEk2 = gerr.transpose() * We * gerr;\r\n\r\n\t\tif(Ek2 < 1E-12)\r\n\t\t{\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if( Ek2 < Ek ) Ek = Ek2;\r\n\t\telse\r\n\t\t{\r\n\t\t\tMoveJoints(idx, -dq);\r\n\t\t\treturn true;\r\n\t\t}\r\n\t}\r\n\treturn false;\r\n}\r\n", "meta": {"hexsha": "26a95fe56b0d11e26a9199a0a4b39e5f2ea365ff", "size": 4597, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sample/SERIAL/Kinematics.cpp", "max_stars_repo_name": "Akira794/biped-kinematics", "max_stars_repo_head_hexsha": "9a392e4c7fb71593bac34a62e7532a4b5c17a73d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/sample/SERIAL/Kinematics.cpp", "max_issues_repo_name": "Akira794/biped-kinematics", "max_issues_repo_head_hexsha": "9a392e4c7fb71593bac34a62e7532a4b5c17a73d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-03-09T00:41:59.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-03T06:21:30.000Z", "max_forks_repo_path": "src/sample/SERIAL/Kinematics.cpp", "max_forks_repo_name": "Akira794/biped-kinematics", "max_forks_repo_head_hexsha": "9a392e4c7fb71593bac34a62e7532a4b5c17a73d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.1193181818, "max_line_length": 112, "alphanum_fraction": 0.5975636285, "num_tokens": 1674, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541593883189, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.6522291984113898}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\n// N * E = B * T\r\n#define N 128*150\t// number of training data samples\r\n#define D 784\t// number of features\r\n#define T 150\t// total number of iterations per epoch\r\n#define B_size 128\t// size of mini-batch\r\n#define ALPHA 128\t// 2^7\r\n#define epoch 1\r\n#define SCALING_FACTOR 8192\r\n\r\ntypedef Matrix MATRIX;\r\ntypedef Matrix MATRIXd;\r\ntypedef Matrix ColVectorXi64;\r\ntypedef Matrix ColVectorXd;\r\ntypedef Matrix RowVectorXd;\r\ntypedef Matrix RowVectorXi64;\r\n\r\n\r\n// Simulates dditive shares created by the clients and distributed to the two servers.\r\nvoid genDataShares(MATRIX& X0, MATRIX& X1, MATRIX& Y0, MATRIX& Y1);\r\n\r\n// Initialize W0 and W1 to be random\r\nvoid initializeW(MATRIX& W0, MATRIX& W1);\r\n\r\n// Simulates generation of U, V, Z multiplication triplets\r\nvoid genUVZmultTriplets(MATRIX& U0, MATRIX& U1, MATRIX& V0, MATRIX& V1, MATRIX& Z0, MATRIX& Z1);\r\n\r\n// Simulates generation of V', Z' multiplication triplets\r\nvoid genVZprimeMultTriplets(MATRIX& UB0, MATRIX& UB1, MATRIX& Vp0, MATRIX& Vp1, MATRIX& Zp0, MATRIX& Zp1);\r\n\r\n// Returns set of random indices corresponding to training data for current minibatch(iteration)\r\nset createMiniBatch(set& usedIndices);\r\n\r\n// Reconstructs M, by adding MO and M1\r\nvoid reconstruct(MATRIX M0, MATRIX M1, MATRIX& M);\r\n\r\nvoid maskMatrix(MATRIX Data, MATRIX Mask, MATRIX& Final);\r\n\r\nvoid computeDifference(MATRIX& Dif, MATRIX Y_, MATRIX Y);\r\n\r\nint reverse_int(int i);\r\n\r\nvoid read_MNIST_data(bool train, vector>& vec, int& number_of_images, int& number_of_features);\r\n\r\nvoid read_MNIST_labels(bool train, vector& vec);\r\n\r\nvoid read_MNIST_data_test(bool train, vector>& vec, int& number_of_images, int& number_of_features);\r\n\r\nvoid read_MNIST_labels_test(bool train, vector& vec);\r\n\r\nvoid secretShareData(MATRIX& X, MATRIX& Y, MATRIX& X0, MATRIX& X1, MATRIX& Y0, MATRIX& Y1);\r\n\r\n\r\nint main() {\r\n\r\n\tcout << unsigned long int(-28145) % 4294967296 << endl;\r\n\t\r\n\t// READ TRAINING DATA\r\n\tvector> training_data;\r\n\tint param_n= N; int param_d= D;\r\n\tread_MNIST_data(true, training_data, param_n, param_d);\r\n\tMATRIX X(param_n, param_d);\r\n\tfor(int i = 0; i < training_data.size(); i++){\r\n X.row(i) << Map(training_data[i].data(), training_data[i].size());\r\n }\r\n\tX *= SCALING_FACTOR;\r\n\tX /= 255;\r\n\t//cout << X << endl;\r\n\t//cout << X.rows() << \" \" << X.cols() << endl;\r\n\t/*for (int i = 0 ; i < 784 ; ++i) {\r\n\t\tcout << training_data.at(0).at(i) << \" \";\r\n\t}\r\n\tcout << endl<< X.row(0) << endl;*/\r\n\r\n\t// READ TRAINING LABEL\r\n\tvector training_labels;\r\n\tread_MNIST_labels(true, training_labels);\r\n\tMATRIX Y(N, 1);\r\n\t//for (int i = 0; i < training_labels.size(); ++i) {\r\n\t//\tY(i) = training_labels.at(i);\r\n\t//}\r\n\tY << Map(training_labels.data(), training_labels.size());\r\n\tY *= SCALING_FACTOR;\r\n\tY /= 10;\r\n\r\n\tcout << sizeof(unsigned long long int) << endl;\r\n\tcout << sizeof(uint64_t) << endl;\r\n\r\n\t// READ TESTING DATA\r\n\tvector > testing_data;\r\n\tint n_;\r\n\t//param_n= N; param_d= D;\r\n\tread_MNIST_data_test(false, testing_data, n_, param_d);\r\n\tMATRIXd Xt(n_, param_d);\r\n\tfor(int i = 0; i < testing_data.size(); i++){\r\n Xt.row(i) << Map(testing_data[i].data(), testing_data[i].size());\r\n }\r\n\t//Xt *= SCALING_FACTOR;\t\t\r\n\tXt /= 255;\r\n\r\n\t// READING TESTING LABEL\r\n\tvector testing_labels;\r\n\tread_MNIST_labels_test(false, testing_labels);\r\n\tMATRIXd Yt(n_, 1);\r\n\t//for (int i = 0; i < training_labels.size(); ++i) {\r\n\t//\tY(i) = training_labels.at(i);\r\n\t//}\r\n\tYt << Map(testing_labels.data(), testing_labels.size());\r\n\t//Yt *= SCALING_FACTOR;\t\t\r\n\t//Yt /= 10;\r\n\r\n\r\n\t/*for (long int n : training_labels) {\r\n\t\tcout << n << endl;\r\n\t}\r\n\tcout << training_labels.size() << endl;*/\r\n\t//cout << Yt << endl;\r\n\t//cout << Y.rows() << \" \" << Y.cols() << endl;\r\n\r\n\t//print out numbers\r\n\t/*int c = 0;\r\n\tfor (int i = 0; i < 784; ++i) {\r\n\t\tif (c % 28 == 0) {\r\n\t\t\tcout << endl;\r\n\t\t}\r\n\t\tcout << X(2, i) << \" \";\r\n\t\t++c;\r\n\t}\r\n\tcout << training_labels.at(2) << endl;*/\r\n\t//cout << Xt.row(0) << endl;\r\n\r\n\r\n\r\n\t/*START OF PROTOCOL*/\r\n\r\n\t// shares of training data\r\n\tclock_t start = clock();\r\n\tMATRIX X0(N, D);\tMATRIX X1(N, D);\r\n\tMATRIX Y0(N, 1);\tMATRIX Y1(N, 1);\r\n\t//genDataShares(X0, X1, Y0, Y1);\r\n\tsecretShareData(X, Y, X0, X1, Y0, Y1);\r\n\t\r\n\r\n\t// tests:\r\n\t/*cout << \"X0 MATRIX:\\n\" << X0 << endl;\r\n\tcout << \"X1 MATRIX:\\n\" << X1 << endl;\r\n\tcout << \":\\n\" << X0 + X1 << endl;*/\r\n\t/*cout << \"Y0 MATRIX:\\n\" << Y0 << endl;\r\n\tcout << \"Y1 MATRIX:\\n\" << Y1 << endl;\r\n\tcout << \":\\n\" << Y0 + Y1 << endl;*/\r\n\r\n\t// coefficient vertor w\r\n\tMATRIX W0(D, 1);\tMATRIX W1(D, 1);\r\n\tinitializeW(W0, W1);\r\n\r\n\t// tests:\r\n\t/*cout << \"W0:\\n\" << W0 << endl;\t\r\n\tcout << \"W1:\\n\" << W1 << endl;*/\r\n\r\n\t// generate shared U, V, Z multiplication triplets\r\n\tMATRIX U0(N, D);\tMATRIX U1(N, D);\r\n\tMATRIX V0(D, T);\tMATRIX V1(D, T);\r\n\tMATRIX Z0(N, T);\tMATRIX Z1(N, T);\r\n\tgenUVZmultTriplets(U0, U1, V0, V1, Z0, Z1);\r\n\r\n\t// tests:\r\n\t/*cout << \"MATRIX U0: \\n\" << U0 << endl;\r\n\tcout << \"MATRIX U1: \\n\" << U1 << endl;\r\n\tcout << \"MATRIX V0: \\n\" << V0 << endl;\r\n\tcout << \"MATRIX V1: \\n\" << V1 << endl;\r\n\tcout << \"MATRIX Z0: \\n \" << Z0 << endl;\r\n\tcout << \"MATRIX Z1: \\n \" << Z1 << endl;*/\r\n\r\n\t\r\n\t// * STEP 1: each party runs Ei = Xi - Ui masking\r\n\tMATRIX E0(N, D);\tMATRIX E1(N, D);\tMATRIX E(N, D);\r\n\tmaskMatrix(X0, U0, E0);\r\n\tmaskMatrix(X1, U1, E1);\r\n\treconstruct(E0, E1, E);\t\t// |?| how to code how each party does this independently\r\n\r\n\t// tests:\r\n\t/*cout << \"MATRIX E0:\\n\" << E0 << endl;\r\n\tcout << \"MATRIX E1:\\n\" << E1 << endl;\r\n\tcout << \"MATRIX E: \\n\" << E << endl;*/\r\n\r\n\r\n\t// * STEP 2: start of each iteration\r\n\tset usedIndices;\r\n\tfor (int j = 0; j < T; ++j) {\r\n\r\n\t\t//cout << \"Iteration \" << j+1 << \"...\" << endl;\r\n\r\n\t\t// * STEP 3: select minibatch\r\n\t\tset minibatch = createMiniBatch(usedIndices); // select minibatch indices\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"minibatch:\" << endl;\r\n\t\tfor (int n : minibatch) {\r\n\t\t\tcout << n << \" \";\r\n\t\t}\r\n\t\tcout << endl;*/\r\n\r\n\t\t// submatrices size B\r\n\t\tMATRIX EB(B_size, D);\r\n\t\tMATRIX UB0(B_size, D);\tMATRIX UB1(B_size, D);\r\n\t\tMATRIX XB0(B_size, D);\tMATRIX XB1(B_size, D);\r\n\t\tMATRIX YB0(B_size, 1);\tMATRIX YB1(B_size, 1);\r\n\t\tMATRIX ZB0(B_size, T);\tMATRIX ZB1(B_size, T);\r\n\r\n\t\tint r = 0;\tint k = 0;\r\n\t\tfor (int n : minibatch) {\r\n\t\t\tk = n - 1;\r\n\t\t\tEB.row(r) = E.row(k);\r\n\t\t\tUB0.row(r) = U0.row(k);\r\n\t\t\tUB1.row(r) = U1.row(k);\r\n\t\t\tXB0.row(r) = X0.row(k);\r\n\t\t\tXB1.row(r) = X1.row(k);\r\n\t\t\tYB0.row(r) = Y0.row(k);\r\n\t\t\tYB1.row(r) = Y1.row(k);\r\n\t\t\tZB0.row(r) = Z0.row(k);\r\n\t\t\tZB1.row(r) = Z1.row(k);\r\n\t\t\tr++;\r\n\t\t}\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"MATRIX EB:\\n\" << EB << endl;\r\n\t\tcout << \"MATRIX UB0:\\n\" << UB0 << endl;\r\n\t\tcout << \"MATRIX UB1:\\n\" << UB1 << endl;\r\n\t\tcout << \"MATRIX XB0:\\n\" << XB0 << endl;\r\n\t\tcout << \"MATRIX XB1:\\n\" << XB1 << endl;\r\n\t\tcout << \"MATRIX YB0:\\n\" << YB0 << endl;\r\n\t\tcout << \"MATRIX YB1:\\n\" << YB1 << endl;\r\n\t\tcout << \"MATRIX ZB0:\\n\" << ZB0 << endl;\r\n\t\tcout << \"MATRIX ZB1:\\n\" << ZB1 << endl;*/\r\n\r\n\r\n\t\t// generate V' and Zp multiplication triplets based on minibatch indices\r\n\t\tMATRIX Vp0(B_size, T);\tMATRIX Vp1(B_size, T);\r\n\t\tMATRIX Zp0(D, T);\t\tMATRIX Zp1(D, T);\r\n\t\tgenVZprimeMultTriplets(UB0, UB1, Vp0, Vp1, Zp0, Zp1);\r\n\r\n\t\t// tests:\r\n\t/*\tcout << \"matrix Vp0: \\n\" << Vp0 << endl;\r\n\t\tcout << \"matrix Vp1: \\n\" << Vp1 << endl;\r\n\t\tcout << \"matrix Zp0: \\n\" << Zp0 << endl;\r\n\t\tcout << \"matrix Zp1: \\n\" << Zp1 << endl;*/\r\n\r\n\r\n\t\t//// * STEP 4: each party computes Fji = wi - V[j]i\tjth iteration\r\n\t\tMATRIX F0(D, 1);\tMATRIX F1(D, 1);\tMATRIX F(D, 1);\r\n\t\tMATRIX V0j = V0.col(j);\t\r\n\t\tMATRIX V1j = V1.col(j);\r\n\t\tmaskMatrix(W0, V0j, F0);\r\n\t\tmaskMatrix(W1, V1j, F1);\r\n\t\treconstruct(F0, F1, F);\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"MATRIX V0j: \\n\" << V0j << endl;\r\n\t\tcout << \"MATRIX F0:\\n\" << F0 << endl;\r\n\t\tcout << \"MATRIX V1j: \\n\" << V1j << endl;\r\n\t\tcout << \"MATRIX F1:\\n\" << F1 << endl;\r\n\t\tcout << \"MATRIX F:\\n\" << F << endl;*/\r\n\r\n\r\n\t\t// * STEP 5: calculate predicted output\r\n\t\tMATRIX Ypred_0 = -0 * (EB * F) + (XB0 * F) + (EB * W0) + ZB0.col(j);\t// replace with j\r\n\t\tMATRIX Ypred_1 = -1 * (EB * F) + (XB1 * F) + (EB * W1) + ZB1.col(j);\t// replace with j\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"EB\\n\" << EB << endl;\r\n\t\tcout << \"XB0\\n\" << XB0<< endl;\r\n\t\tcout << \"XB1\\n\" << XB1<< endl;\r\n\t\tcout << \"ZB0.col(0)\\n\" << ZB0.col(0) << endl;\r\n\t\tcout << \"ZB1.col(0)\\n\" << ZB1.col(0) << endl;\r\n\t\tcout << \"Ypred_0:\\n\" << Ypred_0 << endl;\r\n\t\tcout << \"Ypred_1:\\n\" << Ypred_1 << endl;*/\r\n\r\n\r\n\t\t// * STEP 6: \r\n\t\tMATRIX D0; MATRIX D1;\r\n\t\tcomputeDifference(D0, Ypred_0, YB0);\r\n\t\tcomputeDifference(D1, Ypred_1, YB1);\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"Ypred_0:\\n\" << Ypred_0 << endl;\r\n\t\tcout << \"YB0 \\n\" << YB0 << endl;\r\n\t\tcout << \"D0:\\n\" <> d;\r\n\t\t\tdelta1(i) = delta1(i) >> d;\r\n\t\t}\r\n\r\n\t\t// tests:\r\n\t\t/*cout << \"After truncation:\" << endl;\r\n\t\tcout << \"delta0:\\n\" << delta0 << endl;\r\n\t\tcout << \"delta1:\\n\" << delta1 << endl;*/\r\n\r\n\t\t// *STEP 10: \r\n\t\t/*cout << \"W0:\\n\" << W0 << endl;\r\n\t\tcout << \"W1:\\n\" << W1 << endl;*/\r\n\t\t//cout << (B_size * ALPHA) << endl;\r\n\r\n\t\tW0 = W0 - (delta0 / (B_size * ALPHA));\r\n\t\tW1 = W1 - (delta1 / (B_size * ALPHA));\r\n\r\n\t\t/*cout << \"W0:\\n\" << W0 << endl;\r\n\t\tcout << \"W1:\\n\" << W1 << endl;*/\r\n\r\n\t}\r\n\r\n\t// *STEP 11: Reconstruct W\r\n\tMATRIX W(D,1);\r\n reconstruct(W0, W1, W);\r\n\r\n\t// tests:\r\n\t//cout << \"FINAL W:\\n\" << W << endl;\r\n\r\n\tclock_t end = clock();\r\n\tdouble elapsed = (double(end) - double(start)) / CLOCKS_PER_SEC;\r\n\t//cout << \"Time measured : \" << elapsed << \"seconds.\\n\";\r\n\r\n\r\n\tColVectorXd Wd;\r\n\tW /= SCALING_FACTOR;\r\n\tWd = W.cast ();\r\n\r\n\r\n\t//cout << Yt << endl;\r\n\r\n\t/*cout << \"Xt size: \" << Xt.rows() << \" \" << Xt.cols() << endl;\t\r\n\tcout << \"Wd size: \" << Wd.rows() << \" \" << Wd.cols() << endl;*/\r\n\t// Xt will always be 10000 x 784, make sure Wd is also 784\r\n\t\r\n\tColVectorXd prediction = Xt * Wd;\r\n\r\n\tprediction /= SCALING_FACTOR;\r\n\tprediction *= 10;\r\n n_ = Yt.rows();\t// 10000\r\n\tdouble temp1;\r\n\tlong int temp2, temp3;\r\n prediction = round(prediction.array());\r\n\r\n\tcout << \"SIZE: \" << n_ << endl;\r\n\r\n\r\n\tcout << prediction << endl;\r\n\tint count = 0; int count_zero = 0;\r\n for (int i = 0; i < n_ ; i++){\r\n\t\ttemp3 = (long long int)prediction(i);\r\n\t\t\r\n\t\t//temp1 = temp3/(double)pow(2,20+8);\r\n\t\ttemp2 = (long long int)Yt(i);\r\n\t\t//if (temp2 == 0) {\r\n\t\t//\tcount_zero++;\r\n\t\t//}\r\n\r\n\r\n\r\n\t\t//if(temp3>0.5 && temp2 == 1){\r\n\t\t//\tcount++;\r\n\t\t//}\r\n\t\t//else if (temp3 < 0.5 && temp2 == 0) {\r\n\t\t//\tcount++;\r\n\t\t//}\r\n\t\t\r\n\t\tif(prediction(i) == Yt(i))\r\n count++;\r\n\r\n\t\t//cout << \"pred: \" << prediction(i) << \"\ttest label: \" << Yt(i) << endl;\r\n // \r\n }\r\n\r\n\tcout << \"num zeros: \" << count_zero << endl;\r\n\r\n\tcout << \"num correct\" << count << endl;\r\n\tdouble accuracy = count/((double) n_);\r\n\tcout << \"Accuracy on testing the trained model is \" << accuracy * 100 << endl;\r\n\r\n\r\n} // end of main()\r\n\r\n\r\nvoid secretShareData(MATRIX& X, MATRIX& Y, MATRIX& X0, MATRIX& X1, MATRIX& Y0, MATRIX& Y1) {\r\n\tunsigned long long int n, n0;\r\n\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tfor (int j = 0; j < D; j++) {\r\n\t\t\tn = X(i, j);\r\n\t\t\tn0 = rand();\r\n\t\t\tX0(i, j) = n0;\r\n\t\t\tX1(i, j) = (n - n0);\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tn = Y(i);\r\n\t\tn0 = rand();\r\n\t\tY0(i) = n0;\r\n\t\tY1(i) = (n - n0) ;\t// add mod 2l ?\r\n\t}\r\n}\r\n\r\nvoid genDataShares(MATRIX& X0, MATRIX& X1, MATRIX& Y0, MATRIX& Y1) {\r\n\tunsigned long long int n, n0, n1;\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tfor (int j = 0; j < D; j++) {\r\n\t\t\tn = rand();\r\n\t\t\tn0 = rand();\r\n\t\t\tn1 = (n - n0); \t\t// add mod 2l ?\r\n\t\t\tX0(i, j) = n0;\r\n\t\t\tX1(i, j) = n1;\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < N; ++i) {\r\n\t\tn = rand();\r\n\t\tn0 = rand();\r\n\t\tn1 = (n - n0) ;\t\t// add mod 2l ?\r\n\t\tY0(i) = n0;\r\n\t\tY1(i) = n1;\r\n\t}\r\n}\r\n\r\nvoid initializeW(MATRIX& W0, MATRIX& W1) {\r\n\tfor (int i = 0; i < D; ++i) {\t\t\r\n\t\tW0(i) = rand();\r\n\t\tW1(i) = rand();\r\n\t}\r\n}\r\n\r\nvoid genUVZmultTriplets(MATRIX& U0, MATRIX& U1, MATRIX& V0, MATRIX& V1, MATRIX& Z0, MATRIX& Z1) {\r\n\t\r\n\tunsigned long long int n, n0;\r\n\tfor (int i = 0; i < N; i++) {\r\n\t\tfor (int j = 0; j < D; j++) {\r\n\t\t\tn = rand();\r\n\t\t\tn0 = rand();\r\n\t\t\tU0(i, j) = n0;\r\n\t\t\tU1(i, j) = (n - n0);\r\n\t\t}\r\n\t}\r\n\r\n\tfor (int i = 0; i < D; i++) {\r\n\t\tfor (int j = 0; j < T; j++) {\r\n\t\t\tn = rand();\r\n\t\t\tn0 = rand();\r\n\t\t\tV0(i, j) = n0;\r\n\t\t\tV1(i, j) = (n - n0);\r\n\t\t}\r\n\t}\r\n\r\n\tZ0 = U0 * V0;\r\n\tZ1 = U1 * V1;\r\n}\r\n\r\nvoid genVZprimeMultTriplets(MATRIX& UB0, MATRIX& UB1, MATRIX& Vp0, MATRIX& Vp1, MATRIX& Zp0, MATRIX& Zp1) {\r\n\tMATRIX UBT0 = UB0.transpose();\r\n\tMATRIX UBT1 = UB1.transpose();\r\n\r\n\tunsigned long long int n, n0;\r\n\tfor (int i = 0; i < B_size; i++) {\r\n\t\tfor (int j = 0; j < T; j++) {\r\n\t\t\tn = rand();\r\n\t\t\tn0 = rand();\r\n\t\t\tVp0(i, j) = n0;\r\n\t\t\tVp1(i, j) = n - n0;\r\n\t\t}\r\n\t}\r\n\r\n\tZp0 = UBT0 * Vp0;\r\n\tZp1 = UBT1 * Vp1;\r\n\t/*cout << \"MATRIX UBT0:\\n\" << UBT0 << endl;\r\n\tcout << \"MATRIX UBT1:\\n\" << UBT1 << endl;*/\r\n}\r\n\r\nvoid reconstruct(MATRIX M0, MATRIX M1, MATRIX& M) {\tM = M0 + M1;}\r\n\r\nvoid maskMatrix(MATRIX Data, MATRIX Mask, MATRIX& Final) {\tFinal = Data - Mask;}\r\n\r\nset createMiniBatch(set& usedIndices) {\r\n\tset minibatch;\r\n\tint num = 0;\r\n\t//srand(time(NULL));\r\n\twhile (minibatch.size() != B_size) {\r\n\t\tnum = (rand() % (N - 1 + 1)) + 1;\r\n\t\tif (usedIndices.count(num) == 0) {\r\n\t\t\tusedIndices.insert(num);\r\n\t\t\tminibatch.insert(num);\r\n\t\t}\r\n\t}\r\n\treturn minibatch;\r\n}\r\n\r\nvoid computeDifference(MATRIX& Dif, MATRIX Y_, MATRIX Y) { Dif = Y_ - Y;}\r\n\r\n\r\nint reverse_int(int i){\r\n unsigned char ch1, ch2, ch3, ch4;\r\n ch1 = i & 255;\r\n ch2 = (i >> 8) & 255;\r\n ch3 = (i >> 16) & 255;\r\n ch4 = (i >> 24) & 255;\r\n return ((int) ch1 << 24) + ((int) ch2 << 16) + ((int) ch3 << 8) + ch4;\r\n}\r\n\r\nvoid read_MNIST_data(bool train, vector> &vec, int& number_of_images, int& number_of_features){\r\n std::ifstream file;\r\n\tif (train == true)\r\n\t\tfile.open(\"/Users/ariad/Documents/train-images-idx3-ubyte\", std::ios::binary);\r\n\telse\r\n\t\tfile.open(\"/Users/ariad/Documents/t10k-images-idx3-ubyte\", std::ios::binary);\r\n \r\n if(!file){\r\n std::cout<<\"Unable to open file\";\r\n return;\r\n }\r\n if (file.is_open()){\r\n int magic_number = 0;\r\n int n_rows = 0;\r\n int n_cols = 0;\r\n file.read((char*) &magic_number, sizeof(magic_number));\r\n magic_number = reverse_int(magic_number);\r\n file.read((char*) &number_of_images, sizeof(number_of_images));\r\n number_of_images = reverse_int(number_of_images);\r\n if(train == true)\r\n number_of_images = N;\r\n file.read((char*) &n_rows, sizeof(n_rows));\r\n n_rows = reverse_int(n_rows);\r\n file.read((char*) &n_cols, sizeof(n_cols));\r\n n_cols = reverse_int(n_cols);\r\n number_of_features = n_rows * n_cols;\r\n std::cout << \"Number of Images: \" << number_of_images << std::endl;\r\n std::cout << \"Number of Features: \" << number_of_features << std::endl;\r\n for(int i = 0; i < number_of_images; ++i){\r\n std::vector tp;\r\n for(int r = 0; r < n_rows; ++r)\r\n for(int c = 0; c < n_cols; ++c){\r\n unsigned char temp = 0;\r\n file.read((char*) &temp, sizeof(temp));\r\n tp.push_back(((unsigned long long int) temp));\r\n }\r\n vec.push_back(tp);\r\n }\r\n }\r\n}\r\n\r\n\r\nvoid read_MNIST_labels(bool train, vector &vec){\r\n std::ifstream file;\r\n\tif (train == true) {\r\n\t\tfile.open(\"/Users/ariad/Documents/train-labels-idx1-ubyte\", std::ios::binary);\r\n\t}\r\n\telse {\r\n\t\tfile.open(\"/Users/ariad/Documents/t10k-labels-idx1-ubyte\", std::ios::binary);\r\n\t}\r\n if(!file){\r\n std::cout << \"Unable to open file\";\r\n return;\r\n }\r\n if (file.is_open()){\r\n int magic_number = 0;\r\n int number_of_images = 0;\r\n file.read((char*) &magic_number, sizeof(magic_number));\r\n magic_number = reverse_int(magic_number);\r\n file.read((char*) &number_of_images, sizeof(number_of_images));\r\n number_of_images = reverse_int(number_of_images);\r\n\t\tcout << \"number of images inside MNIST LAbels: \" << number_of_images << endl;\r\n\r\n if(train == true)\r\n number_of_images = N;\r\n for(int i = 0; i < number_of_images; ++i){\r\n unsigned char temp = 0;\r\n file.read((char*) &temp, sizeof(temp));\r\n\t\t\t//vec.push_back((unsigned long int) temp);\r\n\t\t\t\r\n if((unsigned long long int) temp == 0)\r\n vec.push_back((unsigned long long int) 0);\r\n else\r\n vec.push_back((unsigned long long int) 1);\r\n }\r\n }\r\n}\r\n\r\n\r\nvoid read_MNIST_data_test(bool train, vector> &vec, int& number_of_images, int& number_of_features){\r\n std::ifstream file;\r\n\tif (train == true)\r\n\t\tfile.open(\"/Users/ariad/Documents/train-images-idx3-ubyte\", std::ios::binary);\r\n\telse\r\n\t\tfile.open(\"/Users/ariad/Documents/t10k-images-idx3-ubyte\", std::ios::binary);\r\n \r\n if(!file){\r\n std::cout<<\"Unable to open file\";\r\n return;\r\n }\r\n if (file.is_open()){\r\n int magic_number = 0;\r\n int n_rows = 0;\r\n int n_cols = 0;\r\n file.read((char*) &magic_number, sizeof(magic_number));\r\n magic_number = reverse_int(magic_number);\r\n file.read((char*) &number_of_images, sizeof(number_of_images));\r\n number_of_images = reverse_int(number_of_images);\r\n if(train == true)\r\n number_of_images = N;\r\n file.read((char*) &n_rows, sizeof(n_rows));\r\n n_rows = reverse_int(n_rows);\r\n file.read((char*) &n_cols, sizeof(n_cols));\r\n n_cols = reverse_int(n_cols);\r\n number_of_features = n_rows * n_cols;\r\n std::cout << \"Number of Images: \" << number_of_images << std::endl;\r\n std::cout << \"Number of Features: \" << number_of_features << std::endl;\r\n for(int i = 0; i < number_of_images; ++i){\r\n std::vector tp;\r\n for(int r = 0; r < n_rows; ++r)\r\n for(int c = 0; c < n_cols; ++c){\r\n unsigned char temp = 0;\r\n file.read((char*) &temp, sizeof(temp));\r\n tp.push_back(((double) temp));\r\n }\r\n vec.push_back(tp);\r\n }\r\n }\r\n}\r\n\r\nvoid read_MNIST_labels_test(bool train, vector &vec){\r\n std::ifstream file;\r\n\tif (train == true) {\r\n\t\tfile.open(\"/Users/ariad/Documents/train-labels-idx1-ubyte\", std::ios::binary);\r\n\t}\r\n\telse {\r\n\t\tfile.open(\"/Users/ariad/Documents/t10k-labels-idx1-ubyte\", std::ios::binary);\r\n\t}\r\n if(!file){\r\n std::cout << \"Unable to open file\";\r\n return;\r\n }\r\n if (file.is_open()){\r\n int magic_number = 0;\r\n int number_of_images = 0;\r\n file.read((char*) &magic_number, sizeof(magic_number));\r\n magic_number = reverse_int(magic_number);\r\n file.read((char*) &number_of_images, sizeof(number_of_images));\r\n number_of_images = reverse_int(number_of_images);\r\n\t\tcout << \"number of images inside MNIST LAbels: \" << number_of_images << endl;\r\n\r\n if(train == true)\r\n number_of_images = N;\r\n for(int i = 0; i < number_of_images; ++i){\r\n unsigned char temp = 0;\r\n file.read((char*) &temp, sizeof(temp));\r\n\t\t\t//vec.push_back((double) temp);\r\n\t\t\t\r\n if((double) temp == 0)\r\n vec.push_back((double) 0);\r\n else\r\n vec.push_back((double) 1);\r\n }\r\n }\r\n}\r\n\r\n/*\r\n\tModulus\r\n\tEpochs, testing accuracy\r\n*/", "meta": {"hexsha": "ea07a775107de32beda301035b9e16453546632e", "size": 20880, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "sarahathar/SecureML-Privacy-Preserving-Linear-Regression", "max_stars_repo_head_hexsha": "d4b83cdc163d7f84a5befef0f48734cfef6fc2e6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-29T12:41:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-29T12:41:51.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "sarahathar/SecureML-Privacy-Preserving-Linear-Regression", "max_issues_repo_head_hexsha": "d4b83cdc163d7f84a5befef0f48734cfef6fc2e6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "sarahathar/SecureML-Privacy-Preserving-Linear-Regression", "max_forks_repo_head_hexsha": "d4b83cdc163d7f84a5befef0f48734cfef6fc2e6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-08T01:06:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-08T01:06:55.000Z", "avg_line_length": 29.4915254237, "max_line_length": 127, "alphanum_fraction": 0.5518678161, "num_tokens": 6884, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972818382005, "lm_q2_score": 0.7490872243177519, "lm_q1q2_score": 0.6521533013507571}} {"text": "/* -*- 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 . The license is also available online at\n .\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE. See the license for more details.\n*/\n\n/*! \\file cevrndcalculator.cpp */\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\nnamespace QuantLib {\n\n CEVRNDCalculator::CEVRNDCalculator(Real f0, Real alpha, Real beta)\n : f0_(f0),\n alpha_(alpha),\n beta_(beta),\n delta_((1.0-2.0*beta)/(1.0-beta)),\n x0_(X(f0)) {\n QL_REQUIRE(beta != 1.0, \"beta can not be one\");\n }\n\n Real CEVRNDCalculator::massAtZero(Time t) const {\n if (delta_ < 2.0)\n return 1.0-boost::math::gamma_p(-0.5*delta_+1.0,x0_/(2.0*t));\n else\n return 0.0;\n }\n\n Real CEVRNDCalculator::X(Real f) const {\n return std::pow(f, 2.0*(1.0-beta_))/square()(alpha_*(1.0-beta_));\n }\n\n Real CEVRNDCalculator::invX(Real x) const {\n return std::pow(x*square()(alpha_*(1.0-beta_)),\n 1.0/(2.0*(1.0-beta_)));\n }\n\n Real CEVRNDCalculator::pdf(Real f, Time t) const {\n const Real y = X(f);\n\n if (delta_ < 2.0) {\n return boost::math::pdf(\n boost::math::non_central_chi_squared_distribution(\n 4.0-delta_, y/t), x0_/t)/t * 2.0*(1.0-beta_)*y/f;\n }\n else {\n return boost::math::pdf(\n boost::math::non_central_chi_squared_distribution(\n delta_, x0_/t), y/t)/t * 2.0*(beta_-1.0)*y/f;\n }\n }\n\n Real CEVRNDCalculator::cdf(Real f, Time t) const {\n const Real y = X(f);\n\n if (delta_ < 2.0)\n return 1.0 - boost::math::cdf(\n boost::math::non_central_chi_squared_distribution(\n 2.0-delta_, y/t), x0_/t);\n else\n return 1.0 - boost::math::cdf(\n boost::math::non_central_chi_squared_distribution(\n delta_, x0_/t), y/t);\n }\n\n Real CEVRNDCalculator::sankaranApprox(Real c, Time t, Real x) const {\n const Real a = x0_/t;\n const Real b = 2.0 - delta_;\n\n c = std::max(c, -0.45*b);\n\n const Real h = 1 - 2*(b+c)*(b+3*c)/(3*square()(b+2*c));\n const Real p = (b+2*c)/square()(b+c);\n const Real m = (h-1)*(1-3*h);\n\n const Real u = (std::pow(a/(b+c), h) - (1 + h*p*(h-1-0.5*(2-h)*m*p)))/\n (h*std::sqrt(2*p)*(1+0.5*m*p));\n\n return u - x;\n }\n\n Real CEVRNDCalculator::invcdf(Real q, Time t) const {\n if (delta_ < 2.0) {\n if (f0_ < QL_EPSILON || q < massAtZero(t))\n return 0.0;\n\n const Real x = InverseCumulativeNormal()(1-q);\n\n auto cdfApprox = [&](Real _c){ return sankaranApprox(_c, t, x); };\n\n const Real y0 = X(f0_)/t;\n\n try {\n Brent brent;\n brent.setMaxEvaluations(20);\n const Real guess =\n invX(brent.solve(cdfApprox, 1e-8, y0, 0.02*y0) * t);\n\n return InvCDFHelper(this, guess, 1e-8, 100).inverseCDF(q, t);\n }\n catch (...) {\n return InvCDFHelper(this, f0_, 1e-8, 100).inverseCDF(q, t);\n }\n }\n else {\n const Real x = t * boost::math::quantile(\n boost::math::non_central_chi_squared_distribution(\n delta_, x0_/t), 1-q);\n return invX(x);\n }\n }\n}\n", "meta": {"hexsha": "a36078d8dcde1092eb0d76009ca6a66df1641861", "size": 4400, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ql/methods/finitedifferences/utilities/cevrndcalculator.cpp", "max_stars_repo_name": "jiangjiali/QuantLib", "max_stars_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3358.0, "max_stars_repo_stars_event_min_datetime": "2015-12-18T02:56:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T02:42:47.000Z", "max_issues_repo_path": "ql/methods/finitedifferences/utilities/cevrndcalculator.cpp", "max_issues_repo_name": "jiangjiali/QuantLib", "max_issues_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 965.0, "max_issues_repo_issues_event_min_datetime": "2015-12-21T10:35:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T02:47:00.000Z", "max_forks_repo_path": "ql/methods/finitedifferences/utilities/cevrndcalculator.cpp", "max_forks_repo_name": "jiangjiali/QuantLib", "max_forks_repo_head_hexsha": "37c98eccfa18a95acb1e98b276831641be92b38e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1663.0, "max_forks_repo_forks_event_min_datetime": "2015-12-17T17:45:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T07:58:29.000Z", "avg_line_length": 32.8358208955, "max_line_length": 79, "alphanum_fraction": 0.5634090909, "num_tokens": 1276, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425311777929, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6520441565020746}} {"text": "#include \n#include \n#include \"spaND.h\"\n#include \n#include \n#include \"mmio.hpp\"\n\nusing namespace Eigen;\nusing namespace std;\nusing namespace spaND;\n\nint main(int argc, char* argv[]) {\n assert(argc == 5);\n string folder(argv[1]);\n int nlevels = atoi(argv[2]);\n double tol = atof(argv[3]);\n int skip = atoi(argv[4]);\n cout << \"Inputs folder \" << folder << \" nlevels = \" << nlevels << \" tol = \" << tol << \" skip = \" << skip << endl;\n string file = folder + \"/jac4.mm\";\n string xfile = folder + \"/xCoords.mm\";\n string yfile = folder + \"/yCoords.mm\";\n cout << \"Reading from \" << file << \" \" << xfile << \" \" << yfile << endl;\n SpMat A = mmio::sp_mmread(file);\n int N = A.rows();\n cout << \"A has \" << N << \" rows\" << endl;\n VectorXd xcoords = mmio::dense_mmread(xfile);\n VectorXd ycoords = mmio::dense_mmread(yfile);\n // Create X coordinate matrix\n MatrixXd X(2, N);\n assert(xcoords.size() == N/2);\n assert(ycoords.size() == N/2);\n for(int i = 0; i < N; i++) {\n X(0,i) = xcoords(i/2);\n X(1,i) = ycoords(i/2);\n }\n Tree t = Tree(nlevels);\n t.set_tol(tol);\n t.set_skip(skip);\n t.set_use_geo(true);\n t.set_Xcoo(&X);\n // Run algo \n timer start = wctime();\n t.partition(A);\n // Rest\n timer part = wctime();\n t.assemble(A);\n timer ass = wctime();\n try {\n t.factorize();\n } catch (exception& ex) {\n cout << ex.what();\n exit(1);\n }\n timer end = wctime();\n t.print_log();\n cout << \"Timings:\" << endl << \" Partition: \" << elapsed(start,part) << \" s.\" << endl << \" Assembly: \" << elapsed(part,ass) << \" s.\" << endl << \" Factorization: \" << elapsed(ass, end) << \" s.\" << endl;\n // Use CG\n VectorXd x = VectorXd::Zero(N);\n VectorXd b = VectorXd::Random(N);\n timer cg0 = wctime();\n int iter = cg(A, b, x, t, 500, 1e-12, true);\n timer cg1 = wctime();\n cout << \"CG: #iterations: \" << iter << \", residual |Ax-b|/|b|: \" << (A*x-b).norm() / b.norm() << endl;\n cout << \" CG: \" << elapsed(cg0, cg1) << \" s.\" << endl;\n return 0;\n}\n", "meta": {"hexsha": "e52c414f3f794e89d8af9d96ced10331b716bc19", "size": 2200, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "tests/icesheet.cpp", "max_stars_repo_name": "leopoldcambier/spaND_public", "max_stars_repo_head_hexsha": "fc344dc1ff4b36832aad3f86adb4a23111c67366", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2019-05-06T21:17:07.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-11T14:56:30.000Z", "max_issues_repo_path": "tests/icesheet.cpp", "max_issues_repo_name": "leopoldcambier/spaND_public", "max_issues_repo_head_hexsha": "fc344dc1ff4b36832aad3f86adb4a23111c67366", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "tests/icesheet.cpp", "max_forks_repo_name": "leopoldcambier/spaND_public", "max_forks_repo_head_hexsha": "fc344dc1ff4b36832aad3f86adb4a23111c67366", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-06-23T12:04:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-23T12:04:28.000Z", "avg_line_length": 32.8358208955, "max_line_length": 207, "alphanum_fraction": 0.5422727273, "num_tokens": 677, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357701094304, "lm_q2_score": 0.7520125848754472, "lm_q1q2_score": 0.6520218106594667}} {"text": "// Group B - Perpetual American Option\r\n//\r\n// by Scott Sidoli\r\n//\r\n// 6-10-19\r\n//\r\n// Main.cpp\r\n//\r\n// We program the formula for pricing perptual American Options (part a). We test the data.\r\n// Again, we take the input of an array to compute prices for a varying parameter. We then \r\n// code a matrix pricer that allows us to vary two parameters. The structure of this project\r\n// mirrors the structure of group A. We have defined types for the option parameters in\r\n// Types.hpp. We have the struct in OptionData.hpp and we have our pricing functions in\r\n// OptionPricing.hpp. The perpetual American Option Class is in PerpetualAmericanOption.hpp\r\n// We have MeshArray.hpp to use the method for creating an array of parameter values.\r\n\r\n#include \"PerpetualAmericanOption.hpp\"\r\n#include \"MeshArray.hpp\"\r\n#include \r\n\r\nint main()\r\n{\t// 2 b)\r\n\t// We test our perpetual American option class. First we create the option and set the data.\r\n\tPerpetualAmericanOption Amer_Option;\r\n\tStrike_Price K = (Strike_Price)100.0;\r\n\tVolatility sig = (Volatility) 0.1;\r\n\trate r = (rate)0.1;\r\n\tcost_of_carry b = (cost_of_carry)0.02;\r\n\tcurr_stock_price S = (curr_stock_price)110;\r\n\tAmer_Option.SetOption(K,sig,r,b,S);\r\n\r\n\t// Now we print the call and put prices.\r\n\tcout << \"Perpetual American Option Call Price: \" << Amer_Option.CallPriceAmer() << endl;\r\n\tcout << \"Perpetual American Option Put Price: \" < S_array = MeshArray(start, end, interval);\r\n\r\n\t// Create vector of Calls and puts\r\n\tvector CallPrices = Amer_Option.CallPriceAmer(S_array);\r\n\tvector PutPrices = Amer_Option.PutPriceAmer(S_array);\r\n\r\n\t\r\n\t// Print the result\r\n\tcout << \"S - value, Call, Put \" << endl;\r\n\tPrintArray(S_array, CallPrices, PutPrices);\r\n\r\n\t// Reset the Option\r\n\tAmer_Option.SetOption(K, sig, r, b, S);\r\n\tcout << endl;\r\n\t//============================================================================================== =\r\n\t// 2 d) We create a matrix of option parameters and output a matrix of option prices.\r\n\t// For the parameters, we use K and sig. We create two vectors.\r\n\tStrike_Price K_start = (Strike_Price)80.0;\r\n\tStrike_Price K_end = (Strike_Price)120.0;\r\n\tStrike_Price K_interval = (Strike_Price)1.0;\r\n\tvector K_array = MeshArray(K_start, K_end, K_interval);\r\n\r\n\tVolatility sig_start = (Volatility) 0.01;\r\n\tVolatility sig_end = (Volatility) 0.20;\r\n\tVolatility sig_interval = (Volatility)0.01;\r\n\tvector sig_array = MeshArray(sig_start, sig_end, sig_interval);\r\n\r\n\t// Create a Matrix to store the call prices and put prices.\r\n\ttypedef boost::tuple CallPrice_PutPrice;\r\n\tconst int num_rows = 50;\r\n\tconst int num_cols = 50;\r\n\tCallPrice_PutPrice PriceMatrix[num_rows][num_cols]; // Price matrix stores call and put price when parameter I takes value x and parameter J takes value y.\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t // In this example we use expiry time and volatility. \r\n\r\n\tcout << \"(Strike Price, Volatility, (Call Price Put Price))\" << endl;\r\n\r\n\tfor (int i = 0; i < K_array.size(); ++i)\r\n\t{\r\n\t\tAmer_Option.SetOption(K_array[i]);\r\n\r\n\t\tfor (int j = 0; j < sig_array.size(); ++j)\r\n\t\t{\r\n\t\t\tAmer_Option.SetOption(sig_array[j]);\r\n\t\t\tPriceMatrix[i][j] = CallPrice_PutPrice(Amer_Option.CallPriceAmer(), Amer_Option.PutPriceAmer());\r\n\r\n\t\t\tcout << \"(\" << K_array[i] << \", \" << sig_array[j] << \", \" << PriceMatrix[i][j] << \")\" << endl;\r\n\t\t}\r\n\t}\r\n\tcout << endl;\r\n\r\n\t// reset the option\r\n\tAmer_Option.SetOption(K, sig, r, b, S);\r\n\treturn 0;\r\n}", "meta": {"hexsha": "e0b12b4ba7f1d22d224b74ac2875543878602439", "size": 3900, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Group B/Group B/Main.cpp", "max_stars_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_stars_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T08:14:37.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T08:14:37.000Z", "max_issues_repo_path": "Group B/Group B/Main.cpp", "max_issues_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_issues_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Group B/Group B/Main.cpp", "max_forks_repo_name": "scottsidoli/C-for-Financial-Engineering---Baruch-Pre-MFE-Certificate", "max_forks_repo_head_hexsha": "79c2fb297a85c914d5f0b8671bb17636801e3ce7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.625, "max_line_length": 157, "alphanum_fraction": 0.6664102564, "num_tokens": 1005, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6519485337242289}} {"text": "/* =========================================================================\n Copyright (c) 2010-2014, Institute for Microelectronics,\n Institute for Analysis and Scientific Computing,\n TU Wien.\n Portions of this software are copyright by UChicago Argonne, LLC.\n\n -----------------\n ViennaCL - The Vienna Computing Library\n -----------------\n\n Project Head: Karl Rupp rupp@iue.tuwien.ac.at\n\n (A list of authors and contributors can be found in the PDF manual)\n\n License: MIT (X11), see file LICENSE in the base directory\n============================================================================= */\n\n/*\n*\n* Tutorial: Calculation of the eigenvalue with largest modulus using the power iteration method\n* (power-iter.cpp and power-iter.cu are identical, the latter being required for compilation using CUDA nvcc)\n*\n*/\n\n// include necessary system headers\n#include \n\n#ifndef NDEBUG\n #define NDEBUG\n#endif\n\n#define VIENNACL_WITH_UBLAS\n\n//include basic scalar and vector types of ViennaCL\n#include \"viennacl/scalar.hpp\"\n#include \"viennacl/vector.hpp\"\n#include \"viennacl/compressed_matrix.hpp\"\n\n\n#include \"viennacl/linalg/power_iter.hpp\"\n#include \"viennacl/io/matrix_market.hpp\"\n// Some helper functions for this tutorial:\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\nint main()\n{\n typedef double ScalarType;\n\n boost::numeric::ublas::compressed_matrix ublas_A;\n\n if (!viennacl::io::read_matrix_market_file(ublas_A, \"../examples/testdata/mat65k.mtx\"))\n {\n std::cout << \"Error reading Matrix file\" << std::endl;\n return 0;\n }\n\n viennacl::compressed_matrix vcl_A(ublas_A.size1(), ublas_A.size2());\n viennacl::copy(ublas_A, vcl_A);\n\n viennacl::linalg::power_iter_tag ptag(1e-6);\n\n std::cout << \"Starting computation of eigenvalue with largest modulus (might take about a minute)...\" << std::endl;\n std::cout << \"Result of power iteration with ublas matrix (single-threaded): \" << viennacl::linalg::eig(ublas_A, ptag) << std::endl;\n std::cout << \"Result of power iteration with ViennaCL (OpenCL accelerated): \" << viennacl::linalg::eig(vcl_A, ptag) << std::endl;\n\n}\n\n", "meta": {"hexsha": "3028ca75c3f67877ac13a8b7271600fcc1d78af0", "size": 2655, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/tutorial/power-iter.cpp", "max_stars_repo_name": "denis14/ViennaCL-1.5.2", "max_stars_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "examples/tutorial/power-iter.cpp", "max_issues_repo_name": "denis14/ViennaCL-1.5.2", "max_issues_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/tutorial/power-iter.cpp", "max_forks_repo_name": "denis14/ViennaCL-1.5.2", "max_forks_repo_head_hexsha": "fec808905cca30196e10126681611bdf8da5297a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.1875, "max_line_length": 134, "alphanum_fraction": 0.6433145009, "num_tokens": 619, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127529517043, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6519485315613961}} {"text": "#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"geohash/math.hpp\"\n\nnamespace geohash {\n\n// Geographic point\nstruct Point {\n double lng{};\n double lat{};\n};\n\n// A box made of two describing points\nclass Box {\n public:\n // Default constructor\n Box() = default;\n\n // Constructor taking the minimum corner point and the maximum corner point\n Box(const Point& min_corner, const Point& max_corner)\n : min_corner_(min_corner), max_corner_(max_corner) {}\n\n // Returns the center of the box.\n [[nodiscard]] inline constexpr auto center() const -> Point {\n return {(min_corner_.lng + max_corner_.lng) * 0.5,\n (min_corner_.lat + max_corner_.lat) * 0.5};\n }\n\n // Returns the delta of the box in latitude and longitude.\n [[nodiscard]] inline auto delta(bool round) const\n -> std::tuple {\n auto x = max_corner_.lng - min_corner_.lng;\n auto y = max_corner_.lat - min_corner_.lat;\n if (round) {\n x = Box::max_decimal_power(x);\n y = Box::max_decimal_power(y);\n }\n return std::make_tuple(x, y);\n }\n\n // Returns a point inside the box, making an effort to round to minimal\n // precision.\n [[nodiscard]] inline auto round() const -> Point {\n double x;\n double y;\n std::tie(x, y) = delta(true);\n return {std::ceil(min_corner_.lng / x) * x,\n std::ceil(min_corner_.lat / y) * y};\n }\n\n // Returns the box, or the two boxes on either side of the dateline if the\n // defined box wraps around the globe (i.e. the longitude of the min corner\n // is greater than the longitude of the max corner.)\n [[nodiscard]] auto split() const -> std::list {\n // box wraps around the globe ?\n if (min_corner_.lng > max_corner_.lng) {\n return {Box({min_corner_.lng, min_corner_.lat}, {180, max_corner_.lat}),\n Box({-180, min_corner_.lat}, {max_corner_.lng, max_corner_.lat})};\n }\n return {*this};\n }\n\n // Returns true if the geographic point is within the box\n [[nodiscard]] auto contains(const Point& point) const -> bool {\n // box wraps around the globe ?\n if (min_corner_.lng > max_corner_.lng) {\n for (const auto& item : split()) {\n if (!item.contains(point)) {\n return false;\n }\n }\n return true;\n }\n return (min_corner_.lat <= point.lat && point.lat <= max_corner_.lat &&\n min_corner_.lng <= point.lng && point.lng <= max_corner_.lng);\n }\n\n // Returns the minimum corner point\n [[nodiscard]] auto min_corner() const -> const Point& { return min_corner_; }\n\n // Returns the minimum corner point\n [[nodiscard]] auto min_corner() -> Point& { return min_corner_; }\n\n // Returns the maximum corner point\n [[nodiscard]] auto max_corner() const -> const Point& { return max_corner_; }\n\n // Returns the maximum corner point\n [[nodiscard]] auto max_corner() -> Point& { return max_corner_; }\n\n private:\n Point min_corner_{};\n Point max_corner_{};\n\n // Returns the maximum power of 10 from a number (x > 0)\n static auto max_decimal_power(const double x) -> double {\n auto m = static_cast(std::floor(std::log10(x)));\n return power10(m);\n }\n};\n\n} // namespace geohash\n\nBOOST_GEOMETRY_REGISTER_POINT_2D(\n geohash::Point, double,\n boost::geometry::cs::geographic, lng, lat)\n\nBOOST_GEOMETRY_REGISTER_BOX(geohash::Box, geohash::Point, min_corner(),\n max_corner())\n\nnamespace geohash {\n\nusing Polygon = boost::geometry::model::polygon;\n\n} // namespace geohash\n", "meta": {"hexsha": "743f875c0a6e1d1ae78636b098730eab7407a12f", "size": 3674, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/geohash/core/include/geohash/geometry.hpp", "max_stars_repo_name": "fbriol/pangeo-geohash", "max_stars_repo_head_hexsha": "2f02985f789d91f4bb8ee28ff9ae224c2a990b04", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/geohash/core/include/geohash/geometry.hpp", "max_issues_repo_name": "fbriol/pangeo-geohash", "max_issues_repo_head_hexsha": "2f02985f789d91f4bb8ee28ff9ae224c2a990b04", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/geohash/core/include/geohash/geometry.hpp", "max_forks_repo_name": "fbriol/pangeo-geohash", "max_forks_repo_head_hexsha": "2f02985f789d91f4bb8ee28ff9ae224c2a990b04", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.3636363636, "max_line_length": 80, "alphanum_fraction": 0.6551442569, "num_tokens": 930, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942067038785, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6519464569765024}} {"text": "// Vec2.cpp\n#include \"Vec2.h\"\n\n#include \n\nnamespace ugps\n{\n num_ug Vec2::length() const\n {\n return sqrt(length2());\n }\n\n num_ug Vec2::length2() const\n {\n return x*x + y*y;\n }\n\n\n arma::Col Vec2::col() const \n {\n arma::Col c = {x,y};\n return c;\n }\n\t\n arma::Row Vec2::row() const \n {\n arma::Row r = {x,y};\n return r;\n }\n \n Vec2 Vec2::rotate(const num_ug& angle) const\n {\n return Vec2(\n cos(angle)*x - sin(angle)*y,\n sin(angle)*y + cos(angle)*x\n );\n }\n\n num_ug Vec2::angle() const\n {\n return atan2(y,x);\n }\n}\n", "meta": {"hexsha": "269e509cafaa47db0efde4c0a6de5ac2edc0eba0", "size": 706, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Vec2.cpp", "max_stars_repo_name": "ScrambledEggsOnToast/UniversalGPS", "max_stars_repo_head_hexsha": "721c6740a02a7c2792bcd7b6d03f6e0552190b1a", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Vec2.cpp", "max_issues_repo_name": "ScrambledEggsOnToast/UniversalGPS", "max_issues_repo_head_hexsha": "721c6740a02a7c2792bcd7b6d03f6e0552190b1a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Vec2.cpp", "max_forks_repo_name": "ScrambledEggsOnToast/UniversalGPS", "max_forks_repo_head_hexsha": "721c6740a02a7c2792bcd7b6d03f6e0552190b1a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 16.0454545455, "max_line_length": 48, "alphanum_fraction": 0.4645892351, "num_tokens": 215, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970717197771, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6519434106460197}} {"text": "//---------------------------------------------------------------------------//\n// Copyright (c) 2020-2021 Mikhail Komarov \n// Copyright (c) 2020-2021 Nikita Kaskov \n//\n// MIT License\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n//---------------------------------------------------------------------------//\n\n#ifndef CRYPTO3_MATH_XGCD_HPP\n#define CRYPTO3_MATH_XGCD_HPP\n\n#include \n#include \n\n#include \n#include \n\n#include \n\nnamespace nil {\n namespace crypto3 {\n namespace math {\n\n /*!\n * @brief Perform the standard Extended Euclidean Division algorithm.\n * Input: Polynomial A, Polynomial B.\n * Output: Polynomial G, Polynomial U, Polynomial V, such that G = (A * U) + (B * V).\n */\n template\n void extended_euclidean(const Range1 &a, const Range2 &b, Range3 &g, Range4 &u, Range5 &v) {\n\n typedef\n typename std::iterator_traits()))>::value_type value_type;\n\n if (is_zero(b)) {\n g = a;\n u = std::vector(1, value_type::one());\n v = std::vector(1, value_type::zero());\n return;\n }\n\n std::vector U(1, value_type::one());\n std::vector V1(1, value_type::zero());\n std::vector G(a);\n std::vector V3(b);\n\n std::vector Q(1, value_type::zero());\n std::vector R(1, value_type::zero());\n std::vector T(1, value_type::zero());\n\n while (!is_zero(V3)) {\n division(Q, R, G, V3);\n multiplication(G, V1, Q);\n subtraction(T, U, G);\n\n U = V1;\n G = V3;\n V1 = T;\n V3 = R;\n }\n\n multiplication(V3, a, U);\n subtraction(V3, G, V3);\n division(V1, R, V3, b);\n\n value_type lead_coeff = G.back().inversed();\n std::transform(G.begin(), G.end(), G.begin(),\n std::bind(std::multiplies(), lead_coeff, std::placeholders::_1));\n std::transform(U.begin(), U.end(), U.begin(),\n std::bind(std::multiplies(), lead_coeff, std::placeholders::_1));\n std::transform(V1.begin(), V1.end(), V1.begin(),\n std::bind(std::multiplies(), lead_coeff, std::placeholders::_1));\n\n g = G;\n u = U;\n v = V1;\n }\n } // namespace math\n } // namespace crypto3\n} // namespace nil\n\n#endif // ALGEBRA_FFT_XGCD_HPP\n", "meta": {"hexsha": "2411e1e5fc4310557097ffe916108ef698b78ea7", "size": 4234, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/math/polynomial/xgcd.hpp", "max_stars_repo_name": "NilFoundation/fft", "max_stars_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/nil/crypto3/math/polynomial/xgcd.hpp", "max_issues_repo_name": "NilFoundation/fft", "max_issues_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/nil/crypto3/math/polynomial/xgcd.hpp", "max_forks_repo_name": "NilFoundation/fft", "max_forks_repo_head_hexsha": "87609ea4b36eedf0426ddec69a34df2d1c990f7d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9207920792, "max_line_length": 119, "alphanum_fraction": 0.5529050543, "num_tokens": 916, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797051879431, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.651879831090975}} {"text": "#include \n#include \n#include \n#include \n\n#define pi 3.14159\n\nusing namespace std;\n\nstatic boost::random::mt19937 gen;\n\nint test(float bounds[8]);\nfloat rand_gen(float lim[2]);\n\nint test(float bounds[8]){\n\n USING_NAMESPACE_ACADO\n\n DifferentialState q1,q2,qd1,qd2; // the differential states\n Control tau1,tau2; // the control input u\n Parameter T;\n DifferentialEquation f( 0.0, 0.5 );\n\n // -------------------------------------\n OCP ocp( 0.0, 0.5 );\n \n ocp.minimizeLagrangeTerm(tau1*tau1 + tau2*tau2);\n // ocp.minimizeMayerTerm(T*T + tau1*tau1 + tau2*tau2);\n\n f << dot(q1) == qd1;\n f << dot(q2) == qd2;\n f << dot(qd1) == -(48*tau1 - 48*tau2 + 24*qd1*qd1*sin(q2) + 24*qd2*qd2*sin(q2) + 18*qd1*qd1*sin(2*q2) - 72*tau2*cos(q2) + 48*qd1*qd2*sin(q2))/(36*cos(q2)*cos(q2) - 64);\n f << dot(qd2) == (48*tau1 - 240*tau2 + 120*qd1*qd1*sin(q2) + 24*qd2*qd2*sin(q2) + 36*qd1*qd1*sin(2*q2) + 18*qd2*qd2*sin(2*q2) + 72*tau1*cos(q2) - 144*tau2*cos(q2) + 48*qd1*qd2*sin(q2) + 36*qd1*qd2*sin(2*q2))/(18*cos(2*q2) - 46);\n\n ocp.subjectTo(f);\n ocp.subjectTo(AT_START, q1 == bounds[0] ); \n\n ocp.subjectTo(AT_START, q2 == bounds[1] ); \n\n ocp.subjectTo(AT_START, qd1 == bounds[2] );\n ocp.subjectTo(AT_START, qd2 == bounds[3] );\n\n ocp.subjectTo(AT_END, q1 == bounds[4]);\n ocp.subjectTo(AT_END, q2 == bounds[5]);\n ocp.subjectTo(AT_END, qd1 == bounds[6]);\n ocp.subjectTo(AT_END, qd2 == bounds[7]);\n\n ocp.subjectTo(-400 <= tau1 <= 400); // bounds on the control input u,\n ocp.subjectTo(-400 <= tau2 <= 400);\n // -------------------------------------\n\n // ---------PLOT FOR TESTING\n // GnuplotWindow window;\n // window.addSubplot(q1, \"q1\");\n // window.addSubplot(q2, \"q2\");\n // window.addSubplot(qd1, \"qd1\");\n // window.addSubplot(qd2, \"qd2\");\n // window.addSubplot(tau1, \"tau1\");\n // window.addSubplot(tau2, \"tau2\");\n\n OptimizationAlgorithm algorithm(ocp); // the optimization algorithm\n algorithm.set( DISCRETIZATION_TYPE , MULTIPLE_SHOOTING);\n algorithm.set( INTEGRATOR_TYPE , INT_RK45);\n algorithm.set( HESSIAN_APPROXIMATION , BLOCK_BFGS_UPDATE);\n algorithm.set( KKT_TOLERANCE , 1e-4); \n algorithm.set( ABSOLUTE_TOLERANCE, 1e-4);\n algorithm.set( INTEGRATOR_TOLERANCE, 1e-4);\n algorithm.set( MAX_NUM_ITERATIONS, 1000);\n algorithm.set( MAX_NUM_INTEGRATOR_STEPS, 10000);\n\n algorithm.set(PRINT_COPYRIGHT,BT_FALSE);\n algorithm.set(PRINTLEVEL,LOW);\n algorithm.set(PRINT_INTEGRATOR_PROFILE,BT_FALSE);\n algorithm.set(PRINT_SCP_METHOD_PROFILE,BT_FALSE);\n // algorithm << window;\n algorithm.solve(); // solves the problem.\n\n algorithm.getDifferentialStates(\"states.txt\");\n algorithm.getObjectiveValue(\"parameters.txt\");\n algorithm.getControls(\"control.txt\");\n\n clearAllStaticCounters();\n return 0;\n}\n\nfloat rand_gen(float lim[2]) {\n static boost::random::uniform_real_distribution<> dist(0, 1);\n return lim[0] + dist(gen)*(lim[1] - lim[0]);\n}\n\nint main(int argc, char const *argv[])\n{\n float q_lims[2] = {0.0,2*pi};\n float qd_lims[2] = {-30.0,30.0};\n float bounds[8] = {5.11906, 0.851226, 24.3475, 20.1005, 0.797881, 6.08757, 24.8026, -16.738};\n // float bounds[8] = {rand_gen(q_lims),rand_gen(q_lims),rand_gen(qd_lims),rand_gen(qd_lims),rand_gen(q_lims),rand_gen(q_lims),rand_gen(qd_lims),rand_gen(qd_lims)};\n cout << bounds[0] << \" \" << bounds[1] << \" \" << bounds[2] << \" \" << bounds[3] << \" \" << bounds[4] << \" \" << bounds[5] << \" \" << bounds[6] << \" \" << bounds[7] << endl;\n bool success = test(bounds);\n return 0;\n}\n", "meta": {"hexsha": "0894d8f07f99a665d50362773dc9a0fee4ba7e3b", "size": 3671, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "2link_direct/src/old/2link_final.cpp", "max_stars_repo_name": "DeepakParamkusam/learning-based-RRT", "max_stars_repo_head_hexsha": "1ca3960c30cacfa86351bf3ebdfa0491589e1d77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-06-13T11:36:45.000Z", "max_stars_repo_stars_event_max_datetime": "2018-06-13T11:36:45.000Z", "max_issues_repo_path": "2link_direct/src/old/2link_final.cpp", "max_issues_repo_name": "DeepakParamkusam/learning-based-RRT", "max_issues_repo_head_hexsha": "1ca3960c30cacfa86351bf3ebdfa0491589e1d77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "2link_direct/src/old/2link_final.cpp", "max_forks_repo_name": "DeepakParamkusam/learning-based-RRT", "max_forks_repo_head_hexsha": "1ca3960c30cacfa86351bf3ebdfa0491589e1d77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3465346535, "max_line_length": 230, "alphanum_fraction": 0.6327976028, "num_tokens": 1283, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797003640645, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.651879822111247}} {"text": "#ifndef LSC_PLANNER_BERNSTEIN_TRAJECTORY_HPP\n#define LSC_PLANNER_BERNSTEIN_TRAJECTORY_HPP\n\n#include \n#include \n#include \n\nnamespace DynamicPlanning{\n static int nChoosek(int n, int k){\n if(k > n) return 0;\n if(k * 2 > n) k = n-k;\n if(k == 0) return 1;\n\n int result = n;\n for(int i = 2; i <= k; i++){\n result *= (n-i+1);\n result /= i;\n }\n return result;\n }\n\n static double getBernsteinBasis(int n, int i, double t_normalized){\n return nChoosek(n, i) * pow(t_normalized, i) * pow(1-t_normalized, n - i);\n }\n\n static octomap::point3d getPointFromControlPoints(std::vector control_points,\n double t_normalized){\n octomap::point3d point;\n double t = t_normalized;\n if(t < 0 - SP_EPSILON || t > 1 + SP_EPSILON){\n throw std::invalid_argument(\"[Polynomial] Input of getPointFromControlPoints is out of bound\");\n }\n\n int n_ctrl = (int)control_points.size() - 1;\n double x = 0, y = 0, z = 0;\n for(int i = 0; i < n_ctrl + 1; i++){\n double b_i_n = getBernsteinBasis(n_ctrl, i, t_normalized);\n x += control_points[i].x() * b_i_n;\n y += control_points[i].y() * b_i_n;\n z += control_points[i].z() * b_i_n;\n }\n\n point = octomap::point3d((float)x, (float)y, (float)z);\n return point;\n }\n\n static double getPointFromControlPoints(std::vector control_points, double t_normalized){\n double t = t_normalized;\n if(t < 0 - SP_EPSILON || t > 1 + SP_EPSILON){\n throw std::invalid_argument(\"[Polynomial] Input of getPointFromControlPoints is out of bound\");\n }\n\n int n_ctrl = (int)control_points.size() - 1;\n double x = 0;\n for(int i = 0; i < n_ctrl + 1; i++){\n double b_i_n = getBernsteinBasis(n_ctrl, i, t_normalized);\n x += control_points[i] * b_i_n;\n }\n\n return x;\n }\n\n static dynamic_msgs::State getStateFromControlPoints(std::vector> control_points,\n double current_time, int M, int n, double dt){\n dynamic_msgs::State state;\n int m = static_cast(current_time / dt);\n if(m == M and current_time < M * dt + SP_EPSILON){\n m = M - 1;\n }\n else if(m >= M){\n throw std::invalid_argument(\"[Polynomial] Input of getOdom is out of bound\");\n }\n\n octomap::point3d position = getPointFromControlPoints(control_points[m], current_time/dt - m);\n state.pose.position.x = position.x();\n state.pose.position.y = position.y();\n state.pose.position.z = position.z();\n\n std::vector velocity_points;\n velocity_points.resize(n);\n for(int i = 0; i < n; i++){\n velocity_points[i] = (control_points[m][i+1] - control_points[m][i]) * n * pow(dt, -1);\n }\n octomap::point3d velocity = getPointFromControlPoints(velocity_points, current_time/dt - m);\n state.velocity.linear.x = velocity.x();\n state.velocity.linear.y = velocity.y();\n state.velocity.linear.z = velocity.z();\n\n std::vector acceleration_points;\n acceleration_points.resize(n-1);\n for(int i = 0; i < n-1; i++){\n acceleration_points[i] = (velocity_points[i+1] - velocity_points[i]) * (n-1) * pow(dt, -1);\n }\n octomap::point3d acceleration = getPointFromControlPoints(acceleration_points, current_time/dt - m);\n state.acceleration.linear.x = acceleration.x();\n state.acceleration.linear.y = acceleration.y();\n state.acceleration.linear.z = acceleration.z();\n\n std::vector jerk_points;\n jerk_points.resize(n-2);\n for(int i = 0; i < n-2; i++){\n jerk_points[i] = (acceleration_points[i+1] - acceleration_points[i]) * (n-2) * pow(dt, -1);\n }\n octomap::point3d jerk = getPointFromControlPoints(jerk_points, current_time/dt - m);\n\n octomap::point3d thrust = acceleration + octomap::point3d(0, 0, 9.81); // add gravity\n\n octomap::point3d z_body = thrust.normalized();\n octomap::point3d x_world(1, 0, 0);\n octomap::point3d y_body = (z_body.cross(x_world)).normalized();\n octomap::point3d x_body = y_body.cross(z_body);\n\n octomap::point3d jerk_orth_zbody = jerk - z_body * jerk.dot(z_body);\n octomap::point3d h_w = jerk_orth_zbody * (1 / thrust.norm());\n octomap::point3d omega(-h_w.dot(y_body), h_w.dot(x_body), 0); //TODO: yaw is 0\n state.velocity.angular.x = omega.x();\n state.velocity.angular.y = omega.y();\n state.velocity.angular.z = omega.z();\n\n return state;\n }\n\n static dynamic_msgs::State getStateFromControlPoints(std::vector> control_points,\n double current_time, int M, int n,\n std::vector time_segments){\n dynamic_msgs::State state;\n int m = 0;\n double t_normalized, segment_length, segment_start_time = 0;\n bool is_time_end = false;\n while(m < M and current_time > time_segments[m+1]){\n segment_start_time = time_segments[m];\n m++;\n }\n if(m == M){\n m = M - 1;\n segment_length = time_segments[m+1] - time_segments[m];\n t_normalized = 1.0;\n is_time_end = true;\n }\n else{\n segment_length = time_segments[m+1] - time_segments[m];\n t_normalized = (current_time - time_segments[m]) / segment_length;\n }\n\n octomap::point3d position = getPointFromControlPoints(control_points[m], t_normalized);\n state.pose.position.x = position.x();\n state.pose.position.y = position.y();\n state.pose.position.z = position.z();\n\n if(is_time_end){\n return state;\n }\n\n std::vector velocity_points;\n velocity_points.resize(n);\n for(int i = 0; i < n; i++){\n velocity_points[i] = (control_points[m][i+1] - control_points[m][i]) * n * pow(segment_length, -1);\n }\n octomap::point3d velocity = getPointFromControlPoints(velocity_points, t_normalized);\n state.velocity.linear.x = velocity.x();\n state.velocity.linear.y = velocity.y();\n state.velocity.linear.z = velocity.z();\n\n std::vector acceleration_points;\n acceleration_points.resize(n-1);\n for(int i = 0; i < n-1; i++){\n acceleration_points[i] = (velocity_points[i+1] - velocity_points[i]) * (n-1) * pow(segment_length, -1);\n }\n octomap::point3d acceleration = getPointFromControlPoints(acceleration_points, t_normalized);\n state.acceleration.linear.x = acceleration.x();\n state.acceleration.linear.y = acceleration.y();\n state.acceleration.linear.z = acceleration.z();\n\n std::vector jerk_points;\n jerk_points.resize(n-1);\n for(int i = 0; i < n-1; i++){\n jerk_points[i] = (acceleration_points[i+1] - acceleration_points[i]) * (n-2) * pow(segment_length, -1);\n }\n octomap::point3d jerk = getPointFromControlPoints(jerk_points, t_normalized);\n\n octomap::point3d thrust = acceleration + octomap::point3d(0, 0, 9.81); // add gravity\n\n octomap::point3d z_body = thrust.normalized();\n octomap::point3d x_world(1, 0, 0);\n octomap::point3d y_body = (z_body.cross(x_world)).normalized();\n octomap::point3d x_body = y_body.cross(z_body);\n\n octomap::point3d jerk_orth_zbody = jerk - z_body * jerk.dot(z_body);\n octomap::point3d h_w = jerk_orth_zbody * (1 / thrust.norm());\n octomap::point3d omega(-h_w.dot(y_body), h_w.dot(x_body), 0); //TODO: yaw is 0\n state.velocity.angular.x = omega.x();\n state.velocity.angular.y = omega.y();\n state.velocity.angular.z = omega.z();\n\n return state;\n }\n\n static std::vector bernsteinFitting(std::vector target_points,\n std::vector ts_normalized){\n int n = (int)target_points.size() - 1;\n Eigen::MatrixXd B = Eigen::MatrixXd(n+1, n+1);\n for(int i = 0; i < n + 1; i++){\n for(int j = 0; j < n + 1; j++){\n B(i, j) = getBernsteinBasis(n, j, ts_normalized[i]);\n }\n }\n\n Eigen::MatrixXd X = Eigen::MatrixXd(n+1, 3);\n for(int i = 0; i < n + 1; i++){\n X(i, 0) = target_points[i].x();\n X(i, 1) = target_points[i].y();\n X(i, 2) = target_points[i].z();\n }\n\n Eigen::MatrixXd C = B.inverse() * X;\n std::vector control_points;\n control_points.resize(n+1);\n for(int i = 0; i < n + 1; i++){\n control_points[i] = octomap::point3d(C(i, 0), C(i, 1), C(i, 2));\n }\n return control_points;\n }\n\n static int coef_derivative(int n, int phi){\n if(n < phi){\n return 0;\n }\n\n int coef = 1;\n for(int i = 0; i < phi; i++){\n coef *= n - i;\n }\n return coef;\n }\n\n struct BisectionElement{\n double c;\n int k;\n Eigen::VectorXd coef;\n };\n\n // return list of [a,b] includes one real root of polynomial which coefficient is coef\n static std::vector> realRootIsolation(const Eigen::VectorXd& coef, int n) {\n std::queue L;\n L.push(BisectionElement{0, 0, coef});\n std::vector> Isol;\n int n_poly = 2 * n - 1;\n\n while (not L.empty()) {\n BisectionElement current_element = L.front();\n L.pop();\n// std::cout << \"current_coef: \" << std::endl << current_element.coef << std::endl;\n if (current_element.coef(0) == 0) {\n for (int i = 0; i < n_poly; i++) {\n current_element.coef(i) = current_element.coef(0, i + 1);\n }\n current_element.coef(n_poly) = 0;\n n_poly--;\n Isol.emplace_back(std::make_pair(current_element.c / pow(2, current_element.k),\n current_element.c / pow(2, current_element.k)));\n }\n\n Eigen::VectorXd coef_test = Eigen::VectorXd::Zero(n_poly + 1);\n for (int i = 0; i < n_poly + 1; i++) {\n for (int j = 0; j < n_poly + 1 - i; j++) {\n coef_test(j) += current_element.coef(i) * nChoosek(n_poly - i, j);\n }\n }\n// std::cout << \"coef_test: \" << std::endl << coef_test << std::endl;\n int var = 0;\n for (int i = 0; i < n_poly; i++) {\n if (coef_test(i) * coef_test(i + 1) < 0) {\n var++;\n }\n }\n if (var == 1) {\n Isol.emplace_back(std::make_pair(current_element.c / pow(2, current_element.k),\n (current_element.c + 1) / pow(2, current_element.k)));\n }\n if (var > 1) {\n Eigen::VectorXd coef1 = current_element.coef;\n for (int i = 0; i < n_poly + 1; i++) {\n coef1(i) *= pow(2, n_poly - i);\n }\n// std::cout << \"coef1: \" << std::endl << coef1 << std::endl;\n L.push(BisectionElement{2 * current_element.c, current_element.k + 1, coef1});\n\n Eigen::VectorXd coef2 = Eigen::VectorXd::Zero(n_poly + 1);\n for (int i = 0; i < n_poly + 1; i++) {\n for (int j = 0; j < i + 1; j++) {\n coef2(j) += current_element.coef(i) * pow(2, n_poly - i) * nChoosek(i, j);\n }\n }\n// std::cout << \"coef2: \" << std::endl << coef2 << std::endl;\n L.push(BisectionElement{2 * current_element.c + 1, current_element.k + 1, coef2});\n }\n }\n return Isol;\n }\n\n static double evalPoly(const Eigen::VectorXd& coef, double t){\n double ret = 0;\n for(int i = 0; i < coef.size(); i++){\n ret += coef(i) * pow(t, i);\n }\n return ret;\n }\n\n // pi_i = obstacle position, pi_j = agent_position\n static double distanceBetweenPolys(const std::vector& control_points_agent,\n const std::vector& control_points_obs,\n const Eigen::MatrixXd& B,\n double poly_root_tolerance,\n octomap::point3d& closest_point) {\n if(control_points_agent.size() != control_points_obs.size()){\n throw std::invalid_argument(\"[Polynomial] degree of two polynomials are not same.\");\n }\n\n int n = (int)control_points_agent.size() - 1;\n int dim = 3;\n\n //get control points of relative trajectory\n std::vector control_points_rel;\n control_points_rel.resize(n + 1);\n for(int i = 0; i < n + 1; i++){\n control_points_rel[i].x() = control_points_agent[i].x() - control_points_obs[i].x();\n control_points_rel[i].y() = control_points_agent[i].y() - control_points_obs[i].y();\n control_points_rel[i].z() = control_points_agent[i].z() - control_points_obs[i].z();\n }\n\n Eigen::MatrixXd control_points_rel_mtx = Eigen::MatrixXd::Zero(dim, n + 1);\n for(int j = 0; j < n + 1; j++){\n control_points_rel_mtx(0, j) = control_points_rel[j].x();\n control_points_rel_mtx(1, j) = control_points_rel[j].y();\n control_points_rel_mtx(2, j) = control_points_rel[j].z();\n }\n\n // convert to coef of standard basis\n Eigen::MatrixXd coef = control_points_rel_mtx * B;\n\n // get derivative of coef\n Eigen::MatrixXd coef_derivative = Eigen::MatrixXd::Zero(dim, n + 1);\n for(int j = 0; j < n; j++){\n coef_derivative(0, j) = (j + 1) * coef(0, j + 1);\n coef_derivative(1, j) = (j + 1) * coef(1, j + 1);\n coef_derivative(2, j) = (j + 1) * coef(2, j + 1);\n }\n\n // coef dot coef_derivative\n Eigen::VectorXd coef_g = Eigen::VectorXd::Zero(2 * n);\n for(int j0 = 0; j0 < n + 1; j0++){\n for(int j1 = 0; j1 < n; j1++){\n for(int k = 0; k < dim; k++) {\n coef_g(j0 + j1) += coef(k, j0) * coef_derivative(k, j1);\n }\n }\n }\n\n // real root isolation\n std::vector> Isol = realRootIsolation(coef_g, n);\n\n // compute closest point by Newton method\n bool isClosestPointInSection = false;\n double a, b, m, g_m, t_cand, dist_cand;\n double dist_closest = SP_INFINITY;\n octomap::point3d p_cand;\n for(auto section : Isol){\n a = section.first;\n b = section.second;\n if(evalPoly(coef_g, a) < 0 and evalPoly(coef_g, b) > 0) {\n while (true) {\n if (b - a < poly_root_tolerance) {\n t_cand = (a + b) / 2;\n break;\n }\n m = (a + b) / 2;\n g_m = evalPoly(coef_g, m);\n if (g_m == 0) {\n t_cand = m;\n break;\n } else if (g_m < 0) {\n a = m;\n } else {\n b = m;\n }\n }\n p_cand = getPointFromControlPoints(control_points_rel, t_cand);\n dist_cand = p_cand.norm();\n if(dist_cand < dist_closest){\n closest_point = p_cand;\n dist_closest = dist_cand;\n// t_normalized_closest = t_cand;\n isClosestPointInSection = true;\n }\n }\n }\n if(not isClosestPointInSection){\n if(control_points_rel[0].norm() < control_points_rel[n].norm()){\n closest_point = control_points_rel[0];\n// t_normalized_closest = 0;\n }\n else{\n closest_point = control_points_rel[n];\n// t_normalized_closest = 1;\n }\n }\n\n return closest_point.norm();\n// // Exception handle for first segment\n// if(m == 0 && p_closest.norm() < d[0] - SP_EPSILON_FLOAT){\n// p_closest = control_points_rel[0];\n// }\n }\n\n static void buildBernsteinBasis(int n, Eigen::MatrixXd& B, Eigen::MatrixXd& B_inv) {\n B = Eigen::MatrixXd::Zero(n + 1, n + 1);\n for(int i = 0; i < n + 1; i++){\n for(int j = 0; j < n + 1; j++){\n if(j >= i){\n B(i,j) = nChoosek(n, i) * nChoosek(n-i, n-j) * pow(-1, j-i);\n }\n else{\n B(i,j) = 0;\n }\n }\n }\n B_inv = B.inverse();\n }\n\n static std::vector subdivisionBernsteinCurve(\n const std::vector& control_points, double a, double b,\n const Eigen::MatrixXd& B, const Eigen::MatrixXd& B_inv){\n size_t n = control_points.size() - 1;\n Eigen::MatrixXd A = Eigen::MatrixXd::Zero(n + 1, n + 1);\n for(int i = 0; i < n + 1; i++){\n for(int j = 0; j < i + 1; j++){\n A(i, j) = nChoosek(i, j) * pow(a, j) * pow(b, i - j);\n }\n }\n\n Eigen::MatrixXd c_tr = Eigen::MatrixXd::Zero(3, n + 1);\n for(int k = 0; k < 3; k++){\n for(int i = 0; i < n + 1; i++){\n c_tr(k, i) = control_points[i](k);\n }\n }\n c_tr = c_tr * B * A * B_inv;\n\n std::vector control_points_tr;\n control_points_tr.resize(n + 1);\n for(int i = 0; i < n + 1; i++){\n control_points_tr[i] = octomap::point3d(c_tr(0, i), c_tr(1, i), c_tr(2, i));\n }\n return control_points_tr;\n }\n}\n#endif //LSC_PLANNER_BERNSTEIN_TRAJECTORY_HPP\n", "meta": {"hexsha": "17085b7f40656da6f54ff3c75b2ade3d16981440", "size": 18622, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/polynomial.hpp", "max_stars_repo_name": "dabinkim-LGOM/lsc_planner", "max_stars_repo_head_hexsha": "88dcb1de59bac810d1b1fd194fe2b8d24d1860c9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9.0, "max_stars_repo_stars_event_min_datetime": "2021-09-04T15:14:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T04:34:13.000Z", "max_issues_repo_path": "include/polynomial.hpp", "max_issues_repo_name": "dabinkim-LGOM/lsc_planner", "max_issues_repo_head_hexsha": "88dcb1de59bac810d1b1fd194fe2b8d24d1860c9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/polynomial.hpp", "max_forks_repo_name": "dabinkim-LGOM/lsc_planner", "max_forks_repo_head_hexsha": "88dcb1de59bac810d1b1fd194fe2b8d24d1860c9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2021-09-29T11:32:54.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-06T05:24:33.000Z", "avg_line_length": 40.6593886463, "max_line_length": 115, "alphanum_fraction": 0.5202448717, "num_tokens": 4800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6518798203856876}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n/// helper functions\ntemplate void fill_random(ForwardIt begin, ForwardIt end) {\n\tstd::random_device rndDev;\n\tstd::mt19937 rndEng{rndDev()};\n\tusing T = typename std::iterator_traits::value_type;\n\tstd::uniform_real_distribution dist{-1.0, 1.0};\n\n\tstd::generate(begin, end, [&] { return dist(rndEng); });\n}\n\ntemplate auto timed(T&& f) {\n\tconst auto starttime = std::chrono::high_resolution_clock::now();\n\tf();\n\treturn std::chrono::duration{\n\t std::chrono::high_resolution_clock::now() - starttime}\n\t .count();\n}\n\ntemplate [[noreturn]] void failInvalidArgs(const Map& modes) {\n\tstd::cerr << \"invalid args!\\nusage: prog \"\n\t << boost::algorithm::join(\n\t modes | boost::adaptors::transformed(\n\t [](const auto& p) { return p.first; }),\n\t \"|\")\n\t << \"\\n\";\n\tstd::exit(EXIT_FAILURE);\n}\n\n/// gemm implementations\ntemplate \nvoid serialIkj(const T* a, const T* b, T* c, std::size_t aRows,\n std::size_t aCols, std::size_t bCols) {\n\tfor (std::size_t i{0}; i < aRows; ++i) {\n\t\tfor (std::size_t k{0}; k < aCols; ++k) {\n\t\t\tfor (std::size_t j{0}; j < bCols; ++j) {\n\t\t\t\tc[i * bCols + j] += a[i * aCols + k] * b[k * bCols + j];\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate \nvoid serialIjk(const T* a, const T* b, T* c, std::size_t aRows,\n std::size_t aCols, std::size_t bCols) {\n\tfor (std::size_t i{0}; i < aRows; ++i) {\n\t\tfor (std::size_t j{0}; j < bCols; ++j) {\n\t\t\tfor (std::size_t k{0}; k < aCols; ++k) {\n\t\t\t\tc[i * bCols + j] += a[i * aCols + k] * b[k * bCols + j];\n\t\t\t}\n\t\t}\n\t}\n}\n\ntemplate \nvoid parallelGemm(const T* a, const T* b, T* c, std::size_t aRows,\n std::size_t aCols, std::size_t bCols) {\n// use std::for_each(std::execution::par, ... ) in\n// C++17 instead\n#pragma omp parallel for\n\tfor (std::size_t i = 0; i < aRows; ++i) {\n\t\tfor (std::size_t k{0}; k < aCols; ++k) {\n\t\t\tfor (std::size_t j{0}; j < bCols; ++j) {\n\t\t\t\tc[i * bCols + j] += a[i * aCols + k] * b[k * bCols + j];\n\t\t\t}\n\t\t}\n\t}\n}\n\n// float overload\nvoid blasGemm(const float* a, const float* b, float* c, std::size_t aRows,\n std::size_t aCols, std::size_t bCols) {\n\tconst auto m = aRows;\n\tconst auto k = aCols;\n\tconst auto n = bCols;\n\tconst float alf = 1;\n\tconst float bet = 0;\n\n\tcblas_sgemm(CblasRowMajor, // CBLAS_LAYOUT layout,\n\t CblasNoTrans, // CBLAS_TRANSPOSE TransA,\n\t CblasNoTrans, // CBLAS_TRANSPOSE TransB,\n\t m, // const int M,\n\t n, // const int N,\n\t k, // const int K,\n\t alf, // const float alpha,\n\t a, // const float *A,\n\t k, // const int lda,\n\t b, // const float *B,\n\t n, // const int ldb,\n\t bet, // const float beta,\n\t c, // float *C,\n\t n // const int ldc\n\t );\n}\n\n// double overload\nvoid blasGemm(const double* a, const double* b, double* c, std::size_t aRows,\n std::size_t aCols, std::size_t bCols) {\n\tconst auto m = aRows;\n\tconst auto k = aCols;\n\tconst auto n = bCols;\n\tconst double alf = 1;\n\tconst double bet = 0;\n\n\tcblas_dgemm(CblasRowMajor, // CBLAS_LAYOUT layout,\n\t CblasNoTrans, // CBLAS_TRANSPOSE TransA,\n\t CblasNoTrans, // CBLAS_TRANSPOSE TransB,\n\t m, // const int M,\n\t n, // const int N,\n\t k, // const int K,\n\t alf, // const double alpha,\n\t a, // const double *A,\n\t k, // const int lda,\n\t b, // const double *B,\n\t n, // const int ldb,\n\t bet, // const double beta,\n\t c, // double *C,\n\t n // const int ldc\n\t );\n}\n\nint main(int argc, char* argv[]) {\n\tusing Real = float;\n\tusing gemmFuncType = void(const Real*, const Real*, Real*, std::size_t,\n\t std::size_t, std::size_t);\n\tusing gemmFuncPrtType = void (*)(const Real*, const Real*, Real*,\n\t std::size_t, std::size_t, std::size_t);\n\n\t// this map manages all implementations\n\tstd::map> modes{\n\t {\"serialikj\", &serialIkj},\n\t {\"serialijk\", &serialIjk},\n\t {\"parallel\", ¶llelGemm},\n\t {\"blas\", static_cast(&blasGemm)}};\n\n\t// validate cmd args and select gemm implementation\n\tif (argc != 2) { failInvalidArgs(modes); }\n\tconst std::string modeArg = argv[1];\n\tif (modes.count(modeArg) != 1) { failInvalidArgs(modes); }\n\tconst auto gemm = modes[modeArg];\n\n\t// benchmark sizes\n\tconst auto minSize = 2u;\n\tconst auto maxSize = 2048u;\n\tconst auto maxRepetitions = 2048u;\n\n\t// do measurements with increasing matrix dimensions and decreasing\n\t// repetitions to keep wall clock time short\n\tstd::size_t repetitions{};\n\tstd::size_t size{};\n\tfor (size = minSize, repetitions = maxRepetitions; size <= maxSize;\n\t size *= 2, repetitions /= 2) {\n\n\t\t/// set up data\n\t\tconst auto aRows = size;\n\t\tconst auto aCols = size;\n\t\tconst auto bRows = size;\n\t\tconst auto bCols = size;\n\n\t\tstd::vector a(aRows * aCols); // m * k\n\t\tstd::vector b(bRows * bCols); // k * n\n\t\tstd::vector c(aRows * bCols); // m * n\n\n\t\tfill_random(std::begin(a), std::end(a));\n\t\tfill_random(std::begin(b), std::end(b));\n\n\t\t// create reference solution matrix using serialIkj\n\t\tstd::vector reference(c.size());\n\t\tserialIkj(a.data(), b.data(), reference.data(), aRows, aCols, bCols);\n\n\t\t/// warm up the caches\n\t\tgemm(a.data(), b.data(), c.data(), aRows, aCols, bCols);\n\n\t\t/// timed computations\n\t\tauto time = 0.0;\n\t\tfor (std::size_t r{0}; r < repetitions; ++r) {\n\t\t\tstd::fill(std::begin(c), std::end(c), 0);\n\t\t\ttime += timed([&]() {\n\t\t\t\tgemm(a.data(), b.data(), c.data(), aRows, aCols, bCols);\n\t\t\t});\n\n\t\t\t// validate the result c\n\t\t\tif (!std::equal(std::begin(c), std::end(c), std::begin(reference),\n\t\t\t std::end(reference),\n\t\t\t [](const Real& l, const Real& r) {\n\t\t\t\t return std::abs(l - r) < 1.0e-3;\n\t\t\t\t })) {\n\t\t\t\tstd::cerr << \"validation error!\\n\";\n\t\t\t\treturn EXIT_FAILURE;\n\t\t\t}\n\t\t}\n\t\ttime /= repetitions; // get avg time per call\n\n\t\tstd::cout << size << \";\" << time << '\\n';\n\t}\n}", "meta": {"hexsha": "e68816e1057edbbb259ce1349537a8addd3d1d38", "size": 6771, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gemm/mklblas/main.cpp", "max_stars_repo_name": "pengdada/dense_linear_algebra", "max_stars_repo_head_hexsha": "4787deb76e9afb602511ff3eceb1b3c00361d5be", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gemm/mklblas/main.cpp", "max_issues_repo_name": "pengdada/dense_linear_algebra", "max_issues_repo_head_hexsha": "4787deb76e9afb602511ff3eceb1b3c00361d5be", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gemm/mklblas/main.cpp", "max_forks_repo_name": "pengdada/dense_linear_algebra", "max_forks_repo_head_hexsha": "4787deb76e9afb602511ff3eceb1b3c00361d5be", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.2428571429, "max_line_length": 80, "alphanum_fraction": 0.5499926156, "num_tokens": 1938, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8244619350028204, "lm_q2_score": 0.7905303186696747, "lm_q1q2_score": 0.6517621562087963}} {"text": "#include \n\n#include \n\n#include \"polynomial.hpp\"\n\nint main(int argc, char* argv[])\n{\n (void)argc;\n (void)argv;\n\n NTL::ZZ p((long)17);\n NTL::ZZ_p::init(p);\n NTL::ZZ_p k(6);\n\n std::cout << k << std::endl;\n std::cout << k * 2 << std::endl;\n std::cout << k * 3 << std::endl;\n std::cout << k * 4 << std::endl;\n\n unsigned int arity = 3;\n unsigned int degree = 5;\n unsigned int order = 7;\n\n MultiVariatePolynomial poly(arity, degree, order);\n\n NTL::ZZ_p value(5);\n std::vector monomial = { 0, 3, 1 };\n poly.setElement(monomial, value);\n\n poly.print();\n\n std::cout << poly.to_string() << std::endl;\n std::cout << poly.add(poly).to_string() << std::endl;\n std::cout << (poly + poly).to_string() << std::endl;\n std::cout << (poly - poly).to_string() << std::endl;\n\n std::cout << poly.getMaxNbElements() << std::endl;\n\n std::vector point = { NTL::ZZ_p(1), NTL::ZZ_p(1), NTL::ZZ_p(4) };\n std::cout << poly.evaluate(point) << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "ebdce3a06ccd40e8edf97929edd9c638f964c541", "size": 1059, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/polynomial/main.cc", "max_stars_repo_name": "pierreeliseeflory/PANDA", "max_stars_repo_head_hexsha": "871ac4db92e3ed0a769b1a1f69c67d8ccdaf911d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/polynomial/main.cc", "max_issues_repo_name": "pierreeliseeflory/PANDA", "max_issues_repo_head_hexsha": "871ac4db92e3ed0a769b1a1f69c67d8ccdaf911d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/polynomial/main.cc", "max_forks_repo_name": "pierreeliseeflory/PANDA", "max_forks_repo_head_hexsha": "871ac4db92e3ed0a769b1a1f69c67d8ccdaf911d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.5333333333, "max_line_length": 80, "alphanum_fraction": 0.5646836638, "num_tokens": 348, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392878563336, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6516767720229667}} {"text": "#include \n#include \n#include \n#include \n#include \"bateman.hpp\"\n\nusing Real_t = boost::multiprecision::cpp_dec_float_50;\nusing vec_t = std::vector;\nReal_t exp_cb(Real_t arg){\n return boost::multiprecision::exp(arg);\n}\n\nint main(){\n Real_t one = 1;\n Real_t d = one/365;\n Real_t h = d/24;\n Real_t ln2 = boost::multiprecision::log(2*one);\n vec_t lmbd {{ ln2/1.405e10, ln2/5.75, ln2/(6.25*h),\n ln2/1.9116, ln2/(3.6319*d), ln2/(10.64*h), ln2/(60.55/60*h) }};\n auto p = bateman::bateman_parent(lmbd, static_cast(100), exp_cb);\n std::cout << std::setprecision(30); // show 30 of our 50 digits\n for (auto v : p)\n std::cout << v << \" \";\n std::cout << std::endl;\n return 0;\n}\n", "meta": {"hexsha": "71f9db0765e0879a4c2317f46cb03cc526f88f8e", "size": 782, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "examples/multi.cpp", "max_stars_repo_name": "bjodah/batemaneq", "max_stars_repo_head_hexsha": "00ba061737151a5eb46bd2281a8351e5c5e7966c", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2017-02-02T13:04:41.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-27T16:04:55.000Z", "max_issues_repo_path": "examples/multi.cpp", "max_issues_repo_name": "Rolleroo/batemaneq", "max_issues_repo_head_hexsha": "bd8c24d1f77ccb166b3210d81d9468f7789813ad", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-08-27T22:21:08.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-09T06:42:15.000Z", "max_forks_repo_path": "examples/multi.cpp", "max_forks_repo_name": "Rolleroo/batemaneq", "max_forks_repo_head_hexsha": "bd8c24d1f77ccb166b3210d81d9468f7789813ad", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2019-07-27T16:05:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-05-05T08:15:21.000Z", "avg_line_length": 28.962962963, "max_line_length": 76, "alphanum_fraction": 0.6406649616, "num_tokens": 267, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897509188345, "lm_q2_score": 0.6926419767901475, "lm_q1q2_score": 0.651630472820332}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n\n#define KEY_BYTES_SIZE 32\n\nusing BigInt = boost::multiprecision::int1024_t;\n\nstruct Point {\n int x;\n BigInt y;\n\n Point(int x, const BigInt& y) : x(x), y(y) {}\n\n friend std::ostream& operator<<(std::ostream& stream, const Point& rhs);\n};\n\nstd::string format_to_hex(const BigInt& num) {\n std::stringstream ss;\n ss << std::hex << std::setfill('0') << std::setw(KEY_BYTES_SIZE * 2) << num;\n\n return ss.str();\n}\n\nstd::ostream& operator<<(std::ostream& stream, const Point& rhs) {\n stream << rhs.x << \" \" << format_to_hex(rhs.y);\n\n return stream;\n}\n\ntemplate \nT convert_from_hex(const std::string& hex_str) {\n std::stringstream ss;\n ss << std::hex << hex_str;\n\n T v;\n ss >> v;\n\n return v;\n}\n\ntemplate \nstd::string generate_random_hex() {\n std::stringstream ss;\n ss << std::hex << std::setfill('0');\n\n for (size_t i = 0; i < bytes_count; i++) {\n ss << std::setw(2) << rand() % 256;\n }\n\n return ss.str();\n}\n\nBigInt PRIME = convert_from_hex(\"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF43\");\n\nstd::vector generate_random_coefficients(uint32_t size) {\n std::vector coefficients;\n for (uint32_t i = 0; i < size; i++) {\n BigInt random = convert_from_hex(generate_random_hex());\n coefficients.push_back(random % PRIME);\n }\n\n return coefficients;\n}\n\nBigInt calculate_polynomial(\n std::vector& coefficients,\n uint8_t argument\n) {\n BigInt result = 0;\n size_t coefficients_count = coefficients.size();\n for (size_t i = 1; i <= coefficients_count; i++) {\n result += coefficients[i - 1] * pow(BigInt(argument), coefficients_count - i);\n }\n\n return result % PRIME;\n}\n\nstd::vector split(\n uint8_t shares_count, \n uint8_t entry_threshold, \n const BigInt& secret\n) {\n std::vector coefficients = generate_random_coefficients(entry_threshold - 1);\n coefficients.push_back(secret);\n\n std::vector points;\n for (uint8_t i = 1; i <= shares_count; i++) {\n points.push_back(Point(i, calculate_polynomial(coefficients, i)));\n }\n\n return points;\n}\n\nBigInt recover(std::vector& shares) {\n auto l = [shares](int x, size_t i) -> BigInt {\n double result = 1;\n\n for (size_t j = 0; j < shares.size(); j++) {\n if (j != i) {\n result *= (\n static_cast(x) - \n static_cast(shares[j].x)) / \n (static_cast(shares[i].x) - \n static_cast(shares[j].x)\n );\n }\n }\n \n return BigInt(result);\n };\n\n BigInt result = 0;\n for (size_t i = 0; i < shares.size(); i++) {\n result += shares[i].y * l(0, i);\n }\n\n return result % PRIME;\n}\n\nint main(int args_count, char** args_value) {\n srand(static_cast(time(0)));\n\n if (args_count < 2) {\n return 1;\n }\n\n std::string first_argument(args_value[1]);\n\n if (first_argument == \"recover\") {\n int shares_count = 0;\n std::cin >> shares_count;\n\n std::vector shares;\n for (int i = 0; i < shares_count; i++) {\n int x = 0;\n std::string y;\n\n std::cin >> x >> y;\n shares.push_back(Point(x, convert_from_hex(y)));\n }\n\n BigInt result = recover(shares);\n\n std::cout << format_to_hex(result) << std::endl;\n } else if (first_argument == \"split\") {\n int shares_count = 0;\n int entry_threshold = 0;\n std::string string_secret;\n\n std::cin >> shares_count >> entry_threshold >> string_secret;\n\n if (shares_count < entry_threshold) {\n std::cout << \"Shares count must be higher than entry threshold\" << std::endl;\n return 1;\n }\n\n BigInt secret = convert_from_hex(string_secret);\n\n if (secret > PRIME) {\n std::cout << \"Your secret must be less than prime number\" << std::endl;\n return 1;\n }\n\n auto shares = split(shares_count, entry_threshold, secret);\n\n for (const auto& point : shares) {\n std::cout << point << std::endl;\n }\n } else {\n std::cout << \"Unknow arguments\" << std::endl;\n }\n}", "meta": {"hexsha": "5b77ff23cf9f2c999a192ac09462765d449ac731", "size": 4499, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "AleksMVP/shamir-secret", "max_stars_repo_head_hexsha": "b240e2aeab01cf8b8f2e680133c619812b3aae43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-09T15:36:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T15:36:14.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "AleksMVP/shamir-secret", "max_issues_repo_head_hexsha": "b240e2aeab01cf8b8f2e680133c619812b3aae43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "AleksMVP/shamir-secret", "max_forks_repo_head_hexsha": "b240e2aeab01cf8b8f2e680133c619812b3aae43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.5625, "max_line_length": 108, "alphanum_fraction": 0.5814625472, "num_tokens": 1133, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9362850039701655, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6516153431170159}} {"text": "/**\n * linalg.hpp\n *\n * 2021 Gabriel Moreira\n *\n * https://github.com/gabmoreira/maks\n *\n * This software and the related documents are provided as is, with no express\n * or implied warranties, other than those that are expressly stated in the\n * License.\n *\n * Copyright © 2021 Gabriel Moreira. All rights reserved.\n */\n\n#ifndef LINALG_HPP\n#define LINALG_HPP\n\n#include \n#include \n#include \n\n/* Linear algebra namespace */\nnamespace alg {\n\n\n/**\n * Converts two vectors i and j to matrix indices (in-place).\n *\n * @param ei (input) Eigen::VectorXi - row indices.\n * @param ej (input) Eigen::VectorXi - column indices.\n * @param num_nodes (output) int - number of nodes.\n */\nvoid convertToIdx(Eigen::Ref ei,\n Eigen::Ref ej,\n int& num_nodes);\n\n\n/**\n * Builds sparse graph adjacency matrix.\n *\n * @param ei (input) Eigen::VectorXi - row indices.\n * @param ej (input) Eigen::VectorXi - column indices.\n * @param num_edges (input) int - number of edges.\n * @param sym (input) bool - whether to make the matrix symmetric.\n * @param dst (output) Eigen::SparseMatrix - output adjacency matrix.\n */\nvoid adjacency(const Eigen::Ref ei,\n const Eigen::Ref ej,\n int num_edges,\n bool sym,\n Eigen::SparseMatrix& dst);\n\n\n/**\n * Builds sparse block matrix.\n *\n * @param ei (input) Eigen::VectorXi - row indices.\n * @param ej (input) Eigen::VectorXi - column indices.\n * @param blocks (input) Eigen::MatrixXd - row block matrix containing contiguous blocks.\n * @param block_height (input) int - block height.\n * @param block_width (input) int - block width.\n * @param num_blocks (input) int - number of contiguous blocks.\n * @param sym (input) bool - whether to make the matrix symmetric.\n * @param dst (output) Eigen::SparseMatrix - output adjacency matrix.\n */\nvoid sparseBlocks(const Eigen::Ref ei,\n const Eigen::Ref ej,\n const Eigen::Ref blocks,\n int block_height,\n int block_width,\n int num_blocks,\n bool sym,\n Eigen::SparseMatrix& dst);\n\n\n/**\n * Solves the orthogonal Procrustes problem in SO(3) (in-place).\n *\n * @param mat (input/output) Eigen::MatrixXd - 3x3 matrix\n */\nvoid orthoProcrustesSO3(Eigen::Ref mat);\n\n\n/**\n * Solves the orthogonal Procrustes problem in O(3) (in-place).\n *\n * @param mat (input/output) Eigen::MatrixXd - 3x3 matrix.\n */\nvoid orthoProcrustesO3(Eigen::Ref mat);\n\n\n/**\n * Finds the projection of a vector on a subpace spanned by the columns of a matrix.\n *\n * @param subspace_basis (input) Eigen::MatrixXd - Dense matrix whose columns span a subspace\n * where we want to project the vector v.\n * @param idx (input) unsigned int - Sub-selects of the first idx columns of A only.\n * @param v (input) Eigen::VectorXd - Vector to project.\n * @return The component of the vector in the subspace spanned by the first\n * idx columns of the input matrix A.\n */\nEigen::VectorXd projectionOnto(const Eigen::Ref subspace_basis,\n unsigned int idx,\n const Eigen::Ref v);\n\n\n/**\n * Projects a vector onto a subpace spanned by the columns of a matrix (in-place)\n *\n * @param subspace_basis (input) Eigen::MatrixXd - Dense matrix whose columns span a subspace where we\n * want to project the vector v.\n * @param idx (input) unsigned int - Sub-selects of the first idx columns of A only.\n * @param v (input/output) Eigen::VectorXd - Vector to project.\n */\nvoid projectOnto(const Eigen::Ref subspace_basis,\n unsigned int idx,\n Eigen::Ref v);\n\n\n/**\n * Symmetric sparse solver via LDLT decomposition.\n *\n * Solves sparse system Ax = b via LDLt decomposition.\n *\n * @param solver (input) Eigen::PardisoLDLT - LDLt Intel PARDISO solver\n * @param mat (input) Eigen::MatrixXd - matrix to factorize.\n * @param rhs (input) Eigen::VectorXd - right hand side.\n * @param x (output) Eigen::VectorXd - solution of the system.\n */\nvoid sparseSolverLDL(Eigen::PardisoLDLT>* solver,\n const Eigen::SparseMatrix& mat,\n const Eigen::Ref rhs,\n Eigen::Ref x);\n\n\n/**\n * Robust reorthogonalization. For an input matrix V and an input\n * vector r, tries to iteratively orthogonalize r against the j first columns\n * of V. This prevents numerical errors and ensures orthogonality. If, by any\n * chance, and after multiple iterations of subtracting projections, the vector\n * has a norm smaller than 1/sqrt(2) of its starting norm, it cannot be\n * reorthogonalized. This method then attempts to find another orthogonal vector\n * through random restarts. The flag stop is activated if everything fails.\n * (See G. W. Stewart 2001)\n *\n * @param V (input) Dense matrix of doubles whose columns contain orthogonal basis\n * vectors\n * @param r (input/output) Vector to orthogonalize\n * @param residual_norm (output) Residual norm or r after it has been orthogonalized against the first j columns of V.\n * @param idx (input) Index specifying the number of columns of V used in the orthogonalization.\n * @param stop (output) Stop the algorithm flag. Indicates that it is impossible to find, to machine precision, a vector r orthogonal to the first j cols of V.\n */\nvoid reorthogonalize(const Eigen::Ref V,\n Eigen::Ref r,\n double& residual_norm,\n unsigned int idx,\n int& stop);\n\n\n/**\n * Symmetric Krylov-Schur LDLt eigensolver.\n *\n * For a real sparse symmetric matrix A, this function computes k real eigenvalues\n * near a real target sigma using the Krylov-Schur method (G. W. Stewart 2001).\n *\n * @param solver (input) Eigen::PardisoLDLT - LDLt Intel PARDISO solver.\n * @param mat (input) Eigen::SparseMatrix - sparse matrix to compute eigenvalues and eigenvectors.\n * @param eigenvalues (output) Eigen::VectorXd - k x 1 matrix to store the computed eigenvalues.\n * @param eigenvectors (output) Eigen::MatrixXd - n x k matrix to store normalized eigenvectors.\n * @param k (input) int - number of eigenvalues and eigenvectors to be computed.\n * @param sigma (input) double - spectral shift / eigenvalue target.\n*/\nvoid symKrylovSchurLDL(Eigen::PardisoLDLT>* solver,\n const Eigen::SparseMatrix& mat,\n Eigen::Ref eigenvalues,\n Eigen::Ref eigenvectors,\n unsigned int k,\n double sigma);\n\n};\n\n#endif /* LINALG_HPP */\n", "meta": {"hexsha": "641e8ad61483b2c9921c0f55fcdd9c5f7d8be944", "size": 7074, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/linalg.hpp", "max_stars_repo_name": "rjanvier/maks", "max_stars_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 50.0, "max_stars_repo_stars_event_min_datetime": "2020-12-15T10:15:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T03:19:07.000Z", "max_issues_repo_path": "include/linalg.hpp", "max_issues_repo_name": "rjanvier/maks", "max_issues_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-12-15T12:24:14.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T12:47:43.000Z", "max_forks_repo_path": "include/linalg.hpp", "max_forks_repo_name": "rjanvier/maks", "max_forks_repo_head_hexsha": "30808dd29cc29ba447bd23823259eca4695579aa", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-11-06T07:22:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-18T09:31:30.000Z", "avg_line_length": 38.6557377049, "max_line_length": 159, "alphanum_fraction": 0.6668080294, "num_tokens": 1700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637505099167, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6514483560276051}} {"text": "#ifndef CPPMATH_OPTIMIZATION_DOWNHILLSIMPLEXMETHOD_HPP_\n#define CPPMATH_OPTIMIZATION_DOWNHILLSIMPLEXMETHOD_HPP_\n\n#include // size_t\n\n#include \n\nnamespace cppmath\n{\n /**\n * Implementation of Downhill Simplex or Nelder-Mead method for nonlinear optimization from 1998.\n * J. Lagarias, J. Reeds, M. Wright, P. Wright,\n * \"Convergence Properties of the Nelder-Mead Simplex Method in Low Dimensions,\"\n * SIAM Journal of Optimization, 1998, 9, 112-147\n *\n * \\author cpieloth\n * \\copyright Copyright 2014 Christof Pieloth, Licensed under the Apache License, Version 2.0\n */\n template< size_t DIM >\n class DownhillSimplexMethod\n {\n public:\n typedef Eigen::Matrix< double, DIM, 1 > ParamsT; /**< Abbreviation for a vector of parameters. */\n\n /**\n * Enum to indicate how the optimization was converged.\n */\n enum Converged\n {\n CONVERGED_NO, /**< Optimization was not started. */\n CONVERGED_EPSILON, /**< Optimization is smaller than epsilon/threshold. */\n CONVERGED_ITERATIONS, /**< Maximum iterations was reached. */\n CONVERGED_YES /**< Optimization is converged, but not specified how. */\n };\n\n DownhillSimplexMethod();\n virtual ~DownhillSimplexMethod();\n\n /**\n * Implementation of the function to minimize.\n *\n * \\param x n-dimensional parameter vector.\n * \\return function value for vector x.\n */\n virtual double func( const ParamsT& x ) const = 0;\n\n double getReflectionCoeff() const;\n\n void setReflectionCoeff( double coeff );\n\n double getContractionCoeff() const;\n\n void setContractionCoeff( double coeff );\n\n double getExpansionCoeff() const;\n\n void setExpansionCoeff( double coeff );\n\n double getShrinkageCoeff() const;\n\n void setShrinkageCoeff( double coeff );\n\n size_t getMaximumIterations() const;\n\n void setMaximumIterations( size_t iterations );\n\n double getEpsilon() const;\n\n void setEpsilon( double eps );\n\n double getInitialFactor() const;\n\n void setInitialFactor( double factor );\n\n size_t getResultIterations() const;\n\n ParamsT getResultParams() const;\n\n double getResultError() const;\n\n /**\n * Starts the optimization.\n *\n * \\param initial Initial start point.\n * \\return Enum::Converged\n */\n Converged optimize( const ParamsT& initial );\n\n protected:\n /**\n * Orders the parameters x and f(x) from min to max.\n */\n virtual void order();\n\n /**\n * Checks if the optimization has been converged.\n *\n * \\return Enum::Converged\n */\n virtual Converged converged() const;\n\n /**\n * Creates the initial parameter set and their function values.\n *\n * \\param initial Start parameter used to calculate initials.\n */\n virtual void createInitials( const ParamsT& initial );\n\n double m_initFactor; /**< Factor to create the initial parameter set. */\n\n ParamsT m_x[DIM + 1]; /**< Vector of all n+1 points. */\n double m_f[DIM + 1]; /**< Stores the function values to reduce re-calculation. */\n\n double m_epsilon; /**< Threshold or deviation for convergence. */\n size_t m_maxIterations; /**< Maximum iterations until the algorithm is canceled. */\n size_t m_iterations; /**< Iteration counter used for break condition. */\n\n const size_t DIMENSION; /**< Constant for dimension. */\n const size_t VALUES; /**< Constant for DIM+1. */\n\n private:\n enum Step\n {\n STEP_START, STEP_EXIT, STEP_REFLECTION, STEP_EXPANSION, STEP_CONTRACTION, STEP_SHRINKAGE\n };\n\n const size_t N; /**< Index n=DIM-1 */\n const size_t N1; /**< Index n+1=DIM */\n\n double m_refl; /**< Reflection coefficient. */\n double m_contr; /**< Contraction coefficient. */\n double m_exp; /**< Expansion coefficient. */\n double m_shri; /**< Shrinkage coefficient. */\n\n void centroid();\n void accept( const ParamsT& x, double f );\n\n Step reflection();\n Step expansion();\n Step contraction();\n Step shrinkage();\n\n ParamsT m_xo;\n ParamsT m_xr;\n double m_fr;\n };\n} /* namespace cppmath */\n\n// Load the implementation\n#include \"DownhillSimplexMethod-impl.hpp\"\n\n#endif // CPPMATH_OPTIMIZATION_DOWNHILLSIMPLEXMETHOD_HPP_\n", "meta": {"hexsha": "c559bef18842d96c329e71e0e6662f7ca361d976", "size": 4591, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/cppmath/optimization/DownhillSimplexMethod.hpp", "max_stars_repo_name": "cpieloth/CppMath", "max_stars_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/cppmath/optimization/DownhillSimplexMethod.hpp", "max_issues_repo_name": "cpieloth/CppMath", "max_issues_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/cppmath/optimization/DownhillSimplexMethod.hpp", "max_forks_repo_name": "cpieloth/CppMath", "max_forks_repo_head_hexsha": "58d1c7f0ea07dab9f913b946a251a01b0827bb39", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0065359477, "max_line_length": 105, "alphanum_fraction": 0.6144630799, "num_tokens": 1007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.7577943767446202, "lm_q1q2_score": 0.6514483505784399}} {"text": "#ifndef SM_MATH_HOMOGENEOUS_COORDINATES_HPP\n#define SM_MATH_HOMOGENEOUS_COORDINATES_HPP\n\n#include \n\nnamespace sm {\nnamespace kinematics {\n\nEigen::Matrix toHomogeneousJacobian(const Eigen::Vector3d& v);\nEigen::Vector4d toHomogeneous(const Eigen::Vector3d& v, Eigen::Matrix* jacobian = NULL);\n\nEigen::Matrix fromHomogeneousJacobian(const Eigen::Vector4d& v);\nEigen::Vector3d fromHomogeneous(const Eigen::Vector4d& v, Eigen::Matrix* jacobian = NULL);\n\nEigen::MatrixXd toHomogeneousColumns(const Eigen::MatrixXd& M);\nEigen::MatrixXd fromHomogeneousColumns(const Eigen::MatrixXd& M);\n\ntemplate \nEigen::Matrix normalize(const Eigen::Matrix& v) {\n return v / v.norm();\n}\n\ntemplate \nEigen::Matrix normalizeAndJacobian(const Eigen::Matrix& v,\n Eigen::Matrix& outJacobian) {\n double recip_s_vtv = 1.0 / v.norm();\n\n outJacobian = (Eigen::Matrix::Identity() * recip_s_vtv) -\n (recip_s_vtv * recip_s_vtv * recip_s_vtv) * v * v.transpose();\n\n return v * recip_s_vtv;\n}\n\n/// \\brief to the matrix that implements \"plus\" for homogeneous coordinates.\n/// this operation has the same result as adding the corresponding Euclidean points.\nEigen::Matrix4d toHomogeneousPlus(const Eigen::Vector4d& ph);\n\n/// \\brief to the matrix that implements \"minus\" for homogeneous coordinates.\n/// this operation has the same result as adding the corresponding Euclidean points.\nEigen::Matrix4d toHomogeneousMinus(const Eigen::Vector4d& ph);\n\n} // namespace kinematics\n} // namespace sm\n\n#endif /* SM_MATH_HOMOGENEOUS_COORDINATES_HPP */\n", "meta": {"hexsha": "c7ebfcd409f2175ca1bc753054a96296802d073d", "size": 1761, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Schweizer-Messer/sm_kinematics/include/sm/kinematics/homogeneous_coordinates.hpp", "max_stars_repo_name": "chengfzy/kalibr", "max_stars_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_stars_repo_licenses": ["BSD-4-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Schweizer-Messer/sm_kinematics/include/sm/kinematics/homogeneous_coordinates.hpp", "max_issues_repo_name": "chengfzy/kalibr", "max_issues_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_issues_repo_licenses": ["BSD-4-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Schweizer-Messer/sm_kinematics/include/sm/kinematics/homogeneous_coordinates.hpp", "max_forks_repo_name": "chengfzy/kalibr", "max_forks_repo_head_hexsha": "fe9705b380b160dc939607135f7d30efa64ea2e9", "max_forks_repo_licenses": ["BSD-4-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.2826086957, "max_line_length": 104, "alphanum_fraction": 0.710959682, "num_tokens": 468, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637433190938, "lm_q2_score": 0.7577943603346811, "lm_q1q2_score": 0.6514483364714101}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"logistic_regression.h\"\r\n#include \"utils.h\"\r\n#include \r\n#include \r\n\r\nusing namespace std;\r\nusing namespace Eigen;\r\n\r\nLogisticRegression::LogisticRegression() : max_iter(1000), alpha(0.01), lambda(0.0), tolerance(1e-7), seed(2018), use_batch(false) {}\r\n\r\nLogisticRegression::LogisticRegression(const int& max_iter, const double& alpha, const double& lambda, const double& tolerance, const int& seed, bool use_batch): max_iter(max_iter), alpha(alpha), lambda(lambda), tolerance(tolerance), seed(seed), use_batch(use_batch){}\r\n\r\nLogisticRegression::~LogisticRegression(){}\r\n\r\n\r\nvoid LogisticRegression::fit(const MatrixXd& X, const VectorXd& y, const int& batch_size, const int& early_stopping_round, double (*metric)(double* y, double* pred, int size)){\r\n\t// learn VectorXd W, consider reg, max_iter, tol\r\n\tsrand(seed);\r\n\tW = VectorXd::Random(X.cols()+1); // the last column of weight represent bias\r\n\tMatrixXd X_new(X.rows(), X.cols()+1);\r\n\tX_new<(X.rows()));\r\n\t\t\tint end_idx = min(start_idx+batch_size, static_cast(X.rows()));\r\n\r\n\t\t\tX_batch = Utils::slice(X, start_idx, end_idx-1);\r\n\t\t\ty_batch = Utils::slice(y, start_idx, end_idx-1);\r\n\t\t\tX_new_batch = Utils::slice(X_new, start_idx, end_idx-1);\r\n\r\n\t\t\tVectorXd y_pred = predict_prob(X_batch);\r\n\t\t\tVectorXd E = y_pred - y_batch;\r\n\r\n\t\t\t// update W\r\n\t\t\tW -= (alpha * X_new_batch.transpose() * E + lambda * W);\r\n\t\t\t// calcalate the logloss and accuracy after this step\r\n\t\t\ty_pred = predict_prob(X_batch);\r\n\r\n\t\t\tdouble loss = Utils::crossEntropyLoss(y_batch, y_pred);\r\n\t\t\t//double acc = metric(y_batch, y_pred);\r\n\t\t\tdouble acc = metric(Utils::VectorXd_to_double_array(y_batch), Utils::VectorXd_to_double_array(y_pred), end_idx-start_idx);\r\n\t\t\tcout << boost::format(\"Iteration: %d, logloss:%.5f, accuracy:%.5f\") %iter %loss %acc << endl;\r\n\r\n\t\t\t// when loss < tolerance, break\r\n\t\t\tif(loss <= tolerance) break;\r\n\r\n\t\t\t// perform early stopping\r\n\t\t\tif(acc < best_acc){\r\n\t\t\t\tbecome_worse_round += 1;\r\n\t\t\t}else{\r\n\t\t\t\tbecome_worse_round = 0;\r\n\t\t\t\tbest_acc = acc;\r\n\t\t\t\tbestW = W;\r\n\t\t\t\tbest_loss = loss;\r\n\t\t\t}\r\n\t\t\tif(become_worse_round >= early_stopping_round){\r\n\t\t\t\tW = bestW;\r\n\t\t\t\tcout << boost::format(\"Early stopping in %d, the best iteration is: %d, logloss: %.5f, accuracy:%.5f\") %iter %(iter-early_stopping_round) %best_loss %best_acc << endl;\r\n\t\t\t\tcout << \"Early stopping.\" << endl;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\telse{\r\n\t\tfor(int iter = 0; iter < max_iter; iter++){\r\n\t\t\t// index of this batch samples\r\n\r\n\t\t\tVectorXd y_pred = predict_prob(X);\r\n\t\t\tVectorXd E = y_pred - y;\r\n\r\n\t\t\t// update W\r\n\t\t\tW -= (alpha * X_new.transpose() * E + lambda * W);\r\n\t\t\t// calcalate the logloss and accuracy after this step\r\n\t\t\ty_pred = predict_prob(X);\r\n\r\n\t\t\tdouble loss = Utils::crossEntropyLoss(y, y_pred);\r\n\t\t\t//double acc = metric(y, y_pred);\r\n\t\t\tdouble acc = metric(Utils::VectorXd_to_double_array(y), Utils::VectorXd_to_double_array(y_pred), X.rows());\r\n\t\t\tcout << boost::format(\"Iteration: %d, logloss:%.5f, accuracy:%.5f\") %iter %loss %acc << endl;\r\n\r\n\t\t\t// when loss < tolerance, break\r\n\t\t\tif(loss <= tolerance) break;\r\n\r\n\t\t\t// perform early stopping\r\n\t\t\tif(acc < best_acc){\r\n\t\t\t\tbecome_worse_round += 1;\r\n\t\t\t}else{\r\n\t\t\t\tbecome_worse_round = 0;\r\n\t\t\t\tbest_acc = acc;\r\n\t\t\t\tbestW = W;\r\n\t\t\t\tbest_loss = loss;\r\n\t\t\t}\r\n\t\t\tif(become_worse_round >= early_stopping_round){\r\n\t\t\t\tW = bestW;\r\n\t\t\t\tcout << boost::format(\"Early stopping in %d, the best iteration is: %d, logloss: %.5f, accuracy:%.5f\") %iter %(iter-early_stopping_round) %best_loss %best_acc << endl;\r\n\t\t\t\tcout << \"Early stopping.\" << endl;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\nVectorXd LogisticRegression::predict_prob(const MatrixXd& X){\r\n\t// predict the probability (of label 1) for given data X\r\n\tMatrixXd X_new(X.rows(), X.cols()+1);\r\n\tX_new << X, MatrixXd::Ones(X.rows(),1);\r\n\tint num_samples = X_new.rows();\r\n\tVectorXd y_pred_prob = VectorXd::Zero(num_samples);\r\n\t#pragma omp parallel for\r\n\tfor(int num = 0; num < num_samples; num++){\r\n\t\ty_pred_prob(num) = Utils::sigmoid(X_new.row(num).dot(W));\r\n\t}\r\n\treturn y_pred_prob;\r\n}\r\n\r\nVectorXi LogisticRegression::predict(const MatrixXd& X){\r\n\t// predict the label for given data X\r\n\tVectorXd y_pred_prob = predict_prob(X);\r\n\tVectorXi y_pred(y_pred_prob.size());\r\n\t#pragma omp parallel for\r\n\tfor(int num = 0; num < y_pred_prob.size(); num++){\r\n\t\ty_pred(num) = y_pred_prob(num)>0.5?1:0;\r\n\t}\r\n\treturn y_pred;\r\n}\r\n\r\nVectorXd LogisticRegression::getW(){\r\n\treturn W;\r\n}\r\n\r\nvoid LogisticRegression::saveWeights(const std::string& fpath){\r\n\t// save the model (save the weight)\r\n\tstd::ofstream ofile;\r\n\tofile.open(fpath.c_str());\r\n\tif (!ofile.is_open()){\r\n\t\tstd::cerr << \"Can not open the file when call LogisticRegression::saveWeights\" << std::endl;\r\n\t\treturn;\r\n\t}\r\n\t// W wirte into the file\r\n\tfor(int i = 0; i < W.size() - 1; i++){\r\n\t\tofile << W(i) << \" \";\r\n\t}\r\n\tofile << W(W.size()-1);\r\n\tofile.close();\r\n}\r\n\r\nvoid LogisticRegression::loadWeights(const std::string& fpath){\r\n\t// load the model (load the weight ) from filename\r\n\tstd::ifstream ifile;\r\n\tifile.open(fpath.c_str());\r\n\tif (!ifile.is_open()){\r\n\t\tstd::cerr << \"Can not open the file when call LogisticRegression::loadWeights\" << std::endl;\r\n\t\treturn;\r\n\t}\r\n\t// read the weights into vector\r\n\tstd::string line;\r\n\tstd::vector weights;\r\n\tgetline(ifile, line); // only one line\r\n\tstd::stringstream ss(line);\r\n\tdouble tmp;\r\n\twhile(!ss.eof()){\r\n\t\tss >> tmp;\r\n\t\tweights.push_back(tmp);\r\n\t}\r\n\t// initialize VectorXd with std::vector\r\n\tW = VectorXd::Map(weights.data(), weights.size());\r\n\tifile.close();\r\n}\r\n", "meta": {"hexsha": "ef8d76a5da62777c161504adf740f624120a15e5", "size": 6043, "ext": "cc", "lang": "C++", "max_stars_repo_path": "src/logistic_regression.cc", "max_stars_repo_name": "KaiminLai/tiny-machine-learning-system", "max_stars_repo_head_hexsha": "e29625dfb513032b40712663b63f874e2ae6f924", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-09T16:03:50.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-09T16:03:50.000Z", "max_issues_repo_path": "src/logistic_regression.cc", "max_issues_repo_name": "KaiminLai/tiny-machine-learning-system", "max_issues_repo_head_hexsha": "e29625dfb513032b40712663b63f874e2ae6f924", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/logistic_regression.cc", "max_forks_repo_name": "KaiminLai/tiny-machine-learning-system", "max_forks_repo_head_hexsha": "e29625dfb513032b40712663b63f874e2ae6f924", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6648648649, "max_line_length": 269, "alphanum_fraction": 0.6577858679, "num_tokens": 1652, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894661025424, "lm_q2_score": 0.727975460709318, "lm_q1q2_score": 0.651384773823843}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"IIR_Butterworth.h\"\r\n\r\n//#define ARMA_DONT_USE_CXX11\r\n#define ARMA_DONT_USE_CXX11_MUTEX\r\n#include \r\n\r\n\r\n#define PI 3.141592653589793\r\n\r\n//Global variables\r\ndouble fs = 2;\r\ndouble u_f1;\r\ndouble u_f2;\r\ndouble Wn;\r\ndouble Bw;\r\n\r\nstd::vector> ptemp;\r\nstd::complex complex_real(1.0, 0.0);\r\nstd::complex complex_imag(0.0, 1.0);\r\nstd::vector> p;\r\n\r\nint temp_dim_arr_matr;\r\nstd::vector> > a;\r\nstd::vector> b;\r\nstd::vector> c;\r\n\r\ndouble d[1];\r\ndouble t[1];\r\n\r\narma::cx_mat a_arma;\r\narma::cx_mat b_arma;\r\narma::cx_mat c_arma;\r\narma::cx_mat d_arma;\r\n\r\narma::cx_mat t1_arma;\r\narma::cx_mat t2_arma;\r\narma::cx_mat ad_arma;\r\narma::cx_mat bd_arma;\r\narma::cx_mat cd_arma;\r\narma::cx_mat dd_arma;\r\n\r\nstd::vector num_filt; //Vector where to temporarily save the numerator\r\nstd::vector den_filt; // Vector where to temporarily save the denumerator\r\nstd::vector > save_filt_coeff; //Matrix where to save the numerator and denominator. First row is the numerator; second row is the denominator\r\n\r\nusing namespace IIR_B_F;\r\n\r\n//Step 1: get analog, pre - warped frequencies\r\nvoid IIR_Butterworth::freq_pre_wrapped(int type_filt, double Wnf_1, double Wnf_2)\r\n{\r\n\r\n Bw = 0;\r\n\r\n switch (type_filt)\r\n {\r\n\r\n //Band-pass\r\n case 0:\r\n\r\n u_f1 = 2 * fs * tan(PI * Wnf_1 / fs);\r\n u_f2 = 2 * fs * tan(PI * Wnf_2 / fs);\r\n\r\n break;\r\n\r\n //Band-stop\r\n case 1:\r\n\r\n u_f1 = 2 * fs * tan(PI * Wnf_1 / fs);\r\n u_f2 = 2 * fs * tan(PI * Wnf_2 / fs);\r\n\r\n\r\n break;\r\n\r\n //High-pass\r\n case 2:\r\n\r\n u_f1 = 2 * fs * tan(PI * Wnf_1 / fs);\r\n\r\n break;\r\n\r\n //Low-pass\r\n case 3:\r\n\r\n u_f2 = 2 * fs * tan(PI * Wnf_2 / fs);\r\n\r\n break;\r\n\r\n }\r\n}\r\n\r\n\r\n//Step 2: convert to low-pass prototype estimate\r\nvoid IIR_Butterworth::Wn_f1_Wn_f2(int type_filt, double u_f1, double u_f2)\r\n{\r\n\r\n switch (type_filt)\r\n {\r\n\r\n //Band-pass\r\n case 0:\r\n Bw = u_f2 - u_f1;\r\n Wn = sqrt(u_f1 * u_f2);\r\n\r\n break;\r\n\r\n //Band-stop\r\n case 1:\r\n\r\n Bw = u_f2 - u_f1;\r\n Wn = sqrt(u_f1 * u_f2);\r\n\r\n break;\r\n\r\n //Low-pass\r\n case 2:\r\n\r\n Wn = u_f1;\r\n\r\n break;\r\n\r\n //High-pass\r\n case 3:\r\n\r\n Wn = u_f2;\r\n\r\n break;\r\n\r\n }\r\n}\r\n\r\n\r\n\r\n//Step 3: Get N - th order Butterworth analog lowpass prototype\r\nvoid IIR_Butterworth::buttap(int order_filt)\r\n{\r\n double order_filt_exp = (double)order_filt;\r\n int temp_length_vec = 0;\r\n int kkk = 1;\r\n do {\r\n\r\n temp_length_vec++;\r\n kkk += 2;\r\n\r\n } while (kkk <= order_filt - 1);\r\n\r\n //Initialize the vector \"ptemp\" \r\n for (int i = 0; i < temp_length_vec; i++)\r\n {\r\n\r\n ptemp.push_back(0);\r\n\r\n }\r\n \r\n int track_cell = 0;\r\n for (double kk = 0; kk < (double)order_filt - 1; kk += 2)\r\n {\r\n\r\n ptemp.at(track_cell) = exp(complex_imag * ((PI * (kk + 1)) / (2 * order_filt_exp) + PI / 2));\r\n\r\n track_cell++;\r\n\r\n }\r\n\r\n //Initialize the vector \"p\"\r\n for (int i = 0; i < order_filt; i++)\r\n\r\n {\r\n\r\n p.push_back(0);\r\n\r\n }\r\n\r\n \r\n double temp_rem = remainder(order_filt, 2);\r\n\r\n if (temp_rem != 0)\r\n {\r\n\r\n for (int kk = 0; kk < order_filt; kk++)\r\n {\r\n\r\n if (kk < order_filt - 1)\r\n {\r\n\r\n p.at(kk) = complex_imag;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n p.at(kk) = -complex_real;\r\n\r\n }\r\n\r\n\r\n }\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n for (int kk = 0; kk < order_filt; kk++)\r\n {\r\n\r\n p.at(kk) = complex_imag;\r\n\r\n }\r\n\r\n\r\n }\r\n\r\n if (order_filt > 1)\r\n {\r\n track_cell = 0;\r\n for (int kk = 0; kk < temp_length_vec * 2; kk += 2)\r\n {\r\n\r\n p.at(kk) = ptemp.at(track_cell);\r\n p.at(kk + 1) = conj(ptemp.at(track_cell));\r\n\r\n track_cell++;\r\n\r\n }\r\n }\r\n\r\n}\r\n\r\n\r\n//Step 4: Transform to state-space\r\n//Intermidiate step: calculate the coefficients of the polynomial (based on Matlab code)\r\nstd::vector> IIR_Butterworth::poly(std::vector> temp_array_poly, int col_poly)\r\n{\r\n std::vector> coeff_pol_f(col_poly + 1);\r\n coeff_pol_f.at(0) = 1;\r\n\r\n for (int ll = 0; ll < col_poly; ll++)\r\n {\r\n\r\n int yy = 0;\r\n\r\n do\r\n {\r\n\r\n coeff_pol_f.at(ll + 1 - yy) = coeff_pol_f.at(ll + 1 - yy) - temp_array_poly.at(ll) * coeff_pol_f.at(ll - yy);\r\n yy++;\r\n\r\n } while (yy <= ll);\r\n\r\n }\r\n\r\n return coeff_pol_f;\r\n\r\n}\r\n\r\n//Calculate the factorial of the given number\r\nint IIR_Butterworth::factorial(int i)\r\n{\r\n\r\n if (i <= 1) \r\n {\r\n\r\n return 1;\r\n\r\n }\r\n\r\n return i * factorial(i - 1);\r\n\r\n}\r\n\r\n\r\n\r\n//Method to calculate all the possible combinations. Code taken and slightly modified from: \r\n//http://rosettacode.org/wiki/Combinations#C.2B.2B\r\nstd::vector > IIR_Butterworth::combination_method(int N, int K, int comb_n)\r\n{\r\n \r\n int rows_f = 0;\r\n \r\n std::vector > matrix_comb_f;\r\n\r\n std::vector temp_v;\r\n\r\n for (int ff = 0; ff < K; ff++)\r\n {\r\n\r\n temp_v.push_back(0);\r\n\r\n }\r\n\r\n for (int hh = 0; hh < comb_n; hh++)\r\n {\r\n\r\n matrix_comb_f.push_back(temp_v);\r\n\r\n }\r\n\r\n std::string bitmask(K, 1); // K leading 1's\r\n bitmask.resize(N, 0); // N-K trailing 0's\r\n\r\n int col_f;\r\n do {\r\n\r\n col_f = 0;\r\n\r\n for (int i = 0; i < N; ++i) // [0..N-1] integers\r\n {\r\n\r\n if (bitmask[i])\r\n\r\n {\r\n \r\n \r\n matrix_comb_f[rows_f][col_f] = i;\r\n \r\n col_f++;\r\n\r\n }\r\n }\r\n \r\n rows_f++;\r\n\r\n } while (std::prev_permutation(bitmask.begin(), bitmask.end()));\r\n\r\n return matrix_comb_f;\r\n\r\n}\r\n\r\n\r\n\r\n//Intermidiate step: calculate the coefficients of the polynomial (Bernard Brooks' paper (2016))\r\nstd::vector> IIR_Butterworth::char_poly(arma::cx_mat temp_matr_poly, int row_col)\r\n{\r\n \r\n std::vector> coeff_pol_ff(row_col + 1);\r\n arma::cx_mat temp_val = arma::zeros (1,1);\r\n double num_det;\r\n arma::cx_mat temp_matr = arma::zeros (row_col, row_col);\r\n \r\n std::vector > matrix_comb;\r\n\r\n for (int kk = 0; kk < row_col + 1; kk++)\r\n\r\n {\r\n\r\n if (kk == 0)\r\n {\r\n\r\n coeff_pol_ff[row_col - kk] = pow(-1, row_col) * arma::det(temp_matr_poly);\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n temp_val(0, 0) = 0;\r\n\r\n\r\n num_det = (double)factorial(row_col) / (double)(factorial(row_col - kk) * (double)factorial(kk)); //Calculate the number of combinations \r\n\r\n\r\n //Catching the situation where the denominator is zero. Assign the default value of 10^10 to the denominator\r\n if (isnan(num_det))\r\n {\r\n\r\n for (int ff = 0; ff < row_col + 1; ff++)\r\n {\r\n\r\n coeff_pol_ff[ff] = pow(10, 10);\r\n\r\n }\r\n\r\n break;\r\n\r\n }\r\n\r\n if (num_det < 1) //Handling the situation where numerical overflow generates a negative or zero value for the num_det because of the instability of the filter\r\n {\r\n\r\n for (int ff = 0; ff < row_col + 1; ff++)\r\n {\r\n\r\n coeff_pol_ff[ff] = pow(10, 10);\r\n\r\n }\r\n\r\n break;\r\n\r\n }\r\n\r\n std::vector temp_v;\r\n\r\n for (int ff = 0; ff < num_det; ff++)\r\n {\r\n\r\n temp_v.push_back(0);\r\n\r\n }\r\n\r\n for (int hh = 0; hh < num_det; hh++)\r\n {\r\n\r\n matrix_comb.push_back(temp_v);\r\n\r\n }\r\n\r\n if (num_det - (int)num_det == 0)\r\n {\r\n // Generate the combinations \r\n matrix_comb = combination_method(row_col, kk, (int)num_det);\r\n\r\n for (int mm = 0; mm < num_det; mm++)\r\n\r\n {\r\n\r\n temp_matr = temp_matr_poly;\r\n\r\n for (int pp = 0; pp < row_col; pp++)\r\n {\r\n\r\n temp_matr(matrix_comb[mm][0], pp) = 0;\r\n temp_matr(pp, matrix_comb[mm][0]) = 0;\r\n temp_matr(matrix_comb[mm][0], matrix_comb[mm][0]) = -1;\r\n\r\n }\r\n\r\n for (int nn = 1; nn < kk; nn++)\r\n {\r\n\r\n for (int pp = 0; pp < row_col; pp++)\r\n {\r\n\r\n temp_matr(matrix_comb[mm][nn], pp) = 0;\r\n temp_matr(pp, matrix_comb[mm][nn]) = 0;\r\n temp_matr(matrix_comb[mm][nn], matrix_comb[mm][nn]) = -1;\r\n\r\n }\r\n\r\n }\r\n\r\n temp_val(0, 0) += det(temp_matr);\r\n\r\n }\r\n\r\n coeff_pol_ff[row_col - kk] = pow(-1, row_col) * temp_val(0, 0);\r\n\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n for (int ff = 0; ff < row_col + 1; ff++)\r\n {\r\n\r\n coeff_pol_ff[ff] = pow(10, 10);\r\n\r\n }\r\n\r\n break;\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n \r\n return coeff_pol_ff;\r\n \r\n}\r\n\r\n\r\n\r\n//Step 4: Transform to state-space\r\nvoid IIR_Butterworth::zp2ss(int order_filt)\r\n{\r\n\r\n //Order the pairs of complex conjugate. The pairs with the smallest real part come first. Within pairs, the ones with the negative imaginary part comes first \r\n std::complex temp_max;\r\n\r\n //Using the selection sort algorithm to order based on the real part\r\n double order_filt_d = (double)order_filt;\r\n double temp_rem;\r\n if (remainder(order_filt, 2) == 0)\r\n {\r\n\r\n temp_rem = order_filt_d;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n temp_rem = order_filt_d - 1;\r\n\r\n }\r\n\r\n int min_real;\r\n for (int kk = 0; kk < temp_rem - 1; kk++)\r\n {\r\n min_real = kk;\r\n\r\n for (int jj = kk + 1; jj < temp_rem; jj++)\r\n {\r\n if (real(p[jj]) < real(p[min_real]))\r\n {\r\n\r\n min_real = jj;\r\n\r\n temp_max = p[kk];\r\n p[kk] = p[min_real];\r\n p[min_real] = temp_max;\r\n\r\n }\r\n }\r\n }\r\n\r\n //Using the selection sort algorithm to order the values based on the imaginary part\r\n for (int kk = 0; kk < temp_rem - 1; kk += 2)\r\n {\r\n min_real = kk;\r\n\r\n\r\n if (imag(p[kk]) > imag(p[kk + 1]))\r\n {\r\n\r\n min_real = kk + 1;\r\n\r\n temp_max = p[kk];\r\n p[kk] = p[min_real];\r\n p[min_real] = temp_max;\r\n\r\n }\r\n }\r\n\r\n\r\n // Initialize state - space matrices for running series\r\n d[0] = 1;\r\n\r\n int track_index = 1;\r\n\r\n // Take care of any left over unmatched pole pairs.\r\n // H(s) = 1 / (s ^ 2 + den(2)s + den(3))\r\n std::vector> temp_poly_p;\r\n\r\n double wn = 1;\r\n\r\n if (order_filt > 1)\r\n {\r\n\r\n double b1[2] = { 1,0 };\r\n double c1[2] = { 0,1 };\r\n double d1 = 0;\r\n\r\n\r\n temp_rem = remainder(order_filt, 2);\r\n int order_filt_temp;\r\n int dim_matr;\r\n std::vector> > temp_matrix_a; //Temporary matrix where to save the coefficients at each interaction\r\n int coeff_numb = 3;\r\n\r\n if (temp_rem == 0)\r\n {\r\n\r\n order_filt_temp = order_filt;\r\n dim_matr = order_filt_temp / 2;\r\n\r\n std::vector> temp_v;\r\n\r\n for (int ll = 0; ll < coeff_numb; ll++)\r\n {\r\n\r\n temp_v.push_back(0);\r\n\r\n }\r\n\r\n for (int kk = 0; kk < dim_matr; kk++)\r\n {\r\n\r\n temp_matrix_a.push_back(temp_v);\r\n \r\n }\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n order_filt_temp = order_filt - 1;\r\n dim_matr = order_filt_temp / 2;\r\n\r\n std::vector> temp_v;\r\n\r\n for (int ll = 0; ll < coeff_numb; ll++)\r\n {\r\n\r\n temp_v.push_back(0);\r\n\r\n }\r\n\r\n for (int kk = 0; kk < dim_matr; kk++)\r\n {\r\n\r\n temp_matrix_a.push_back(temp_v);\r\n \r\n }\r\n\r\n }\r\n\r\n int track_cycles = 0;\r\n int temp_val_pos_check;\r\n int dim_poly_p = 2;\r\n \r\n for (int i = 0; i < dim_poly_p; i++)\r\n {\r\n\r\n temp_poly_p.push_back(0);\r\n\r\n }\r\n\r\n temp_dim_arr_matr = dim_poly_p + (order_filt % 2);\r\n\r\n while (track_index < order_filt_temp)\r\n {\r\n\r\n for (int rr = track_index - 1; rr < track_index + 1; rr++)\r\n {\r\n\r\n temp_poly_p[rr - track_index + 1] = p[rr];\r\n\r\n }\r\n\r\n std::vector> coeff_pol(dim_poly_p + 1);\r\n\r\n coeff_pol = poly(temp_poly_p, dim_poly_p);\r\n\r\n\r\n for (int qq = 0; qq < coeff_numb; qq++)\r\n {\r\n\r\n temp_matrix_a[track_cycles][qq] = -real(coeff_pol[qq]);\r\n\r\n }\r\n\r\n //Update the state-space arrays/matrix\r\n track_cycles += 1;\r\n\r\n std::vector> temp_v;\r\n\r\n for (int ll = 0; ll < temp_dim_arr_matr; ll++)\r\n {\r\n\r\n temp_v.push_back(0);\r\n\r\n }\r\n\r\n for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n {\r\n\r\n a.push_back(temp_v);\r\n \r\n }\r\n\r\n int track_index_coeff = 0;\r\n\r\n if (remainder(order_filt, 2) == 0)\r\n {\r\n ///////////////////////////////////////////////////////////////////////////////////////////////\r\n //Even number of poles\r\n for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n {\r\n\r\n for (int gg = 0; gg < temp_dim_arr_matr; gg++)\r\n\r\n {\r\n\r\n temp_val_pos_check = kk - gg;\r\n\r\n switch (temp_val_pos_check)\r\n {\r\n case 1:\r\n\r\n a[kk][gg] = 1;\r\n\r\n break;\r\n\r\n\r\n case 0:\r\n\r\n if ((remainder(kk + 1, 2) != 0) || (kk == 0))\r\n {\r\n\r\n a[kk][gg] = temp_matrix_a[track_index_coeff][1];\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n a[kk][gg] = 0;\r\n\r\n }\r\n\r\n break;\r\n\r\n case -1:\r\n\r\n if ((remainder(kk + 1, 2) != 0) || (kk == 0))\r\n {\r\n\r\n a[kk][gg] = temp_matrix_a[track_index_coeff][2];\r\n track_index_coeff++;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n a[kk][gg] = 0;\r\n\r\n }\r\n break;\r\n\r\n default:\r\n\r\n a[kk][gg] = 0;\r\n\r\n break;\r\n\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n ///////////////////////////////////////////////////////////////////////////////////////////////\r\n }\r\n\r\n else\r\n {\r\n ///////////////////////////////////////////////////////////////////////////////////////////////\r\n //Odd number of poles\r\n for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n {\r\n\r\n for (int gg = 0; gg < temp_dim_arr_matr; gg++)\r\n\r\n {\r\n\r\n temp_val_pos_check = kk - gg;\r\n\r\n switch (temp_val_pos_check)\r\n {\r\n case 1:\r\n\r\n a[kk][gg] = 1;\r\n\r\n break;\r\n\r\n\r\n case 0:\r\n\r\n if (kk == 0)\r\n {\r\n\r\n a[kk][gg] = -1;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n if ((remainder(kk + 1, 2) == 0))\r\n {\r\n\r\n a[kk][gg] = temp_matrix_a[track_index_coeff][1];\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n a[kk][gg] = 0;\r\n\r\n }\r\n }\r\n\r\n break;\r\n\r\n case -1:\r\n\r\n if ((remainder(kk + 1, 2) == 0))\r\n {\r\n\r\n a[kk][gg] = temp_matrix_a[track_index_coeff][2];\r\n track_index_coeff++;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n a[kk][gg] = 0;\r\n\r\n }\r\n break;\r\n\r\n default:\r\n\r\n a[kk][gg] = 0;\r\n\r\n break;\r\n\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n ///////////////////////////////////////////////////////////////////////////////////////////////\r\n\r\n //Initialize the vectors \"b\" and \"c\"\r\n for (int i = 0; i < temp_dim_arr_matr; i++)\r\n {\r\n\r\n b.push_back(0);\r\n c.push_back(0);\r\n\r\n }\r\n\r\n \r\n for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n {\r\n\r\n if (kk == 0)\r\n {\r\n\r\n b[kk] = 1;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n b[kk] = 0;\r\n\r\n }\r\n\r\n }\r\n\r\n for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n {\r\n\r\n if (kk == temp_dim_arr_matr - 1)\r\n {\r\n\r\n c[kk] = 1;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n c[kk] = 0;\r\n\r\n }\r\n\r\n }\r\n\r\n track_index += 2;\r\n\r\n if (track_index < order_filt_temp)\r\n {\r\n\r\n //Clean up the matrix \"a\" and the arrays \"b\" and \"c\", so they can be re-initialized\r\n a.erase(a.begin(), a.begin() + temp_dim_arr_matr);\r\n b.erase(b.begin(), b.begin() + temp_dim_arr_matr);\r\n c.erase(c.begin(), c.begin() + temp_dim_arr_matr);\r\n\r\n }\r\n\r\n dim_matr += 2;\r\n temp_dim_arr_matr += 2;\r\n\r\n } \r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n\r\n std::vector> temp_v;\r\n temp_v.push_back(0);\r\n a.push_back(temp_v);\r\n a[0][0] = p[0];\r\n\r\n b.push_back(1);\r\n c.push_back(1);\r\n\r\n }\r\n \r\n d[0] = 0;\r\n\r\n\r\n}\r\n\r\n\r\n//Extract the coefficients of the band pass filter\r\nstd::vector > IIR_Butterworth::lp2bp(double W_f1, double W_f2, int order_filt)\r\n{\r\n\r\n //Check that the low cut-off frequency is higher than the low cut-off frequency\r\n if (W_f2 <= W_f1)\r\n {\r\n\r\n throw new std::exception(\"The low cut-off frequency needs to be higher than the low cut-off frequency\");\r\n\r\n }\r\n\r\n //Check that the normalized frequencies are within the correct range of values\r\n if ((W_f1 <= 0) || (W_f1 >= 1) || (W_f2 <= 0) || (W_f2 >= 1))\r\n {\r\n\r\n throw new std::exception(\"Cut-off frequencies must be in the (0,1) range\");\r\n\r\n }\r\n\r\n //Check that the order of the filter is > 0\r\n if (order_filt <= 0)\r\n {\r\n\r\n throw new std::exception(\"The order of the filter must be > 0\");\r\n\r\n }\r\n\r\n //Clean up the global variables for a new analysis\r\n if (save_filt_coeff.size() > 0)\r\n {\r\n\r\n save_filt_coeff.erase(save_filt_coeff.begin(), save_filt_coeff.begin() + save_filt_coeff.size());\r\n ptemp.erase(ptemp.begin(), ptemp.begin() + ptemp.size());\r\n p.erase(p.begin(), p.begin() + p.size());\r\n\r\n a.erase(a.begin(), a.begin() + a.size());\r\n b.erase(b.begin(), b.begin() + b.size());\r\n c.erase(c.begin(), c.begin() + c.size());\r\n\r\n num_filt.erase(num_filt.begin(), num_filt.begin() + num_filt.size());\r\n den_filt.erase(den_filt.begin(), den_filt.begin() + den_filt.size());\r\n\r\n }\r\n\r\n std::vector temp_v;\r\n\r\n for (int ff = 0; ff < 2*order_filt + 1; ff++)\r\n {\r\n\r\n temp_v.push_back(0);\r\n\r\n }\r\n\r\n for (int hh = 0; hh < 2; hh++)\r\n {\r\n\r\n save_filt_coeff.push_back(temp_v);\r\n \r\n }\r\n\r\n int type_filt = 0;\r\n\r\n //Step 1: get analog, pre - warped frequencies\r\n freq_pre_wrapped(type_filt, W_f1, W_f2); \r\n\r\n \r\n //Step 2: convert to low-pass prototype estimate\r\n Wn_f1_Wn_f2(type_filt, u_f1, u_f2);\r\n\r\n \r\n //Step 3: Get N - th order Butterworth analog lowpass prototype\r\n buttap(order_filt);\r\n \r\n //Step 4: Transform to state-space\r\n zp2ss(order_filt);\r\n\r\n \r\n if (order_filt > 1)\r\n {\r\n\r\n temp_dim_arr_matr -= 2;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n temp_dim_arr_matr = order_filt;\r\n\r\n }\r\n\r\n \r\n //Copy the values of the matrix/arrays \"arma\" matrix/array in order to compute the pseudo-inverse of the matrix and other matrix operations\r\n a_arma = arma::zeros (2 * temp_dim_arr_matr, 2 * temp_dim_arr_matr);\r\n arma::cx_mat a_arma_p_eye = arma::zeros (temp_dim_arr_matr, temp_dim_arr_matr);\r\n a_arma_p_eye = a_arma_p_eye.eye();\r\n arma::cx_mat a_arma_n_eye = arma::zeros (temp_dim_arr_matr, temp_dim_arr_matr);\r\n a_arma_n_eye = -a_arma_p_eye.eye();\r\n b_arma = arma::zeros (2 * temp_dim_arr_matr, 1);\r\n c_arma = arma::zeros (1, 2 * temp_dim_arr_matr);\r\n d_arma = arma::zeros (1, 1);\r\n\r\n \r\n double q = Wn / Bw;\r\n for (int kk = 0; kk < 2 * temp_dim_arr_matr; kk++)\r\n {\r\n if (kk < temp_dim_arr_matr)\r\n {\r\n\r\n b_arma(kk, 0) = b[kk] * Wn / q;\r\n c_arma(0, kk) = c[kk];\r\n\r\n }\r\n\r\n for (int ll = 0; ll < 2 * temp_dim_arr_matr; ll++)\r\n {\r\n\r\n if (kk < temp_dim_arr_matr)\r\n {\r\n\r\n if (ll < temp_dim_arr_matr)\r\n\r\n {\r\n\r\n a_arma(kk, ll) = Wn * a[kk][ll] / q;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n a_arma(kk, ll) = Wn * a_arma_p_eye(kk, ll - temp_dim_arr_matr);\r\n\r\n }\r\n }\r\n\r\n else\r\n {\r\n if (ll < temp_dim_arr_matr)\r\n {\r\n\r\n a_arma(kk, ll) = Wn * a_arma_n_eye(kk - temp_dim_arr_matr, ll);\r\n\r\n }\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n d_arma = d_arma;\r\n \r\n\r\n //Step 5: Use Bilinear transformation to find discrete equivalent\r\n bilinear(a_arma, b_arma, c_arma, d_arma, fs, type_filt);\r\n \r\n //Step 6: Transform to zero-pole-gain and polynomial forms\r\n zero_pole_gain(ad_arma, type_filt, order_filt, Wn, Bw);\r\n\r\n return save_filt_coeff;\r\n\r\n}\r\n\r\n \r\n//Extract the coefficients of the band stop filter\r\nstd::vector > IIR_Butterworth::lp2bs(double W_f1, double W_f2, int order_filt)\r\n{\r\n\r\n //Check that the low cut-off frequency is higher than the low cut-off frequency\r\n if (W_f2 <= W_f1)\r\n {\r\n\r\n throw new std::exception(\"The low cut-off frequency needs to be higher than the low cut-off frequency\");\r\n\r\n }\r\n\r\n //Check that the normalized frequencies are within the correct range of values\r\n if ((W_f1 <= 0) || (W_f1 >= 1) || (W_f2 <= 0) || (W_f2 >= 1))\r\n {\r\n\r\n throw new std::exception(\"Cut-off frequencies must be in the (0,1) range\");\r\n\r\n }\r\n\r\n //Check that the order of the filter is > 0\r\n if (order_filt <= 0)\r\n {\r\n\r\n throw new std::exception(\"The order of the filter must be > 0\");\r\n\r\n }\r\n\r\n //Clean up the global variables for a new analysis\r\n if (save_filt_coeff.size() > 0)\r\n {\r\n\r\n save_filt_coeff.erase(save_filt_coeff.begin(), save_filt_coeff.begin() + save_filt_coeff.size());\r\n ptemp.erase(ptemp.begin(), ptemp.begin() + ptemp.size());\r\n p.erase(p.begin(), p.begin() + p.size());\r\n\r\n a.erase(a.begin(), a.begin() + a.size());\r\n b.erase(b.begin(), b.begin() + b.size());\r\n c.erase(c.begin(), c.begin() + c.size());\r\n\r\n num_filt.erase(num_filt.begin(), num_filt.begin() + num_filt.size());\r\n den_filt.erase(den_filt.begin(), den_filt.begin() + den_filt.size());\r\n\r\n }\r\n\r\n\r\n std::vector temp_v;\r\n\r\n for (int ff = 0; ff < 2 * order_filt + 1; ff++)\r\n {\r\n\r\n temp_v.push_back(0);\r\n\r\n }\r\n\r\n for (int hh = 0; hh < 2; hh++)\r\n {\r\n\r\n save_filt_coeff.push_back(temp_v);\r\n\r\n }\r\n\r\n int type_filt = 1;\r\n\r\n //Step 1: get analog, pre - warped frequencies\r\n freq_pre_wrapped(type_filt, W_f1, W_f2);\r\n\r\n //Step 2: convert to low-pass prototype estimate\r\n Wn_f1_Wn_f2(type_filt, u_f1, u_f2);\r\n\r\n //Step 3: Get N - th order Butterworth analog lowpass prototype\r\n buttap(order_filt);\r\n\r\n //Step 4: Transform to state-space\r\n zp2ss(order_filt);\r\n\r\n if (order_filt > 1)\r\n {\r\n\r\n temp_dim_arr_matr -= 2;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n temp_dim_arr_matr = order_filt;\r\n\r\n }\r\n\r\n //Copy the values of the matrix/arrays \"arma\" matrix/array in order to compute the pseudo-inverse of the matrix and other matrix operations\r\n a_arma = arma::zeros (2 * temp_dim_arr_matr, 2 * temp_dim_arr_matr);\r\n arma::cx_mat a_arma_p_eye = arma::zeros (temp_dim_arr_matr, temp_dim_arr_matr);\r\n a_arma_p_eye = a_arma_p_eye.eye();\r\n arma::cx_mat a_arma_n_eye = arma::zeros (temp_dim_arr_matr, temp_dim_arr_matr);\r\n a_arma_n_eye = -a_arma_p_eye.eye();\r\n b_arma = arma::zeros (2 * temp_dim_arr_matr, 1);\r\n c_arma = arma::zeros (1, 2 * temp_dim_arr_matr);\r\n d_arma = arma::zeros (1, 1);\r\n\r\n\r\n arma::cx_mat a_arma_pinv = arma::zeros (temp_dim_arr_matr, temp_dim_arr_matr);\r\n arma::cx_mat b_arma_temp = arma::zeros (temp_dim_arr_matr, 1);\r\n arma::cx_mat c_arma_temp = arma::zeros (1, temp_dim_arr_matr);\r\n\r\n arma::cx_mat a_b_arma_temp = arma::zeros (temp_dim_arr_matr, 1);\r\n arma::cx_mat c_a_arma_temp = arma::zeros (1, temp_dim_arr_matr);\r\n\r\n for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n {\r\n b_arma_temp(kk, 0) = b[kk];\r\n c_arma_temp(0, kk) = c[kk];\r\n\r\n for (int ll = 0; ll < temp_dim_arr_matr; ll++)\r\n {\r\n\r\n a_arma_pinv(kk, ll) = a[kk][ll];\r\n\r\n }\r\n\r\n }\r\n\r\n double q = Wn / Bw;\r\n\r\n try\r\n {\r\n\r\n a_arma_pinv = (Wn / q) * arma::pinv(a_arma_pinv);\r\n\r\n }\r\n\r\n catch (std::runtime_error)\r\n {\r\n\r\n for (int kk = 0; kk < 2; kk++)\r\n {\r\n\r\n for (int hh = 0; hh < 2 * order_filt + 1; hh++)\r\n {\r\n\r\n save_filt_coeff[kk][hh] = pow(10, 10);\r\n\r\n }\r\n \r\n\r\n }\r\n \r\n return save_filt_coeff;\r\n\r\n }\r\n\r\n\r\n a_b_arma_temp = (Wn) * (a_arma_pinv * b_arma_temp) / q;\r\n c_a_arma_temp = c_arma_temp * a_arma_pinv;\r\n\r\n for (int kk = 0; kk < 2 * temp_dim_arr_matr; kk++)\r\n {\r\n if (kk < temp_dim_arr_matr)\r\n {\r\n\r\n b_arma(kk, 0) = -a_b_arma_temp(kk, 0);\r\n c_arma(0, kk) = c_a_arma_temp(0, kk);\r\n\r\n }\r\n\r\n for (int ll = 0; ll < 2 * temp_dim_arr_matr; ll++)\r\n {\r\n\r\n if (kk < temp_dim_arr_matr)\r\n {\r\n\r\n if (ll < temp_dim_arr_matr)\r\n\r\n {\r\n\r\n a_arma(kk, ll) = a_arma_pinv(kk, ll);\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n a_arma(kk, ll) = Wn * a_arma_p_eye(kk, ll - temp_dim_arr_matr);\r\n\r\n }\r\n }\r\n\r\n else\r\n {\r\n if (ll < temp_dim_arr_matr)\r\n {\r\n\r\n a_arma(kk, ll) = Wn * a_arma_n_eye(kk - temp_dim_arr_matr, ll);\r\n\r\n }\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n d_arma = d[0] + c_a_arma_temp * b_arma_temp;\r\n\r\n //Step 5: Use Bilinear transformation to find discrete equivalent\r\n bilinear(a_arma, b_arma, c_arma, d_arma, fs, type_filt);\r\n\r\n //Step 6: Transform to zero-pole-gain and polynomial forms\r\n zero_pole_gain(ad_arma, type_filt, order_filt, Wn, Bw);\r\n\r\n return save_filt_coeff;\r\n\r\n}\r\n\r\n//Extract the coefficients of the high pass filter\r\nstd::vector > IIR_Butterworth::lp2hp(double W_f2, int order_filt)\r\n{\r\n\r\n //Check that the normalized frequencies are within the correct range of values\r\n if ((W_f2 <= 0) || (W_f2 >= 1))\r\n {\r\n\r\n throw new std::exception(\"Cut-off frequencies must be in the (0,1) range\");\r\n\r\n }\r\n\r\n //Check that the order of the filter is > 0\r\n if (order_filt <= 0)\r\n {\r\n\r\n throw new std::exception(\"The order of the filter must be > 0\");\r\n\r\n }\r\n\r\n //Clean up the global variables for a new analysis\r\n if (save_filt_coeff.size() > 0)\r\n {\r\n\r\n save_filt_coeff.erase(save_filt_coeff.begin(), save_filt_coeff.begin() + save_filt_coeff.size());\r\n ptemp.erase(ptemp.begin(), ptemp.begin() + ptemp.size());\r\n p.erase(p.begin(), p.begin() + p.size());\r\n\r\n a.erase(a.begin(), a.begin() + a.size());\r\n b.erase(b.begin(), b.begin() + b.size());\r\n c.erase(c.begin(), c.begin() + c.size());\r\n\r\n num_filt.erase(num_filt.begin(), num_filt.begin() + num_filt.size());\r\n den_filt.erase(den_filt.begin(), den_filt.begin() + den_filt.size());\r\n\r\n }\r\n\r\n std::vector temp_v;\r\n\r\n for (int ff = 0; ff < 2 * order_filt; ff++)\r\n {\r\n\r\n temp_v.push_back(0);\r\n\r\n }\r\n\r\n for (int hh = 0; hh < 2; hh++)\r\n {\r\n\r\n save_filt_coeff.push_back(temp_v);\r\n\r\n }\r\n\r\n int type_filt = 2;\r\n\r\n //Step 1: get analog, pre - warped frequencies\r\n freq_pre_wrapped(type_filt, W_f2, 0);\r\n\r\n //Step 2: convert to low-pass prototype estimate\r\n Wn_f1_Wn_f2(type_filt, u_f1, u_f2);\r\n\r\n //Step 3: Get N - th order Butterworth analog lowpass prototype\r\n buttap(order_filt);\r\n\r\n //Step 4: Transform to state-space\r\n zp2ss(order_filt);\r\n\r\n if (order_filt > 1)\r\n {\r\n\r\n temp_dim_arr_matr -= 2;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n temp_dim_arr_matr = order_filt;\r\n\r\n }\r\n\r\n //Copy the values of the matrix/arrays \"arma\" matrix/array in order to compute the pseudo-inverse of the matrix and other matrix operations\r\n a_arma = arma::zeros (temp_dim_arr_matr, temp_dim_arr_matr);\r\n b_arma = arma::zeros (temp_dim_arr_matr, 1);\r\n c_arma = arma::zeros (1, temp_dim_arr_matr);\r\n d_arma = arma::zeros (1, 1);\r\n\r\n for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n {\r\n b_arma(kk, 0) = b[kk];\r\n c_arma(0, kk) = c[kk];\r\n\r\n for (int ll = 0; ll < temp_dim_arr_matr; ll++)\r\n {\r\n\r\n a_arma(kk, ll) = a[kk][ll];\r\n\r\n }\r\n\r\n }\r\n\r\n try\r\n {\r\n\r\n d_arma = d_arma - (c_arma * arma::pinv(a_arma)) * b_arma;\r\n\r\n }\r\n\r\n catch (std::runtime_error)\r\n {\r\n\r\n for (int kk = 0; kk < 2; kk++)\r\n {\r\n\r\n for (int hh = 0; hh < order_filt + 1; hh++)\r\n {\r\n\r\n save_filt_coeff[kk][hh] = pow(10, 10);\r\n\r\n }\r\n\r\n\r\n }\r\n\r\n return save_filt_coeff;\r\n\r\n }\r\n\r\n c_arma = c_arma * arma::pinv(a_arma);\r\n b_arma = -Wn * arma::pinv(a_arma) * b_arma;\r\n a_arma = Wn * arma::pinv(a_arma);\r\n\r\n\r\n //Step 5: Use Bilinear transformation to find discrete equivalent\r\n bilinear(a_arma, b_arma, c_arma, d_arma, fs, type_filt);\r\n\r\n //Step 6: Transform to zero-pole-gain and polynomial forms\r\n zero_pole_gain(ad_arma, type_filt, order_filt, Wn, Bw);\r\n\r\n return save_filt_coeff;\r\n\r\n}\r\n\r\n\r\n//Extract the coefficients of the low pass filter\r\nstd::vector > IIR_Butterworth::lp2lp(double W_f1, int order_filt)\r\n{\r\n //Check that the normalized frequencies are within the correct range of values\r\n if ((W_f1 <= 0) || (W_f1 >= 1))\r\n {\r\n\r\n throw new std::exception(\"Cut-off frequencies must be in the (0,1) range\");\r\n\r\n }\r\n\r\n //Check that the order of the filter is > 0\r\n if (order_filt <= 0)\r\n {\r\n\r\n throw new std::exception(\"The order of the filter must be > 0\");\r\n\r\n }\r\n\r\n //Clean up the global variables for a new analysis\r\n if (save_filt_coeff.size() > 0)\r\n {\r\n\r\n save_filt_coeff.erase(save_filt_coeff.begin(), save_filt_coeff.begin() + save_filt_coeff.size());\r\n ptemp.erase(ptemp.begin(), ptemp.begin() + ptemp.size());\r\n p.erase(p.begin(), p.begin() + p.size());\r\n\r\n a.erase(a.begin(), a.begin() + a.size());\r\n b.erase(b.begin(), b.begin() + b.size());\r\n c.erase(c.begin(), c.begin() + c.size());\r\n\r\n num_filt.erase(num_filt.begin(), num_filt.begin() + num_filt.size());\r\n den_filt.erase(den_filt.begin(), den_filt.begin() + den_filt.size());\r\n\r\n }\r\n\r\n\r\n std::vector temp_v;\r\n\r\n for (int ff = 0; ff < 2 * order_filt; ff++)\r\n {\r\n\r\n temp_v.push_back(0);\r\n\r\n }\r\n\r\n for (int hh = 0; hh < 2; hh++)\r\n {\r\n\r\n save_filt_coeff.push_back(temp_v);\r\n\r\n }\r\n\r\n int type_filt = 3;\r\n\r\n //Step 1: get analog, pre - warped frequencies\r\n freq_pre_wrapped(type_filt, 0, W_f1);\r\n\r\n //Step 2: convert to low-pass prototype estimate\r\n Wn_f1_Wn_f2(type_filt, u_f1, u_f2);\r\n\r\n //Step 3: Get N - th order Butterworth analog lowpass prototype\r\n buttap(order_filt);\r\n\r\n //Step 4: Transform to state-space\r\n zp2ss(order_filt);\r\n\r\n if (order_filt > 1)\r\n {\r\n\r\n temp_dim_arr_matr -= 2;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n temp_dim_arr_matr = order_filt;\r\n\r\n }\r\n\r\n //Copy the values of the matrix/arrays \"arma\" matrix/array in order to compute the pseudo-inverse of the matrix and other matrix operations\r\n a_arma = arma::zeros (temp_dim_arr_matr, temp_dim_arr_matr);\r\n b_arma = arma::zeros (temp_dim_arr_matr, 1);\r\n c_arma = arma::zeros (1, temp_dim_arr_matr);\r\n d_arma = arma::zeros (1, 1);\r\n\r\n for (int kk = 0; kk < temp_dim_arr_matr; kk++)\r\n {\r\n b_arma(kk, 0) = b[kk];\r\n c_arma(0, kk) = c[kk];\r\n\r\n for (int ll = 0; ll < temp_dim_arr_matr; ll++)\r\n {\r\n\r\n a_arma(kk, ll) = a[kk][ll];\r\n\r\n }\r\n\r\n }\r\n\r\n d_arma = d_arma;\r\n c_arma = c_arma;\r\n b_arma = Wn * b_arma;\r\n a_arma = Wn * a_arma;\r\n\r\n\r\n //Step 5: Use Bilinear transformation to find discrete equivalent\r\n bilinear(a_arma, b_arma, c_arma, d_arma, fs, type_filt);\r\n\r\n //Step 6: Transform to zero-pole-gain and polynomial forms\r\n zero_pole_gain(ad_arma, type_filt, order_filt, Wn, Bw);\r\n\r\n return save_filt_coeff;\r\n\r\n}\r\n\r\n\r\n\r\n\r\n//Step 5: Use Bilinear transformation to find discrete equivalent\r\nvoid IIR_Butterworth::bilinear(arma::cx_mat a_arma_f, arma::cx_mat b_arma_f, arma::cx_mat c_arma_f, arma::cx_mat d_arma_f, double fs_f, int type_filt_f)\r\n{\r\n\r\n double t_arma;\r\n double r_arma;\r\n\r\n if (type_filt_f > 1)\r\n {\r\n t1_arma = arma::zeros (temp_dim_arr_matr, temp_dim_arr_matr);\r\n t2_arma = arma::zeros (temp_dim_arr_matr, temp_dim_arr_matr);\r\n ad_arma = arma::zeros (temp_dim_arr_matr, temp_dim_arr_matr);\r\n bd_arma = arma::zeros (temp_dim_arr_matr, 1);\r\n cd_arma = arma::zeros (1, temp_dim_arr_matr);\r\n dd_arma = arma::zeros (1, 1);\r\n }\r\n\r\n else\r\n {\r\n\r\n t1_arma = arma::zeros (2 * temp_dim_arr_matr, 2 * temp_dim_arr_matr);\r\n t2_arma = arma::zeros (2 * temp_dim_arr_matr, 2 * temp_dim_arr_matr);\r\n ad_arma = arma::zeros (2 * temp_dim_arr_matr, 2 * temp_dim_arr_matr);\r\n bd_arma = arma::zeros (2 * temp_dim_arr_matr, 1);\r\n cd_arma = arma::zeros (1, 2 * temp_dim_arr_matr);\r\n dd_arma = arma::zeros (1, 1);\r\n\r\n }\r\n\r\n try\r\n {\r\n t_arma = (1 / fs_f);\r\n r_arma = sqrt(t_arma);\r\n t1_arma = t1_arma.eye() + a_arma_f * t_arma * 0.5; //t1_arma.eye() \r\n t2_arma = t2_arma.eye() - a_arma_f * t_arma * 0.5;\r\n ad_arma = t1_arma * arma::pinv(t2_arma);\r\n bd_arma = (t_arma / r_arma) * arma::solve(t2_arma, b_arma_f);\r\n cd_arma = (r_arma * c_arma_f) * arma::pinv(t2_arma);\r\n dd_arma = (c_arma_f * arma::pinv(t2_arma)) * b_arma_f * (t_arma / 2) + d_arma_f;\r\n }\r\n\r\n catch (std::runtime_error)\r\n {\r\n\r\n\r\n\r\n }\r\n}\r\n\r\n\r\n\r\n//Step 6: Transform to zero-pole-gain and polynomial forms\r\nvoid IIR_Butterworth::zero_pole_gain(arma::cx_mat a_arma_f, int type_filt_f, int order_filt_f, double Wn_f_f, double Bw_f)\r\n{\r\n\r\n int dim_array;\r\n\r\n if (type_filt_f > 1)\r\n {\r\n\r\n //Initialize the vectors \"num_filt\" and \"den_filt\"\r\n for (int i = 0; i < order_filt_f + 1; i++)\r\n {\r\n\r\n num_filt.push_back(0);\r\n den_filt.push_back(0);\r\n\r\n }\r\n\r\n\r\n dim_array = temp_dim_arr_matr;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n //Initialize the vectors \"num_filt\" and \"den_filt\"\r\n for (int i = 0; i < 2 * order_filt_f + 1; i++)\r\n {\r\n\r\n num_filt.push_back(0);\r\n den_filt.push_back(0);\r\n\r\n }\r\n\r\n\r\n dim_array = 2 * temp_dim_arr_matr;\r\n\r\n }\r\n\r\n //Extract the coefficients of the denumerator\r\n std::vector> coeff_pol(temp_dim_arr_matr + 1);\r\n\r\n if (type_filt_f > 1)\r\n\r\n {\r\n\r\n coeff_pol = char_poly(a_arma_f, temp_dim_arr_matr);\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n coeff_pol = char_poly(a_arma_f, 2 * temp_dim_arr_matr);\r\n\r\n }\r\n\r\n\r\n for (int qq = 0; qq < dim_array + 1; qq++)\r\n {\r\n\r\n den_filt[qq] = real(coeff_pol[qq]);\r\n save_filt_coeff[1][qq] = den_filt[qq];\r\n\r\n }\r\n\r\n\r\n //Extract the coefficients of the denominator\r\n double w;\r\n Wn = 2 * std::atan2(Wn, 4);\r\n std::vector> r;\r\n\r\n switch (type_filt_f)\r\n {\r\n\r\n case 0: // band-pass\r\n\r\n for (int i = 0; i <= dim_array; i++)\r\n {\r\n\r\n r.push_back(0);\r\n\r\n }\r\n\r\n for (int kk = 0; kk < dim_array; kk++)\r\n {\r\n\r\n if (kk < temp_dim_arr_matr)\r\n {\r\n\r\n r[kk] = 1;\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n r[kk] = -1;\r\n\r\n }\r\n\r\n }\r\n\r\n w = Wn;\r\n\r\n break;\r\n\r\n case 1: // band-stop\r\n\r\n for (int i = 0; i <= dim_array; i++)\r\n {\r\n\r\n r.push_back(0);\r\n\r\n }\r\n\r\n\r\n for (int kk = 0; kk < dim_array; kk++)\r\n {\r\n\r\n r[kk] = exp(complex_imag * Wn * pow(-1, kk));\r\n\r\n }\r\n w = 0;\r\n\r\n break;\r\n\r\n case 2: //high-pass\r\n\r\n for (int i = 0; i <= dim_array; i++)\r\n {\r\n\r\n r.push_back(0);\r\n\r\n }\r\n\r\n for (int kk = 0; kk < dim_array; kk++)\r\n {\r\n\r\n r[kk] = 1;\r\n\r\n }\r\n\r\n w = PI;\r\n break;\r\n\r\n case 3: // low-pass\r\n\r\n for (int i = 0; i <= dim_array; i++)\r\n {\r\n\r\n r.push_back(0);\r\n\r\n }\r\n\r\n for (int kk = 0; kk < dim_array; kk++)\r\n {\r\n\r\n r[kk] = -1;\r\n\r\n }\r\n w = 0;\r\n break;\r\n\r\n default:\r\n for (int i = 0; i <= dim_array; i++)\r\n {\r\n\r\n r.push_back(0);\r\n\r\n }\r\n\r\n }\r\n\r\n std::vector> coeff_pol_num(dim_array + 1);\r\n\r\n coeff_pol_num = poly(r, dim_array);\r\n\r\n std::vector> kern(dim_array + 1);\r\n\r\n for (int kk = 0; kk < dim_array + 1; kk++)\r\n {\r\n\r\n kern[kk] = exp(-complex_imag * w * double(kk));\r\n\r\n }\r\n\r\n std::complex temp_sum_I;\r\n std::complex temp_sum_II;\r\n\r\n for (int kk = 0; kk < dim_array + 1; kk++)\r\n {\r\n\r\n temp_sum_I = 0.0;\r\n temp_sum_II = 0.0;\r\n\r\n for (int hh = 0; hh < dim_array + 1; hh++)\r\n {\r\n\r\n temp_sum_I += kern[hh] * den_filt[hh];\r\n temp_sum_II += kern[hh] * coeff_pol_num[hh];\r\n\r\n }\r\n\r\n num_filt[kk] = real(coeff_pol_num[kk] * temp_sum_I / temp_sum_II);\r\n save_filt_coeff[0][kk] = num_filt[kk];\r\n\r\n }\r\n\r\n}\r\n //Check the stability of the filter\r\n bool IIR_Butterworth::check_stability_iir(std::vector > coeff_filt)\r\n {\r\n bool stability_flag = true;\r\n\r\n //Calculate the roots\r\n arma::mat roots_den_matrix = arma::zeros(coeff_filt[1].size() - 1, coeff_filt[1].size() - 1);\r\n for (int kk = 0; kk < coeff_filt[1].size() - 2; kk++)\r\n {\r\n\r\n roots_den_matrix(kk + 1, kk) = 1;\r\n\r\n }\r\n\r\n for (int kk = 0; kk < coeff_filt[1].size() - 1; kk++)\r\n {\r\n\r\n roots_den_matrix(0, kk) = -coeff_filt[1][kk + 1];\r\n\r\n }\r\n \r\n \r\n std::vector magnitude_roots_den (coeff_filt[1].size() - 1);\r\n arma::cx_vec roots_den;\r\n arma::cx_mat eigvec;\r\n\r\n arma::eig_gen(roots_den,eigvec, roots_den_matrix);\r\n \r\n for (int kk = 0; kk < coeff_filt[1].size() - 1; kk++)\r\n {\r\n\r\n magnitude_roots_den[kk] = abs(roots_den[kk]);\r\n\r\n if (magnitude_roots_den[kk] >= 1)\r\n {\r\n\r\n stability_flag = false;\r\n break;\r\n }\r\n\r\n }\r\n\r\n return stability_flag;\r\n\r\n }\r\n \r\n//Filter the data by using the Direct-Form II Transpose, as explained in the Matlab documentation\r\nstd::vector IIR_Butterworth::Filter_Data(std::vector > coeff_filt, std::vector pre_filt_signal)\r\n{\r\n\r\n std::vector filt_signal(pre_filt_signal.size(), 0.0);\r\n\r\n std::vector> w_val;\r\n std::vector temp_v;\r\n\r\n for (int ff = 0; ff < pre_filt_signal.size(); ff++)\r\n {\r\n\r\n temp_v.push_back(0);\r\n\r\n }\r\n\r\n for (int hh = 0; hh < coeff_filt[0].size(); hh++)\r\n {\r\n\r\n w_val.push_back(temp_v);\r\n\r\n }\r\n\r\n\r\n //Convolution product to filter the data\r\n for (int kk = 0; kk < pre_filt_signal.size(); kk++)\r\n {\r\n\r\n if (kk == 0)\r\n {\r\n\r\n filt_signal[kk] = pre_filt_signal[kk] * coeff_filt[0][0];\r\n\r\n for (int ww = 1; ww < coeff_filt[0].size(); ww++)\r\n {\r\n\r\n w_val[ww - 1][kk] = pre_filt_signal[kk] * coeff_filt[0][ww] - filt_signal[kk] * coeff_filt[1][ww];\r\n\r\n }\r\n\r\n }\r\n\r\n else\r\n {\r\n\r\n filt_signal[kk] = pre_filt_signal[kk] * coeff_filt[0][0] + w_val[0][kk - 1];\r\n\r\n for (int ww = 1; ww < coeff_filt[0].size(); ww++)\r\n {\r\n\r\n w_val[ww - 1][kk] = pre_filt_signal[kk] * coeff_filt[0][ww] + w_val[ww][kk - 1] - filt_signal[kk] * coeff_filt[1][ww];\r\n\r\n if (ww == coeff_filt[0].size() - 1)\r\n {\r\n\r\n w_val[ww - 1][kk] = pre_filt_signal[kk] * coeff_filt[0][ww] - filt_signal[kk] * coeff_filt[1][ww];\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n }\r\n\r\n\r\n return filt_signal;\r\n\r\n}\r\n", "meta": {"hexsha": "811f9e432a924fcfd2910025e91bb5a8156fb88f", "size": 44955, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "IIR_Butterworth_H.cpp", "max_stars_repo_name": "InterTriplete2010/IIR_Butterworth_Filter_Cpp", "max_stars_repo_head_hexsha": "3e22ace5c6b854423f987461ce10199f77456b07", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "IIR_Butterworth_H.cpp", "max_issues_repo_name": "InterTriplete2010/IIR_Butterworth_Filter_Cpp", "max_issues_repo_head_hexsha": "3e22ace5c6b854423f987461ce10199f77456b07", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "IIR_Butterworth_H.cpp", "max_forks_repo_name": "InterTriplete2010/IIR_Butterworth_Filter_Cpp", "max_forks_repo_head_hexsha": "3e22ace5c6b854423f987461ce10199f77456b07", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.1726804124, "max_line_length": 174, "alphanum_fraction": 0.4678011345, "num_tokens": 11614, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.894789457685656, "lm_q2_score": 0.7279754371026368, "lm_q1q2_score": 0.6513847465735467}} {"text": "#ifndef MLT_UTILS_OPTIMIZERS_STOCHASTIC_GRADIENT_DESCENT_TRAINER_HPP\n#define MLT_UTILS_OPTIMIZERS_STOCHASTIC_GRADIENT_DESCENT_TRAINER_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"../../defs.hpp\"\n#include \"../eigen.hpp\"\n#include \"gradient_descent_updates.hpp\"\n\nnamespace mlt {\nnamespace utils {\nnamespace optimizers {\n\tusing namespace eigen;\n\n // Implementation of Stochastic Gradient Descent\n // Parameters:\n // - size_t batch_size: size of each batch when using mini-batches (set to 0 if using full batch gradient descent)\n // - size_t epochs: number of epochs to run the descent steps through the training data \n // - double learning_rate: initial learning rate\n // - double learning_rate_decay: learning_rate is multiplied by this after each epoch\n // - UpdateMethod update_method: object implementing the update strategy to use\n\ttemplate \n class StochasticGradientDescent {\n public:\n\t\tStochasticGradientDescent(size_t batch_size = 1, size_t epochs = 1000, double learning_rate = 0.001, double learning_rate_decay = 0.99,\n\t\t\tconst UpdateMethod& update_method = UpdateMethod()) : _batch_size(batch_size), _epochs(epochs), _learning_rate(learning_rate), \n\t\t\t_current_learning_rate(learning_rate), _learning_rate_decay(learning_rate_decay), _update_method(update_method) {}\n\n template \n\t\tauto operator()(const Model& model, Features input, Target target, MatrixXdRef init, bool cold_start) {\n\t\t\tassert(input.cols() == target.cols());\n\n if (cold_start) {\n _current_learning_rate = _learning_rate;\n\t\t\t\t_update_method.restart();\n }\n\n auto iters_per_epoch = _batch_size > 0 && _batch_size <= input.cols() ? input.cols() / _batch_size : 1;\n\n\t\t\tMatrixXd params = init;\n\n\t\t\trandom_device rd;\n default_random_engine generator(rd());\n\n for (auto epoch = 0; epoch < _epochs; epoch++) {\n for (auto iter = 0; iter < iters_per_epoch; iter++) {\n\t\t\t\t\tif (_batch_size > 0) {\n\t\t\t\t\t\tauto subset = tied_random_cols_subset(input, target, _batch_size, generator);\n\t\t\t\t\t\tauto input_batch = get<0>(subset);\n\t\t\t\t\t\tauto target_batch = get<1>(subset);\n\n\t\t\t\t\t\tparams += _update_method.step(_current_learning_rate, model.gradient(params, input_batch, target_batch));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparams += _update_method.step(_current_learning_rate, model.gradient(params, input, target));\n\t\t\t\t\t}\n }\n\n#ifdef MLT_VERBOSE\n\t\t\t\tif (epoch % 10 == 0) {\n\t\t\t\t\tauto loss = model.loss(params, input, target);\n\t\t\t\t\tMLT_LOG_LINE(\"[SGD]: Epoch \" << epoch + 1 << \"/\" << _epochs << \" Loss \" << loss);\n\t\t\t\t}\n#endif\n\n\t\t\t\t_current_learning_rate *= _learning_rate_decay;\n }\n\n\t\t\treturn params;\n }\n\n\tprotected:\n\t\tsize_t _batch_size;\n\t\tsize_t _epochs;\n\t\tdouble _learning_rate;\n\t\tdouble _current_learning_rate;\n\t\tdouble _learning_rate_decay;\n\t\tUpdateMethod _update_method;\n };\n}\n}\n}\n#endif", "meta": {"hexsha": "61496aaa9658ed863f2b270af5aba1bb0630d2da", "size": 3033, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/mlt/utils/optimizers/stochastic_gradient_descent.hpp", "max_stars_repo_name": "fedeallocati/MachineLearningToolkit", "max_stars_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-08-31T11:43:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-22T11:03:47.000Z", "max_issues_repo_path": "src/mlt/utils/optimizers/stochastic_gradient_descent.hpp", "max_issues_repo_name": "fedeallocati/MachineLearningToolkit", "max_issues_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mlt/utils/optimizers/stochastic_gradient_descent.hpp", "max_forks_repo_name": "fedeallocati/MachineLearningToolkit", "max_forks_repo_head_hexsha": "8614ee2c8c5211a3eefceb10a50576e0485cefd9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8620689655, "max_line_length": 137, "alphanum_fraction": 0.6983184965, "num_tokens": 717, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024556, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.6513549372754316}} {"text": "// Copyright Nick Thompson, 2017\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0.\r\n// (See accompanying file LICENSE_1_0.txt\r\n// or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing boost::math::quadrature::tanh_sinh;\r\nusing boost::math::quadrature::sinh_sinh;\r\nusing boost::math::quadrature::exp_sinh;\r\nusing boost::math::constants::pi;\r\nusing boost::math::constants::half_pi;\r\nusing boost::math::constants::half;\r\nusing boost::math::constants::third;\r\nusing boost::math::constants::root_pi;\r\nusing std::log;\r\nusing std::cos;\r\nusing std::cosh;\r\nusing std::exp;\r\nusing std::sqrt;\r\n\r\nint main()\r\n{\r\n std::cout << std::setprecision(std::numeric_limits::digits10);\r\n double tol = sqrt(std::numeric_limits::epsilon());\r\n // For an integral over a finite domain, use tanh_sinh:\r\n tanh_sinh tanh_integrator(tol, 10);\r\n auto f1 = [](double x) { return log(x)*log(1-x); };\r\n double Q = tanh_integrator.integrate(f1, (double) 0, (double) 1);\r\n double Q_expected = 2 - pi()*pi()*half()*third();\r\n\r\n std::cout << \"tanh_sinh quadrature of log(x)log(1-x) gives \" << Q << std::endl;\r\n std::cout << \"The exact integral is \" << Q_expected << std::endl;\r\n\r\n // For an integral over the entire real line, use sinh-sinh quadrature:\r\n sinh_sinh sinh_integrator(tol, 10);\r\n auto f2 = [](double t) { return cos(t)/cosh(t);};\r\n Q = sinh_integrator.integrate(f2);\r\n Q_expected = pi()/cosh(half_pi());\r\n std::cout << \"sinh_sinh quadrature of cos(x)/cosh(x) gives \" << Q << std::endl;\r\n std::cout << \"The exact integral is \" << Q_expected << std::endl;\r\n\r\n // For half-infinite intervals, use exp-sinh.\r\n // Endpoint singularities are handled well:\r\n exp_sinh exp_integrator(tol, 10);\r\n auto f3 = [](double t) { return exp(-t)/sqrt(t); };\r\n Q = exp_integrator.integrate(f3, 0, std::numeric_limits::infinity());\r\n Q_expected = root_pi();\r\n std::cout << \"exp_sinh quadrature of exp(-t)/sqrt(t) gives \" << Q << std::endl;\r\n std::cout << \"The exact integral is \" << Q_expected << std::endl;\r\n\r\n\r\n\r\n}\r\n", "meta": {"hexsha": "fc3b161b1798dd7567f9b22ec990e49e13ae8b22", "size": 2455, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/double_exponential.cpp", "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 32.0, "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_issues_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/double_exponential.cpp", "max_issues_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_issues_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_forks_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/math/example/double_exponential.cpp", "max_forks_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_forks_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "avg_line_length": 40.9166666667, "max_line_length": 93, "alphanum_fraction": 0.6431771894, "num_tokens": 665, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583696, "lm_q2_score": 0.7662936430859597, "lm_q1q2_score": 0.65132751453714}} {"text": "#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\n#include \"GraphDefs.h\"\r\n#include \"Timer.h\"\r\n#include \"GraphUtil.h\"\r\n#include \"GraphParse.h\"\r\n#include \"GraphGen.h\"\r\n\r\n#include \r\n#include \r\n\r\n#define SHOW_DEBUG false\r\n\r\nvoid printGraph(const char* title, VertexVector* vertices, EdgeVector* edges, bool printVertices = false) {\r\n\tstd::cout << std::endl << \"=== \" << title << std::endl;\r\n\r\n\tif (printVertices) {\r\n\t\t// Iterate through the vertices and print them out\r\n\t\tfor (int i = 0; i < vertices->size(); i++) {\r\n\t\t\tCGALPoint* v = (*vertices)[i];\r\n\t\t\tstd::cout << \"index: \" << i << \" (\" << v->x() << \", \" << v->y() << \")\" << std::endl;\r\n\t\t}\r\n\t}\r\n\r\n\t// Iterate through the edges and print them out\r\n\tstd::cout << std::endl << \"Edges: \" << std::endl;\r\n\tfor (int i = 0; i < edges->size(); i++) {\r\n\t\tSimpleEdge* e = (*edges)[i];\r\n\t\tCGALPoint* src = (*vertices)[e->u];\r\n\t\tCGALPoint* tar = (*vertices)[e->v];\r\n\t\t//std::cout << edgeWeightMap->at(e).weight << \" (\" << (*g)[src].pt << \") (\" << (*g)[tar].pt << \")\" << std::endl;\r\n\t\tstd::cout << e->weight << \" (\" << (*src) << \") (\" << (*tar) << \")\" << std::endl;\r\n\t}\r\n\r\n\tstd::cout << std::endl;\r\n}\r\n\r\nvoid printGDFGraph(const char* fileName, VertexVector* vertices, EdgeVector* edges) {\r\n\tstd::ofstream myfile;\r\n\tmyfile.open(fileName, std::ios::out | std::ios::in);\r\n\r\n\tmyfile << \"nodedef> name VARCHAR,label VARCHAR,width DOUBLE,height DOUBLE,x DOUBLE,y DOUBLE,color VARCHAR\" << std::endl;\r\n\r\n\t// Iterate through the vertices and print them out\r\n\tboost::unordered_map vertexHandles;\r\n\tfor (int i = 0; i < vertices->size(); i++) {\r\n\t\tCGALPoint* v = (*vertices)[i];\r\n\t\tmyfile << i << \",,10.0,10.0,\" << (*v).x() << \",\" << (*v).y() << \",'153,153,153'\" << std::endl;\r\n\t\tvertexHandles.emplace(v, i);\r\n\t}\r\n\r\n\tmyfile << \"edgedef> node1,node2,weight DOUBLE,directed BOOLEAN,color VARCHAR\" << std::endl;\r\n\r\n\t// Iterate through the edges and print them out\r\n\tfor (int i = 0; i < edges->size(); i++) {\r\n\t\tSimpleEdge* e = (*edges)[i];\r\n\t\tCGALPoint* src = (*vertices)[e->u];\r\n\t\tCGALPoint* tar = (*vertices)[e->v];\r\n\t\tVertexIndex srcInd = vertexHandles[src];\r\n\t\tVertexIndex tarInd = vertexHandles[tar];\r\n\t\t//EdgeWeight weight = sqrt(CGAL::squared_distance(*src, *tar));\r\n\t\tEdgeWeight weight = 1.0;\r\n\t\tmyfile << srcInd << \",\" << tarInd << \",\" << weight << \",false,'128,128,128'\" << std::endl;\r\n\t}\r\n\r\n\tmyfile.close();\r\n}\r\n\r\nCDT* computeCdt(VertexVector* vertices, EdgeVector* edges, boost::unordered_map** handlesToIndex) {\r\n\tCDT* cdt = new CDT();\r\n\r\n\t(*handlesToIndex) = new boost::unordered_map();\r\n\tboost::unordered_map vertexHandles;\r\n\tfor (int i = 0; i < vertices->size(); i++) {\r\n\t\tCGALPoint* pt = (*vertices)[i];\r\n\t\tTriVertexHandle vHandle = cdt->insert(*pt);\r\n\t\tvertexHandles.emplace(i, vHandle);\r\n\t\t(*handlesToIndex)->emplace(vHandle, i);\r\n\t}\r\n\r\n\t// Insert constraint edges\r\n\tfor (int i = 0; i < edges->size(); i++) {\r\n\t\tSimpleEdge* edge = (*edges)[i];\r\n\t\tVertexIndex u = edge->u;\r\n\t\tVertexIndex v = edge->v;\r\n\t\tTriVertexHandle uH = vertexHandles[u];\r\n\t\tTriVertexHandle vH = vertexHandles[v];\r\n\t\tcdt->insert_constraint(uH, vH);\r\n\t}\r\n\r\n\tassert(cdt->is_valid());\r\n\r\n\treturn cdt;\r\n}\r\n\r\n// Given 3 colinear points, if the 2 furthest points are constrained, how is this delaunay triangulated?\r\n// It seems the outcome is implementation dependent. CGAL will split the constraint into 2 edges.\r\n// Other implementations might allow for overlapping, collinear edges. Either way, the current plan\r\n// is to assume that an input forest, F, with collinear edges will be replaced by smaller constraint edges.\r\nEdgeVector* newConstraintSetFromCdt(CDT* cdt, VertexVector* originalVertices) {\r\n\tEdgeVector* newEdgeVector = new EdgeVector();\r\n\r\n\tboost::unordered_map vertexIndex;\r\n\tfor (int i = 0; i < originalVertices->size(); i++) {\r\n\t\tvertexIndex[*(*originalVertices)[i]] = i;\r\n\t}\r\n\r\n\t// Add edges to graph\r\n\tfor (CDT::Edge_iterator eit = cdt->edges_begin(); eit != cdt->edges_end(); ++eit) {\r\n\t\tCDT::Edge cgal_e = *eit;\r\n\r\n\t\tif (cdt->is_constrained(cgal_e)) {\r\n\t\t\t// Assumes point coord are unique\r\n\t\t\tCGALSegment segement = cdt->segment(cgal_e);\r\n\t\t\tCGALPoint cgal_u = segement.point(0);\r\n\t\t\tCGALPoint cgal_v = segement.point(1);\r\n\t\t\tVertexIndex u = vertexIndex[cgal_u];\r\n\t\t\tVertexIndex v = vertexIndex[cgal_v];\r\n\r\n\t\t\tSimpleEdge* edge = new SimpleEdge(u, v, 0);\r\n\t\t\tnewEdgeVector->push_back(edge);\r\n\t\t}\r\n\t}\r\n\treturn newEdgeVector;\r\n}\r\n\r\nTriVertexHandle OppositeOfEdge(TriVertexHandle ev0, TriVertexHandle ev1, TriFaceHandle f) {\r\n\tTriVertexHandle v0 = f->vertex(0);\r\n\tif (v0 != ev0 && v0 != ev1) {\r\n\t\treturn v0;\r\n\t}\r\n\r\n\tTriVertexHandle v1 = f->vertex(1);\r\n\tif (v1 != ev0 && v1 != ev1) {\r\n\t\treturn v1;\r\n\t}\r\n\r\n\tTriVertexHandle v2 = f->vertex(2);\r\n\tif (v2 != ev0 && v2 != ev1) {\r\n\t\treturn v2;\r\n\t}\r\n\r\n\tassert(false); // Unreachable\r\n\treturn NULL;\r\n}\r\n\r\nbool IsInsideCircle(CGALPoint* p, CGALPoint* q, CGALPoint* t) {\r\n\tif (SHOW_DEBUG) {\r\n\t\tstd::cout << \"(\" << (*p) << \") (\" << (*q) << \") (\" << (*t) << \")\" << std::endl;\r\n\t}\r\n\tCGALCircle c(*p, *q);\r\n\tCGAL::Bounded_side side = c.bounded_side(*t);\r\n\r\n\t// v is outside or on the circumcircle of f\r\n\treturn side == CGAL::Bounded_side::ON_BOUNDED_SIDE\r\n\t\t|| side == CGAL::Bounded_side::ON_BOUNDARY;\r\n}\r\n\r\nvoid computeNonLocallyGabriel(\r\n\tVertexVector* vertices,\r\n\tEdgeVector* edges,\r\n\tEdgeVector** NewEdges,\r\n\tEdgeVector** S_Edges) {\r\n\r\n\tboost::chrono::high_resolution_clock::time_point start;\r\n\tboost::chrono::high_resolution_clock::time_point end;\r\n\tboost::chrono::milliseconds duration(0);\r\n\tboost::chrono::milliseconds total(0);\r\n\r\n\t// Compute CDT(F)\r\n\tstart = boost::chrono::high_resolution_clock::now();\r\n\tboost::unordered_map* handlesToIndex;\r\n\tCDT* cdt = computeCdt(vertices, edges, &handlesToIndex);\r\n\tend = boost::chrono::high_resolution_clock::now();\r\n\tduration = (boost::chrono::duration_cast(end - start));\r\n\ttotal += duration;\r\n\tprintDuration(\"CDT(F)\", duration);\r\n\r\n\t// Replace F with NewF\r\n\tstart = boost::chrono::high_resolution_clock::now();\r\n\t(*NewEdges) = newConstraintSetFromCdt(cdt, vertices);\r\n\tend = boost::chrono::high_resolution_clock::now();\r\n\tduration = (boost::chrono::duration_cast(end - start));\r\n\ttotal += duration;\r\n\tprintDuration(\"F -> NewF\", duration);\r\n\r\n\t// Compute Non-Locally Gabriel edges\r\n\tstart = boost::chrono::high_resolution_clock::now();\r\n\tboost::unordered_set* S = new boost::unordered_set();\r\n\tTriVertexHandle infiniteVertex = cdt->infinite_vertex();\r\n\tint edgeCount = 0;\r\n\tfor (FiniteEdgeIter iter = cdt->finite_edges_begin(); iter != cdt->finite_edges_end(); ++iter) {\r\n\t\tedgeCount++;\r\n\r\n\t\t// typedef std::pair Edge;\r\n\t\tTriEdge e = *iter;\r\n\t\tint eIndex = e.second;\r\n\r\n\t\t// Edge shared by faces f0 and f1\r\n\t\tTriFaceHandle f0 = e.first;\r\n\t\tTriFaceHandle f1 = e.first->neighbor(eIndex);\r\n\r\n\t\t// Vertex opposite of edge e in f0, f1\r\n\t\tTriVertexHandle opp0 = f0->vertex(eIndex);\r\n\r\n\t\t// Vertex of edge e\r\n\t\tTriVertexHandle e0 = f0->vertex(f0->cw(eIndex));\r\n\t\tTriVertexHandle e1 = f0->vertex(f0->ccw(eIndex));\r\n\r\n\t\tTriVertexHandle opp1 = OppositeOfEdge(e0, e1, f1);\r\n\r\n\t\tif (SHOW_DEBUG) {\r\n\t\t\t// Vertex endpoint v0, v1 of edge e for f0 (doesn't seem to be possible to identify the same edge for f1 in a similar way)\r\n\t\t\tstd::cout << eIndex << std::endl;\r\n\t\t\tstd::cout << \"(\" << *e0 << \") (\" << *e1 << \")\" << std::endl;\r\n\t\t\tstd::cout << \"(\" << *opp0 << \")\" << std::endl;\r\n\t\t}\r\n\r\n\t\tif (e0 != infiniteVertex && e1 != infiniteVertex) {\r\n\t\t\tCGALPoint p = e0->point();\r\n\t\t\tCGALPoint q = e1->point();\r\n\r\n\t\t\tbool addToConstraint = false;\r\n\r\n\t\t\tif (opp0 != infiniteVertex) {\r\n\t\t\t\tCGALPoint t = opp0->point();\r\n\t\t\t\tif (IsInsideCircle(&p, &q, &t)) {\r\n\t\t\t\t\taddToConstraint = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (opp1 != infiniteVertex) {\r\n\t\t\t\tCGALPoint t = opp1->point();\r\n\t\t\t\tif (IsInsideCircle(&p, &q, &t)) {\r\n\t\t\t\t\taddToConstraint = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (addToConstraint) {\r\n\t\t\t\tS->emplace(e);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t(*S_Edges) = new EdgeVector();\r\n\tfor (boost::unordered_set::iterator iter = S->begin(); iter != S->end(); ++iter) {\r\n\t\tTriEdge e = *iter;\r\n\t\tint eIndex = e.second;\r\n\t\tTriFaceHandle f0 = e.first;\r\n\t\tTriVertexHandle e0 = f0->vertex(f0->cw(eIndex));\r\n\t\tTriVertexHandle e1 = f0->vertex(f0->ccw(eIndex));\r\n\r\n\t\tVertexIndex u = (*handlesToIndex)[e0];\r\n\t\tVertexIndex v = (*handlesToIndex)[e1];\r\n\r\n\t\t(*S_Edges)->push_back(new SimpleEdge(u, v, 0));\r\n\t}\r\n\r\n\tend = boost::chrono::high_resolution_clock::now();\r\n\tduration = (boost::chrono::duration_cast(end - start));\r\n\ttotal += duration;\r\n\tprintDuration(\"computeNonLocallyGabriel duration\", duration);\r\n\r\n\tprintDuration(\"Total\", total);\r\n\r\n\tdelete S;\r\n\tdelete cdt;\r\n\tdelete handlesToIndex;\r\n}\r\n\r\nvoid computeCgg(\r\n\tVertexVector* vertices,\r\n\tEdgeVector* edges,\r\n\tEdgeVector** NewEdges,\r\n\tEdgeVector** gabriel) {\r\n\r\n\tboost::unordered_set* constraintEdgesSet = createSimpleEdgeSet(edges);\r\n\r\n\tboost::unordered_map* handlesToIndex;\r\n\tCDT* cdt = computeCdt(vertices, edges, &handlesToIndex);\r\n\t(*NewEdges) = newConstraintSetFromCdt(cdt, vertices);\r\n\r\n\tboost::unordered_set* S = new boost::unordered_set();\r\n\r\n\tTriVertexHandle infiniteVertex = cdt->infinite_vertex();\r\n\tint edgeCount = 0;\r\n\r\n\tboost::chrono::high_resolution_clock::time_point startTotal = boost::chrono::high_resolution_clock::now();\r\n\r\n\tfor (FiniteEdgeIter iter = cdt->finite_edges_begin(); iter != cdt->finite_edges_end(); ++iter) {\r\n\t\tedgeCount++;\r\n\r\n\t\t// typedef std::pair Edge;\r\n\t\tTriEdge e = *iter;\r\n\t\tint eIndex = e.second;\r\n\r\n\t\t// Edge shared by faces f0 and f1\r\n\t\tTriFaceHandle f0 = e.first;\r\n\t\tTriFaceHandle f1 = e.first->neighbor(eIndex);\r\n\r\n\t\t// Vertex opposite of edge e in f0\r\n\t\tTriVertexHandle opp0 = f0->vertex(eIndex);\r\n\r\n\t\t// Vertex of edge e\r\n\t\tTriVertexHandle e0 = f0->vertex(f0->cw(eIndex));\r\n\t\tTriVertexHandle e1 = f0->vertex(f0->ccw(eIndex));\r\n\r\n\t\tTriVertexHandle opp1 = OppositeOfEdge(e0, e1, f1);\r\n\r\n\t\tif (SHOW_DEBUG) {\r\n\t\t\t// Vertex endpoint v0, v1 of edge e for f0 (doesn't seem to be possible to identify the same edge for f1 in a similar way)\r\n\t\t\tstd::cout << eIndex << std::endl;\r\n\t\t\tstd::cout << \"(\" << *e0 << \") (\" << *e1 << \")\" << std::endl;\r\n\t\t\tstd::cout << \"(\" << *opp0 << \")\" << std::endl;\r\n\t\t}\r\n\r\n\t\tif (e0 != infiniteVertex && e1 != infiniteVertex) {\r\n\t\t\tCGALPoint p = e0->point();\r\n\t\t\tCGALPoint q = e1->point();\r\n\t\t\tVertexIndex u = (*handlesToIndex)[e0];\r\n\t\t\tVertexIndex v = (*handlesToIndex)[e1];\r\n\r\n\t\t\tbool addToS = true;\r\n\r\n\t\t\tif (opp0 != infiniteVertex) {\r\n\t\t\t\tCGALPoint t = opp0->point();\r\n\t\t\t\t// Is not locally gabriel\r\n\t\t\t\t// Is not a constraint edge\r\n\t\t\t\tif (IsInsideCircle(&p, &q, &t)\r\n\t\t\t\t\t&& (constraintEdgesSet->count(SimpleEdge(u, v, 0)) < 1)) {\r\n\t\t\t\t\taddToS = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (opp1 != infiniteVertex) {\r\n\t\t\t\tCGALPoint t = opp1->point();\r\n\t\t\t\t// Is not locally gabriel\r\n\t\t\t\t// Is not a constraint edge\r\n\t\t\t\tif (IsInsideCircle(&p, &q, &t)\r\n\t\t\t\t\t&& (constraintEdgesSet->count(SimpleEdge(u, v, 0)) < 1)) {\r\n\t\t\t\t\taddToS = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (addToS) {\r\n\t\t\t\tS->emplace(e);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t(*gabriel) = new EdgeVector();\r\n\tfor (boost::unordered_set::iterator iter = S->begin(); iter != S->end(); ++iter) {\r\n\t\tTriEdge e = *iter;\r\n\t\tint eIndex = e.second;\r\n\t\tTriFaceHandle f0 = e.first;\r\n\t\tTriVertexHandle e0 = f0->vertex(f0->cw(eIndex));\r\n\t\tTriVertexHandle e1 = f0->vertex(f0->ccw(eIndex));\r\n\r\n\t\tVertexIndex u = (*handlesToIndex)[e0];\r\n\t\tVertexIndex v = (*handlesToIndex)[e1];\r\n\r\n\t\t(*gabriel)->push_back(new SimpleEdge(u, v, 0));\r\n\t}\r\n\r\n\tboost::chrono::high_resolution_clock::time_point endTotal = boost::chrono::high_resolution_clock::now();\r\n\tboost::chrono::milliseconds total = (boost::chrono::duration_cast(endTotal - startTotal));\r\n\tprintDuration(\"computeCgg duration\", total);\r\n\r\n\tdelete S;\r\n\tdelete cdt;\r\n\tdelete handlesToIndex;\r\n\tdelete constraintEdgesSet;\r\n}\r\n\r\nEdgeVector* intersectInputSetWithConstraintSet(EdgeVector* inputSet, EdgeVector* constraintSet) {\r\n\tboost::unordered_set* NewEdges_Hashset = new boost::unordered_set();\r\n\tfor (int i = 0; i < inputSet->size(); i++) {\r\n\t\tSimpleEdge* e = (*inputSet)[i];\r\n\t\tNewEdges_Hashset->emplace((*e));\r\n\t}\r\n\r\n\tEdgeVector* intersect = new EdgeVector();\r\n\tfor (int i = 0; i < constraintSet->size(); i++) {\r\n\t\tSimpleEdge* se = (*constraintSet)[i];\r\n\t\tif (NewEdges_Hashset->count(*se) > 0) {\r\n\t\t\tintersect->push_back(new SimpleEdge(se->u, se->v, se->weight));\r\n\t\t}\r\n\t}\r\n\r\n\treturn intersect;\r\n}\r\n\r\nbool containsEdge(boost::unordered_set* edgeSet, SimpleEdge* edge) {\r\n\tSimpleEdge se(edge->u, edge->v, 0);\r\n\treturn edgeSet->count(se) > 0;\r\n}\r\n\r\n// True if A a subgraph of B\r\nbool isSubgraph(VertexVector* vertices, EdgeVector* a, EdgeVector* b) {\r\n\tboost::unordered_set* bEdgeSet = createSimpleEdgeSet(b);\r\n\r\n\t// Iterate through the edges\r\n\tfor (int i = 0; i < a->size(); i++) {\r\n\t\tSimpleEdge* edge = (*a)[i];\r\n\t\tif (!containsEdge(bEdgeSet, edge)) {\r\n\t\t\tCGALPoint* u = (*vertices)[edge->u];\r\n\t\t\tCGALPoint* v = (*vertices)[edge->v];\r\n\t\t\t//EdgeWeight weight = CGAL::squared_distance(*u, *v);\r\n\t\t\tCGAL::Lazy_exact_nt exactWeight = CGAL::squared_distance(*u, *v);\r\n\t\t\tEdgeWeight weight = CGAL::to_double(exactWeight);\r\n\t\t\tstd::cout << \"b contains edge not in a: \" << weight << \" (\" << *u << \") (\" << *v << \")\" << std::endl;\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\nEdgeVector* convertCdtToGraph(VertexVector* vertices, CDT* cdt) {\r\n\tEdgeVector* edgeVec = new EdgeVector();\r\n\t// edgeVec->reserve(cdt->number_of_faces() * 3); // Upper bound on number of edges (typically too much)\r\n\r\n\t// Map CGALPoint -> VertexIndex\r\n\tboost::unordered_map vertexIndex;\r\n\tfor (int i = 0; i < vertices->size(); i++) {\r\n\t\tvertexIndex[*(*vertices)[i]] = i;\r\n\t}\r\n\r\n\t// Add edges to graph\r\n\tfor (CDT::Edge_iterator eit = cdt->edges_begin(); eit != cdt->edges_end(); ++eit) {\r\n\t\tCDT::Edge cgal_e = *eit;\r\n\t\tCGALSegment segement = cdt->segment(cgal_e);\r\n\t\tCGALPoint cgal_u = segement.point(0);\r\n\t\tCGALPoint cgal_v = segement.point(1);\r\n\t\tVertexIndex u = vertexIndex[cgal_u];\r\n\t\tVertexIndex v = vertexIndex[cgal_v];\r\n\r\n\t\tSimpleEdge* edge = new SimpleEdge(u, v, 0);\r\n\t\tedgeVec->push_back(edge);\r\n\t}\r\n\r\n\treturn edgeVec;\r\n}\r\n\r\nbool isCdtSubgraph(VertexVector* vertices, EdgeVector* edgesF, EdgeVector* edgesS) {\r\n\tboost::unordered_map* handlesToIndex;\r\n\tCDT* cdtS = computeCdt(vertices, edgesS, &handlesToIndex); // CDT of mimimum edge constraint\r\n\tEdgeVector* ev_cdtS = convertCdtToGraph(vertices, cdtS);\r\n\tbool res = isSubgraph(vertices, edgesF, ev_cdtS);\r\n\r\n\tdelete ev_cdtS;\r\n\tdelete cdtS;\r\n\tdelete handlesToIndex;\r\n\r\n\treturn res;\r\n}\r\n\r\nbool isCggSubgraph(VertexVector* vertices, EdgeVector* edgesF, EdgeVector* edgesS) {\r\n\tEdgeVector* newEdgesS;\r\n\tEdgeVector* gabriel_S;\r\n\tcomputeCgg(vertices, edgesS, &newEdgesS, &gabriel_S);\r\n\tbool res = isSubgraph(vertices, edgesF, gabriel_S);\r\n\r\n\tdelete gabriel_S;\r\n\tdelete newEdgesS;\r\n\r\n\treturn res;\r\n}\r\n\r\nint main(int argc, char* argv[]) {\r\n\tconst char* vertFile = (argc > 2) ? argv[1] : NULL;\r\n\tconst char* edgeFile = (argc > 2) ? argv[2] : NULL;\r\n\r\n\tVertexVector* vertices = NULL;\r\n\tEdgeVector* edges = NULL;\r\n\r\n\tif (vertFile == NULL || edgeFile == NULL) {\r\n\t\t// Random graph\r\n\t\t//createRandomCirclePlaneForest(1000, 1000, 100, &vertices, &edges);\r\n\t\t//createRandomMediumLengthPlaneForest(1000, 1000, 100, &vertices, &edges);\r\n\t\tcreateRandomNearTriangulation(1000, 1000, 100, &vertices, &edges);\r\n\t}\r\n\telse {\r\n\t\t// Load graph from file\r\n\t\t// e.g. D:\\g\\data\\HI.nodes D:\\g\\data\\HI.edges\r\n\t\tparseGraph(vertFile, edgeFile, &vertices, &edges);\r\n\t}\r\n\r\n\tif (SHOW_DEBUG) {\r\n\t\tprintGraph(\"Input\", vertices, edges, true);\r\n\t}\r\n\r\n\t// Compute CGG(V, E)\r\n\tEdgeVector* NewEdges;\r\n\tEdgeVector* cggS;\r\n\tcomputeNonLocallyGabriel(vertices, edges, &NewEdges, &cggS);\r\n\tEdgeVector* S = intersectInputSetWithConstraintSet(NewEdges, cggS);\r\n\t//std::cout << \"Edges in E: \" << NewEdges->size() << \" Edges in S: \" << S->size() << \" Ratio: \" << (double)((double)S->size() / (double)NewEdges->size()) << std::endl;\r\n\tstd::cout << S->size() << std::endl;\r\n\tstd::cout << (double)((double)S->size() / (double)NewEdges->size()) << std::endl;\r\n\tstd::cout << std::endl;\r\n\r\n\t//printGDFGraph(\"D:\\\\g\\\\results\\\\graph examples\\\\hi_gg_S.gdf\", vertices, S);\r\n\r\n\t// Other possible validatation\r\n\t// CGG ⊆ CDT\r\n\t// S ⊆ CDT\r\n\r\n\t// S ⊆ E\r\n\tif (!isSubgraph(vertices, S, NewEdges)) {\r\n\t\tstd::cout << \"Error: isSubgraph is false\" << std::endl;\r\n\t}\r\n\r\n\t// F ⊆ CDT(V, S) (Note: CGG is contained in CDT)\r\n\tif (!isCdtSubgraph(vertices, NewEdges, S)) {\r\n\t\tstd::cout << \"Error: isCdtSubgraph is false\" << std::endl;\r\n\t}\r\n\r\n\t// F ⊆ CGG(V, S), CGG is computed by running a CDT on S, followed by\r\n\t// a locally gabriel check on all edge from the CDT and eliminating edges\r\n\t// that are non-locally gabriel AND not a constraint edge\r\n\tif (!isCggSubgraph(vertices, NewEdges, S)) {\r\n\t\tstd::cout << \"Error: isCggSubgraph is false\" << std::endl;\r\n\t}\r\n\r\n\t\t\r\n\tdeleteEdgeVector(S);\r\n\tdeleteEdgeVector(cggS);\r\n\tdeleteEdgeVector(NewEdges);\r\n\r\n\tdeleteEdgeVector(edges);\r\n\tdeleteVerticesVector(vertices);\r\n\r\n\treturn 0;\r\n}", "meta": {"hexsha": "0a3647665e0ec28c979143d2bd5f769aaf83aef9", "size": 17593, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gabriel.cpp", "max_stars_repo_name": "eduong/cgal_gabriel", "max_stars_repo_head_hexsha": "2dba139b1724a418c788ac19d9a04b9a28ddf8f0", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/gabriel.cpp", "max_issues_repo_name": "eduong/cgal_gabriel", "max_issues_repo_head_hexsha": "2dba139b1724a418c788ac19d9a04b9a28ddf8f0", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gabriel.cpp", "max_forks_repo_name": "eduong/cgal_gabriel", "max_forks_repo_head_hexsha": "2dba139b1724a418c788ac19d9a04b9a28ddf8f0", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5194085028, "max_line_length": 169, "alphanum_fraction": 0.6467913375, "num_tokens": 5256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199552262967, "lm_q2_score": 0.7772998663336158, "lm_q1q2_score": 0.6510818792357697}} {"text": "\n// Copyright(c) 2019-present, Alexander Silva Barbosa & bflib contributors.\n// Distributed under the MIT License (http://opensource.org/licenses/MIT)\n\n/**\n * @author Alexander Silva Barbosa \n * @date 2019\n * Particle Filter (Monte Carlo)\n */\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\ntemplate \nclass PF\n{\n private:\n typedef Matrix MatNx1;\n typedef Matrix MatMx1;\n typedef Matrix MatPx1;\n typedef Matrix MatNxN;\n\n public:\n typedef MatNx1 State;\n typedef MatMx1 Input;\n typedef MatPx1 Output;\n typedef Input Control;\n typedef Output Sensor;\n typedef MatPx1 SensorStd;\n typedef MatNx1 ResampleStd;\n\n double eps;\n\n private:\n typedef void (*ModelFunction)(State &x, Input &u, double dt);\n typedef void (*SensorFunction)(std::vector &y, State &x, double dt);\n\n std::default_random_engine gen;\n std::normal_distribution distr{0.0, 1.0};\n std::chrono::time_point start;\n\n int N, NMax;\n std::vector W;\n std::vector< std::vector > Y;\n std::vector w;\n double wMax;\n\n State minState, maxState, meanState;\n\n State x;\n ResampleStd Q;\n SensorStd R;\n \n MatNxN resampleMatrix;\n MatNx1 randX;\n\n ModelFunction modelFn;\n SensorFunction sensorFn;\n\n void init()\n {\n modelFn = NULL;\n sensorFn = NULL;\n\n resampleMatrix = Q.asDiagonal();\n\n N = NMax;\n W.resize(N);\n Y.resize(N);\n w.resize(N);\n meanState = (maxState - minState) / 2;\n initW();\n\n eps = 1e-10;\n\n start = std::chrono::high_resolution_clock::now();\n }\n public:\n\n PF(int N, State minState, State maxState) : NMax(N), minState(minState), maxState(maxState)\n {\n Q.setIdentity();\n R.setIdentity();\n x.setZero();\n init();\n }\n\n PF(int N, State X, State minState, State maxState) : x(X), NMax(N), minState(minState), maxState(maxState)\n {\n Q.setIdentity();\n R.setIdentity();\n init();\n }\n\n PF(int N, State minState, State maxState, ResampleStd Q, SensorStd R) : Q(Q), R(R), NMax(N), minState(minState), maxState(maxState)\n {\n x.setZero();\n init();\n }\n\n PF(int N, State X, State minState, State maxState, ResampleStd Q, SensorStd R) : x(X), Q(Q), R(R), NMax(N), minState(minState), maxState(maxState)\n {\n init();\n }\n\n virtual ~PF()\n {\n\n }\n\n void seed()\n {\n unsigned int s = std::chrono::system_clock::now().time_since_epoch().count();\n seed(s);\n }\n\n void seed(unsigned int s)\n {\n gen = std::default_random_engine(s);\n srand (s);\n std::srand(s);\n initW();\n }\n\n State state()\n {\n MatNx1 x;\n x.setZero();\n return x;\n }\n\n Input input()\n {\n MatMx1 u;\n u.setZero();\n return u;\n }\n\n Output output()\n {\n MatPx1 y;\n y.setZero();\n return y;\n }\n\n SensorStd createR()\n {\n SensorStd R;\n R.setZero();\n return R;\n }\n\n void setR(SensorStd R)\n {\n this->R = R;\n }\n\n ResampleStd createQ()\n {\n ResampleStd Q;\n Q.setZero();\n return Q;\n }\n\n void setQ(ResampleStd Q)\n {\n this->Q = Q;\n resampleMatrix = Q.asDiagonal();\n }\n\n double time()\n {\n auto end = std::chrono::high_resolution_clock::now();\n std::chrono::duration diff = end - start;\n start = std::chrono::high_resolution_clock::now();\n return diff.count();\n }\n\n double delay(double s)\n {\n double ellapsed = time();\n double remain = s - ellapsed;\n if(remain < 0)\n return ellapsed;\n std::this_thread::sleep_for(std::chrono::nanoseconds((long long)(remain * 1e9)));\n ellapsed += time();\n return ellapsed;\n }\n\n std::vector& particles()\n {\n return W;\n }\n\n void setModel(ModelFunction fn)\n {\n modelFn = fn;\n }\n\n void setSensor(SensorFunction fn)\n {\n sensorFn = fn;\n }\n\n virtual void model(State &x, Input &u, double dt)\n {\n\n }\n\n virtual void sensor(std::vector &z, State &x, double dt)\n {\n\n }\n\n void simulate(State &x, std::vector &y, Input &u, double dt)\n {\n doModel(x, u, dt);\n\n y.resize(outputSize);\n doSensor(y, x, dt);\n }\n\n void run(State &xK, std::vector &y, Input &u, double dt)\n {\n y.resize(outputSize);\n\n applyControl(u, dt);\n sense(dt);\n compare(y);\n resample();\n measure();\n\n xK = x;\n }\n\t\n\tvoid VaryN(float error, int Nmin, int Ni, float error_lim, int Nmax)\n\t{\n\t int Np=0;\n\t if(error>error_lim)\n\t {\n\t \tfloat l;\n\t \n \tl = round(error/error_lim);\n\t \tint k = (int)l;\n Np = Nmin + Ni*k;\n \tif(Np > Nmax)\n\t\t{\n\t\t\tthis->N = Nmax;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis->N = Np;\n\t\t}\n }\n\t else\n\t {\n Np = Nmin;\n\t\tthis->N = Np;\n }\n\t cout << this-> N << endl;\n\t}\n\n private:\n void initW()\n {\n for(int n = 0; n < N; n++)\n {\n W[n] = State::Random();\n for (size_t i = 0; i < states; i++)\n {\n W[n](i) = meanState(i) + W[n](i) * meanState(i);\n }\n }\n }\n\n void applyControl( Input &u, double dt)\n {\n for(int i = 0; i < N; i++)\n {\n doModel(W[i], u, dt);\n }\n }\n\n void sense(double dt)\n {\n for(int i = 0; i < N; i++)\n {\n Y[i].resize(outputSize);\n doSensor(Y[i], W[i], dt);\n }\n }\n\n void compare(std::vector &y)\n {\n double sum = 0;\n double lh = 0;\n for(int i = 0; i < N; i++)\n {\n w[i] = 1.0;\n for(int j = 0; j < outputSize; j++)\n {\n lh = likelihood(y[j], Y[i][j]);\n w[i] *= lh;\n }\n sum += w[i];\n }\n\n wMax = 0;\n for(int i = 0; i < N; i++)\n {\n w[i] /= sum;\n if(w[i] > wMax)\n wMax = w[i];\n }\n }\n\n double likelihood(Output y, Output z)\n {\n double lh = 0;\n double df, sq, ex, pi2, m;\n\n pi2 = sqrt(2 * 3.14159265358979);\n\n for (size_t i = 0; i < outputs; i++)\n {\n if(R(i) == 0)\n continue;\n\n m = 1.0 / ( R(i) * pi2 );\n\n df = (z(i) - y(i)) / R(i);\n\n sq = df*df;\n ex = exp( -0.5 * sq );\n\n lh += m * ex;\n }\n\n lh += eps;\n }\n\n void resample()\n {\n int index = rand() % N;\n double F;\n std::vector nW(N);\n\n for(int i = 0; i < N; i++)\n {\n F = 10 * wMax * ( ( rand() % 100 ) / 100.0);\n while(F > w[index])\n {\n F -= w[index];\n index = ( index + 1 ) % N;\n }\n randn(randX);\n nW[i] = W[index] + resampleMatrix * randX;\n for (size_t j = 0; j < outputs; j++)\n {\n if(nW[i](j) < minState(j))\n nW[i](j) = maxState(j) - ( minState(j) - nW[i](j) );\n else if(nW[i](j) > maxState(j))\n nW[i](j) = minState(j) + ( nW[i](j) - maxState(j) );\n }\n }\n\n W = nW;\n }\n\n void measure()\n {\n x.setZero();\n for(int i = 0; i < N; i++)\n {\n x += W[i];\n }\n x /= N;\n }\n\n void doModel(State &x, Input &u, double dt)\n {\n if(modelFn != NULL)\n modelFn(x, u, dt);\n else\n model(x, u, dt);\n }\n\n void doSensor(std::vector &z, State &x, double dt)\n {\n if(sensorFn != NULL)\n sensorFn(z, x, dt);\n else\n sensor(z, x, dt);\n }\n\n template\n void randn(T &mat)\n {\n for (size_t i = 0; i < mat.rows(); i++)\n {\n for (size_t j = 0; j < mat.cols(); j++)\n {\n mat(i, j) = distr(gen);\n }\n }\n }\n\n};\n", "meta": {"hexsha": "a3741a3d13e8a2058592972e82d3fa4c6553a2be", "size": 9702, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bflib/PF.hpp", "max_stars_repo_name": "olggc/bflib", "max_stars_repo_head_hexsha": "15a43a6ca1db2a4c061b4a90b804518c75e9b514", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-21T12:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-21T12:31:03.000Z", "max_issues_repo_path": "bflib/PF.hpp", "max_issues_repo_name": "viniciusreis21/bflib", "max_issues_repo_head_hexsha": "15a43a6ca1db2a4c061b4a90b804518c75e9b514", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bflib/PF.hpp", "max_forks_repo_name": "viniciusreis21/bflib", "max_forks_repo_head_hexsha": "15a43a6ca1db2a4c061b4a90b804518c75e9b514", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2105263158, "max_line_length": 154, "alphanum_fraction": 0.4128014842, "num_tokens": 2375, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.935346511643776, "lm_q2_score": 0.6959583313396339, "lm_q1q2_score": 0.6509621974679498}} {"text": "#include \n#include \n\n\nint main(int argc, char* argv [])\n{\n Eigen::Vector3d pos(1, 0, 0);\n Eigen::Displacementd H_1_0 = Eigen::Displacementd(pos);\n Eigen::Displacementd H_2_1 = Eigen::Displacementd(pos);\n\n Eigen::Vector3d axis(0, 0, 1);\n\n Eigen::Twistd tw(Eigen::AngularVelocityd(axis), pos.cross(axis));\n\n tw *= 1 * M_PI / 2.0;\n\n // See Murray Lie Sastry page 50. \n Eigen::Displacementd H_2_0 = tw.exp() * H_1_0 * H_2_1;\n //std::cout << \"twist : \" << tw.transpose() << std::endl;\n std::cout << \"H_1_0 : \" << H_1_0 << std::endl;\n std::cout << \"eTw \" << tw.exp() << std::endl;\n //std::cout << \"H_2_1 : \" << H_2_1 << std::endl;\n //std::cout << \"Brockett factor : \" << tw.exp() * H_1_0 << std::endl;\n std::cout << \"H_2_0 \" << H_2_0 << std::endl;\n //std::cout << tw.exp() * H_1_0 * H_2_1 << std::endl;\n std::cout << tw.exp() * H_1_0 << std::endl;\n \n return 0;\n}\n", "meta": {"hexsha": "42aa061c11e2f7c437bfaec71816ad93eca3e09e", "size": 904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "extra/testTwist.cpp", "max_stars_repo_name": "kayhman/lisphys", "max_stars_repo_head_hexsha": "4e339022f2e2ea886d598dfce2365958ff5b87bb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2016-01-11T13:56:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-30T15:36:05.000Z", "max_issues_repo_path": "extra/testTwist.cpp", "max_issues_repo_name": "kayhman/lisphys", "max_issues_repo_head_hexsha": "4e339022f2e2ea886d598dfce2365958ff5b87bb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2015-02-13T13:00:40.000Z", "max_issues_repo_issues_event_max_datetime": "2016-06-23T12:57:34.000Z", "max_forks_repo_path": "extra/testTwist.cpp", "max_forks_repo_name": "kayhman/lisphys", "max_forks_repo_head_hexsha": "4e339022f2e2ea886d598dfce2365958ff5b87bb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-05T02:29:02.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-05T02:29:02.000Z", "avg_line_length": 30.1333333333, "max_line_length": 72, "alphanum_fraction": 0.578539823, "num_tokens": 360, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206818021529, "lm_q2_score": 0.7217432003123989, "lm_q1q2_score": 0.6509551193118266}} {"text": "\n#include \n#include \n#include \n#include \n#include \n#include \"Timer.h\"\n#include \"Projection.h\"\n#include \"Volumetric_helper.h\"\n#include \"KinectFrame.h\"\n#include \"KinectSpecs.h\"\n#include \"ICP.h\"\n\ntypedef double Decimal;\n\n\n\n\n\nvoid compute_vertices(std::vector>& vertices, const KinectFrame& frame, Decimal fovy, Decimal aspect_ratio, Decimal near_plane, Decimal far_plane)\n{\n\tEigen::Matrix vert_uv, vert_u1v, vert_uv1;\n\n\tfor (int x = 0; x < frame.depth_width() - 1; ++x)\n\t{\n\t\tfor (int y = 0; y < frame.depth_height() - 1; ++y)\n\t\t{\n\t\t\tconst Decimal depth = frame.depth[y * frame.depth_width() + x];\n\n\t\t\tif (depth > 0.01)\n\t\t\t{\n\t\t\t\tvert_uv = window_coord_to_3d(Eigen::Matrix(x, y), depth, fovy, aspect_ratio, near_plane, far_plane, frame.depth_width(), frame.depth_height());\n\n\t\t\t\tint i = y * frame.depth_width() + x;\n\n#if 1\n\t\t\t\tvertices[i] = vert_uv.homogeneous();\n#else\n\n\t\t\t\tif (!vert_uv.isZero(0.0001))\n\t\t\t\t{\n\t\t\t\t\tvertices.push_back(vert_uv.homogeneous());\n\t\t\t\t}\n#endif\n\t\t\t}\n\n\t\t}\n\t}\n}\n\n\n\n// Usage: ./Icp.exe ../../data/frame_0.knt ../../data/frame_1.knt 0 10 3\nint main(int argc, char **argv)\n{\n\n\tif (argc < 3)\n\t{\n\t\tstd::cerr\n\t\t\t<< \"Missing parameters. Abort.\"\n\t\t\t<< std::endl\n\t\t\t<< \"Usage: ./Icp.exe \"\n\t\t\t<< \"Usage: ./Icp.exe ../../data/frame_1.knt ../../data/frame_1.knt 10 3\"\n\t\t\t<< std::endl;\n\t\treturn EXIT_FAILURE;\n\t}\n\n\n\tTimer timer;\n\tconst std::string input_filename[] = { argv[1], argv[2] };\n\n\tconst int filter_width = (argc > 2) ? atoi(argv[3]) : 10;\n\tconst Decimal max_distance = (Decimal)((argc > 3) ? atof(argv[4]) : 100);\n\n\ttry\n\t{\n\t\ttimer.start();\n\t\tKinectFrame frame[2] =\n\t\t{\n\t\t\tKinectFrame(input_filename[0]),\n\t\t\tKinectFrame(input_filename[1])\n\t\t};\n\t\ttimer.print_interval(\"Importing frames : \");\n\t\t\n\n\t\tif (frame[0].depth_width() != frame[1].depth_width() ||\n\t\t\tframe[0].depth_height() != frame[1].depth_height())\n\t\t{\n\t\t\tstd::cout\n\t\t\t\t<< \"Frame size doens not match: \" << std::endl\n\t\t\t\t<< frame[0].depth_width() << \", \" << frame[0].depth_height() << std::endl\n\t\t\t\t<< frame[1].depth_width() << \", \" << frame[1].depth_height() << std::endl\n\t\t\t\t<< std::endl;\n\t\t\treturn EXIT_FAILURE;\n\t\t}\n\n\t\tconst uint16_t width = frame[0].depth_width();\n\t\tconst uint16_t height = frame[0].depth_height();\n\t\tconst uint32_t pixel_count = width * height;\n\n\t\tDecimal fovy = KINECT_V2_FOVY;\n\t\tDecimal aspect_ratio = KINECT_V2_DEPTH_ASPECT_RATIO;\n\t\tDecimal near_plane = KINECT_V2_DEPTH_MIN;\n\t\tDecimal far_plane = KINECT_V2_DEPTH_MAX;\n\n\t\tif (width != 512)\t// it is not kinect version 2. It is version 1\n\t\t{\n\t\t\tfovy = KINECT_V1_FOVY;\n\t\t\taspect_ratio = KINECT_V1_ASPECT_RATIO;\n\t\t\tnear_plane = KINECT_V1_DEPTH_MIN;\n\t\t\tfar_plane = KINECT_V1_DEPTH_MAX;\n\t\t}\n\n\n\t\tstd::vector> vertices[2] = \n\t\t{\n\t\t\tstd::vector>(pixel_count, Eigen::Matrix(0, 0, 0, 0)), \n\t\t\tstd::vector>(pixel_count, Eigen::Matrix(0, 0, 0, 0))\n\t\t};\n\n\n\t\tfor (int i = 0; i < 2; ++i)\n\t\t{\n\t\t\ttimer.start();\n\t\t\tcompute_vertices(vertices[i], frame[i], fovy, aspect_ratio, near_plane, far_plane);\n\t\t\ttimer.print_interval(\"Depth map back projection : \");\n\t\t}\n\n\t\n\n\t\tICP icp;\n\t\ticp.setInputCloud(vertices[0]);\n\t\ticp.setTargetCloud(vertices[1]);\n\n\n\t\tEigen::Matrix identity = Eigen::Matrix::Identity();\n\t\tEigen::Matrix rigidTransform = Eigen::Matrix::Identity();\n\t\tEigen::Matrix R;\n\t\tEigen::Matrix t;\n\t\n\t\tfor (int i = 0; i < 1; i++)\n\t\t{\n\n\t\t\ttimer.start();\n\t\t\tbool icp_success = icp.align_iteration(vertices[0], vertices[1], \n\t\t\t\tfilter_width, max_distance, width, height, \n\t\t\t\tR, t);\n\t\t\t\n\t\t\ttimer.print_interval(\"Computing icp : \");\n\n\t\t\tif (icp_success)\n\t\t\t{\n\t\t\t\tstd::cout << \"Icp Success\" << std::endl;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << \"Icp Failed\" << std::endl;\n\t\t\t}\n\n\t\t\tstd::cout \n\t\t\t\t<< std::fixed << std::endl\n\t\t\t\t<< R << std::endl << std::endl\n\t\t\t\t<< t.transpose() << std::endl << std::endl;\n\t\t}\n\n\n\t}\n\tcatch (const std::exception& ex)\n\t{\n\t\tstd::cerr << \"Error: \" << ex.what() << std::endl;\n\t}\n\n\n\n\treturn 0;\n}\n\n\n\n", "meta": {"hexsha": "32a661dc2f339898aa5f92553a593e477447b43f", "size": 4256, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Icp_cpu.cpp", "max_stars_repo_name": "diegomazala/QtKinect", "max_stars_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2016-08-04T14:14:11.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-27T13:46:13.000Z", "max_issues_repo_path": "src/Icp_cpu.cpp", "max_issues_repo_name": "diegomazala/QtKinect", "max_issues_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Icp_cpu.cpp", "max_forks_repo_name": "diegomazala/QtKinect", "max_forks_repo_head_hexsha": "c51819980af92b857d87a417d19c5f01d8fada77", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2015-12-08T06:22:46.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T10:29:17.000Z", "avg_line_length": 23.6444444444, "max_line_length": 175, "alphanum_fraction": 0.6278195489, "num_tokens": 1418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942319436397, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.650857230550537}} {"text": "#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\ntypedef CGAL::Simple_cartesian K;\r\ntypedef CGAL::Surface_mesh Mesh;\r\n\r\nnamespace PMP = CGAL::Polygon_mesh_processing;\r\n\r\nint main(int argc, char *argv[])\r\n{\r\n const char* filename1 = \"../meshes/BIG_SCREW.off\";\r\n std::ifstream input1(filename1);\r\n Mesh mesh1;\r\n if (!input1 || !(input1 >> mesh1) || !CGAL::is_triangle_mesh(mesh1))\r\n {\r\n std::cerr << \"Not a valid input file.\" << std::endl;\r\n return 1;\r\n }\r\n\r\n const char* filename2 = \"../meshes/fingertip_8faces.off\";\r\n std::ifstream input2(filename2);\r\n Mesh mesh2;\r\n if (!input2 || !(input2 >> mesh2) || !CGAL::is_triangle_mesh(mesh2))\r\n {\r\n std::cerr << \"Not a valid input file.\" << std::endl;\r\n return 1;\r\n }\r\n\r\n Eigen::Matrix3d R = Eigen::Matrix3d::Identity();\r\n for (int i = 0; i < 10; ++i) {\r\n double begin = std::clock();\r\n Eigen::Vector3d p;\r\n p << 0, 2*i, 0;\r\n K::Aff_transformation_3 transform_cgal(\r\n R(0,0), R(0,1), R(0,2), p(0),\r\n R(1,0), R(1,1), R(1,2), p(1),\r\n R(2,0), R(2,1), R(2,2), p(2), 1);\r\n // K::Aff_transformation_3 transform_cgal(CGAL::TRANSLATION, K::Vector_3(0,i*2,0));\r\n PMP::transform (transform_cgal, mesh1);\r\n bool intersecting = PMP::do_intersect (mesh1, mesh2);\r\n std::cout << \"Computation Time: \" << (std::clock() - begin) / CLOCKS_PER_SEC << \" sec\" << std::endl;\r\n std::cout << \"intersecting: \" << intersecting << std::endl;\r\n }\r\n}\r\n", "meta": {"hexsha": "1ac23c5aae6fe33e17a3660dbf0eea6e1698dea7", "size": 1759, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "yifan-hou/triangle-mesh-collision", "max_stars_repo_head_hexsha": "a7fac1eb25ca62e84abbf1bd6f19de797191fe3e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "yifan-hou/triangle-mesh-collision", "max_issues_repo_head_hexsha": "a7fac1eb25ca62e84abbf1bd6f19de797191fe3e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "yifan-hou/triangle-mesh-collision", "max_forks_repo_head_hexsha": "a7fac1eb25ca62e84abbf1bd6f19de797191fe3e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5740740741, "max_line_length": 105, "alphanum_fraction": 0.6219442865, "num_tokens": 562, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.650856879370451}} {"text": "#include \n#include \n#include \n#include \n\n\nusing namespace std;\n\ntypedef vector> VecVector2d;\n\n// Camera intrinsics\ndouble fx = 718.856, fy = 718.856, cx = 607.1928, cy = 185.2157;\n// baseline\ndouble baseline = 0.573;\n// paths\nstring left_file = \"../../images/left.png\";\nstring disparity_file = \"../../images/disparity.png\";\nboost::format fmt_others(\"../../images/%06d.png\"); // other files\n\n// useful typedefs\ntypedef Eigen::Matrix Matrix6d;\ntypedef Eigen::Matrix Matrix26d;\ntypedef Eigen::Matrix Vector6d;\n\n/// class for accumulator jacobians in parallel\nclass JacobianAccumulator {\npublic:\n JacobianAccumulator(\n const cv::Mat &img1_,\n const cv::Mat &img2_,\n const VecVector2d &px_ref_,\n const vector depth_ref_, //FIXME: Use &?//FIXME: Use &?\n Sophus::SE3d &T21_) :\n img1(img1_), img2(img2_), px_ref(px_ref_), depth_ref(depth_ref_), T21(T21_) {\n projection = VecVector2d(px_ref.size(), Eigen::Vector2d(0, 0));\n }\n\n /// accumulate jacobians in a range\n void accumulate_jacobian(const cv::Range &range);\n\n /// get hessian matrix\n Matrix6d hessian() const { return H; }\n\n /// get bias\n Vector6d bias() const { return b; }\n\n /// get total cost\n double cost_func() const { return cost; }\n\n /// get projected points\n VecVector2d projected_points() const { return projection; }\n\n /// reset h, b, cost to zero\n void reset() {\n H = Matrix6d::Zero();\n b = Vector6d::Zero();\n cost = 0;\n }\n\nprivate:\n const cv::Mat &img1;\n const cv::Mat &img2;\n const VecVector2d &px_ref;\n const vector depth_ref; //FIXME: Use &?\n Sophus::SE3d &T21;\n VecVector2d projection; // projected points\n\n std::mutex hessian_mutex;\n Matrix6d H = Matrix6d::Zero();\n Vector6d b = Vector6d::Zero();\n double cost = 0;\n};\n\n/**\n * pose estimation using direct method\n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationMultiLayer(\n const cv::Mat &img1,\n const cv::Mat &img2,\n const VecVector2d &px_ref,\n const vector depth_ref,\n Sophus::SE3d &T21\n);\n\n/**\n * pose estimation using direct method\n * @param img1\n * @param img2\n * @param px_ref\n * @param depth_ref\n * @param T21\n */\nvoid DirectPoseEstimationSingleLayer(\n const cv::Mat &img1,\n const cv::Mat &img2,\n const VecVector2d &px_ref,\n const vector depth_ref,\n Sophus::SE3d &T21\n);\n\n// bilinear interpolation\ninline float GetPixelValue(const cv::Mat &img, float x, float y) {\n // boundary check\n if (x < 0) x = 0;\n if (y < 0) y = 0;\n if (x >= img.cols) x = img.cols - 1;\n if (y >= img.rows) y = img.rows - 1;\n uchar *data = &img.data[int(y) * img.step + int(x)];\n float xx = x - floor(x);\n float yy = y - floor(y);\n return float(\n (1 - xx) * (1 - yy) * data[0] +\n xx * (1 - yy) * data[1] +\n (1 - xx) * yy * data[img.step] +\n xx * yy * data[img.step + 1]\n );\n}\n\nint main(int argc, char **argv) {\n\n cv::Mat left_img = cv::imread(left_file, 0);\n cv::Mat disparity_img = cv::imread(disparity_file, 0);\n\n // let's randomly pick pixels in the first image and generate some 3d points in the first image's frame\n cv::RNG rng;\n int nPoints = 2000;\n int boarder = 20;\n VecVector2d pixels_ref;\n vector depth_ref;\n\n // generate pixels in ref and load depth data\n for (int i = 0; i < nPoints; i++) {\n int x = rng.uniform(boarder, left_img.cols - boarder); // don't pick pixels close to boarder\n int y = rng.uniform(boarder, left_img.rows - boarder); // don't pick pixels close to boarder\n int disparity = disparity_img.at(y, x);\n double depth = fx * baseline / disparity; // you know this is disparity to depth\n depth_ref.push_back(depth);\n pixels_ref.push_back(Eigen::Vector2d(x, y));\n }\n\n // estimates 01~05.png's pose using this information\n Sophus::SE3d T_cur_ref;\n\n for (int i = 1; i < 6; i++) { // 1~10\n cv::Mat img = cv::imread((fmt_others % i).str(), 0);\n // try single layer by uncomment this line\n // DirectPoseEstimationSingleLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref);\n DirectPoseEstimationMultiLayer(left_img, img, pixels_ref, depth_ref, T_cur_ref);\n }\n return 0;\n}\n\nvoid DirectPoseEstimationSingleLayer(\n const cv::Mat &img1,\n const cv::Mat &img2,\n const VecVector2d &px_ref,\n const vector depth_ref, //FIXME: Use &?\n Sophus::SE3d &T21) {\n\n const int iterations = 10;\n double cost = 0, lastCost = 0;\n auto t1 = chrono::steady_clock::now();\n JacobianAccumulator jaco_accu(img1, img2, px_ref, depth_ref, T21);\n\n for (int iter = 0; iter < iterations; iter++) {\n jaco_accu.reset();\n cv::parallel_for_(cv::Range(0, px_ref.size()),\n std::bind(&JacobianAccumulator::accumulate_jacobian, &jaco_accu, std::placeholders::_1));\n Matrix6d H = jaco_accu.hessian();\n Vector6d b = jaco_accu.bias();\n\n // solve update and put it into estimation\n Vector6d update = H.ldlt().solve(b);;\n T21 = Sophus::SE3d::exp(update) * T21;\n cost = jaco_accu.cost_func();\n\n if (std::isnan(update[0])) {\n // sometimes occurred when we have a black or white patch and H is irreversible\n cout << \"update is nan\" << endl;\n break;\n }\n if (iter > 0 && cost > lastCost) {\n cout << \"cost increased: \" << cost << \", \" << lastCost << endl;\n break;\n }\n if (update.norm() < 1e-3) {\n // converge\n break;\n }\n\n lastCost = cost;\n cout << \"iteration: \" << iter << \", cost: \" << cost << endl;\n }\n\n cout << \"T21 = \\n\" << T21.matrix() << endl;\n auto t2 = chrono::steady_clock::now();\n auto time_used = chrono::duration_cast>(t2 - t1);\n cout << \"direct method for single layer: \" << time_used.count() << endl;\n\n // plot the projected pixels here\n cv::Mat img2_show;\n cv::cvtColor(img2, img2_show, CV_GRAY2BGR);\n VecVector2d projection = jaco_accu.projected_points();\n for (size_t i = 0; i < px_ref.size(); ++i) {\n auto p_ref = px_ref[i];\n auto p_cur = projection[i];\n if (p_cur[0] > 0 && p_cur[1] > 0) {\n cv::circle(img2_show, cv::Point2f(p_cur[0], p_cur[1]), 2, cv::Scalar(0, 250, 0), 2);\n cv::line(img2_show, cv::Point2f(p_ref[0], p_ref[1]), cv::Point2f(p_cur[0], p_cur[1]),\n cv::Scalar(0, 250, 0));\n }\n }\n cv::imshow(\"current\", img2_show);\n cv::waitKey();\n}\n\nvoid JacobianAccumulator::accumulate_jacobian(const cv::Range &range) {\n\n // parameters\n const int half_patch_size = 1;\n int cnt_good = 0;\n Matrix6d hessian = Matrix6d::Zero();\n Vector6d bias = Vector6d::Zero();\n double cost_tmp = 0;\n\n for (size_t i = range.start; i < range.end; i++) {\n\n // compute the projection in the second image\n Eigen::Vector3d point_ref =\n depth_ref[i] * Eigen::Vector3d((px_ref[i][0] - cx) / fx, (px_ref[i][1] - cy) / fy, 1);\n Eigen::Vector3d point_cur = T21 * point_ref;\n if (point_cur[2] < 0) // depth invalid\n continue;\n\n float u = fx * point_cur[0] / point_cur[2] + cx, v = fy * point_cur[1] / point_cur[2] + cy;\n if (u < half_patch_size || u > img2.cols - half_patch_size || v < half_patch_size ||\n v > img2.rows - half_patch_size)\n continue;\n\n projection[i] = Eigen::Vector2d(u, v);\n double X = point_cur[0], Y = point_cur[1], Z = point_cur[2],\n Z2 = Z * Z, Z_inv = 1.0 / Z, Z2_inv = Z_inv * Z_inv;\n cnt_good++;\n\n // and compute error and jacobian\n for (int x = -half_patch_size; x <= half_patch_size; x++)\n for (int y = -half_patch_size; y <= half_patch_size; y++) {\n\n double error = GetPixelValue(img1, px_ref[i][0] + x, px_ref[i][1] + y) -\n GetPixelValue(img2, u + x, v + y);\n Matrix26d J_pixel_xi;\n Eigen::Vector2d J_img_pixel;\n\n J_pixel_xi(0, 0) = fx * Z_inv;\n J_pixel_xi(0, 1) = 0;\n J_pixel_xi(0, 2) = -fx * X * Z2_inv;\n J_pixel_xi(0, 3) = -fx * X * Y * Z2_inv;\n J_pixel_xi(0, 4) = fx + fx * X * X * Z2_inv;\n J_pixel_xi(0, 5) = -fx * Y * Z_inv;\n\n J_pixel_xi(1, 0) = 0;\n J_pixel_xi(1, 1) = fy * Z_inv;\n J_pixel_xi(1, 2) = -fy * Y * Z2_inv;\n J_pixel_xi(1, 3) = -fy - fy * Y * Y * Z2_inv;\n J_pixel_xi(1, 4) = fy * X * Y * Z2_inv;\n J_pixel_xi(1, 5) = fy * X * Z_inv;\n\n J_img_pixel = Eigen::Vector2d(\n 0.5 * (GetPixelValue(img2, u + 1 + x, v + y) - GetPixelValue(img2, u - 1 + x, v + y)),\n 0.5 * (GetPixelValue(img2, u + x, v + 1 + y) - GetPixelValue(img2, u + x, v - 1 + y))\n );\n\n // total jacobian\n Vector6d J = -1.0 * (J_img_pixel.transpose() * J_pixel_xi).transpose();\n\n hessian += J * J.transpose();\n bias += -error * J;\n cost_tmp += error * error;\n }\n }\n\n if (cnt_good) {\n // set hessian, bias and cost\n unique_lock lck(hessian_mutex);\n H += hessian;\n b += bias;\n cost += cost_tmp / cnt_good;\n }\n}\n\nvoid DirectPoseEstimationMultiLayer(\n const cv::Mat &img1,\n const cv::Mat &img2,\n const VecVector2d &px_ref,\n const vector depth_ref, //FIXME: Use &?\n Sophus::SE3d &T21) {\n\n // parameters\n int pyramids = 4;\n double pyramid_scale = 0.5;\n double scales[] = {1.0, 0.5, 0.25, 0.125};\n\n // create pyramids\n vector pyr1, pyr2; // image pyramids\n for (int i = 0; i < pyramids; i++) {\n if (i == 0) {\n pyr1.push_back(img1);\n pyr2.push_back(img2);\n } else {\n cv::Mat img1_pyr, img2_pyr;\n cv::resize(pyr1[i - 1], img1_pyr,\n cv::Size(pyr1[i - 1].cols * pyramid_scale, pyr1[i - 1].rows * pyramid_scale));\n cv::resize(pyr2[i - 1], img2_pyr,\n cv::Size(pyr2[i - 1].cols * pyramid_scale, pyr2[i - 1].rows * pyramid_scale));\n pyr1.push_back(img1_pyr);\n pyr2.push_back(img2_pyr);\n }\n }\n\n double fxG = fx, fyG = fy, cxG = cx, cyG = cy; // backup the old values\n for (int level = pyramids - 1; level >= 0; level--) {\n VecVector2d px_ref_pyr; // set the keypoints in this pyramid level\n for (auto &px: px_ref) {\n px_ref_pyr.push_back(scales[level] * px);\n }\n\n // scale fx, fy, cx, cy in different pyramid levels\n fx = fxG * scales[level];\n fy = fyG * scales[level];\n cx = cxG * scales[level];\n cy = cyG * scales[level];\n DirectPoseEstimationSingleLayer(pyr1[level], pyr2[level], px_ref_pyr, depth_ref, T21);\n }\n\n}\n", "meta": {"hexsha": "c8294f608ba52d9cde01d0d29dc15806e7081d8e", "size": 11302, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nicolas/ch8/optical_flow_book_examples/src/direct_method_original.cpp", "max_stars_repo_name": "nicolasrosa-forks/slambook2", "max_stars_repo_head_hexsha": "9cae572378fc5da758b6404e45d443b0bde71853", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nicolas/ch8/optical_flow_book_examples/src/direct_method_original.cpp", "max_issues_repo_name": "nicolasrosa-forks/slambook2", "max_issues_repo_head_hexsha": "9cae572378fc5da758b6404e45d443b0bde71853", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nicolas/ch8/optical_flow_book_examples/src/direct_method_original.cpp", "max_forks_repo_name": "nicolasrosa-forks/slambook2", "max_forks_repo_head_hexsha": "9cae572378fc5da758b6404e45d443b0bde71853", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-15T14:55:53.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-15T14:55:53.000Z", "avg_line_length": 33.1436950147, "max_line_length": 115, "alphanum_fraction": 0.5652981773, "num_tokens": 3418, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869786798664, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6508568698960397}} {"text": "/*\nPart of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)\nCopyright 2017-2019 University of Huddersfield.\nLicensed under the BSD-3 License.\nSee license.md file in the project root for full license information.\nThis project has received funding from the European Research Council (ERC)\nunder the European Union’s Horizon 2020 research and innovation programme\n(grant agreement No 725899).\n*/\n\n#pragma once\n\n#include \"FluidEigenMappings.hpp\"\n#include \"../../data/FluidIndex.hpp\"\n#include \"../../data/TensorTypes.hpp\"\n#include \n#include \n#include \n\nnamespace fluid {\nnamespace algorithm {\n\nclass WeightedStats\n{\npublic:\n Eigen::ArrayXd process(Eigen::Ref input,\n Eigen::Ref weights, double low,\n double mid, double high)\n {\n using namespace Eigen;\n using namespace std;\n index length = input.size();\n ArrayXd out = ArrayXd::Zero(7);\n double mean = (weights * input).sum();\n double stdev = sqrt((weights * (input - mean).square()).sum());\n double skewness =\n (weights * ((input - mean) / (stdev == 0 ? 1 : stdev)).cube()).sum();\n double kurtosis =\n (weights * ((input - mean) / (stdev == 0 ? 1 : stdev)).pow(4)).sum();\n ArrayXd sorted = input;\n ArrayXidx perm = ArrayXidx::LinSpaced(length, 0, length - 1);\n std::sort(perm.data(), perm.data() + length,\n [&](index i, index j) { return input(i) < input(j); });\n index level = 0;\n double lowVal{input(perm(0))};\n double midVal{input(perm(lrint(length - 1) / 2))};\n double hiVal{input(perm(lrint(length - 1)))};\n double acc = weights(perm(0)), prevAcc = 0;\n for (index i = 1; i < length; i++)\n {\n acc += weights(perm(i));\n if (level == 0 && acc >= low)\n {\n lowVal = abs(prevAcc - low) <= abs(acc - low) ? input(perm(i - 1))\n : input(perm(i));\n level = 1;\n }\n if (level == 1 && acc >= mid)\n {\n midVal = abs(prevAcc - mid) < abs(acc - mid) ? input(perm(i - 1))\n : input(perm(i));\n level = 2;\n }\n if (level == 2 && acc >= high)\n {\n hiVal = abs(prevAcc - high) < abs(acc - high) ? input(perm(i - 1))\n : input(perm(i));\n break;\n }\n prevAcc = acc;\n }\n out << mean, stdev, skewness, kurtosis, lowVal, midVal, hiVal;\n return out;\n }\n};\n} // namespace algorithm\n} // namespace fluid\n", "meta": {"hexsha": "b3e22f78591cbbbff1b8e6632e5e405ce5cdc4e6", "size": 2596, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/algorithms/util/WeightedStats.hpp", "max_stars_repo_name": "jamesb93/flucoma-core", "max_stars_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/algorithms/util/WeightedStats.hpp", "max_issues_repo_name": "jamesb93/flucoma-core", "max_issues_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/algorithms/util/WeightedStats.hpp", "max_forks_repo_name": "jamesb93/flucoma-core", "max_forks_repo_head_hexsha": "3e964dd569f6fff15bd5249a705dc0da8f7b2ad8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.2820512821, "max_line_length": 77, "alphanum_fraction": 0.5546995378, "num_tokens": 680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869851639067, "lm_q2_score": 0.7431680029241322, "lm_q1q2_score": 0.6508568647512072}} {"text": "#include \n#include \n#include \n#include \n\n#include \n\ndouble SignedTriangleVolume6(double3 a, double3 b, double3 c) {\n double z = a.z;\n z += b.z;\n z += c.z;\n double s;\n s = (a.y + b.y) * (a.x - b.x);\n s += (b.y + c.y) * (b.x - c.x);\n s += (c.y + a.y) * (c.x - a.x);\n return s * z;\n}\n\ndouble SignedRingVolume6(cspan ring) {\n double z = 0;\n for (auto e : ring) z += e.z;\n double s = 0;\n for (auto e : Edges(ring)) s += (e.a.y + e.b.y) * (e.a.x - e.b.x);\n return s * z;\n}\n\ndouble SignedVolume(const mesh3& mesh) {\n double v = 0;\n for (const triangle3& f : mesh) v += SignedTriangleVolume6(f.a, f.b, f.c);\n return v / 6.0;\n}\n\ndouble SignedVolume(const xmesh3& mesh) {\n double v = 0;\n for (face f : mesh)\n for (auto ring : f) v += SignedRingVolume6(ring);\n return v / 6.0;\n}\n\n// TODO test with volume of cube (randomly rotated)\n\n// Center of mass of a valid polyhedron\ndouble3 CenterOfMass(const mesh3& mesh) {\n double3 P = {0, 0, 0};\n double V = 0;\n for (const triangle3& f : mesh) {\n double v = dot(f.a, cross(f.b, f.c));\n P += (f.a + f.b + f.c) * v;\n V += v;\n }\n return P / (V * 4);\n}\n\ndouble2 centroid(cspan poly) {\n double2 P = {0, 0};\n double2 V = 0;\n for (auto i : range(poly.size())) {\n double2 a = poly[i];\n double2 b = poly[(i + 1) % poly.size()];\n double v = a.x * b.y - a.y * b.x;\n P += (a + b) * v;\n V += v;\n }\n return P / (V * 3);\n}\n\ndouble2 CenterOfMass(const polygon2& poly) {\n double2 P = {0, 0};\n double2 V = 0;\n for (auto [a, b] : Edges(poly)) {\n double v = a.x * b.y - a.y * b.x;\n P += (a + b) * v;\n V += v;\n }\n return P / (V * 3);\n}\n\n// Moment of inertia of a valid polyhedron with Center of Mass = 0 and Density = 1\ndouble33 moment_of_inertia(const mesh3& mesh) {\n constexpr double a = 1 / 60., b = 1 / 120.;\n const double33 canonical = {{a, b, b}, {b, a, b}, {b, b, a}};\n auto C = double33::make(0); // covariance\n for (const auto& f : mesh) {\n double33 A;\n // TODO setting rows or columns?\n A.a = f[0];\n A.b = f[1];\n A.c = f[2];\n C += transpose(A) * canonical * A * det(A);\n }\n return double33::make(trace(C)) - C; // C -> I\n}\n\nbool is_aabb(const mesh3& mesh) {\n aabb3 box(mesh);\n\n // All vertices must be made from extreme coordinates\n for (auto f : mesh)\n for (double3 v : f)\n if (v.x != box.min[0] && v.x != box.max[0] && v.y != box.min[1] && v.y != box.max[1] && v.z != box.min[2] &&\n v.z != box.max[2])\n return false;\n\n // Every face must have one coordinate constant\n for (auto f : mesh) {\n bool xx = f.a.x == f.b.x && f.b.x == f.c.x;\n bool yy = f.a.y == f.b.y && f.b.y == f.c.y;\n bool zz = f.a.z == f.b.z && f.b.z == f.c.z;\n if (!xx && !yy && !zz) return false;\n }\n return true;\n}\n\ndouble3 eigen_vector(cspan points) {\n // compute mean\n double3 m = {0, 0, 0};\n for (auto p : points) m += p;\n m /= points.size();\n\n // compute matrix\n double3 ss = {0, 0, 0};\n double xy = 0, xz = 0, yz = 0;\n for (auto p : points) {\n p -= m;\n ss += p * p;\n xy += p.x * p.y;\n xz += p.x * p.z;\n yz += p.y * p.z;\n }\n\n Eigen::MatrixXd a = Eigen::MatrixXd::Zero(3, 3);\n a(0, 0) = ss.x;\n a(1, 1) = ss.y;\n a(2, 2) = ss.z;\n a(0, 1) = a(1, 0) = xy;\n a(0, 2) = a(2, 0) = xz;\n a(1, 2) = a(2, 1) = yz;\n\n Eigen::EigenSolver es(a, true);\n auto values = es.eigenvalues();\n int i = 0;\n if (values(1).real() < values(i).real()) i = 1;\n if (values(2).real() < values(i).real()) i = 2;\n\n auto vectors = es.eigenvectors();\n return {vectors(0, i).real(), vectors(1, i).real(), vectors(2, i).real()};\n}\n", "meta": {"hexsha": "620f678a6641a058e377268ba7808ffd92d66655", "size": 3958, "ext": "cc", "lang": "C++", "max_stars_repo_path": "geom/properties.cc", "max_stars_repo_name": "tintor/sima", "max_stars_repo_head_hexsha": "7bc21cf1383ee81b7082158ce690befe025f0a4e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-07-06T15:01:00.000Z", "max_stars_repo_stars_event_max_datetime": "2019-07-06T15:01:00.000Z", "max_issues_repo_path": "geom/properties.cc", "max_issues_repo_name": "tintor/sima", "max_issues_repo_head_hexsha": "7bc21cf1383ee81b7082158ce690befe025f0a4e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "geom/properties.cc", "max_forks_repo_name": "tintor/sima", "max_forks_repo_head_hexsha": "7bc21cf1383ee81b7082158ce690befe025f0a4e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.7432432432, "max_line_length": 120, "alphanum_fraction": 0.4936836786, "num_tokens": 1387, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6508270384469711}} {"text": "//######################################################################\n//# SDF_Fusion Module \n//# \n//# Copyright (C) 2020 Siemens AG\n//# SPDX-License-Identifier: MIT\n//# Author 2020: This module has been developed by \n//# or under supervision of Slobodan Ilic\n//#######################################################################\n\n#include \"visualizer.hpp\"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace cv;\nusing namespace Eigen;\nusing namespace std;\n\nvector transform_and_project(const vector& points, const Mat& intrinsics, const Mat& pose)\n{\n\tvector projected_2d_points(points.size());\n\ttransform(points.begin(), points.end(), projected_2d_points.begin(), [&pose, &intrinsics] (const auto &point)\n\t{\n\t\tMat transformed = pose * point;\n\t\tMat projected = intrinsics * transformed.rowRange(0, 3);\n\t\tprojected /= projected.at(2);\n\t\treturn projected;\n\t});\n\n\treturn projected_2d_points;\n}\n\n\nvoid draw_origin_axis(Mat &colored_img, const Mat& intrinsics, const Mat& pose, float basis_length = 0.1) {\n\tvector axes_endpoints;\n\taxes_endpoints.push_back((Mat_(4, 1) << 0, 0, 0, 1));\n\taxes_endpoints.push_back((Mat_(4, 1) << basis_length, 0, 0, 1));\n\taxes_endpoints.push_back((Mat_(4, 1) << 0, basis_length, 0, 1));\n\taxes_endpoints.push_back((Mat_(4, 1) << 0, 0, basis_length, 1));\n\n\t// transform cube into camera reference frame\n\n\tvector p2d = transform_and_project(axes_endpoints, intrinsics, pose);\n\n\tPoint p0 = Point(p2d[0].at(0), p2d[0].at(1));\n\tPoint px = Point(p2d[1].at(0), p2d[1].at(1));\n\tPoint py = Point(p2d[2].at(0), p2d[2].at(1));\n\tPoint pz = Point(p2d[3].at(0), p2d[3].at(1));\n\n\tline(colored_img, p0, px, cv::Scalar(0, 0, 255), 1, 8);\n\tline(colored_img, p0, py, cv::Scalar(0, 255, 0), 1, 8);\n\tline(colored_img, p0, pz, cv::Scalar(255, 0, 0), 1, 8);\n\n\tcircle(colored_img, p0, 200 / 32.0, cv::Scalar(255, 255, 0), -1, 8);\n}\n\n\nvoid visualize_volume(const Mat &source_image, const Mat &intrinsics, const Mat &rotation, const Mat &translation, const Mat& llc, const Mat& upc)\n{\n\tMat image = source_image.clone();\n\t\n\tMat pose = Mat::eye(4, 4, CV_32F);\n\trotation.copyTo(pose.colRange(0, 3).rowRange(0, 3));\n\ttranslation.copyTo(pose.col(3).rowRange(0, 3));\n\n\tPoint3f llc_p(llc);\n\tPoint3f upc_p(upc);\n\n\t// Points in the world coordinates\n\tvector volume_points;\n\tvolume_points.push_back((Mat_(4, 1) << llc_p.x, llc_p.y, llc_p.z, 1));\n\tvolume_points.push_back((Mat_(4, 1) << llc_p.x, llc_p.y, upc_p.z, 1));\n\tvolume_points.push_back((Mat_(4, 1) << upc_p.x, llc_p.y, upc_p.z, 1));\n\tvolume_points.push_back((Mat_(4, 1) << upc_p.x, llc_p.y, llc_p.z, 1));\n\tvolume_points.push_back((Mat_(4, 1) << llc_p.x, upc_p.y, llc_p.z, 1));\n\tvolume_points.push_back((Mat_(4, 1) << llc_p.x, upc_p.y, upc_p.z, 1));\n\tvolume_points.push_back((Mat_(4, 1) << upc_p.x, upc_p.y, upc_p.z, 1));\n\tvolume_points.push_back((Mat_(4, 1) << upc_p.x, upc_p.y, llc_p.z, 1));\n\n\t// transform cube into camera reference frame\n\tvector p2d = transform_and_project(volume_points, intrinsics, pose);\n\n\t// Draw cube\n\tScalar line_color = Scalar(148, 24, 248);\n\t// Generate edge points\n\tvector> edge_point_indices;\n\tedge_point_indices.push_back(make_pair(1, 5));\n\tedge_point_indices.push_back(make_pair(2, 6));\n\tedge_point_indices.push_back(make_pair(3, 7));\n\tedge_point_indices.push_back(make_pair(0, 4));\n\n\tedge_point_indices.push_back(make_pair(0, 1));\n\tedge_point_indices.push_back(make_pair(1, 2));\n\tedge_point_indices.push_back(make_pair(2, 3));\n\tedge_point_indices.push_back(make_pair(3, 0));\n\n\tedge_point_indices.push_back(make_pair(4, 7));\n\tedge_point_indices.push_back(make_pair(7, 6));\n\tedge_point_indices.push_back(make_pair(6, 5));\n\tedge_point_indices.push_back(make_pair(5, 4));\n\n\t// Draw edges\n\n\tfor (const auto &point_indices : edge_point_indices)\n\t{\n\t\tint p0_i = point_indices.first;\n\t\tPoint p0 = Point(p2d[p0_i].at(0), p2d[p0_i].at(1));\n\t\tint p1_i = point_indices.second;\n\t\tPoint p1 = Point(p2d[p1_i].at(0), p2d[p1_i].at(1));\n\t\tline(image, p0, p1, line_color, 1, 8);\n\t\t\n\t}\n\n\t// Draw circles\n\tfor (const auto& point : p2d)\n\t{\n\t\tPoint point_to_draw = Point(point.at(0), point.at(1));\n\t\tcircle(image, point_to_draw, 200 / 32.0, line_color, -1, 8);\n\t}\n\n\tdraw_origin_axis(image, intrinsics, pose);\n\n\tMat image_to_show;\n\n\t// resize if too big for showing\n\tif (image.cols > 800)\n\t{\n\t\tSize show_size = Size(image.cols / 2, image.rows / 2);\n\t\tresize(image, image_to_show, show_size);\n\t} else\n\t{\n\t\timage_to_show = image;\n\t}\n\t\n\t\n\timshow(\"image\", image_to_show);\n}\n\n\nvoid visualize_volume(const Mat& input_image, const Matrix3f& intrinsics, const Isometry3f& pose, const vector& volume)\n{\n\tMat intrinsics_cv;\n\n\teigen2cv(intrinsics, intrinsics_cv);\n\n\tMat llc = (Mat_(3, 1) << volume[0], volume[2], volume[4]);\n\tMat upc = (Mat_(3, 1) << volume[1], volume[3], volume[5]);\n\n\tconst Matrix4f &pose_eigen = pose.matrix();\n\tMat pose_cv;\n\teigen2cv(pose_eigen, pose_cv);\n\n\tMat rotation = pose_cv(Range(0, 3), Range(0, 3));\n\tMat translation = pose_cv(Range(0, 3), Range(3, 4));\n\n\tvisualize_volume(input_image, intrinsics_cv, rotation, translation, llc, upc);\n}", "meta": {"hexsha": "3b6b820f95c7f0ce825e1ed561e158a549502342", "size": 5414, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdf_fusion/src/aruco_sdffusion/src/visualizer.cpp", "max_stars_repo_name": "YyYyYong0331/homebrewdb", "max_stars_repo_head_hexsha": "02fb883b1630f21db6348e2605def5bd8cc6e2c0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 18.0, "max_stars_repo_stars_event_min_datetime": "2020-10-21T16:29:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-29T05:47:29.000Z", "max_issues_repo_path": "sdf_fusion/src/aruco_sdffusion/src/visualizer.cpp", "max_issues_repo_name": "YyYyYong0331/homebrewdb", "max_issues_repo_head_hexsha": "02fb883b1630f21db6348e2605def5bd8cc6e2c0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-04-16T15:03:54.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T07:28:52.000Z", "max_forks_repo_path": "sdf_fusion/src/aruco_sdffusion/src/visualizer.cpp", "max_forks_repo_name": "YyYyYong0331/homebrewdb", "max_forks_repo_head_hexsha": "02fb883b1630f21db6348e2605def5bd8cc6e2c0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-08-27T09:02:02.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-11T10:42:33.000Z", "avg_line_length": 34.0503144654, "max_line_length": 146, "alphanum_fraction": 0.6769486516, "num_tokens": 1753, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.650827038446971}} {"text": "/*********************************************************************\n * Software License Agreement (BSD License)\n *\n * Copyright (c) 2019, Robert Bosch GmbH\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n * * Neither the name of the Robert Bosch GmbH nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *********************************************************************/\n\n/* Author: Leonard Bruns */\n\n#include \"ompl/base/samplers/deterministic/HaltonSequence.h\"\n#include \"ompl/util/Console.h\"\n#include \n#include \n#include \n#include \n\nnamespace ompl\n{\n namespace base\n {\n HaltonSequence1D::HaltonSequence1D() : i_(1), base_(2)\n {\n }\n\n HaltonSequence1D::HaltonSequence1D(unsigned int base) : i_(1), base_(base)\n {\n }\n\n void HaltonSequence1D::setBase(unsigned int base)\n {\n base_ = base;\n }\n\n double HaltonSequence1D::sample()\n {\n double f = 1, r = 0;\n unsigned int i = i_;\n\n while (i > 0)\n {\n f /= base_;\n r += f * (i % base_);\n i = std::floor(i / base_);\n }\n\n ++i_;\n return r;\n }\n\n HaltonSequence::HaltonSequence(unsigned int dimensions)\n : DeterministicSequence(dimensions), halton_sequences_1d_(dimensions)\n {\n setBasesToPrimes();\n }\n\n HaltonSequence::HaltonSequence(unsigned int dimensions, std::vector bases)\n : DeterministicSequence(dimensions), halton_sequences_1d_(dimensions)\n {\n if (bases.size() != dimensions)\n {\n OMPL_WARN(\"Number of bases does not match dimensions. Using first n primes instead.\");\n }\n else\n {\n int i = 0;\n for (auto base : bases)\n {\n halton_sequences_1d_[i].setBase(base);\n i++;\n }\n }\n }\n\n std::vector HaltonSequence::sample()\n {\n std::vector samples;\n for (auto &seq : halton_sequences_1d_)\n {\n samples.push_back(seq.sample());\n }\n return samples;\n }\n\n void HaltonSequence::setBasesToPrimes()\n {\n // set the base of the halton sequences to the first n prime numbers, where n is dimensions\n unsigned int current = 2;\n for (unsigned int i = 0; i < dimensions_; i++)\n {\n current = boost::math::prime(i);\n halton_sequences_1d_[i].setBase(current);\n }\n }\n } // namespace base\n} // namespace ompl\n", "meta": {"hexsha": "2e54a9a27e6df32e1eecc8d3199d086cb09cf275", "size": 4221, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/ompl/base/samplers/deterministic/src/HaltonSequence.cpp", "max_stars_repo_name": "ericpairet/ompl", "max_stars_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 837.0, "max_stars_repo_stars_event_min_datetime": "2015-01-07T12:01:20.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:42:42.000Z", "max_issues_repo_path": "src/ompl/base/samplers/deterministic/src/HaltonSequence.cpp", "max_issues_repo_name": "ericpairet/ompl", "max_issues_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 271.0, "max_issues_repo_issues_event_min_datetime": "2015-01-12T22:05:06.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:16:01.000Z", "max_forks_repo_path": "src/ompl/base/samplers/deterministic/src/HaltonSequence.cpp", "max_forks_repo_name": "ericpairet/ompl", "max_forks_repo_head_hexsha": "25c76431cef25f0100ed74d09dd88944ecca5ee1", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 452.0, "max_forks_repo_forks_event_min_datetime": "2015-02-10T08:48:21.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T06:53:33.000Z", "avg_line_length": 34.3170731707, "max_line_length": 103, "alphanum_fraction": 0.5825633736, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.868826769445233, "lm_q2_score": 0.7490872131147275, "lm_q1q2_score": 0.6508270234032014}} {"text": "/* Copyright (c) 2021 Grumpy Cat Software S.L.\n *\n * This Source Code is licensed under the MIT 2.0 license.\n * the terms can be found in LICENSE.md at the root of\n * this project, or at http://mozilla.org/MPL/2.0/.\n */\n\n#include \n#include \n#include \n#include \n\naf::array gauss::linalg::eigvalsh(const af::array &m) {\n auto mtype = m.type();\n\n if (mtype == af::dtype::c32) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n auto typed = (std::complex*)matHost.get();\n Eigen::MatrixXcf mat = Eigen::Map(typed, m.dims(0), m.dims(1));\n Eigen::SelfAdjointEigenSolver solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n return af::array(m.dims(0), solver.eigenvalues().data());\n }\n \n if (mtype == af::dtype::c64) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n auto typed = (std::complex*)matHost.get();\n Eigen::MatrixXcd mat = Eigen::Map(typed, m.dims(0), m.dims(1));\n Eigen::SelfAdjointEigenSolver solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n return af::array(m.dims(0), solver.eigenvalues().data());\n }\n \n if (mtype == af::dtype::f64) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n Eigen::MatrixXd mat = Eigen::Map(matHost.get(), m.dims(0), m.dims(1));\n Eigen::SelfAdjointEigenSolver solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n return af::array(m.dims(0), solver.eigenvalues().data());\n } \n \n if (mtype == af::dtype::f32) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n Eigen::MatrixXf mat = Eigen::Map(matHost.get(), m.dims(0), m.dims(1));\n Eigen::SelfAdjointEigenSolver solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n return af::array(m.dims(0), solver.eigenvalues().data());\n }\n \n if (mtype == af::dtype::s64 || mtype == af::dtype::u64) \n return eigvalsh(m.as(af::dtype::f64));\n\n return eigvalsh(m.as(af::dtype::f32));\n}\n\naf::array gauss::linalg::eigvals(const af::array &m) {\n auto mtype = m.type();\n\n if (mtype == af::dtype::c32) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n auto typed = (std::complex*)matHost.get();\n Eigen::MatrixXcf mat = Eigen::Map(typed, m.dims(0), m.dims(1));\n Eigen::ComplexEigenSolver solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n auto eivals = solver.eigenvalues();\n auto eivals_af = (af::af_cfloat*) eivals.data();\n return af::array(m.dims(0), eivals_af);\n }\n \n if (mtype == af::dtype::c64) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n auto typed = (std::complex*)matHost.get();\n Eigen::MatrixXcd mat = Eigen::Map(typed, m.dims(0), m.dims(1));\n Eigen::ComplexEigenSolver solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n\n auto eivals = solver.eigenvalues();\n auto eivals_af = (af::af_cdouble*) eivals.data();\n return af::array(m.dims(0), eivals_af);\n }\n \n if (mtype == af::dtype::f64) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n Eigen::MatrixXd mat = Eigen::Map(matHost.get(), m.dims(0), m.dims(1));\n Eigen::EigenSolver solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n auto eivals = solver.eigenvalues();\n auto eivals_af = (af::af_cdouble*) eivals.data();\n return af::array(m.dims(0), eivals_af);\n } \n \n if (mtype == af::dtype::f32) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n Eigen::MatrixXf mat = Eigen::Map(matHost.get(), m.dims(0), m.dims(1));\n Eigen::EigenSolver solver(mat, Eigen::DecompositionOptions::EigenvaluesOnly);\n auto eivals = solver.eigenvalues();\n auto eivals_af = (af::af_cfloat*) eivals.data();\n return af::array(m.dims(0), eivals_af);\n }\n \n if (mtype == af::dtype::s64 || mtype == af::dtype::u64) \n return eigvals(m.as(af::dtype::f64));\n\n return eigvals(m.as(af::dtype::f32));\n}\n\nstd::tuple gauss::linalg::eig(const af::array &m) {\n\n auto mtype = m.type();\n\n if (mtype == af::dtype::c32) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n auto typed = (std::complex*)matHost.get();\n Eigen::MatrixXcf mat = Eigen::Map(typed, m.dims(0), m.dims(1));\n Eigen::ComplexEigenSolver solver(mat);\n auto eivals = solver.eigenvalues();\n auto eivect = solver.eigenvectors();\n auto eivals_af = (af::af_cfloat*) eivals.data();\n auto eivect_af = (af::af_cfloat*) eivect.data();\n auto eigenValues = af::array(m.dims(0), eivals_af);\n auto eigenVectors = af::array(m.dims(0), m.dims(1), eivect_af);\n return std::make_tuple(eigenValues, eigenVectors);\n }\n \n if (mtype == af::dtype::c64) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n auto typed = (std::complex*)matHost.get();\n\n Eigen::MatrixXcd mat = Eigen::Map(typed, m.dims(0), m.dims(1));\n Eigen::ComplexEigenSolver solver(mat);\n\n auto eivals = solver.eigenvalues();\n auto eivect = solver.eigenvectors();\n auto eivals_af = (af::af_cdouble*) eivals.data();\n auto eivect_af = (af::af_cdouble*) eivect.data();\n auto eigenValues = af::array(m.dims(0), eivals_af);\n auto eigenVectors = af::array(m.dims(0), m.dims(1), eivect_af); \n return std::make_tuple(eigenValues, eigenVectors); \n }\n \n if (mtype == af::dtype::f64) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n Eigen::MatrixXd mat = Eigen::Map(matHost.get(), m.dims(0), m.dims(1));\n Eigen::EigenSolver solver(mat);\n auto eivals = solver.eigenvalues();\n auto eivect = solver.eigenvectors();\n auto eivals_af = (af::af_cdouble*) eivals.data();\n auto eivect_af = (af::af_cdouble*) eivect.data();\n auto eigenValues = af::array(m.dims(0), eivals_af);\n auto eigenVectors = af::array(m.dims(0), m.dims(1), eivect_af); \n return std::make_tuple(eigenValues, eigenVectors);\n } \n \n if (mtype == af::dtype::f32) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n Eigen::MatrixXf mat = Eigen::Map(matHost.get(), m.dims(0), m.dims(1));\n Eigen::EigenSolver solver(mat);\n auto eivals = solver.eigenvalues();\n auto eivect = solver.eigenvectors();\n auto eivals_af = (af::af_cfloat*) eivals.data();\n auto eivect_af = (af::af_cfloat*) eivect.data();\n auto eigenValues = af::array(m.dims(0), eivals_af);\n auto eigenVectors = af::array(m.dims(0), m.dims(1), eivect_af); \n return std::make_tuple(eigenValues, eigenVectors);\n }\n \n if (mtype == af::dtype::s64 || mtype == af::dtype::u64) \n return eig(m.as(af::dtype::f64));\n\n return eig(m.as(af::dtype::f32));\n}\n\n\nstd::tuple gauss::linalg::eigh(const af::array &m) {\n\n auto mtype = m.type();\n\n if (mtype == af::dtype::c32) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n auto typed = (std::complex*)matHost.get();\n Eigen::MatrixXcf mat = Eigen::Map(typed, m.dims(0), m.dims(1));\n Eigen::SelfAdjointEigenSolver solver(mat);\n auto eigenValues = af::array(m.dims(0), solver.eigenvalues().data());\n\n auto eivect = solver.eigenvectors();\n auto eivect_af = (af::af_cfloat*) eivect.data();\n auto eigenVectors = af::array(m.dims(0), m.dims(1), eivect_af); \n\n return std::make_tuple(eigenValues, eigenVectors); \n }\n \n if (mtype == af::dtype::c64) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n auto typed = (std::complex*)matHost.get();\n\n Eigen::MatrixXcd mat = Eigen::Map(typed, m.dims(0), m.dims(1));\n Eigen::SelfAdjointEigenSolver solver(mat);\n\n auto eigenValues = af::array(m.dims(0), solver.eigenvalues().data());\n\n auto eivect = solver.eigenvectors();\n auto eivect_af = (af::af_cdouble*) eivect.data();\n auto eigenVectors = af::array(m.dims(0), m.dims(1), eivect_af); \n\n return std::make_tuple(eigenValues, eigenVectors); \n }\n \n if (mtype == af::dtype::f64) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n Eigen::MatrixXd mat = Eigen::Map(matHost.get(), m.dims(0), m.dims(1));\n Eigen::SelfAdjointEigenSolver solver(mat);\n auto eigenValues = af::array(m.dims(0), solver.eigenvalues().data());\n auto eigenVectors = af::array(m.dims(0), m.dims(1), solver.eigenvectors().data()); \n return std::make_tuple(eigenValues, eigenVectors);\n } \n \n if (mtype == af::dtype::f32) {\n auto matHost = gauss::utils::makeScopedHostPtr(m.host());\n Eigen::MatrixXf mat = Eigen::Map(matHost.get(), m.dims(0), m.dims(1));\n Eigen::SelfAdjointEigenSolver solver(mat);\n\n auto eigenValues = af::array(m.dims(0), solver.eigenvalues().data());\n auto eigenVectors = af::array(m.dims(0), m.dims(1), solver.eigenvectors().data()); \n return std::make_tuple(eigenValues, eigenVectors);\n }\n \n if (mtype == af::dtype::s64 || mtype == af::dtype::u64) \n return eigh(m.as(af::dtype::f64));\n\n return eigh(m.as(af::dtype::f32));\n}\n\n\naf::array gauss::linalg::lls(const af::array &A, const af::array &b) {\n af::array U;\n af::array S;\n af::array VT;\n\n af::svd(U, S, VT, A);\n\n S = af::diag(S, 0, false);\n\n af::array S_dagger = (S != 0).as(S.type()) * af::inverse(S);\n\n long missingRows = static_cast(A.dims(1) - S.dims(0));\n long missingColumns = static_cast(A.dims(0) - S.dims(0));\n af::array toPadRows = af::constant(0, missingRows, A.dims(0), A.type());\n af::array toPadColumns = af::constant(0, A.dims(1), missingColumns, A.type());\n\n S_dagger = af::join(0, S_dagger, toPadRows);\n S_dagger = af::join(1, S_dagger, toPadColumns);\n\n af::array V = af::transpose(VT);\n af::array UT = af::transpose(U);\n af::array x = af::matmul(V, S_dagger, UT, b);\n\n return x;\n}\n\n\naf::array gauss::linalg::levinsonDurbin(af::array acv, int order) {\n af::array result = af::constant(0, order + 1, acv.dims(1), acv.type());\n\n for (int i = 0; i < acv.dims(1); i++) {\n af::array phi = af::constant(0, order + 1, order + 1, acv.type());\n af::array sig = af::constant(0, order + 1, acv.type());\n\n phi(1, 1) = acv(1, i) / acv(0, i);\n sig(1) = acv(0, i) - (phi(1, 1) * acv(1, i));\n\n // First iteration, to avoid problems with negative sequences with 1 element\n int k = 2;\n if (k < (order + 1)) {\n phi(k, k) = (acv(k, i) - af::dot(phi(af::seq(1, k - 1), k - 1), acv(af::seq(1, k - 1), i))) / sig(k - 1);\n for (int j = 1; j < k; j++) {\n phi(j, k) = phi(j, k - 1) - (phi(k, k) * phi(k - j, k - 1));\n }\n sig(k) = sig(k - 1) * (1.0 - phi(k, k) * phi(k, k));\n }\n\n // Second and subsequent iterations\n for (int l = 3; l < (order + 1); l++) {\n af::array aux = acv(af::seq(1, l - 1), i);\n phi(l, l) = (acv(l, i) - af::dot(phi(af::seq(1, l - 1), l - 1),\n aux(af::seq(static_cast(aux.dims(0)) - 1, 0, -1)))) /\n sig(l - 1);\n for (int j = 1; j < l; j++) {\n phi(j, l) = phi(j, l - 1) - (phi(l, l) * phi(l - j, l - 1));\n }\n sig(l) = sig(l - 1) * (1.0 - phi(l, l) * phi(l, l));\n }\n\n af::array pac = af::diag(phi);\n pac(0) = 1.0;\n result(af::span, i) = pac;\n }\n return result;\n}", "meta": {"hexsha": "cb4124715ff19d74181140daec6a1585fd455ddf", "size": 12594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "modules/gauss/src/linalg.cpp", "max_stars_repo_name": "shapelets/shapelets-compute", "max_stars_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_stars_repo_licenses": ["MIT", "BSD-3-Clause"], "max_stars_count": 14.0, "max_stars_repo_stars_event_min_datetime": "2021-05-28T09:43:28.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T01:44:55.000Z", "max_issues_repo_path": "modules/gauss/src/linalg.cpp", "max_issues_repo_name": "shapelets/shapelets-compute", "max_issues_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_issues_repo_licenses": ["MIT", "BSD-3-Clause"], "max_issues_count": 14.0, "max_issues_repo_issues_event_min_datetime": "2021-05-31T11:48:12.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-06T20:30:34.000Z", "max_forks_repo_path": "modules/gauss/src/linalg.cpp", "max_forks_repo_name": "shapelets/shapelets-compute", "max_forks_repo_head_hexsha": "1dffe62d4eab9b1115b95bda5aaa7a3392024d72", "max_forks_repo_licenses": ["MIT", "BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.2783505155, "max_line_length": 117, "alphanum_fraction": 0.5909163094, "num_tokens": 3868, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9136765234137297, "lm_q2_score": 0.7122321842389469, "lm_q1q2_score": 0.650749825958808}} {"text": "#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nvoid vector2transform(vector &vec, Eigen::Matrix4d &t){\n t(0,3) = vec[0];\n t(1,3) = vec[1];\n t(2,3) = vec[2];\n Eigen::Quaterniond temp;\n temp.w() = vec[3];\n temp.x() = vec[4];\n temp.y() = vec[5];\n temp.z() = vec[6];\n t.block(0,0,3,3) = temp.toRotationMatrix();\n}\n\nint main(){\n string path_in = \"/home/chenchr/ttx.txt\";\n fstream file_in(path_in, ios::in);\n vector > all;\n for(int i=0; i<10; ++i){\n double x, y, z, qw, qx, qy, qz;\n char temp;\n file_in >> x >> temp >> y >> temp >> z >> temp >> qw >> temp >> qx >> temp >> qy >> temp >> qz;\n all.push_back({x, y, z, qw, qx, qy, qz});\n }\n vector all_T;\n for(int i=0; i<10; ++i){\n all_T.push_back(Eigen::Matrix4d::Identity());\n vector2transform(all[i], all_T[i]);\n }\n for(int i=0; i<10; ++i){\n cout << i << \": \" << endl;\n for(int j=0; j<7; ++j)\n cout << all[i][j] << \" \";\n cout << endl;\n cout << all_T[i] << endl;\n }\n return 0;\n}", "meta": {"hexsha": "09461dc999e60af2ec031278241413283128f8d4", "size": 1184, "ext": "cc", "lang": "C++", "max_stars_repo_path": "misc_cxx/vector2transform.cc", "max_stars_repo_name": "chenchr/PoseNet", "max_stars_repo_head_hexsha": "d8c0d1071db21652a7cb4b2715747ef346c8f706", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2018-05-09T03:35:42.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-10T00:13:56.000Z", "max_issues_repo_path": "misc_cxx/vector2transform.cc", "max_issues_repo_name": "chenchr/PoseNet", "max_issues_repo_head_hexsha": "d8c0d1071db21652a7cb4b2715747ef346c8f706", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "misc_cxx/vector2transform.cc", "max_forks_repo_name": "chenchr/PoseNet", "max_forks_repo_head_hexsha": "d8c0d1071db21652a7cb4b2715747ef346c8f706", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.9090909091, "max_line_length": 103, "alphanum_fraction": 0.5109797297, "num_tokens": 397, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467675095294, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6507219078576387}} {"text": "//\n// Created by joshua on 9/6/17.\n//\n#include \n#include \n#include \n\nvoid mps::planner::util::math::normalize_orientation(double& value) {\n // from ompl::base::SO2StateSpace::enforceBounds\n double v = fmod(value, 2.0 * boost::math::constants::pi());\n if (v < -boost::math::constants::pi())\n v += 2.0 * boost::math::constants::pi();\n else if (v >= boost::math::constants::pi())\n v -= 2.0 * boost::math::constants::pi();\n value = v;\n}\n\nvoid mps::planner::util::math::normalize_orientation(float& value) {\n float v = fmod(value, 2.0f * boost::math::constants::pi());\n if (v < -boost::math::constants::pi())\n v += 2.0f * boost::math::constants::pi();\n else if (v >= boost::math::constants::pi())\n v -= 2.0f * boost::math::constants::pi();\n value = v;\n}\n\n/**\n * Returns the shortest direction from val_1 to val_2 assuming that both values\n * are angles in radian in [-pi, pi)\n * @param val_1\n * @param val_2\n * @return the smallest change in angle da such that val_1 + da = val_2 mod 2pi\n */\nfloat mps::planner::util::math::shortest_direction_so2(float val_1, float val_2) {\n float value = val_2 - val_1;\n if (std::abs(value) > boost::math::constants::pi()) {\n if (value > 0.0f) { // val_2 > val_1\n value -= 2.0f * boost::math::constants::pi();\n } else {\n value += 2.0f * boost::math::constants::pi();\n }\n }\n return value;\n}\n", "meta": {"hexsha": "5d9dd994808a87ee7a28e94f4eac4adc461b6f0e", "size": 1594, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/mps/planner/util/Math.cpp", "max_stars_repo_name": "JoshuaHaustein/manipulation_planning_suite", "max_stars_repo_head_hexsha": "89f1306c58d747b263535dd4a07c4e8ef4a74cf0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/mps/planner/util/Math.cpp", "max_issues_repo_name": "JoshuaHaustein/manipulation_planning_suite", "max_issues_repo_head_hexsha": "89f1306c58d747b263535dd4a07c4e8ef4a74cf0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/mps/planner/util/Math.cpp", "max_forks_repo_name": "JoshuaHaustein/manipulation_planning_suite", "max_forks_repo_head_hexsha": "89f1306c58d747b263535dd4a07c4e8ef4a74cf0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-07-04T12:59:50.000Z", "max_forks_repo_forks_event_max_datetime": "2018-07-04T12:59:50.000Z", "avg_line_length": 35.4222222222, "max_line_length": 82, "alphanum_fraction": 0.6072772898, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.650721893443995}} {"text": "#include \n#include \n\nusing namespace arma;\nusing namespace std;\n\nint main() {\n mat A {{1.0, 2.0}, {3.0, 4.0}};\n A.print(\"A:\");\n mat B = A*A.i();\n B.print(\"B:\");\n mat C = eye(2, 2);\n C.print(\"C:\");\n cout << \"abs. sum: \" << accu(abs(B - C)) << endl;\n return 0;\n}\n", "meta": {"hexsha": "d9cbc9fd78aadc36bb72c4e9c2dc7aa6b8719175", "size": 312, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Armadillo/inverse.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Armadillo/inverse.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Armadillo/inverse.cpp", "max_forks_repo_name": "gjbex/Scientific-C-", "max_forks_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 59.0, "max_forks_repo_forks_event_min_datetime": "2015-11-26T11:44:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-21T00:27:22.000Z", "avg_line_length": 18.3529411765, "max_line_length": 54, "alphanum_fraction": 0.4967948718, "num_tokens": 111, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.8976952866333483, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6507126356800703}} {"text": "#include \"geo_calculator.h\"\n#include \n#include \n#include \n#include \n\n#include \"cgal_predef.h\"\n\n\n//// CGAL \n// Compute OBB\n#include \n#include \n// convex hull\n#include \n// polyline simplification\n#include \n#include \n// curve reconstruction from unorganized point set\n#include \n// random point generator\n#include \n\ndouble CGeoCalculator::ComputeDistFromPoint2Plane(COpenMeshT::Point p, COpenMeshT::Point b, COpenMeshT::Point n)\n{\n\t// assert n is a unit vector\n\tassert((n.norm() - 1.0) < 10e-5);\n\n\tCOpenMeshT::Point v = p - b;\n\treturn innerProduct(v, n);\n}\n\ndouble CGeoCalculator::ComputeLinearity(std::vector p_list)\n{\n\tif (p_list.size() < 3)\n\t{\n\t\treturn 1.0;\n\t}\n\telse\n\t{\n\t\tstd::vector> eigenvectors;\n\t\tstd::vector lambda;\n\t\tComputePCAwithSVD(p_list, eigenvectors, lambda);\n\t\t//ComputePCAwithEIG(p_list, eigenvectors, lambda);\n\t\treturn lambda[0] / (lambda[0] + lambda[1] + lambda[2]);\n\t}\n}\n\ndouble CGeoCalculator::ComputeLineLinearity(std::vector p_list, COpenMeshT::Point ctr, COpenMeshT::Point dir)\n{\n\tdouble sum_dev = 0.0;\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tdouble dev = (p_list[i] - ctr - innerProduct(p_list[i] - ctr, dir)*dir).norm();\n\t\tsum_dev += dev;\n\t}\n\tstd::cout << \"center = \" << ctr << std::endl;\n\tstd::cout << \"direction = \" << dir << std::endl;\n\tstd::cout << sum_dev <<\" \"<< p_list.size() << std::endl;\n\tsum_dev /= double(p_list.size());\n\treturn sum_dev;\n}\n\nvoid CGeoCalculator::FittingLineSegmentToPointSet(std::vector p_list, COpenMeshT::Point & pstart, COpenMeshT::Point & pend)\n{\n\t// base \n\tCOpenMeshT::Point base(0, 0, 0);\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tbase += p_list[i];\n\t}\n\tbase = base / double(p_list.size());\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tp_list[i] -= base;\n\t}\n\n\t// get line direction\n\tstd::vector direction;\n\tComputePrincipalDirection(p_list, direction);\n\n\tstd::cout << \"line direction: \";\n\tstd::copy(direction.begin(), direction.end(), std::ostream_iterator(std::cout, \" \"));\n\tstd::cout << std::endl;\n\n\t// project every point to direction and find the max and min parameters\n\tdouble max_t = 0, min_t = 0;\n\tCOpenMeshT::Point v(direction[0], direction[1], direction[2]);\n\tfor (int i = 0; i < p_list.size(); i++) {\n\t\tdouble t = innerProduct(v, p_list[i]);\n\t\tstd::cout << \"t = \" << t << std::endl;\n\t\tif (t > max_t)\n\t\t\tmax_t = t;\n\t\tif (t < min_t)\n\t\t\tmin_t = t;\n\t}\n\tstd::cout << \"min_t = \"<< min_t << \", max_t = \" << max_t << std::endl;\n\t// output\n\tpstart = base + v*min_t;\n\tpend = base + v*max_t;\n}\n\nvoid CGeoCalculator::FittingLineSegmentToPointSet(std::vector p_list, \n\tCOpenMeshT::Point base, COpenMeshT::Point dir, \n\tCOpenMeshT::Point & pstart, COpenMeshT::Point & pend)\n{\n\t// base \n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tp_list[i] -= base;\n\t}\n\t// project every point to direction and find the max and min parameters\n\tdouble max_t = 0, min_t = 0;\n\tfor (int i = 0; i < p_list.size(); i++) {\n\t\tdouble t = innerProduct(dir, p_list[i]);\n\t\tstd::cout << \"t = \" << t << std::endl;\n\t\tif (t > max_t)\n\t\t\tmax_t = t;\n\t\tif (t < min_t)\n\t\t\tmin_t = t;\n\t}\n\tstd::cout << \"min_t = \" << min_t << \", max_t = \" << max_t << std::endl;\n\t// output\n\tpstart = base + dir*min_t;\n\tpend = base + dir*max_t;\n}\n\nvoid CGeoCalculator::FittingPlaneToPointSet(std::vector p_list, std::vector& transform)\n{\n\ttransform.clear();\n\tint Dim = 3;\n\tEigen::MatrixXd P(p_list.size(), Dim);\n\tEigen::MatrixXd V(Dim, Dim);\n\n\t\n\tCOpenMeshT::Point center_p(0, 0, 0);\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tcenter_p += p_list[i];\n\t}\n\tcenter_p = center_p / double(p_list.size());\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tP(i, 0) = p_list[i][0] - center_p[0];\n\t\tP(i, 1) = p_list[i][1] - center_p[1];\n\t\tP(i, 2) = p_list[i][2] - center_p[2];\n\t}\n\t\n\n\tEigen::JacobiSVD svd(P, Eigen::ComputeFullU | Eigen::ComputeFullV);\n\tV = svd.matrixV();\n\n\tEigen::Vector3d n = V.col(2);\n\tn.normalized();\n\ttransform.push_back(n[0]);\n\ttransform.push_back(n[1]);\n\ttransform.push_back(n[2]);\n}\n\nvoid CGeoCalculator::ComputePrincipalDirection(std::vector p_list, std::vector& transform)\n{\n\ttransform.clear();\n\tint Dim = 3;\n\tEigen::MatrixXd P(p_list.size(), Dim);\n\tEigen::MatrixXd V(Dim, Dim);\n\n\tCOpenMeshT::Point center_p(0, 0, 0);\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tcenter_p += p_list[i];\n\t}\n\tcenter_p = center_p / double(p_list.size());\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tP(i, 0) = p_list[i][0] - center_p[0];\n\t\tP(i, 1) = p_list[i][1] - center_p[1];\n\t\tP(i, 2) = p_list[i][2] - center_p[2];\n\t}\n\n\tEigen::JacobiSVD svd(P, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\tV = svd.matrixV();\n\n\t//std::cout << \"P = [\" << P << \"]\" << std::endl;\n\t//std::cout << \"V = [\" << V << \"]\" << std::endl;\n\n\tEigen::Vector3d n = V.col(0);\n\tn.normalized();\n\ttransform.push_back(n[0]);\n\ttransform.push_back(n[1]);\n\ttransform.push_back(n[2]);\n}\n\nvoid CGeoCalculator::ComputePCAwithEIG(std::vector p_list, \n\tstd::vector>& eigenvectors, std::vector& eigenvalues)\n{\n\teigenvectors.clear();\n\tint Dim = 3;\n\tEigen::MatrixXd P(p_list.size(), Dim);\n\tEigen::MatrixXd V(Dim, Dim);\n\tEigen::MatrixXd S(Dim, Dim);\n\n\t// construct\n\tCOpenMeshT::Point center_p(0, 0, 0);\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tcenter_p += p_list[i];\n\t}\n\tcenter_p = center_p / double(p_list.size());\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tP(i, 0) = p_list[i][0] - center_p[0];\n\t\tP(i, 1) = p_list[i][1] - center_p[1];\n\t\tP(i, 2) = p_list[i][2] - center_p[2];\n\t}\n\n\tEigen::MatrixXd Pt = P.transpose();\n\tEigen::MatrixXd PtP = P.transpose() * P;\n\tEigen::SelfAdjointEigenSolver eigen_solver(PtP);\n\tS = eigen_solver.eigenvalues().asDiagonal();\n\tV = eigen_solver.eigenvectors();\n\n\t//std::cout << \"using ComputePCAwithEIG function\" << std::endl;\n\t//std::cout << \"S = [\" << S << \"]\" << std::endl;\n\t//std::cout << \"V = [\" << V << \"]\" << std::endl;\n\n\t// make it in the descending order\n\tfor (int i = Dim; i > 0; i--)\n\t{\n\t\tstd::vector tmp_vector;\n\t\tEigen::Vector3d n = V.col(i-1);\n\t\tn.normalized();\n\t\ttmp_vector.push_back(n[0]);\n\t\ttmp_vector.push_back(n[1]);\n\t\ttmp_vector.push_back(n[2]);\n\t\teigenvectors.push_back(tmp_vector);\n\t\teigenvalues.push_back(S(i-1, i-1));\n\t}\n}\n\nvoid CGeoCalculator::ComputePCAwithSVD(std::vector p_list, \n\tstd::vector>& eigenvectors, std::vector& eigenvalues)\n{\n\teigenvectors.clear();\n\teigenvalues.clear();\n\n\tint Dim = 3;\n\tEigen::MatrixXd P(p_list.size(), Dim);\n\tEigen::MatrixXd V(Dim, Dim);\n\tEigen::VectorXd S(Dim);\n\n\tCOpenMeshT::Point center_p(0, 0, 0);\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tcenter_p += p_list[i];\n\t}\n\tcenter_p = center_p / double(p_list.size());\n\tfor (int i = 0; i < p_list.size(); i++)\n\t{\n\t\tP(i, 0) = p_list[i][0] - center_p[0];\n\t\tP(i, 1) = p_list[i][1] - center_p[1];\n\t\tP(i, 2) = p_list[i][2] - center_p[2];\n\t}\n\tEigen::MatrixXd CovP = P.transpose() * P;\n\tCovP = CovP / double(p_list.size());\n\tEigen::JacobiSVD svd(CovP, Eigen::ComputeThinU | Eigen::ComputeThinV);\n\tV = svd.matrixV();\n\tS = svd.singularValues();\n\n\t//std::cout << \"using ComputePCAwithSVD function\" << std::endl;\n\t//std::cout << \"S = [\" << S << \"]\" << std::endl;\n\t//std::cout << \"V = [\" << V << \"]\" << std::endl;\n\n\tfor (int i = 0; i < 3; i++)\n\t{\n\t\tstd::vector tmp_vector;\n\t\tEigen::Vector3d n = V.col(i);\n\t\tn.normalized();\n\t\ttmp_vector.push_back(n[0]);\n\t\ttmp_vector.push_back(n[1]);\n\t\ttmp_vector.push_back(n[2]);\n\t\teigenvectors.push_back(tmp_vector);\n\t\tdouble s = sqrt(S(i));\n\t\teigenvalues.push_back(s);\n\t}\n}\n\nvoid CGeoCalculator::ProjectPointToPlane(COpenMeshT::Point point, std::vector plane, COpenMeshT::Point & projection)\n{\n\tdouble d = point[0] * plane[0] + point[1] * plane[1] + point[2] * plane[2] + plane[3];\n\tCOpenMeshT::Point v(plane[0] * d, plane[1] * d, plane[2] * d);\n\tprojection = point - v;\n}\n\ndouble CGeoCalculator::ComputeDistPointToLine(COpenMeshT::Point q, COpenMeshT::Point sp, COpenMeshT::Point tp)\n{\n\tCOpenMeshT::Point dir = tp - sp;\n\tdir /= dir.norm();\n\treturn (q - sp - innerProduct(q - sp, dir)*dir).norm();\n}\n\nvoid CGeoCalculator::givensTransform(double x, double y, std::vector& g)\n{\n\tdouble absx = fabs(x);\n\tdouble c, s;\n\n\tif (absx == 0.0)\n\t{\n\t\tc = 0.0; s = 1.0;\n\t}\n\telse {\n\t\tdouble nrm = Eigen::Vector2d(x, y).norm();\n\t\tc = absx / nrm;\n\t\ts = x / absx*(y / nrm);\n\t}\n\tg.push_back(c);\n\tg.push_back(s);\n}\n\nvoid CGeoCalculator::computeOBB(const std::vector & pts, std::vector & out_obb)\n{\n\ttypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\n\ttypedef K::Point_2\t\t\t\t\t\t\t\tPoint_2;\n\ttypedef CGAL::Polygon_2\t\t\t\t\t\tPolygon_2;\n\n\tstd::vector pointset;\n\tfor (int i = 0; i < pts.size(); i++)\n\t{\n\t\tpointset.push_back(Point_2(pts[i][1], pts[i][2]));\n\t}\n\n\tPolygon_2 ch, obb;\n\tCGAL::convex_hull_2(pointset.begin(), pointset.end(), std::back_inserter(ch));\n\tCGAL::min_rectangle_2(ch.vertices_begin(), ch.vertices_end(), std::back_inserter(obb));\n\tout_obb.clear();\n\tout_obb.push_back(obb.bbox().xmin());\n\tout_obb.push_back(obb.bbox().xmax());\n\tout_obb.push_back(obb.bbox().ymin());\n\tout_obb.push_back(obb.bbox().xmax());\n}\n\nstd::vector CGeoCalculator::getBernsteinBasis(int n, double step, Eigen::MatrixXd & Bmat)\n{\n\t// parameters\n\tstd::vector t;\n\tdouble it = 0.0;\n\tt.push_back(it);\n\twhile (it < 1)\n\t{\n\t\tit += step;\n\t\tt.push_back(it);\n\t}\n\tif (fabs(t.back() - 1.0) > 0.00001)\n\t\tt.push_back(1.0);\n\n\t//for (int i = 0; i < t.size(); i++)\n\t//\tstd::cout << t[i] << std::endl;\n\n\tBmat.resize(t.size(), n);\n\tfor (int j = 0; j < n; j++)\n\t{\n\t\tfor (int i = 0; i < t.size(); i++) {\n\t\t\tdouble c = CGeoCalculator::nchoosek(n - 1, j);\n\t\t\tBmat(i, j) = c*pow(t[i], j)*pow((1.0-t[i]), (n - 1 - j));\n\t\t}\n\t}\n\n\treturn t;\n}\n\nvoid CGeoCalculator::getBernsteinBasis(int n, std::vector t, Eigen::MatrixXd & Bmat)\n{\n\tBmat.resize(t.size(), n);\n\tBmat.setZero();\n\tfor (int j = 0; j < n; j++)\n\t{\n\t\tfor (int i = 0; i < t.size(); i++) {\n\t\t\tdouble c = CGeoCalculator::nchoosek(n - 1, j);\n\t\t\tBmat(i, j) = c*pow(t[i], j)*pow((1.0 - t[i]), (n - 1 - j));\n\t\t}\n\t}\n}\n\nvoid CGeoCalculator::getSampleFromBezier(\n\tEigen::MatrixXd & sample_pts, \n\tEigen::MatrixXd & ctrl_pts,\n\tdouble step)\n{\n\tint numCPs = ctrl_pts.rows();\n\tEigen::MatrixXd Bmat;\n\tgetBernsteinBasis(numCPs, step, Bmat);\n\tsample_pts = Bmat*ctrl_pts;\n}\n\nvoid CGeoCalculator::getEqualArcLengthSampleFromBezier(\n\tstd::vector& om_sample_pts, \n\tstd::vector& tparas,\n\tconst std::vector& om_ctrl_pts, int Nsamples)\n{\n\tom_sample_pts.clear();\n\ttparas.clear();\n\n\tEigen::MatrixXd ctrl_pts;\n\tconvertOMptToEigenMat(om_ctrl_pts, ctrl_pts);\n\n\tint numCPs = ctrl_pts.rows();\n\tEigen::MatrixXd Bmat;\n\tdouble dt = 0.0001;\n\tstd::vector ts;\n\tts = getBernsteinBasis(numCPs, dt, Bmat);\n\t// get total arc length\n\tEigen::MatrixXd dense_pts;\n\tdense_pts = Bmat*ctrl_pts;\n\tdouble total_length = 0.0;\n\tfor (int i = 1; i < dense_pts.rows(); i++)\n\t{\n\t\ttotal_length += (dense_pts.row(i) - dense_pts.row(i - 1)).norm();\n\t}\n\tdouble dD = total_length / double(Nsamples);\n\tdouble accum_length = 0.0;\n\tstd::vector t_samples;\n\tt_samples.push_back(0);\n\tfor (int i = 1; i < dense_pts.rows(); i++)\n\t{\n\t\tif (accum_length > dD) {\n\t\t\t//std::cout << accum_length << \", \" << dD << std::endl;\n\t\t\tt_samples.push_back(ts[i]);\n\t\t\taccum_length = 0.0;\n\t\t}\n\t\telse {\n\t\t\taccum_length += (dense_pts.row(i) - dense_pts.row(i - 1)).norm();\n\t\t}\n\t}\n\tt_samples.push_back(1.0);\n\tgetBernsteinBasis(numCPs, t_samples, Bmat);\n\tEigen::MatrixXd sample_pts;\n\tsample_pts = Bmat*ctrl_pts;\n\n\t// convert sample_pts to om_pts;\n\tconvertEigenMatToOMpt(sample_pts, om_sample_pts);\n\ttparas = t_samples;\n}\n\ndouble CGeoCalculator::nchoosek(int n, int k)\n{\n\tif (k < 0 || k > n) {\n\t\tstd::cerr << \"Error: k should be less than n\" << std::endl;\n\t\treturn 0;\n\t}\n\tif (k == 0) {\n\t\treturn 1;\n\t}\n\treturn (n * nchoosek(n - 1, k - 1)) / k;\n}\n\nvoid CGeoCalculator::convertOMptToEigenMat(const std::vector om_pts, Eigen::MatrixXd & Mat)\n{\n\tstd::vector om_pt_vec;\n\tfor (int i = 0; i < om_pts.size(); i++)\n\t{\n\t\tom_pt_vec.push_back(om_pts[i][0]);\n\t\tom_pt_vec.push_back(om_pts[i][1]);\n\t\tom_pt_vec.push_back(om_pts[i][2]);\n\t}\n\tMat = Eigen::Map\n\t\t(om_pt_vec.data(), 3, om_pt_vec.size() / 3);\n\tMat.transposeInPlace();\n}\n\nvoid CGeoCalculator::convertEigenMatToOMpt(const Eigen::MatrixXd & Mat, std::vector& om_pts)\n{\n\tom_pts.clear();\n\tfor (int i = 0; i < Mat.rows(); i++)\n\t{\n\t\tCOpenMeshT::Point pt(Mat(i, 0), Mat(i, 1), Mat(i, 2));\n\t\tom_pts.push_back(pt);\n\t}\n}\n\nvoid CGeoCalculator::pts_sorting_alg(std::vector& pts)\n{\n\t// use delaunay to compute the visibility graph\n\tdouble xCoord = pts[0][0];\n\tDelaunayT dt;\n\tfor (int i = 0; i < pts.size(); i++)\n\t{\n\t\tKPoint2 kp(pts[i][1], pts[i][2]);\n\t\tdt.insert(kp);\n\t}\n\n\tCOpenMeshT triMesh;\n\tstd::map cgal_om_vh_map;\n\tstd::vector> f_vhandles_cgal;\n\tfor (DelaunayT::Finite_faces_iterator fiter = dt.finite_faces_begin();\n\t\tfiter != dt.finite_faces_end(); ++fiter)\n\t{\n\t\tstd::vector vhandles;\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tDelaunayT::Vertex_handle vh_cgal = fiter->vertex(i);\n\t\t\tif (cgal_om_vh_map.find(vh_cgal) == cgal_om_vh_map.end()) {\n\t\t\t\tCOpenMeshT::VertexHandle vh_om =\n\t\t\t\t\ttriMesh.add_vertex(COpenMeshT::Point(0, vh_cgal->point().x(), vh_cgal->point().y()));\n\t\t\t\tcgal_om_vh_map[vh_cgal] = vh_om;\n\t\t\t\tvhandles.push_back(vh_om);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCOpenMeshT::VertexHandle vh_om = cgal_om_vh_map[vh_cgal];\n\t\t\t\tvhandles.push_back(vh_om);\n\t\t\t}\n\t\t}\n\t\ttriMesh.add_face(vhandles);\n\t}\n\n\tCOpenMeshT::VertexHandle seed_vh;\n\tfor (COpenMeshT::VertexIter viter = triMesh.vertices_begin(); viter != triMesh.vertices_end(); ++viter)\n\t{\n\t\tif (triMesh.is_boundary(*viter))\n\t\t{\n\t\t\tseed_vh = *viter;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tstd::vector b_vertices;\n\tauto next_vh = seed_vh;\n\tdo {\n\t\tb_vertices.push_back(next_vh);\n\t\tfor (COpenMeshT::VertexOHalfedgeCCWIter voh_ccwiter = triMesh.voh_ccwbegin(next_vh);\n\t\t\tvoh_ccwiter != triMesh.voh_ccwend(next_vh); ++voh_ccwiter)\n\t\t{\n\t\t\tif (triMesh.is_boundary(*voh_ccwiter))\n\t\t\t{\n\t\t\t\tnext_vh = triMesh.to_vertex_handle(*voh_ccwiter);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t} while (next_vh != seed_vh);\n\n\t// output\n\tpts.clear();\n\t//std::cout << b_vertices.size() << std::endl;\n\tfor (int i = 0; i < b_vertices.size(); i++)\n\t{\n\t\tCOpenMeshT::Point p = triMesh.point(b_vertices[i]);\n\t\tp[0] = xCoord;\n\t\tpts.push_back(p);\n\t\t//std::cout << p[1] << \" \" << p[2] << std::endl;\n\t}\n\n}\n\nvoid CGeoCalculator::simplify_polygon(std::vector& pts, double dT)\n{\n\tnamespace PS = CGAL::Polyline_simplification_2;\n\ttypedef PS::Stop_above_cost_threshold\t\tStop;\n\ttypedef PS::Squared_distance_cost\t\t\tCost;\n\n\tdouble xCoord = pts[0][0];\n\tKPolygon2 polygon;\n\tfor (int i = 0; i < pts.size(); i++)\n\t\tpolygon.push_back(KPoint2(pts[i][1], pts[i][2]));\n\n\tCost cost;\n\tpolygon = PS::simplify(polygon, cost, Stop(dT));\n\n\tpts.clear();\n\tfor (int i = 0; i < polygon.size(); i++) {\n\t\tpts.push_back(COpenMeshT::Point(xCoord, polygon[i].x(), polygon[i].y()));\n\t}\n}\n\nvoid CGeoCalculator::sample_polygon(std::vector& pts, double spacing, bool is_closed)\n{\n\tif (is_closed)\n\t\tpts.push_back(pts.front());\n\tstd::vector samples;\n\n\t// step size = ssz\n\tdouble alength = 0.0;\n\tfor (int i = 0; i < pts.size() - 1; i++)\n\t{\n\t\talength += (pts[i] - pts[i + 1]).norm();\n\t}\n\tdouble ssz = alength*spacing;\n\n\t// sample\n\tfor (int i = 0; i < pts.size() - 1; i++)\n\t{\n\t\tdouble t_alength = (pts[i] - pts[i + 1]).norm();\n\t\tint cnt = 0;\n\t\tdouble t = 0.0;\n\t\twhile (t < 1.0)\n\t\t{\n\t\t\tCOpenMeshT::Point pt = pts[i] + t * (pts[i + 1] - pts[i]);\n\t\t\tif ((pt - pts[i + 1]).norm() > ssz) {\n\t\t\t\tsamples.push_back(pt);\n\t\t\t}\n\t\t\tcnt++;\n\t\t\tt = double(cnt)*ssz / t_alength;\n\t\t}\n\t}\n\n\t//if (is_closed)\n\t//\tsamples.push_back(samples.front());\n\tpts = samples;\n}\n\nvoid CGeoCalculator::sample_polygon_parameters(std::vector &tparas, \n\tconst std::vector pts, double spacing, bool is_closed)\n{\n\ttparas.clear();\n\tstd::vector in_pts;\n\tif (is_closed)\n\t\tin_pts.push_back(pts.front());\n\n\t// step size = ssz\n\tdouble alength = 0.0;\n\tfor (int i = 0; i < pts.size() - 1; i++)\n\t{\n\t\talength += (pts[i] - pts[i + 1]).norm();\n\t}\n\tdouble ssz = alength*spacing;\n\n\t// sample\n\tfor (int i = 0; i < pts.size() - 1; i++)\n\t{\n\t\tdouble t_alength = (pts[i] - pts[i + 1]).norm();\n\t\tint cnt = 0;\n\t\tdouble t = 0.0;\n\t\twhile (t < 1.0)\n\t\t{\n\t\t\tCOpenMeshT::Point pt = pts[i] + t * (pts[i + 1] - pts[i]);\n\t\t\tif ((pt - pts[i + 1]).norm() > ssz) {\n\t\t\t\ttparas.push_back(t);\n\t\t\t}\n\t\t\tcnt++;\n\t\t\tt = double(cnt)*ssz / t_alength;\n\t\t}\n\t}\n\t//tparas.push_back(1.0);\n}\n\nvoid CGeoCalculator::sample_polygon_with_parameters(std::vector tparas,\n\tstd::vector cs_pts, std::vector &out_pts, bool is_closed)\n{\n\t//\n\tout_pts.clear();\n\tif (is_closed)\n\t\tcs_pts.push_back(cs_pts.front());\n\n\t// sample\n\tint pid = 0;\n\tfor (int i = 0; i < tparas.size(); i++)\n\t{\n\t\tdouble t = tparas[i];\n\t\tif (t == 0.0) pid++;\n\t\tCOpenMeshT::Point pt = cs_pts[pid-1] + t * (cs_pts[pid] - cs_pts[pid-1]);\n\t\tout_pts.push_back(pt);\n\t}\n}\n\nvoid CGeoCalculator::reconstruct_curve_from_pointset(std::vector &pts, float tolOMT)\n{\n\ttypedef CGAL::Optimal_transportation_reconstruction_2 Otr_2;\n\tstd::vector points;\n\tfor (int i = 0; i < pts.size(); i++)\n\t\tpoints.push_back(KPoint2(pts[i][1], pts[i][2]));\n\n\tstd::cout << \"init pts: \" << points.size() << std::endl;\n\tif (points.size() == 0)\n\t\treturn;\n\n\tstd::vector obb;\n\tcomputeOBB(pts, obb);\n\tdouble dl = (std::max)((obb[1] - obb[0]) / 2.,\n\t\t(obb[3] - obb[2]) / 2.);\n\ttolOMT = dl*tolOMT;\n\tstd::cout << \"tolOMT: \" << tolOMT << std::endl;\n\tOtr_2 otr2(points);\n\t//otr2.set_random_sample_size(15);\n\t//otr2.set_relevance(0.3);\n\tstd::vector ptss;\n\tstd::vector isolated_vertices;\n\tstd::vector > edges;\n\tint cntIter = 0;\n\t//float tolOMT = 0.6;\n\totr2.run_under_wasserstein_tolerance(tolOMT);\n\n\totr2.indexed_output(\n\t\tstd::back_inserter(ptss),\n\t\tstd::back_inserter(isolated_vertices),\n\t\tstd::back_inserter(edges));\n\tstd::cout << \"(-------------List output---------- )\" << tolOMT << \" \" << cntIter << std::endl;\n\t// points\n\tstd::vector::iterator pit;\n\tfor (pit = ptss.begin(); pit != ptss.end(); pit++)\n\t\tstd::cout << *pit << std::endl;\n\t// isolated vertices\n\tstd::vector::iterator vit;\n\tfor (vit = isolated_vertices.begin(); vit != isolated_vertices.end(); vit++)\n\t\tstd::cout << \"1 \" << *vit << std::endl;\n\t// edges\n\tstd::vector >::iterator eit;\n\tfor (eit = edges.begin(); eit != edges.end(); eit++)\n\t\tstd::cout << \"2 \" << eit->first << \" \" << eit->second << std::endl;\n\n\t//KPoint2 orig(0.0, 0.0);\n\t//for (eit = edges.begin(); eit != edges.end(); eit++)\n\t//{\n\t//\tKVector2 v12 = ptss[eit->second] - ptss[eit->first];\n\t//\tKVector2 v01 = ptss[eit->first] - orig;\n\t//\tdouble a = v01.x*v12*\n\t//}\n\n\n\t\n\n}", "meta": {"hexsha": "40e719c3027214517f54d7f3362706b31c9bbd21", "size": 19454, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GeneralTools/geo_calculator.cpp", "max_stars_repo_name": "LeiYangJustin/LibSST", "max_stars_repo_head_hexsha": "2f1493da189a3f77dc9f7ee5020da5b320fd9a00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GeneralTools/geo_calculator.cpp", "max_issues_repo_name": "LeiYangJustin/LibSST", "max_issues_repo_head_hexsha": "2f1493da189a3f77dc9f7ee5020da5b320fd9a00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GeneralTools/geo_calculator.cpp", "max_forks_repo_name": "LeiYangJustin/LibSST", "max_forks_repo_head_hexsha": "2f1493da189a3f77dc9f7ee5020da5b320fd9a00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0947075209, "max_line_length": 142, "alphanum_fraction": 0.6388403413, "num_tokens": 6592, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976953003183443, "lm_q2_score": 0.7248702702332476, "lm_q1q2_score": 0.6507126349288745}} {"text": "#include \"NewtonMethodEqNode.h\"\n#include \n#include \n\nvoid NewtonEqNode::solve(EqNodePtr& root, EqNodePtr var)\n{\n\tEqNodePtr derivRoot;\n\tdouble x1, x2, f1, tol, df1, err;\n\tint kmax, k;\n\n\ttol = 1e-8;\n\tkmax = 100;\n\n\tx1 = var->getValue();\n\tf1 = root->getValue();\n\tdf1 = root->getDerValue(*var);\n\n\tfor (k = 0; k < kmax; k++) {\n\t\tx2 = x1 - f1 / df1;\n\t\terr = abs(x2 - x1);\n\n\t\tvar->v = x2;\n\t\tx1 = x2;\n\t\tif (err < tol)\n\t\t\treturn;\n\n\t\tf1 = root->getValue();\n\t\tdf1 = root->getDerValue(*var);\n\t}\n}\n\nvoid NewtonEqNode::NLASolve(const int& n, std::vector< EqNodePtr >& eqs,\n\tstd::vector < EqNodePtr >& vars, const double& tol)\n{\n\tint kmax, k;\n\tEigen::MatrixXd Jac(n, n);\n\tEigen::VectorXd F(n), x(n);\n\tEigen::VectorXd delta(n);\n\n\tkmax = 300;\n\tdouble err = 0;\n\n\tfor (const auto& var : vars)\n\t\tvar->correctValueInsideBoundaries();\n\n\tfor (k = 0; k < kmax; ++k) {\n\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\tx[i] = vars[i]->v;\n\t\t\tF[i] = eqs[i]->getValue();\n\t\t\tfor (int j = 0; j < n; ++j)\n\t\t\t\tJac(i, j) = eqs[i]->getDerValue(*vars[j]);\n\t\t}\n\n\t\t// Solve linear system\n\t\tdelta = Jac.fullPivLu().solve(-F);\n\t\t// Update x values\n\t\tx = x + delta;\n\n\t\tfor (int i = 0; i < n; ++i) vars[i]->v = x[i];\n\n\t\t// criterion for stop\n\t\t// get max abs value of function\n\t\terr = 0.0;\n\t\tfor (int i = 0; i < n; ++i) {\n\t\t\terr = err < std::abs(F[i]) ? abs(F[i]) : err;\n\t\t\terr = err < std::abs(delta[i]) ? abs(delta[i]) : err;\n\t\t}\n\n\t\tif (err < tol) return;\n\n\t\tfor (auto& var : vars) var->correctValueInsideBoundaries();\n\t}\n}\n", "meta": {"hexsha": "5a1ff1dcb9dd949b426c6ed702c8c62ce10d4719", "size": 1490, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "EqNode/src/NewtonMethodEqNode.cpp", "max_stars_repo_name": "marcusbfs/HydroModel", "max_stars_repo_head_hexsha": "4c9793b338eb21898563396c32469a2740002f1e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "EqNode/src/NewtonMethodEqNode.cpp", "max_issues_repo_name": "marcusbfs/HydroModel", "max_issues_repo_head_hexsha": "4c9793b338eb21898563396c32469a2740002f1e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EqNode/src/NewtonMethodEqNode.cpp", "max_forks_repo_name": "marcusbfs/HydroModel", "max_forks_repo_head_hexsha": "4c9793b338eb21898563396c32469a2740002f1e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.8666666667, "max_line_length": 72, "alphanum_fraction": 0.5657718121, "num_tokens": 557, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952975813454, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6507126329449053}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"helper_func.h\"\n#include \"LongDynamics.h\"\n#include \"EKF.h\"\n\nint main()\n{\n // Define the dataset path\n const std::string dataset_path{\"../data/aircraft_long_dynamics_dataset.txt\"};\n\n // Load dataset\n const int dataset_size = 1001;\n Eigen::VectorXd elev_input(dataset_size);\n Eigen::VectorXd throttle_input(dataset_size);\n Eigen::VectorXd alpha_true(dataset_size);\n Eigen::VectorXd alpha_measured(dataset_size);\n Eigen::VectorXd pitch_rate_true(dataset_size);\n Eigen::VectorXd pitch_rate_measured(dataset_size);\n LoadDataSet(dataset_path, elev_input, throttle_input, alpha_true, \n alpha_measured, pitch_rate_true, pitch_rate_measured);\n \n // Create a csv file to save output data\n std::ofstream outputs_file;\n std::string filename = \"outputs.csv\";\n outputs_file.open(filename);\n outputs_file << \"time\" << \",\" << \"true_alpha\" << \",\" << \"measured_alpha\" \n << \",\" << \"estimated_alpha\" << \",\" << \"true_q\" << \",\" \n << \"measured_q\" << \",\" << \"estimated_q\" << std::endl;\n \n // Define dynamic system parameters\n int num_state = 4;\n int num_input = 2;\n int num_output = 2;\n const double sample_time = 0.01;\n Eigen::MatrixXd Q(num_state, num_state); // Process noise covariance matrix\n Q << 0.0001, 0.0 , 0.0 , 0.0,\n 0.0 , 0.0001, 0.0 , 0.0,\n 0.0 , 0.0 , 0.000001, 0.0,\n 0.0 , 0.0 , 0.0 , 0.0;\n\n Eigen::MatrixXd R(num_output, num_output); // Measurment noise covariance matrix\n R << 0.00001, 0.0,\n 0.0 , 0.00001;\n\n Eigen::MatrixXd P0(num_state, num_state); // Initial estimate error covariance matrix\n P0 << 0.0001, 0.0 , 0.0 , 0.0,\n 0.0 , 0.0001, 0.0 , 0.0,\n 0.0 , 0.0 , 0.000001, 0.0,\n 0.0 , 0.0 , 0.0 , 0.0;\n\n // Construct EKF object\n EKF ekf(Q, R, P0, sample_time);\n\n // Define integration class and a stepper integrator\n state_type x(num_state);\n LongDynamics long_dyn_object;\n boost::numeric::odeint::runge_kutta4 rk4_stepper;\n\n // Define vectors to hold the estimated outputs and the integrator predicted state\n Eigen::VectorXd alpha_estimated(dataset_size);\n Eigen::VectorXd pitch_rate_estimated(dataset_size);\n Eigen::VectorXd predicted_state(num_state);\n\n // Initialize the state\n predicted_state << 74.9167 + 0.03,\n 3.5330 + 0.03,\n 0.0 +0.001,\n 2.7 * PI / 180;\n\n // Run the filter on the dataset of I/O\n Eigen::VectorXd y(num_output);\n Eigen::VectorXd u(num_input);\n double t = 0.0;\n std::cout << \"Processing dataset...\" << std::endl;\n for (int i = 0; i < dataset_size; i++)\n {\n // Run EKF for one step\n y << alpha_measured(i),\n pitch_rate_measured(i);\n u << elev_input(i),\n throttle_input(i);\n ekf.Update(y, u, predicted_state);\n alpha_estimated(i) = ekf.GetEstimatedOutput()(0);\n pitch_rate_estimated(i) = ekf.GetEstimatedOutput()(1);\n\n // Save outputs to the csv file\n outputs_file << sample_time * i << \",\" \n << alpha_true(i) * 180.0 / PI << \",\" \n << alpha_measured(i) * 180.0 / PI << \",\" \n << alpha_estimated(i) * 180.0 / PI << \",\" \n << pitch_rate_true(i) * 180.0 / PI << \",\" \n << pitch_rate_measured(i) * 180.0 / PI << \",\" \n << pitch_rate_estimated(i) * 180.0 / PI << std::endl;\n\n // Pass the updated state back to the integrator\n x[0] = ekf.GetState()(0);\n x[1] = ekf.GetState()(1);\n x[2] = ekf.GetState()(2);\n x[3] = ekf.GetState()(3);\n \n // Run the integrator for one step and get the new state\n t = sample_time * i;\n rk4_stepper.do_step(long_dyn_object, x, t, sample_time);\n predicted_state(0) = x[0];\n predicted_state(1) = x[1];\n predicted_state(2) = x[2];\n predicted_state(3) = x[3]; \n }\n std::cout << \"Finished processing dataset\" << std::endl;\n\n // Close the output csv file\n outputs_file.close();\n\n // Compute and print root mean square error for the estimated outputs (angle of attack and pitch rate)\n std::cout << \"RMSE for the estimated AoA is: \" << ComputeRMSE(alpha_true, alpha_estimated) << std::endl;\n std::cout << \"RMSE for the estimated pitch rate is: \" << ComputeRMSE(pitch_rate_true, pitch_rate_estimated) << std::endl;\n}", "meta": {"hexsha": "e79a33b1bb786deae4b94518f60844b12da0bf3f", "size": 4658, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/main.cpp", "max_stars_repo_name": "ammhassan/EKF_for_Aircraft_Dynamics-", "max_stars_repo_head_hexsha": "aa6a76cfae9c4f59a141efaaebd2b550207e7a00", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-21T14:22:41.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-12T14:34:59.000Z", "max_issues_repo_path": "src/main.cpp", "max_issues_repo_name": "ammhassan/EKF_for_Aircraft_Dynamics-", "max_issues_repo_head_hexsha": "aa6a76cfae9c4f59a141efaaebd2b550207e7a00", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main.cpp", "max_forks_repo_name": "ammhassan/EKF_for_Aircraft_Dynamics-", "max_forks_repo_head_hexsha": "aa6a76cfae9c4f59a141efaaebd2b550207e7a00", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-21T04:23:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-21T04:23:17.000Z", "avg_line_length": 38.4958677686, "max_line_length": 125, "alphanum_fraction": 0.5832975526, "num_tokens": 1308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770433, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6506593844089575}} {"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2012-2015 Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#ifndef ROKKO_UTILITY_FRANK_MATRIX_HPP\n#define ROKKO_UTILITY_FRANK_MATRIX_HPP\n\n#include \n#include \n#include \n#include \n#include \n#if defined(ROKKO_HAVE_PARALLEL_DENSE_SOLVER)\n# include \n#endif\n\nnamespace rokko {\n\nclass frank_matrix {\npublic:\n template\n static void generate(rokko::localized_matrix& mat) {\n if (mat.rows() != mat.cols())\n BOOST_THROW_EXCEPTION(std::invalid_argument(\"frank_matrix::generate() : non-square matrix\"));\n int n = mat.rows();\n for(int i = 0; i < n; ++i) {\n for(int j = 0; j < n; ++j) {\n mat(i,j) = n - std::max(i, j);\n }\n }\n }\n\n#if defined(ROKKO_HAVE_PARALLEL_DENSE_SOLVER)\n template\n static void generate(rokko::distributed_matrix& mat) {\n if (mat.get_m_global() != mat.get_n_global())\n BOOST_THROW_EXCEPTION(std::invalid_argument(\"frank_matrix::generate() : non-square matrix\"));\n for(int local_i = 0; local_i < mat.get_m_local(); ++local_i) {\n for(int local_j = 0; local_j < mat.get_n_local(); ++local_j) {\n int global_i = mat.translate_l2g_row(local_i);\n int global_j = mat.translate_l2g_col(local_j);\n mat.set_local(local_i, local_j, mat.get_m_global() - std::max(global_i, global_j));\n }\n }\n }\n \n // another (slower) implementation using set_global function\n template\n static void generate_global(rokko::distributed_matrix& mat) {\n if (mat.m_global != mat.n_global)\n BOOST_THROW_EXCEPTION(std::invalid_argument(\"frank_matrix::generate() : non-square matrix\"));\n for(int global_i=0; global_i\n#include \n#include \n\n// 2x2 case only for now, also can be sped up.\ntemplate\nstruct EigSensitivity {\n using V2d = Eigen::Matrix;\n using M2d = Eigen::Matrix;\n\n EigSensitivity() { }\n\n template\n EigSensitivity(const Eigen::MatrixBase &A) { setMatrix(A); }\n\n template\n void setMatrix(const Eigen::MatrixBase &A) {\n static_assert((Derived::RowsAtCompileTime == 2) && (Derived::ColsAtCompileTime == 2), \"Only 2x2 supported for now\");\n\n const Real a_minus_c = A(0, 0) - A(1, 1);\n const Real b = A(0, 1);\n if (std::abs(b - A(1, 0)) > 1e-15) throw std::runtime_error(\"Only symmetric matrices are supported\");\n // d := descriminant of characteristic quadratic\n const Real sqrt_d = std::sqrt(a_minus_c * a_minus_c + 4 * b * b);\n m_Lambda << 0.5 * (A.trace() + sqrt_d),\n 0.5 * (A.trace() - sqrt_d);\n\n V2d q0(a_minus_c + sqrt_d, 2 * b);\n q0.normalize();\n m_Q.col(0) = q0;\n m_Q.col(1) << -q0[1], q0[0];\n\n if (sqrt_d < 1e-14) m_degenerate = true;\n else m_degenerate = false;\n }\n\n auto q(size_t i) const { return m_Q.col(i); }\n Real lambda(size_t i) const { return m_Lambda[i]; }\n\n // Access Eigendecomposition\n const M2d & Q() const { return m_Q; }\n const V2d &Lambda() const { return m_Lambda; }\n\n V2d dLambda(const M2d &dA) const { return (m_Q.transpose() * dA * m_Q).diagonal(); }\n M2d dLambda(size_t i) const { return q(i) * q(i).transpose(); }\n Real dLambda(size_t i, const M2d &dA) const { return q(i).dot(dA * q(i)); }\n\n // Only correct for symmetric dA_b!\n V2d d2Lambda(const M2d &dA_a, const M2d &dA_b) const {\n if (m_degenerate) return V2d(0.0, 0.0);\n Real d2lambda_0 = (2.0 / (m_Lambda[0] - m_Lambda[1])) * (q(0).dot(dA_a * q(1))) * (q(0).dot(dA_b * q(1)));\n return V2d(d2lambda_0, -d2lambda_0);\n }\n\n // Only correct for symmetric dA!\n M2d delta_dLambda(size_t i, const M2d &dA) const {\n if (m_degenerate) return M2d::Zero();\n double sign = (i == 0) ? 1.0 : -1.0;\n M2d result = ((sign * (2.0 / (m_Lambda[0] - m_Lambda[1])) * (q(0).dot(dA * q(1)))) * q(0)) * q(1).transpose();\n symmetrize(result);\n return result;\n }\n\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\nprivate:\n M2d m_Q;\n V2d m_Lambda;\n\n bool m_degenerate;\n};\n\n#endif /* end of include guard: EIGSENSITIVITY_HH */\n", "meta": {"hexsha": "38cbbebb9738672dd74e63e0a0e2dc3b0f919f89", "size": 3085, "ext": "hh", "lang": "C++", "max_stars_repo_path": "EigSensitivity.hh", "max_stars_repo_name": "jpanetta/Inflatables", "max_stars_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2021-10-05T18:52:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T06:35:04.000Z", "max_issues_repo_path": "EigSensitivity.hh", "max_issues_repo_name": "jpanetta/Inflatables", "max_issues_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EigSensitivity.hh", "max_forks_repo_name": "jpanetta/Inflatables", "max_forks_repo_head_hexsha": "6941fb1bf4a2f61a847605aea37adef97bf05d76", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-09-24T22:26:45.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-14T21:51:18.000Z", "avg_line_length": 36.2941176471, "max_line_length": 124, "alphanum_fraction": 0.5559157212, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6504889194374132}} {"text": "#ifndef SPLX_INTERNAL_BEZIER_H\n#define SPLX_INTERNAL_BEZIER_H\n#include \n#include \n#include \n\nnamespace splx {\nnamespace internal {\nnamespace bezier {\n\n/*\n* given a bezier curve degree and max parameter, return row r so that\n* multiplying the row with control points gives the kth derivative\n* of the curve at u\n*\n* f^k(u) = \\sum_{i=0}^degree r(i) * p(i)\n* return r\n*/\ntemplate\nRow getBasisRow(unsigned int degree, T maxParameter, T u, unsigned int k) {\n if(u < 0 || u > maxParameter) {\n throw std::domain_error(\n std::string(\"u is outside of the range [0, \")\n + std::to_string(maxParameter)\n + std::string(\"]\")\n );\n }\n\n if(maxParameter == 0) {\n Row result(degree+1);\n result.setZero();\n if(k == 0 && degree >= 0) {\n result(0) = 1.0;\n }\n return result;\n }\n\n Row result(degree + 1);\n\n T oneOverA = 1/maxParameter;\n for(unsigned int i = 0; i <= degree; i++) {\n T base = 0.0;\n T mult = 1.0;\n for(unsigned int j = 0; j+k <= degree; j++, mult *= u) {\n if(j+k >= i) {\n // base += pow(oneOverA, i) * this->comb(degree-i, j+k-i)\n // * pow(-oneOverA, j+k-i) * this->perm(j+k, k)\n // * mult;\n\n base += splx::internal::comb(degree-i, j+k-i)\n * splx::internal::pow(oneOverA, j+k) * splx::internal::perm(j+k, k)\n * mult * ((j+k-i)%2 == 0 ? 1 : -1);\n }\n }\n base *= splx::internal::comb(degree, i);\n result(i) = base;\n }\n return result;\n}\n\n/*\n Coefficient matrix for the k^th derivative bernstein base functions where each row r\n contains coefficients where k^th derivative of i^th bernstein polynomial of degree d\n can be expressed as r(0) + r(1)u + r(2)u^2 + ... + r(d)u^d\n*/\ntemplate\nMatrix bernsteinCoefficientMatrix(unsigned int degree, T maxParameter, unsigned int k) {\n Matrix bernsteinMtr(degree+1, degree+1);\n bernsteinMtr.setZero();\n\n if(maxParameter == 0) {\n if(k == 0 && degree >= 0) {\n bernsteinMtr(0, 0) = 1.0;\n }\n return bernsteinMtr;\n }\n\n unsigned int dcombi = 1;\n for(Index i = 0; \n\n i < degree+1; \n\n dcombi *= (degree-i), \n dcombi /= (i+1), \n i++) {\n\n unsigned int dminicombjmini = 1;\n T min1 = 1;\n T oneOverAPowj = splx::internal::pow(1/maxParameter, i);\n\n for(Index j = i; \n\n j < degree+1; \n\n dminicombjmini *= (degree - j), \n dminicombjmini/= (j+1-i), \n j++, \n min1 *= -1, \n oneOverAPowj *= (1/maxParameter)) {\n\n bernsteinMtr(i, j) = dcombi * dminicombjmini * min1 * oneOverAPowj;\n\n }\n }\n\n Matrix derivative(degree+1, degree+1);\n derivative.setZero();\n\n unsigned int jpermk = splx::internal::fac(k);\n for(unsigned int j = k;\n \n j < degree+1;\n \n jpermk *= (j+1),\n jpermk /= (j+1-k),\n j++) {\n derivative(j, j-k) = jpermk;\n }\n\n return bernsteinMtr * derivative;\n}\n\n} // namespace bezier\n} // namespace internal\n} // namespace splx\n\n#endif", "meta": {"hexsha": "7b6853012f1c0b4fed0d8198b133444577188cea", "size": 3207, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/splx/internal/bezier.hpp", "max_stars_repo_name": "baskinburak/splx", "max_stars_repo_head_hexsha": "0f02bb8c42890e9dde6d8f48f3214e91f88af0fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/splx/internal/bezier.hpp", "max_issues_repo_name": "baskinburak/splx", "max_issues_repo_head_hexsha": "0f02bb8c42890e9dde6d8f48f3214e91f88af0fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2019-02-21T00:30:06.000Z", "max_issues_repo_issues_event_max_datetime": "2019-02-27T01:39:41.000Z", "max_forks_repo_path": "include/splx/internal/bezier.hpp", "max_forks_repo_name": "baskinburak/splx", "max_forks_repo_head_hexsha": "0f02bb8c42890e9dde6d8f48f3214e91f88af0fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-08-12T08:17:37.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T08:17:37.000Z", "avg_line_length": 25.2519685039, "max_line_length": 91, "alphanum_fraction": 0.5447458684, "num_tokens": 976, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6504889148788876}} {"text": "/**\n * @file MathTools.hpp\n * @author John D. Jakeman\n * @date 31 October 2011\n * @brief Miscelaneous math functions.\n */\n\n#ifndef MATH_TOOLS_HPP\n#define MATH_TOOLS_HPP\n\n#include \"LinearAlgebra.hpp\"\n#include \n#include \n#include \n#include \n#include \n\nnamespace Pecos {\n\n/**\n * \\brief Map a scalar index of a flat 1D array to the equivalent\n * d-dimensional index\n *\n * Example:\n \\f[\n \\begin{bmatrix}\n 1 & 4 & 7\\\\\n 2 & 5 & 8\\\\\n 3 & 6 & 9\n \\end{bmatrix}\n \\rightarrow\n \\begin{bmatrix}\n 1,1 & 1,2 & 1,3\\\\\n 2,1 & 2,2 & 2,3\\\\\n 3,1 & 3,2 & 3,3\n \\end{bmatrix}\n \\f]\n *\n * @param sizes the number of elems in each dimension. For a 2D index\n * sizes = [numRows, numCols]\n * @param index the scalar index\n * @param num_elems the total number of elements in the d-dimensional matrix\n * @return result the d-dimensional index\n */\nvoid ind2sub( const IntVector &sizes, int index, int num_elems,\n\t IntVector &result );\n\n/**\n * \\brief Map a d-dimensional index to the scalar index of the equivalent flat \n * 1D array\n * \n * Example:\n \\f[\n \\begin{bmatrix}\n 1,1 & 1,2 & 1,3\\\\\n 2,1 & 2,2 & 2,3\\\\\n 3,1 & 3,2 & 3,3\n \\end{bmatrix}\n \\rightarrow\n \\begin{bmatrix}\n 1 & 4 & 7\\\\\n 2 & 5 & 8\\\\\n 3 & 6 & 9\n \\end{bmatrix}\n \\f]\n *\n * @param sizes the number of elems in each dimension. For a 2D index\n * sizes = [numRows, numCols]\n * @param multi_index the d-dimensional index\n * @return scalar_index the scalar index of the flat array\n */\nint sub2ind( const IntVector &sizes, const IntVector &multi_index );\n\n/**\n * \\brief Compute the cartesian product of an arbitray number of sets. \n * \n * These sets can consist of numbers of be themselves sets of vectors\n * @param inputSets the sets to be used in the cartesian product\n * @param elem_size the size of the vectors within each set.\n * @return the cartesian product\n */\ntemplate\nvoid cartesian_product( const std::vector< Teuchos::SerialDenseVector > &input_sets, Teuchos::SerialDenseMatrix &result, int elem_size )\n{\n#ifdef DEBUG\n if ( input_sets.size() == 0 ) \n {\n throw(std::invalid_argument(\"CartesianProduct() there must be at least one input set\"));\n }\n#endif\n int num_elems = 1;\n int num_sets = input_sets.size();\n IntVector sizes;\n sizes.resize( num_sets );\n IntVector multi_index;\n for ( int i = 0; i < num_sets; i++ )\n {\n sizes[i] = input_sets[i].length() / elem_size;\n num_elems *= sizes[i];\n }\n result.reshape( num_sets*elem_size, num_elems );\n for ( int i = 0; i < num_elems; i++ )\n {\n ind2sub( sizes, i, num_elems, multi_index );\n for ( int j = 0; j < num_sets; j++ )\n\t{\n\t for ( int k = 0; k < elem_size; k++ )\n\t {\n\t result( j*elem_size+k, i ) = \n\t\tinput_sets[j][multi_index[j]*elem_size+k];\n\t }\n\t}\n }\n};\n\n/**\n * \\brief Construct the outer product of an arbitray number of sets.\n *\n * Example: \n \\f[ \\{1,2\\}\\times\\{3,4\\}=\\{1\\times3, 2\\times3, 1\\times4, 2\\times4\\} = \n \\{3, 6, 4, 8\\} \\f]\n * @param input_sets \"Vector.hpp\" of sets to be used in the outer product\n * @return result the outer product\n */\ntemplate\nvoid outer_product( const std::vector< Teuchos::SerialDenseVector > &input_sets, Teuchos::SerialDenseVector &result )\n{\n int num_elems = 1;\n int num_sets = input_sets.size();\n IntVector sizes( num_sets, false );\n for ( int i = 0; i < num_sets; i++ )\n {\n sizes[i] = input_sets[i].numRows();\n num_elems *= sizes[i];\n }\n IntVector multi_index( num_sets, false );\n result.sizeUninitialized( num_elems );\n for ( int i = 0; i < num_elems; i++ )\n {\n result[i] = 1.0;\n ind2sub( sizes, i, num_elems, multi_index );\n for ( int j = 0; j < num_sets; j++ )\n\tresult[i] *= input_sets[j][multi_index[j]];\n }\n}\n\n/**\n * \\brief Build a vector containing all integers in [m,n) seperated by incr\n *\n * E.g Range( 1, 10, 2 ) -> [1,3,5,7,9]\n */\ntemplate\nvoid range( Teuchos::SerialDenseVector &result, T m, T n, T incr = 1 )\n{\n T i = m;\n O j = 0;\n O len = (O)( n - m ) / (O)incr;\n if ( (O)( n - m ) % (O)incr != 0 ) len++;\n result.sizeUninitialized( len );\n while( i < n )\n {\n result[j] = i;\n i += incr;\n j++;\n }\n};\n\n/** \n * \\brief Generate a vector whose n elements are equidistantly spaced in the\n * interval [a,b].\n *\n * @param [a,b] the range\n * @param n the number of times the interval [a,b] is divided\n * @return vec n numbers equidistant is [a,b]\n */\nvoid linspace( RealVector &result, Real a, Real b, int n );\n\n/**\n * \\brief Round a Real to the nearest integer.\n */\nReal round( Real r );\n\n/*\n * \\brief Function to allow for searching for maximum absolute \n * value (Real) in a containter\n *\n * @param a first value\n * @param b second value\n * @return true if a < b, false otherwise\n */\nbool abs_compare( Real a, Real b );\n\n/** \n * \\brief Return the nearest integer to x\n * @param x the value\n * return int the neartest integer to x\n */\nint nearest_integer( Real x );\n\n/**\n * \\brief Calulate n! \n *\n * @param n the factorial of interest\n * @return n!\n */\nReal factorial( int n );\n\n/**\n * \\brief Return the number of possible combinations of k elements that can be\n * chosen from n elements.\n *\n *\\f[ { n \\choose k} = \\frac{n!}{k!(n-k)!}\\f]\n * @param n number of elements\n * @param k the number of elements to be chosen. k<=n. \n * @return the total number of combinations.\n */\nint nchoosek( int n, int k );\n\n/**\n * \\brief Transform a point x in the interval [a,b] onto the interval [0,1] and\n * vice versa.\n *\n * @param x the value to be transformed\n * @param [a,b] the new/old interval\n * @param dir specifies whether to map to [a,b] or from [a,b]. That is \n * dir=0 returns [0,1] -> [a,b]\n * dir!=0 returns [a,b] -> [0,1]\n * @return the rescaled value\n */\nReal rescale( Real x, Real a, Real b, int dir );\n\n/**\n * \\brief Transform a point x in the interval \n * \\f$[a_1,b_1] \\times \\cdots \\times [a_d,b_d] \\f$ onto \n * the hypercube interval \\f$[0,1]^d\\f$ and vice versa.\n *\n * @param x the value to be transformed\n * @param [a,b] the new/old interval\n * @param dir specifies whether to map to [a,b] or from [a,b]. That is \n * dir=0 returns [0,1] -> [a,b]\n * dir!=0 returns [a,b] -> [0,1]\n * @return the rescaled value\n */\nvoid rescale( RealMatrix &x, const RealVector &domain, int dir );\n\n/**\n *\\brief transform points in domain_in to points in domain_out\n */\nvoid hypercube_map( RealMatrix &x, const RealVector &domain_in, \n\t\t const RealVector &domain_out,\n\t\t RealMatrix &result );\n\n/**\n * \\brief Construct a d-dimensional mesh on a hyper-rectangle. The meshes are \n * equidistant with respect to each coordinate direction.\n *\n * @param num_pts_1d array specifying the number of meshpoints for each dimension\n * @param domain the min and max value of each dimension. \n * That is \\f$ [a_1,b_1,...,a_d,b_d]\\f$\n * @return the multi-dimensional mesh coordinates. ( num_dims x num_pts ) array. \n * num_pts = num_pts_1d[0]*...*num_pts_1d[d-1]\n */\nvoid mesh_grid( const IntVector &num_pts_1d, \n\t\tconst RealVector &domain, \n\t\tRealMatrix &result );\n\n/**\n * Get all the multi-dimensional indices of a multi-dimensional polynomial\n * basis with a specified degree sum. A cleaner interface is provided by\n * GetMultiDimensionalPolynomial_indices()\n * @return B the multi-dimensional indices\n */\nvoid get_multi_dimensional_polynomial_subspace_indices( IntMatrix &B, \n\t\t\t\t\t\t\tint* elems, \n\t\t\t\t\t\t\tint len_elems, \n\t\t\t\t\t\t\tint* pos, \n\t\t\t\t\t\t\tint len_pos, \n\t\t\t\t\t\t\tint choices_made, \n\t\t\t\t\t\t\tint first_pos, \n\t\t\t\t\t\t\tint order, int &row );\n\n/**\n * \\brief Get all the multi-dimensional indices of a multi-dimensional polynomial\n * basis with a specified degree sum.\n *\n * @param num_dims the dimensionailty\n * @param degree the degree sum of the polynomial indices wanted\n * @return B the multi-dimensional polynomial_indices\n */\nvoid get_multi_dimensional_polynomial_indices( int num_dims, int degree, \n\t\t\t\t\t IntMatrix &result );\n\n/**\n * \\brief Get the smallest degree of the total degree polynomial such that the\n * number of terms in the basis is larger than or equal to num_samples\n*/\nint get_total_degree_from_num_samples( int num_dims, int num_samples );\n\n/**\n * \\brief Get the multi-dimensional hypercube \\f$[a,b]^d\\f$\n *\n * @param num_dims the dimension of the computational domain.\n * @param \\f$[a,b]\\f$ the one-dimensional bounds of the hypercube.\n * @return result the multi-dimensional bounds of the hypercube.\n */\nvoid set_hypercube_domain( RealVector &result, int num_dims, Real a, Real b );\n\n/// Perturb the columns of a matrix\nvoid get_permutations( IntMatrix &permutations, \n\t\t int M , int N, unsigned int seed );\n\nvoid compute_hyperbolic_level_subdim_indices( int num_dims, int level, \n\t\t\t\t\t int num_active_dims, \n\t\t\t\t\t Real p,\n\t\t\t\t\t IntMatrix &result );\n\nvoid compute_hyperbolic_level_indices( int num_dims, int level, Real p, \n\t\t\t\t IntMatrix &result );\n\nvoid compute_hyperbolic_indices( int num_dims, int level, Real p, \n\t\t\t\t IntMatrix &result );\n\n// weights ( num_dims x 1 ) vector with values in [0,1]\nvoid compute_anisotropic_hyperbolic_indices( int num_dims, int level, Real p, \n\t\t\t\t\t RealVector &weights,\n\t\t\t\t\t IntMatrix &result );\n\n// prepend \"mt_\" for MathTools to avoid name clash\nenum lp_norm\n { \n mt_l1_norm,\n mt_l2_norm,\n mt_linf_norm,\n };\n\n/**\n * \\brief Return the index of the element of x with the minimum value.\n *\n *\\f[\n \\arg \\! \\min_i x_i\\quad i=1,\\ldots,n\n \\f] \n*/\n template\nint argmin( int n, T* x )\n{\n int amin( 0 );\n T min = x[0];\n for ( int i = 1; i < n; i++ )\n {\n if ( x[i] < min )\n\t{\n\t min = x[i];\n\t amin = i;\n\t}\n }\n return amin;\n};\n\n/**\n * \\brief Return the index of the element of x with the maximum value.\n *\n *\\f[\n \\arg \\! \\max_i x_i \\quad i=1,\\ldots,n\n \\f] \n*/\ntemplate\nint argmax( int n, T* x )\n{\n int amax( 0 );\n T max = x[0];\n for ( int i = 1; i < n; i++ )\n {\n if ( x[i] > max )\n\t{\n\t max = x[i];\n\t amax = i;\n\t}\n }\n return amax;\n};\n\ntemplate\nint magnitude_argmax( int n, T* x )\n{\n int amax( 0 );\n T max = std::abs( x[0] );\n for ( int i = 1; i < n; i++ )\n {\n Real abs_x = std::abs( x[i] );\n if ( abs_x > max )\n\t{\n\t max = abs_x;\n\t amax = i;\n\t}\n }\n return amax;\n};\n\n/**\n * \\brief Return the sum of the elements in the array x. \n *\n *\\f[\n \\sum_{i=1}^N x_i\n \\f]\n*/\ntemplate\nT sum( int n, T* x )\n{\n T sum = x[0];\n for ( int i = 1; i < n; i++ )\n sum += x[i];\n return sum;\n};\n\n/**\n * \\brief Return the sum of the elements in the vector x. \n *\n *\\f[\n \\sum_{i=1}^N x_i\n \\f]\n *\n * This will not return the same result as sum( int n, T* x ) if\n * the vector is a subvector of another vector. That is stride does not equal\n * the number of rows.\n */\ntemplate < typename O, typename T >\nT sum( Teuchos::SerialDenseVector &v )\n{\n T tmp = Teuchos::ScalarTraits::zero();\n for ( O i = 0; i < v.length(); i++ )\n tmp += v[i];\n return tmp;\n};\n\n/**\n * \\brief Return the mean of the array x. \n *\n * \\f[\n \\bar{x} = \\frac{1}{N}\\sum_{i=1}^N x_i\n \\f]\n*/\nReal mean( int n, Real *x );\n\n\n/**\n * \\brief Return the sample variance of the array x. \n *\n * \\f[\n \\sigma^2 = \\frac{1}{N-\\text{ddof}}\\sum_{i=1}^N ( x_i-\\bar{x} )^2\n \\f]\n * \n * \\param ddof Delta Degrees of Freedom (ddof). \n * The divisor used in calculations is \\f$N - \\text{ddof}\\f$, \n * where \\$fN\\$f represents the number of elements.\n * By default ddof is one.\n */\nReal variance( int n, Real *x, int ddof = 1 );\n\n\n/**\n * \\brief Calculate one of several different types of \\f$\\ell_p\\f$ error norms\n * of a set of vectors. \n *\n * Each column of the reference_values matrix is considered \n * independently with the correpsonding column in the approximation_values.\n * The error between the each set of two columns tested is returned.\n * \\param reference_values a matrix containing the reference values\n * \\param approximate_values a matrix containig the approximate values\n * \\param active_columns specifies which set of columns to consider. If empty\n * all columns are considered\n * \\pram normalise if true the error norms are normalised. The l_inf norm\n * is normalised by the half the range of the data in the \n * reference_values column. The L_2 norm is normalised by the\n * standard deviation of the data in the reference values column.\n */\nvoid lp_error( RealMatrix &reference_values, \n\t RealMatrix &approximate_values,\n\t std::vector error_norms, RealMatrix &error, \n\t IntVector &active_columns, bool normalise = false );\n\n/**\n *\\brief Construct a Latin Hyperube Design (LHD)\n */\nvoid latin_hypercube_design( int num_pts, int num_dims, RealMatrix &result, \n\t\t\t int seed );\n\n\nvoid compute_next_combination( int num_dims, int level, IntVector &index, \n\t\t\t bool &extend, int &h, int &t );\n\nvoid compute_combinations( int num_dims, int level, IntMatrix &result );\n\n\n/**\n * \\breif Return the sign of x.\n *\n * \\return 1 if the corresponding element of x is greater than zero;\n * 0 if the corresponding element of X equals zero;\n *-1 if the corresponding element of X is less than zero\n */\ntemplate \nint sgn( T x )\n{\n return ( T(0) < x ) - ( x < T(0) );\n}\n\ntemplate \nint num_non_zeros( T *data, int n )\n{\n int num_non_zero_count( 0 );\n for ( int i = 0; i < n; i++ )\n {\n if ( std::abs( data[i] ) > 0 ) \n\tnum_non_zero_count++;\n }\n return num_non_zero_count;\n}\n\n/**\n *\\brief return the median of a std::vector\n */\ntemplate\ndouble median( std::vector &v )\n{\n size_t n = v.size();\n typename std::vector::iterator target = v.begin() + n / 2;\n std::nth_element( v.begin(), target, v.end() );\n if( n % 2 != 0 )\n {\n return (double)*target;\n }\n else\n {\n std::vector::iterator target_neighbour = \n\tstd::max_element( v.begin(), target );\n return (double)( *target + *target_neighbour ) / 2.0;\n }\n};\n\n/**\n *\\brief return the median of a RealVector.\n */\ntemplate\ndouble median( Teuchos::SerialDenseVector &v )\n{\n std::vector tmp( v.length() );\n for ( int i = 0; i < v.length(); i++ )\n tmp[i] = v[i];\n return median( tmp );\n}\n\ntemplate\ndouble pnorm( Teuchos::SerialDenseVector &v, double p )\n{\n double sum = 0.;\n for ( O i = 0; i < v.length(); i++ )\n {\n sum += std::pow( std::abs( (double)v[i] ), p );\n }\n return std::pow( sum, 1./p );\n}\n\ntemplate\nO num_nonzeros( Teuchos::SerialDenseVector &v )\n{\n O num_nonzeros = Teuchos::ScalarTraits::zero();\n for ( int d = 0; d < v.length(); d++ )\n {\n if ( v[d] != Teuchos::ScalarTraits::zero() ) num_nonzeros++;\n }\n return num_nonzeros;\n}\n\ntemplate\nvoid nonzero( Teuchos::SerialDenseVector &v, \n\t IntVector &result )\n{\n int num_nonzeros = 0;\n result.sizeUninitialized( v.length() );\n for ( int d = 0; d < v.length(); d++ )\n {\n if ( v[d] != Teuchos::ScalarTraits::zero() ) \n\t{\n\t result[num_nonzeros] = d;\n\t num_nonzeros++;\n\t}\n }\n // chop off unwanted memory\n result.resize( num_nonzeros );\n}\n\nvoid lhs_indices( int num_dims, int num_pts, int duplication, int seed, \n\t\t IntMatrix &result );\n\n/// Construct the improved distributed hypercube sample\nvoid ilhs( int num_dims, int num_pts, int duplication, int seed, \n\t RealMatrix &result );\n\n/// Construct basic random hypercube sample\nvoid lhs( int num_dims, int num_pts, int seed, \n\t RealMatrix &result );\n\ntemplate\nclass index_sorter {\npublic:\n index_sorter(const T &values){ values_ = values; }\n bool operator()( int lhs, int rhs) const {\n return values_[lhs] < values_[rhs];\n }\nprivate:\n T values_;\n};\n\ntemplate\nclass magnitude_index_sorter {\npublic:\n magnitude_index_sorter(const T &values){ values_ = values; }\n bool operator()( int lhs, int rhs) const {\n return std::abs( values_[lhs] ) > std::abs( values_[rhs] );\n }\nprivate:\n T values_;\n};\n\n// sorts in ascending order\ntemplate\nvoid argsort( const Teuchos::SerialDenseVector &values, \n\t IntVector &result )\n{\n std::vector indices( values.length() );\n for ( O i = 0; i < values.length(); i++ )\n indices[i] = i;\n \n std::sort( indices.begin(), indices.end(), index_sorter< Teuchos::SerialDenseVector >( values ) );\n\t \n result.sizeUninitialized( values.length() );\n for ( O i = 0; i < values.length(); i++ )\n result[i] = indices[i];\n}\n\ntemplate\nvoid argsort( Teuchos::SerialDenseVector &v,\n\t Teuchos::SerialDenseVector &result_0,\n\t IntVector &result_1 )\n{\n argsort( v, result_1 );\n result_0.sizeUninitialized( v.length() );\n for ( O i = 0; i < v.length(); i++ )\n result_0[i] = v[result_1[i]];\n}\n\n// sorts in descending order absolute value of entries\ntemplate\nvoid magnitude_argsort( const Teuchos::SerialDenseVector &values, \n\t\t\tIntVector &result )\n{\n std::vector indices( values.length() );\n for ( O i = 0; i < values.length(); i++ )\n indices[i] = i;\n \n std::sort( indices.begin(), indices.end(), magnitude_index_sorter< Teuchos::SerialDenseVector >( values ) );\n\t \n result.sizeUninitialized( values.length() );\n for ( O i = 0; i < values.length(); i++ )\n result[i] = indices[i];\n}\n\n/**\n * \\brief find the interval containing a target value. Assumes data is \n * in ascending order\n */\ntemplate\nint binary_search( T target, Teuchos::SerialDenseVector &data )\n{\n O low = 0, high = data.length()-1, mid;\n while ( low <= high )\n {\n mid = low + ( high - low ) / 2;\n if ( target < data[mid] ) high = mid - 1;\n else if ( target > data[mid] ) low = mid + 1;\n else return mid;\n }\n if ( high < 0 ) return 0;\n else if ( high < low ) return high;\n else return low;\n}\n\nclass LinearInterpolant1D\n{\nprivate:\n RealVector pts_, vals_;\n\npublic:\n LinearInterpolant1D( RealVector &pts, RealVector &vals )\n {\n pts_ = pts; vals_ = vals;\n };\n\n ~LinearInterpolant1D(){};\n \n void interpolate( RealVector &pts, RealVector &result )\n {\n int num_pts = pts.length();\n if ( result.length() != num_pts )\n result.sizeUninitialized( num_pts );\n for ( int i = 0; i < num_pts; i++ )\n {\n\t// enforce constant interpolation when interpolation is outside the\n\t// range of pts_\n\tif ( pts[i] <= pts_[0] )\n\t result[i] = vals_[0];\n\telse if ( pts[i] >= pts_[pts_.length()-1] )\n\t result[i] = vals_[pts_.length()-1];\n\telse\n\t {\n\t // assumes binary search returns index of the closest point in pts_ \n\t // to the left of pts[i]\n\t int index = binary_search( pts[i], pts_ );\n\t result[i] = vals_[index] + ( ( vals_[index+1] - vals_[index] ) / \n\t\t\t\t\t ( pts_[index+1] - pts_[index] ) ) \n\t * ( pts[i] - pts_[index] );\n\t }\n }\n };\n};\n\n/**\n * \\brief Reverse the contents of a vector. \n *\n * Useful for changing an ordered array to/from ascending/descending order\n */\ntemplate\nvoid reverse( Teuchos::SerialDenseVector &v )\n{\n O n = v.length();\n Teuchos::SerialDenseVector tmp( v );\n for ( O i = 0; i < n; i++ )\n v[i] = tmp[n-i-1];\n}\n\ntemplate \nstruct VectorEqual{\n /*\n * \\brief Determine if two vectors of doubles are equal\n */\n typedef Teuchos::SerialDenseVector VectorType;\n bool operator()( const VectorType &v1, const VectorType &v2 ) const{\n if ( v1.length() != v2.length() )\n return false;\n else{\n Real tol = std::numeric_limits::epsilon();\n Real dist = 0.;\n for ( int i = 0; i < v1.length(); i++ )\n\tdist += ( v1[i]-v2[i] )*( v1[i]-v2[i] );\n dist = std::sqrt( dist );\n if ( dist > tol )\n\treturn false;\n }\n return true;\n }\n};\n\ntemplate\nstruct VectorHash{\n int operator()( const VectorType &v ) const{\n return (int)boost::hash_range(v.values(), v.values() + v.length() );\n }\n};\n\n/*\n * \\brief Get the columns in A that are not in B\n */\ntemplate \nvoid set_difference_matrix_columns( const Teuchos::SerialDenseMatrix &A,\n\t\t\t\t const Teuchos::SerialDenseMatrix &B,\n\t\t\t\t IntVector &result ){\n if ( B.numCols() == 0 ){\n range( result, 0, A.numCols() );\n return;\n }\n\n int num_rows = A.numRows(), num_cols = A.numCols();\n if ( num_rows != B.numRows() ){\n std::string msg = \"set_difference_matrix_columns: A and B are inconsistent\";\n throw(std::runtime_error( msg ) );\n }\n typedef Teuchos::SerialDenseVector VectorType;\n\n // Hash columns of the matrix B\n boost::unordered_set< VectorType,VectorHash,\n\t\t\tVectorEqual > col_set;\n for ( int i = 0; i < B.numCols(); i++ ){\n VectorType col( Teuchos::View, const_cast(B[i]), num_rows );\n col_set.insert( col );\n }\n\n // Find columns of A not in B\n int num_result = 0;\n typename boost::unordered_set< VectorType,VectorHash,\n\t\t\t\t VectorEqual >::const_iterator it;\n result.sizeUninitialized( num_cols );\n for ( int i = 0; i < num_cols; i++ ){\n VectorType col( Teuchos::View, const_cast(A[i]), num_rows );\n it = col_set.find( col );\n if ( it == col_set.end() ){\n // Column is not in B\n result[num_result] = i;\n num_result++;\n }\n }\n \n // Remove unused memory\n result.resize( num_result );\n}\n\ntemplate\nvoid extract_submatrix_from_column_indices( const MatrixType &A,\n\t\t\t\t\t const IntVector &column_indices,\n\t\t\t\t\t MatrixType &submatrix ){\n int num_rows = A.numRows(), num_indices = column_indices.length();\n reshape( submatrix, num_rows, num_indices );\n\n for ( int j = 0; j < num_indices; j++ )\n for ( int i = 0; i < num_rows; i++ )\n submatrix(i,j) = A(i,column_indices[j]);\n}\n\ntemplate\nvoid copy_matrix( const MatrixType &source, MatrixType &dest, \n\t int num_rows, int num_cols, int start_row=0, int start_col=0 ){\n\n MatrixType source_subset( Teuchos::View, source, num_rows, num_cols, \n\t\t\t start_row, start_col );\n reshape( dest, num_rows, num_cols );\n dest.assign( source_subset );\n}\n\ntemplate\nvoid copy_vector( const VectorType &source, VectorType &dest, \n\t int num_rows, int start_row=0 ){\n VectorType source_subset( Teuchos::View, source.values()+start_row, num_rows );\n resize( dest, num_rows );\n dest.assign( source_subset );\n}\n\ntemplate\nvoid hstack( const MatrixType &source1, const MatrixType &source2,\n\t MatrixType &dest ){\n if ( ( source1.numRows() != source2.numRows() ) && \n ( ( source1.numCols()!=0 ) && ( source2.numCols()!=0 ) ) )\n throw( std::runtime_error(\"hstack: matrices are inconsistent\") );\n int num_rows = source1.numRows() ? source1.numRows() : source2.numRows();\n reshape( dest, num_rows, source1.numCols()+source2.numCols() );\n int cntr = 0;\n for ( int j = 0; j < source1.numCols(); j++, cntr++ )\n for ( int i = 0; i < num_rows; i++ )\n dest(i,cntr) = source1(i,j);\n for ( int j = 0; j < source2.numCols(); j++, cntr++ )\n for ( int i = 0; i < num_rows; i++ )\n dest(i,cntr) = source2(i,j);\n}\n\n/**\n * Convert a static array to a \"Vector.hpp\" of vectors.\n * @param a array to be converted\n * @param n the number of vectors\n * @param m the size of each \"Vector.hpp\"\n * @return v the \"Vector.hpp\" of vectors\n */\ntemplate \nvoid convert(T a[], int m, int n, std::vector< Teuchos::SerialDenseVector > &v)\n{\n v.resize( m );\n for ( int i = 0; i < m; i++ )\n {\n Teuchos::SerialDenseVector tmp( Teuchos::View, a + i * n, n );\n v[i] = tmp;\n }\n};\n\n/**\n * Convert a static array to a weakly ordered multiset of vectors.\n * Set allows for multiple keys with the same value.\n * @param a array to be converted\n * @param n the number of vectors\n * @param m the size of each \"Vector.hpp\"\n * @return s the set\n */\ntemplate \nvoid convert(T a[], int m, int n, std::set< Teuchos::SerialDenseVector > &s)\n{\n for ( int i = 0; i < m; i++ )\n {\n Teuchos::SerialDenseVector v( Teuchos::View, a+i*n, n );\n s.insert( v );\n }\n};\n\n/**\n * \\brief Convert a std::vector of vectors to a matrix\n *\n * Each element of the std::vector becomes a column of the matrix\n */\ntemplate \nvoid convert( const std::vector< Teuchos::SerialDenseVector > &V, \n\t Teuchos::SerialDenseMatrix &M )\n{\n M.shapeUninitialized( V[0].length(), (int)V.size() );\n for ( int i = 0; i < (int)V.size(); i++ )\n {\n for ( int j = 0; j < V[0].length(); j++ )\n\t{\n\t M(j,i) = V[i][j];\n\t}\n };\n};\n\n/**\n * Add a set of vectors together.\n * @param vectors set of vectors to be added\n * @param result the accumualted values\n */\ntemplate< typename T, typename Operator>\nvoid accumulate( const std::vector< std::vector > &vectors, \n\t\t std::vector &result, Operator op)\n{\n if( !vectors.empty() )\n {\n\t//invariant: all vectors are of the same size\n result = vectors[0] ;\n int N = result.size() ;\n for( int i = 1 ; i < vectors.size() ; ++i )\n\t{\n\t #ifdef DEBUG\n\t if ( vectors[i].size() != N ) \n\t {\n\t throw(std::runtime_error(\"Accumulate() vectors must all have the same size\"));\n\t }\n\t #endif\n\t std::transform( result.begin(), result.end(), vectors[i].begin(),\n\t\t\t result.begin(), op );\n\t}\n }\n else\n {\n result.clear();\n }\n};\n\n\ntemplate< typename T >\nbool is_nan_or_inf( T x )\n{\n if ( x != x || \n x >= std::numeric_limits::infinity() || \n x <= -std::numeric_limits::infinity() || \n x >= std::numeric_limits::max() ||\n x <= -std::numeric_limits::max() )\n return true;\n return false;\n}\n\ntemplate \nbool has_nan_or_inf( const Teuchos::SerialDenseMatrix &matrix )\n{\n for ( O j = 0 ; j < matrix.numCols(); j++ )\n {\n for ( O i = 0 ; i < matrix.numRows(); i++ )\n\t{\n\t if ( is_nan_or_inf( matrix(i,j ) ) )\n\t {\n\t disp( matrix(i,j) );\n\t return true;\n\t }\n\t}\n }\n return false;\n}\n\n\nvoid get_column_norms( RealMatrix &A, RealVector &result );\n\n\n} // namespace Pecos\n\n#endif\n", "meta": {"hexsha": "82073893fdebf8f26ff38737fff3a12d6d6b0cd1", "size": 26152, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "dakota-6.3.0.Windows.x86/include/MathTools.hpp", "max_stars_repo_name": "seakers/ExtUtils", "max_stars_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "dakota-6.3.0.Windows.x86/include/MathTools.hpp", "max_issues_repo_name": "seakers/ExtUtils", "max_issues_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "dakota-6.3.0.Windows.x86/include/MathTools.hpp", "max_forks_repo_name": "seakers/ExtUtils", "max_forks_repo_head_hexsha": "b0186098063c39bd410d9decc2a765f24d631b25", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-18T14:13:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T14:13:14.000Z", "avg_line_length": 26.4964539007, "max_line_length": 146, "alphanum_fraction": 0.6303150811, "num_tokens": 7671, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528057272543, "lm_q2_score": 0.7634837743174788, "lm_q1q2_score": 0.6504521436570099}} {"text": "#include \n#include\n// CGAL headers\n#include \n#include \n#include \n#include \n#include \n#include\n#include\n#include \n#include \n#include \n#include \n#include \n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n#include \n#endif\n\n// Qt headers\n#include \n#include \n#include \n#include \n#include \n\n// GraphicsView items and event filters (input classes)\n#include \n#include \n#include \n#include \n\n// the two base classes\n#include \"ui_Polygon_2.h\"\n#include \n\ntypedef CGAL::Exact_predicates_inexact_constructions_kernel K;\ntypedef K::Point_2 Point_2;\ntypedef K::Segment_2 Segment_2;\ntypedef K::Line_2 Line_2;\n\ntypedef CGAL::Polygon_2 > Polygon2; // it must be a list for the partition\ntypedef CGAL::Polygon_with_holes_2 > Polygon_with_holes_2;\n\ntypedef CGAL::Straight_skeleton_2 Ss ;\n\ntypedef boost::shared_ptr SsPtr ;\n\ntypedef boost::shared_ptr PolygonPtr ;\n\ntypedef std::vector PolygonPtr_vector ;\n\nclass MainWindow :\n public CGAL::Qt::DemosMainWindow,\n public Ui::Polygon_2\n{\n Q_OBJECT\n\nprivate:\n\n enum PartitionAlgorithm {YMonotone, ApproximateConvex, OptimalConvex} ;\n\n\n CGAL::Qt::Converter convert;\n Polygon2 poly, kgon;\n Polygon_with_holes_2 selfmink;\n QGraphicsScene scene;\n\n CGAL::Qt::PolygonGraphicsItem * pgi;\n\n CGAL::Qt::GraphicsViewPolylineInput * pi;\n\n CGAL::Qt::PolygonWithHolesGraphicsItem * minkgi;\n\n std::list partitionPolygons;\n std::list* > partitionGraphicsItems;\n std::list skeletonGraphicsItems;\n std::list offsetGraphicsItems;\n CGAL::Qt::LineGraphicsItem* lgi;\n\n CGAL::Qt::PolygonGraphicsItem * kgongi;\n\npublic:\n MainWindow();\n\npublic Q_SLOTS:\n\n void processInput(CGAL::Object o);\n\n void on_actionClear_triggered();\n\n void on_actionLoadPolygon_triggered();\n void on_actionSavePolygon_triggered();\n\n void on_actionSelfMinkowskiSum_triggered();\n void on_actionRecenter_triggered();\n void on_actionMaximumAreaKGon_triggered();\n void on_actionInnerSkeleton_triggered();\n void on_actionOuterOffset_triggered();\n void on_actionLinearLeastSquaresFitting_triggered();\n void on_actionLinearLeastSquaresFittingOfSegments_triggered();\n void on_actionCreateInputPolygon_toggled(bool);\n\n void on_actionYMonotonePartition_triggered();\n void on_actionApproximateConvexPartition_triggered();\n void on_actionOptimalConvexPartition_triggered();\n void partition(PartitionAlgorithm);\n\n void clearPartition();\n void clearMinkowski();\n void clearSkeleton();\n void clearOffset();\n void clear();\n\n virtual void open(QString);\nQ_SIGNALS:\n void changed();\n};\n\n\nMainWindow::MainWindow()\n : DemosMainWindow()\n{\n setupUi(this);\n\n this->graphicsView->setAcceptDrops(false);\n\n minkgi = nullptr;\n // Add a GraphicItem for the Polygon2\n pgi = new CGAL::Qt::PolygonGraphicsItem(&poly);\n\n QObject::connect(this, SIGNAL(changed()),\n pgi, SLOT(modelChanged()));\n\n scene.addItem(pgi);\n\n kgongi = new CGAL::Qt::PolygonGraphicsItem(&kgon);\n kgongi->setEdgesPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n kgongi->hide();\n scene.addItem(kgongi);\n\n\n lgi = new CGAL::Qt::LineGraphicsItem();\n lgi->setPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n lgi->hide();\n scene.addItem(lgi);\n assert(lgi->scene() == &scene);\n // Setup input handlers. They get events before the scene gets them\n pi = new CGAL::Qt::GraphicsViewPolylineInput(this, &scene, 0, true);\n\n this->actionCreateInputPolygon->setChecked(true);\n QObject::connect(pi, SIGNAL(generate(CGAL::Object)),\n this, SLOT(processInput(CGAL::Object)));\n\n //\n // Manual handling of actions\n //\n QObject::connect(this->actionQuit, SIGNAL(triggered()),\n this, SLOT(close()));\n\n\n //\n // Setup the scene and the view\n //\n scene.setItemIndexMethod(QGraphicsScene::NoIndex);\n scene.setSceneRect(-100, -100, 100, 100);\n this->graphicsView->setScene(&scene);\n this->graphicsView->setMouseTracking(true);\n\n // Uncomment the following line to get antialiasing by default.\n// actionUse_Antialiasing->setChecked(true);\n\n // Turn the vertical axis upside down\n this->graphicsView->scale(1, -1);\n\n // The navigation adds zooming and translation functionality to the\n // QGraphicsView\n this->addNavigation(this->graphicsView);\n\n this->setupStatusBar();\n this->setupOptionsMenu();\n this->addAboutDemo(\":/cgal/help/about_Polygon_2.html\");\n this->addAboutCGAL();\n this->setupExportSVG(action_Export_SVG, graphicsView);\n\n this->addRecentFiles(this->menuFile, this->actionQuit);\n connect(this, SIGNAL(openRecentFile(QString)),\n this, SLOT(open(QString)));\n}\n\n\nvoid\nMainWindow::processInput(CGAL::Object o)\n{\n this->actionCreateInputPolygon->setChecked(false);\n std::list points;\n if(CGAL::assign(points, o)){\n if((points.size() == 1)&& poly.size()>0){\n\n } else {\n poly.clear();\n if(points.front() == points.back()){\n points.pop_back();\n }\n poly.insert(poly.vertices_begin(), points.begin(), points.end());\n }\n Q_EMIT( changed());\n }\n}\n\n/*\n * Qt Automatic Connections\n * https://doc.qt.io/qt-5/designer-using-a-ui-file.html#automatic-connections\n *\n * setupUi(this) generates connections to the slots named\n * \"on__\"\n */\n\nvoid\nMainWindow::on_actionClear_triggered()\n{\n poly.clear();\n clear();\n this->actionCreateInputPolygon->setChecked(true);\n Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionLoadPolygon_triggered()\n{\n QString fileName = QFileDialog::getOpenFileName(this,\n tr(\"Open Polygon File\"),\n \".\",\n tr( \"Polyline files (*.polygons.cgal);;\"\n \"WSL files (*.wsl);;\"\n #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n \"WKT files (*.wkt *.WKT);;\"\n #endif\n \"All file (*)\"));\n if(! fileName.isEmpty()){\n open(fileName);\n }\n}\n\nvoid\nMainWindow::open(QString fileName)\n{\n this->actionCreateInputPolygon->setChecked(false);\n std::ifstream ifs(qPrintable(fileName));\n poly.clear();\n if(fileName.endsWith(\".wkt\", Qt::CaseInsensitive))\n {\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n CGAL::Polygon_with_holes_2 P;\n CGAL::read_polygon_WKT(ifs, P);\n poly = Polygon2(P.outer_boundary().begin(),\n P.outer_boundary().end());\n#endif\n }\n else\n {\n ifs >> poly;\n }\n clear();\n\n this->addToRecentFiles(fileName);\n Q_EMIT( changed());\n}\n\n\nvoid\nMainWindow::on_actionSavePolygon_triggered()\n{\n QString fileName = QFileDialog::getSaveFileName(this,\n tr(\"Save Polygon\"),\n \".\",\n tr( \"Polyline files (*.polygons.cgal);;\"\n #if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n \"WKT files (*.wkt *.WKT);;\"\n #endif\n \"All file (*)\"));\n if(! fileName.isEmpty()){\n std::ofstream ofs(qPrintable(fileName));\n if(fileName.endsWith(\".wkt\", Qt::CaseInsensitive))\n {\n#if BOOST_VERSION >= 105600 && (! defined(BOOST_GCC) || BOOST_GCC >= 40500)\n CGAL::Polygon_2 P(poly.begin(),\n poly.end());\n CGAL::Polygon_with_holes_2 Pwh(P);\n CGAL::write_polygon_WKT(ofs, Pwh);\n#endif\n }\n else\n ofs << poly;\n }\n}\n\n\nvoid\nMainWindow::on_actionCreateInputPolygon_toggled(bool checked)\n{\n poly.clear();\n clear();\n if(checked){\n scene.installEventFilter(pi);\n } else {\n scene.removeEventFilter(pi);\n }\n Q_EMIT( changed());\n}\n\nvoid\nMainWindow::on_actionRecenter_triggered()\n{\n this->graphicsView->setSceneRect(pgi->boundingRect());\n this->graphicsView->fitInView(pgi->boundingRect(), Qt::KeepAspectRatio);\n}\n\nvoid\nMainWindow::on_actionSelfMinkowskiSum_triggered()\n{\n if(poly.size()>0){\n if(! poly.is_simple()){\n return;\n }\n\n selfmink = minkowski_sum_2 (poly, poly);\n\n minkgi = new CGAL::Qt::PolygonWithHolesGraphicsItem(&selfmink);\n\n minkgi->setVerticesPen(QPen(Qt::red, 3, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n scene.addItem(minkgi);\n minkgi->setEdgesPen(QPen(Qt::darkRed, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n }\n}\n\n\n\n\nvoid\nMainWindow::on_actionInnerSkeleton_triggered()\n{\n if(poly.size()>0){\n if(! poly.is_simple()){\n return;\n }\n clear();\n if(! poly.is_counterclockwise_oriented()){\n poly.reverse_orientation();\n }\n SsPtr iss = CGAL::create_interior_straight_skeleton_2(poly.vertices_begin(), poly.vertices_end());\n\n CGAL::Straight_skeleton_2 const& ss = *iss;\n\n typedef Ss::Vertex_const_handle Vertex_const_handle ;\n typedef Ss::Halfedge_const_handle Halfedge_const_handle ;\n typedef Ss::Halfedge_const_iterator Halfedge_const_iterator ;\n\n Halfedge_const_handle null_halfedge ;\n Vertex_const_handle null_vertex ;\n\n for ( Halfedge_const_iterator i = ss.halfedges_begin(); i != ss.halfedges_end(); ++i )\n {\n if ( i->is_bisector() ){\n Segment_2 s(i->opposite()->vertex()->point(), i->vertex()->point());\n skeletonGraphicsItems.push_back(new QGraphicsLineItem(convert(s)));\n scene.addItem(skeletonGraphicsItems.back());\n skeletonGraphicsItems.back()->setPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n }\n }\n\n }\n\n}\n\nvoid\nMainWindow::on_actionOuterOffset_triggered()\n{\n if(poly.size()>0 && poly.is_simple())\n {\n clear();\n\n if(! poly.is_counterclockwise_oriented())\n poly.reverse_orientation();\n\n double w = poly.bbox().xmax() - poly.bbox().xmin() ;\n double h = poly.bbox().ymax() - poly.bbox().ymin() ;\n double s = (std::max)(w,h);\n double def_offset = s * 0.05 ;\n\n bool ok;\n const double off = QInputDialog::getDouble( this\n , tr(\"Offset distance\")\n , tr(\"Offset distance:\")\n , def_offset\n , 0.0\n , s\n , 2\n , &ok\n );\n if ( ok )\n {\n PolygonPtr_vector lContours = create_exterior_skeleton_and_offset_polygons_2(off,poly) ;\n\n PolygonPtr_vector::const_iterator frame ;\n\n double max_area = 0.0 ;\n\n for( PolygonPtr_vector::const_iterator cit = lContours.begin(); cit != lContours.end(); ++ cit )\n {\n double area = (*cit)->area();\n if ( area > max_area )\n {\n max_area = area ;\n frame = cit ;\n }\n }\n\n for( PolygonPtr_vector::const_iterator cit = lContours.begin(); cit != lContours.end(); ++ cit )\n {\n if ( cit != frame )\n {\n Polygon2 const& lContour = **cit ;\n lContour.area();\n for ( Polygon2::Edge_const_iterator eit = lContour.edges_begin(); eit != lContour.edges_end(); ++ eit )\n {\n Segment_2 s(eit->source(), eit->target());\n offsetGraphicsItems.push_back(new QGraphicsLineItem(convert(s)));\n scene.addItem(offsetGraphicsItems.back());\n offsetGraphicsItems.back()->setPen(QPen(Qt::red, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n }\n }\n }\n }\n }\n}\n\nvoid\nMainWindow::on_actionMaximumAreaKGon_triggered()\n{\n if( (poly.size()>2) && poly.is_convex()){\n clear();\n\n kgon.clear();\n std::vector points(poly.vertices_begin(),\n poly.vertices_end());\n CGAL::maximum_area_inscribed_k_gon_2(points.begin(),\n points.end(),\n 3,\n std::back_inserter(kgon));\n\n kgongi->modelChanged();\n kgongi->show();\n } else {\n std::cout << \"The polygon must be convex\" << std::endl;\n }\n}\n\nvoid\nMainWindow::on_actionLinearLeastSquaresFitting_triggered()\n{\n if(poly.size()>2){\n clear();\n\n Line_2 line;\n CGAL::linear_least_squares_fitting_2(poly.vertices_begin(),\n poly.vertices_end(),\n line,\n CGAL::Dimension_tag<0>());\n\n lgi->setLine(line);\n lgi->show();\n }\n}\n\nvoid\nMainWindow::on_actionLinearLeastSquaresFittingOfSegments_triggered()\n{\n if(poly.size()>2){\n clear();\n\n Line_2 line;\n CGAL::linear_least_squares_fitting_2(poly.edges_begin(),\n poly.edges_end(),\n line,\n CGAL::Dimension_tag<1>());\n\n\n lgi->setLine(line);\n lgi->show();\n }\n}\n\nvoid\nMainWindow::on_actionYMonotonePartition_triggered()\n{\n partition(YMonotone);\n}\n\n\nvoid\nMainWindow::on_actionOptimalConvexPartition_triggered()\n{\n partition(OptimalConvex);\n}\n\n\nvoid\nMainWindow::on_actionApproximateConvexPartition_triggered()\n{\n partition(ApproximateConvex);\n}\n\n\nvoid\nMainWindow::partition(PartitionAlgorithm pa)\n{\n if(poly.size()>0){\n clear();\n if(! poly.is_counterclockwise_oriented()){\n poly.reverse_orientation();\n }\n switch (pa) {\n case YMonotone :\n CGAL::y_monotone_partition_2(poly.vertices_begin(), poly.vertices_end(), std::back_inserter(partitionPolygons));\n break;\n case ApproximateConvex:\n CGAL::approx_convex_partition_2(poly.vertices_begin(), poly.vertices_end(), std::back_inserter(partitionPolygons));\n break;\n default:\n CGAL::optimal_convex_partition_2(poly.vertices_begin(), poly.vertices_end(), std::back_inserter(partitionPolygons));\n break;\n }\n for(std::list::iterator it = partitionPolygons.begin();\n it != partitionPolygons.end();\n ++it){\n partitionGraphicsItems.push_back(new CGAL::Qt::PolygonGraphicsItem(&(*it)));\n scene.addItem(partitionGraphicsItems.back());\n partitionGraphicsItems.back()->setEdgesPen(QPen(Qt::blue, 0, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));\n }\n }\n}\n\nvoid\nMainWindow::clearPartition()\n{\n partitionPolygons.clear();\n for(std::list* >::iterator it = partitionGraphicsItems.begin();\n it != partitionGraphicsItems.end();\n ++it){\n scene.removeItem(*it);\n }\n partitionGraphicsItems.clear();\n}\n\nvoid\nMainWindow::clearMinkowski()\n{\n if(minkgi != nullptr){\n scene.removeItem(minkgi);\n delete minkgi;\n minkgi = nullptr;\n }\n}\n\nvoid\nMainWindow::clearSkeleton()\n{ for(std::list::iterator it = skeletonGraphicsItems.begin();\n it != skeletonGraphicsItems.end();\n ++it){\n scene.removeItem(*it);\n }\n skeletonGraphicsItems.clear();\n}\n\nvoid\nMainWindow::clearOffset()\n{ for(std::list::iterator it = offsetGraphicsItems.begin();\n it != offsetGraphicsItems.end();\n ++it){\n scene.removeItem(*it);\n }\n offsetGraphicsItems.clear();\n}\n\nvoid\nMainWindow::clear()\n{\n clearPartition();\n clearMinkowski();\n clearSkeleton();\n clearOffset();\n lgi->hide();\n kgongi->hide();\n}\n\n\n#include \"Polygon_2.moc\"\n#include \n\nint main(int argc, char **argv)\n{\n QApplication app(argc, argv);\n\n app.setOrganizationDomain(\"geometryfactory.com\");\n app.setOrganizationName(\"GeometryFactory\");\n app.setApplicationName(\"Polygon_2 demo\");\n\n // Import resources from libCGAL (Qt5).\n // See https://doc.qt.io/qt-5/qdir.html#Q_INIT_RESOURCE\n CGAL_QT_INIT_RESOURCES;\n Q_INIT_RESOURCE(Polygon_2);\n\n MainWindow mainWindow;\n mainWindow.show();\n return app.exec();\n}\n", "meta": {"hexsha": "98d66af08c5777a7774c188de29d0f0885bc717a", "size": 17034, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GraphicsView/demo/Polygon/Polygon_2.cpp", "max_stars_repo_name": "mtola/cgal", "max_stars_repo_head_hexsha": "e7b91b92b8c6949e3b62023bdd1e9f3ad8472626", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-04-08T23:06:26.000Z", "max_stars_repo_stars_event_max_datetime": "2019-04-08T23:06:26.000Z", "max_issues_repo_path": "GraphicsView/demo/Polygon/Polygon_2.cpp", "max_issues_repo_name": "samrat2825/cgal-dev", "max_issues_repo_head_hexsha": "eab5df14e118deb20db7373717bac273f1775a92", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-03-12T14:38:20.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-12T14:38:20.000Z", "max_forks_repo_path": "GraphicsView/demo/Polygon/Polygon_2.cpp", "max_forks_repo_name": "szobov/cgal", "max_forks_repo_head_hexsha": "e7b91b92b8c6949e3b62023bdd1e9f3ad8472626", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5185783522, "max_line_length": 127, "alphanum_fraction": 0.6251027357, "num_tokens": 4106, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7634837635542924, "lm_q1q2_score": 0.6504521316173905}} {"text": "#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace StatSim {\n\tdouble BinomialPMF(int tryCount, int occurCount, double probability) {\n\t\tconst auto numberOfCases = [](int n, int r) {\n\t\t\tif (n - r < r) {\n\t\t\t\tr = n - r;\n\t\t\t}\n\n\t\t\tboost::multiprecision::cpp_int result = 1;\n\t\t\tfor (int i = 0; i < r; ++i) {\n\t\t\t\tresult *= n - i;\n\t\t\t}\n\t\t\tfor (int i = 0; i < r; ++i) {\n\t\t\t\tresult /= i + 1;\n\t\t\t}\n\t\t\treturn result;\n\t\t}(tryCount, occurCount);\n\n\t\tconst boost::multiprecision::cpp_bin_float_100 probabilityEx(probability);\n\t\tconst auto occurProbability = boost::multiprecision::pow(probabilityEx, occurCount);\n\t\tconst auto notOccurProbability = boost::multiprecision::pow(1 - probabilityEx, tryCount - occurCount);\n\n\t\tconst auto result = static_cast(numberOfCases) * occurProbability * notOccurProbability;\n\t\treturn static_cast(result);\n\t}\n\tdouble NormalCDF(double value, double mean, double standardDeviation) {\n\t\treturn 0.5 * std::erfc((mean - value) / standardDeviation / std::numbers::sqrt2_v);\n\t}\n}", "meta": {"hexsha": "4d6fdd0d95df36fd02e4c7bba65545158e0d31c2", "size": 1167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Math.cpp", "max_stars_repo_name": "kmc7468/StatSim", "max_stars_repo_head_hexsha": "2d364a0bf3fd3988fd93510c8268a936e6dcb0fb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Math.cpp", "max_issues_repo_name": "kmc7468/StatSim", "max_issues_repo_head_hexsha": "2d364a0bf3fd3988fd93510c8268a936e6dcb0fb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Math.cpp", "max_forks_repo_name": "kmc7468/StatSim", "max_forks_repo_head_hexsha": "2d364a0bf3fd3988fd93510c8268a936e6dcb0fb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.4166666667, "max_line_length": 132, "alphanum_fraction": 0.7000856898, "num_tokens": 322, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9390248123094437, "lm_q2_score": 0.6926419894793246, "lm_q1q2_score": 0.6504080141684625}} {"text": "#include\n#include \n#include \n#include \n#include \n#include \n#include \nusing namespace std;\n//高斯密度函数\nfloat gussian_fx(float x){\n float weight=1/(sqrt(2*M_PI));\n float exow=-pow(x,2)/2;\n return (weight*exp(exow));\n};\n//求Xdata,float x){\n static int i=0,j=0;\n while(i MaxLikelihood(vector &xi){\n float hatu=0; float hatsigma2=0;\n for (int i = 0; i us={hatu/xi.size(),hatsigma2/xi.size()};\n return us;\n};\n\n//生成正态分布,mu均值,sigma2方差,默认个数500\nvectorNormalGenerating(float mu,float sigma2,int length=500){\n random_device rd;\n std::mt19937 gen(rd());\n uniform_real_distribution ud(0.0,1.0);\n int i=0;\n vector seed;\n while(iNormalGenerating2(float mu,float sigma2,int length=500){\n random_device rd;\n std::mt19937 gen(rd());\n normal_distribution normal(mu,sqrt(sigma2));\n vectorseed;\n while(length--){\n seed.push_back(normal(gen));\n }\n return seed;\n}\n\n//需要显示初始化\nstruct MultiNormal{\n int length=500;\n float u=0;\n float sigma2=0;\n vector Gussiandata;\n MultiNormal(vector data){\n u=MaxLikelihood(data).first;\n sigma2=MaxLikelihood(data).second;\n Gussiandata=data;\n }\n};\n//混合高斯分布,将多个正态分布相加\nvectorMultiNormalAdding(vector &kargs){\n vector reciver(500,0);\n int k=kargs.size();\n for (int loc = 0; loc <500 ; ++loc) {\n int j=0;\n while(jMultiNormalMerging(vector &kargs){\n int k=kargs.size();\n int Alllength=0;\n int i=0;\n while(i reciver(Alllength,0);\n int j=0;\n int det=0;\n while(j> CalNormalData(vector &multgassian,int quration,int GMM=2){\n vector temp=multgassian;\n sort(temp.begin(),temp.end());\n float mindata=temp.front();\n float maxdata=temp.back();\n float middle=(mindata+maxdata)/2;\n cout<> SortedHistData;\n int i=0;\n int pos=0;\n while(i tempdata;\n while(mindata+i*step<=temp[pos]&&temp[pos]<=mindata+(i+1)*step){\n tempdata.push_back(temp[pos]);\n pos++;\n }\n if(tempdata.size()==0) tempdata.push_back(0);//防止该分区为空\n SortedHistData.push_back(tempdata);\n tempdata.clear();\n i++;\n }\n Eigen::MatrixXf QKI(quration,GMM);\n Eigen::MatrixXf SITA(GMM,2);//同列0表示mu 1表示sigma2\n SITA< cof;\n for (int i = 0; i seed1=NormalGenerating(0,2);\n vector seed2=NormalGenerating2(10,2);\n //vector seed3=NormalGenerating2(15,2);\n MultiNormal No1(seed1);\n MultiNormal No2(seed2);\n // MultiNormal No3(seed3);\n vector Multiseeds;\n Multiseeds.push_back(No1);\n Multiseeds.push_back(No2);\n //Multiseeds.push_back(No3);\n vector merge=MultiNormalMerging(Multiseeds);\n //for(auto &item:merge)cout<\n\n#include \n\n#include \"headers/euler.hpp\"\n\nconst int EXPANSIONS_BEGIN = 1;\nconst int EXPANSIONS_NUM = 1000;\n\ntypedef boost::multiprecision::mpz_int big_int;\ntypedef euler::fraction fraction;\n\nfraction expandSqrt(int n, int depth = 0) {\n if (depth == n) {\n return fraction(1, 2);\n }\n\n fraction cd = expandSqrt(n, depth + 1);\n\n big_int a = cd.denom + (depth ? 0 : cd.numer);\n big_int b = depth ? (2 * cd.denom + cd.numer) : cd.denom;\n\n return fraction(a, b);\n}\n\nint main(int argc, char** argv) {\n int termsWithHigherDigitCountNumers = 0;\n\n for (int i = EXPANSIONS_BEGIN; i <= EXPANSIONS_NUM; i++) {\n fraction expandedTerm = expandSqrt(i);\n\n if (euler::countDigits(expandedTerm.numer) > euler::countDigits(expandedTerm.denom)) {\n termsWithHigherDigitCountNumers++;\n }\n }\n\n std::cout << \"Total expansions between \" << EXPANSIONS_BEGIN << \" and \" << EXPANSIONS_NUM\n << \" of sqrt(2) with higher counts of digits in numerator than denominator: \"\n << termsWithHigherDigitCountNumers << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "b75a620e2d5d526e693835ee7c0ae8d446fb1b5c", "size": 1111, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "57.cpp", "max_stars_repo_name": "DouglasSherk/project-euler", "max_stars_repo_head_hexsha": "f3b188b199ff31671c6d7683b15675be7484c5b8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "57.cpp", "max_issues_repo_name": "DouglasSherk/project-euler", "max_issues_repo_head_hexsha": "f3b188b199ff31671c6d7683b15675be7484c5b8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "57.cpp", "max_forks_repo_name": "DouglasSherk/project-euler", "max_forks_repo_head_hexsha": "f3b188b199ff31671c6d7683b15675be7484c5b8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.8372093023, "max_line_length": 91, "alphanum_fraction": 0.6714671467, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.934395168021653, "lm_q2_score": 0.6959583250334526, "lm_q1q2_score": 0.6503000960557012}} {"text": "#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace cv;\n\n\nstring file_1 = \"./LK1.png\"; // first image\nstring file_2 = \"./LK2.png\"; // second image\n\n\n\n\nclass OpticalFlowTracker{\npublic:\n OpticalFlowTracker(const Mat &img1_,\n const Mat &img2_,\n const vector &kp1_,\n vector &kp2_,\n vector &success_,\n bool inverse_ = true,\n bool has_initial_ = false):\n img1(img1_), img2(img2_), kp1(kp1_), kp2(kp2_), success(success_), inverse(inverse_),\n has_initial(has_initial_) {}\n \n void calculateOpticalFlow(const Range &range);\n\nprivate:\n const Mat &img1;\n const Mat &img2;\n const vector &kp1;\n vector &kp2;\n vector &success;\n bool inverse = true;\n bool has_initial = false;\n};\n\nvoid OpticalFlowMultiLevel(\n const Mat &img1,\n const Mat &img2,\n const vector &kp1,\n vector &kp2,\n vector &success,\n bool inverse = false\n);\n\n\nvoid OpticalFlowSingleLevel(\n const Mat &img1,\n const Mat &img2,\n const vector &kp1,\n vector &kp2,\n vector &success,\n bool inverse = false, bool has_initial = false);\n\n\n\n\n\ninline float GetPixelValue(const Mat &img, double x, double y){\n if (x < 0) x = 0;\n else if (x > img.cols - 1) x = img.cols - 1;\n if (y < 0) y = 0;\n else if (y > img.rows - 1) y = img.rows - 1;\n\n uchar *data = &img.data[int(y) * img.step + int(x)];\n float xx = x - floor(x);\n float yy = y - floor(y);\n float pixelValue = (1-xx)*(1-yy)*data[0] + (xx)*(1-yy)*data[1] \n + (1-xx)*(yy)*data[img.step] + (xx)*(yy)*data[img.step+1];\n return pixelValue;\n}\n\n\n\n\n\n\n\nint main(int argc, char **argv){\n cv::Mat img_1 = cv::imread(file_1, 0);\n cv::Mat img_2 = cv::imread(file_2, 0);\n\n // 从img1中提取特征点,使用GFTT特征\n vector kp_1;\n Ptr detector = GFTTDetector::create(500, 0.01, 20);\n detector->detect(img_1, kp_1);\n\n\n // OpenCV LK光流\n vector pts_1, pts_2;\n for (auto &kp:kp_1){\n pts_1.push_back(kp.pt);\n }\n vector status;\n vector error;\n cv::calcOpticalFlowPyrLK(img_1, img_2, pts_1, pts_2, status, error);\n // 画图:By OpenCV LK光流\n Mat img_2_CV;\n cv::cvtColor(img_2,img_2_CV, CV_GRAY2BGR);\n for (int i=0; i kp_2_single;\n vector success_single;\n OpticalFlowSingleLevel(img_1, img_2, kp_1, kp_2_single, success_single);\n // 画图:单层LK光流\n Mat img_2_single;\n cv::cvtColor(img_2,img_2_single, CV_GRAY2BGR);\n for (int i=0; i kp_2_single_inverse;\n vector success_single_inverse;\n OpticalFlowSingleLevel(img_1, img_2, kp_1, kp_2_single_inverse, success_single_inverse, true);\n // 画图:单层LK光流\n Mat img_2_single_inverse;\n cv::cvtColor(img_2,img_2_single_inverse, CV_GRAY2BGR);\n for (int i=0; i kp_2_multi;\n vector success_multi;\n OpticalFlowMultiLevel(img_1, img_2, kp_1, kp_2_multi, success_multi, true);\n // OpticalFLowMultiLevel(img_1, img_2, kp_1, kp_2_multi, success_multi, true);\n // 画图:多层LK光流\n Mat img_2_multi;\n cv::cvtColor(img_2,img_2_multi, CV_GRAY2BGR);\n for (int i=0; i &kp1,\n vector &kp2,\n vector &success,\n bool inverse, bool has_initial){\n \n kp2.resize(kp1.size());\n success.resize(kp1.size());\n OpticalFlowTracker tracker(img1, img2, kp1, kp2, success, inverse, has_initial);\n parallel_for_(Range(0, kp1.size()), \n std::bind(&OpticalFlowTracker::calculateOpticalFlow, &tracker, placeholders::_1));\n}\n\n\nvoid OpticalFlowMultiLevel(\n const Mat &img1,\n const Mat &img2,\n const vector &kp1,\n vector &kp2,\n vector &success,\n bool inverse) {\n\n int pyramids = 4;\n double pyramid_scale = 0.5;\n double scales[] = {1.0, 0.5, 0.25, 0.125};\n\n vector pyr1, pyr2;\n for (int i = 0; i < pyramids; i++){\n if(i==0){\n pyr1.push_back(img1);\n pyr2.push_back(img2);\n }\n else{\n Mat img1_ptr, img2_ptr;\n cv::resize(pyr1[i-1], img1_ptr, Size(), pyramid_scale, pyramid_scale);\n cv::resize(pyr2[i-1], img2_ptr, Size(), pyramid_scale, pyramid_scale);\n pyr1.push_back(img1_ptr);\n pyr2.push_back(img2_ptr);\n }\n }\n\n vector kp1_ptr, kp2_ptr;\n for (auto &kp: kp1){\n auto kp_top = kp;\n kp_top.pt *= (pow(pyramid_scale, pyramids - 1));\n kp1_ptr.push_back(kp_top);\n kp2_ptr.push_back(kp_top);\n }\n\n for(int level = pyramids - 1; level >= 0; level--){\n success.clear();\n OpticalFlowSingleLevel(pyr1[level], pyr2[level], kp1_ptr, kp2_ptr, success, inverse, true);\n\n if (level > 0){\n for (auto &kp:kp1_ptr){\n kp.pt /= pyramid_scale; \n }\n for (auto &kp:kp2_ptr){\n kp.pt /= pyramid_scale; \n }\n }\n }\n\n for(auto &kp: kp2_ptr){\n kp2.push_back(kp);\n }\n}\n\n\n\n\n\n\n\n\n// void OpticalFlowTracker::calculateOpticalFlow(const Range &range){\n// int half_patch_size = 4;\n// int iterations = 10;\n// for(size_t i = range.start; i < range.end; i++){\n// auto kp = kp1[i];\n// double dx = 0, dy = 0;\n// if (has_initial){\n// dx = kp2[i].pt.x - kp.pt.x;\n// dy = kp2[i].pt.y - kp.pt.y;\n// }\n\n// double cost = 0, lastCost = 0;\n// bool succ = true;\n\n// // Gauss-Newton iterations\n// Eigen::Matrix2d H = Eigen::Matrix2d::Zero();\n// Eigen::Vector2d b = Eigen::Vector2d::Zero();\n// Eigen::Vector2d J;\n\n// for (int iter = 0; iter < iterations; iter++){\n\n// cost = 0;\n// if (inverse == false){\n// H = Eigen::Matrix2d::Zero();\n// b = Eigen::Vector2d::Zero();\n// }\n// else{\n// b = Eigen::Vector2d::Zero();\n// }\n\n// for (int x = -half_patch_size; x < half_patch_size; x++){\n// for (int y = -half_patch_size; y < half_patch_size; y++) {\n// double error = GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y) -\n// GetPixelValue(img2, kp.pt.x + x + dx, kp.pt.y + y + dy);; // Jacobian\n// if (inverse == false) {\n// J = -1.0 * Eigen::Vector2d(\n// 0.5 * (GetPixelValue(img2, kp.pt.x + dx + x + 1, kp.pt.y + dy + y) -\n// GetPixelValue(img2, kp.pt.x + dx + x - 1, kp.pt.y + dy + y)),\n// 0.5 * (GetPixelValue(img2, kp.pt.x + dx + x, kp.pt.y + dy + y + 1) -\n// GetPixelValue(img2, kp.pt.x + dx + x, kp.pt.y + dy + y - 1))\n// );\n// } else if (iter == 0) {\n// // in inverse mode, J keeps same for all iterations\n// // NOTE this J does not change when dx, dy is updated, so we can store it and only compute error\n// J = -1.0 * Eigen::Vector2d(\n// 0.5 * (GetPixelValue(img1, kp.pt.x + x + 1, kp.pt.y + y) -\n// GetPixelValue(img1, kp.pt.x + x - 1, kp.pt.y + y)),\n// 0.5 * (GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y + 1) -\n// GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y - 1))\n// );\n// }\n// // compute H, b and set cost;\n// b += -error * J;\n// cost += error * error;\n// if (inverse == false || iter == 0) {\n// // also update H\n// H += J * J.transpose();\n// }\n// }\n// }\n\n\n// Eigen::Vector2d update = H.ldlt().solve(b);\n\n// if (std::isnan(update[0])) {\n// // sometimes occurred when we have a black or white patch and H is irreversible\n// cout << \"update is nan\" << endl;\n// succ = false;\n// break;\n// }\n\n// if (iter > 0 && cost > lastCost) {\n// break;\n// }\n\n// // update dx, dy\n// dx += update[0];\n// dy += update[1];\n// lastCost = cost;\n// succ = true;\n\n// if (update.norm() < 1e-2) {\n// // converge\n// break;\n// }\n// }\n\n// success[i] = succ;\n\n// // set kp2\n// kp2[i].pt = kp.pt + Point2f(dx, dy);\n// }\n// }\n\n\nvoid OpticalFlowTracker::calculateOpticalFlow(const Range &range) {\n // parameters\n int half_patch_size = 4;\n int iterations = 10;\n for (size_t i = range.start; i < range.end; i++) {\n auto kp = kp1[i];\n double dx = 0, dy = 0; // dx,dy need to be estimated\n if (has_initial) {\n dx = kp2[i].pt.x - kp.pt.x;\n dy = kp2[i].pt.y - kp.pt.y;\n }\n\n double cost = 0, lastCost = 0;\n bool succ = true; // indicate if this point succeeded\n\n // Gauss-Newton iterations\n Eigen::Matrix2d H = Eigen::Matrix2d::Zero(); // hessian\n Eigen::Vector2d b = Eigen::Vector2d::Zero(); // bias\n Eigen::Vector2d J; // jacobian\n for (int iter = 0; iter < iterations; iter++) {\n if (inverse == false) {\n H = Eigen::Matrix2d::Zero();\n b = Eigen::Vector2d::Zero();\n } else {\n // only reset b\n b = Eigen::Vector2d::Zero();\n }\n\n cost = 0;\n\n // compute cost and jacobian\n for (int x = -half_patch_size; x < half_patch_size; x++)\n for (int y = -half_patch_size; y < half_patch_size; y++) {\n double error = GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y) -\n GetPixelValue(img2, kp.pt.x + x + dx, kp.pt.y + y + dy);; // Jacobian\n if (inverse == false) {\n J = -1.0 * Eigen::Vector2d(\n 0.5 * (GetPixelValue(img2, kp.pt.x + dx + x + 1, kp.pt.y + dy + y) -\n GetPixelValue(img2, kp.pt.x + dx + x - 1, kp.pt.y + dy + y)),\n 0.5 * (GetPixelValue(img2, kp.pt.x + dx + x, kp.pt.y + dy + y + 1) -\n GetPixelValue(img2, kp.pt.x + dx + x, kp.pt.y + dy + y - 1))\n );\n } else if (iter == 0) {\n // in inverse mode, J keeps same for all iterations\n // NOTE this J does not change when dx, dy is updated, so we can store it and only compute error\n J = -1.0 * Eigen::Vector2d(\n 0.5 * (GetPixelValue(img1, kp.pt.x + x + 1, kp.pt.y + y) -\n GetPixelValue(img1, kp.pt.x + x - 1, kp.pt.y + y)),\n 0.5 * (GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y + 1) -\n GetPixelValue(img1, kp.pt.x + x, kp.pt.y + y - 1))\n );\n }\n // compute H, b and set cost;\n b += -error * J;\n cost += error * error;\n if (inverse == false || iter == 0) {\n // also update H\n H += J * J.transpose();\n }\n }\n\n // compute update\n Eigen::Vector2d update = H.ldlt().solve(b);\n\n if (std::isnan(update[0])) {\n // sometimes occurred when we have a black or white patch and H is irreversible\n cout << \"update is nan\" << endl;\n succ = false;\n break;\n }\n\n if (iter > 0 && cost > lastCost) {\n break;\n }\n\n // update dx, dy\n dx += update[0];\n dy += update[1];\n lastCost = cost;\n succ = true;\n\n if (update.norm() < 1e-2) {\n // converge\n break;\n }\n }\n\n success[i] = succ;\n\n // set kp2\n kp2[i].pt = kp.pt + Point2f(dx, dy);\n }\n}", "meta": {"hexsha": "80cb4fd90b892e76dd2c9ba5126a8f216707d2c8", "size": 14124, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "my_implementation_1/ch8/optical_flow.cpp", "max_stars_repo_name": "Mingrui-Yu/slambook2", "max_stars_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-09T14:18:15.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-09T14:18:15.000Z", "max_issues_repo_path": "my_implementation_1/ch8/optical_flow.cpp", "max_issues_repo_name": "Mingrui-Yu/slambook2", "max_issues_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "my_implementation_1/ch8/optical_flow.cpp", "max_forks_repo_name": "Mingrui-Yu/slambook2", "max_forks_repo_head_hexsha": "d31273192bd9fb5ac618f147105082022c87a005", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.7393258427, "max_line_length": 123, "alphanum_fraction": 0.4819456245, "num_tokens": 4007, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.793105951184112, "lm_q2_score": 0.8198933271118221, "lm_q1q2_score": 0.6502622770685279}} {"text": "/**\n * @file\n * @brief NPDE UnstableBVP. Solution of source-free heat equation and\n * computation of H1 seminorms on different triangular meshes and refinement\n * levels\n * @author Julien Gacon, Ralf Hiptmair, Amélie Loher\n * @date March 2019\n * @copyright MIT License\n */\n#include \"unstablebvp.h\"\n// General includes\n#include \n#include \n#include \n// Math includes\n#include \n// Eigen\n#include \n// Lehrfempp\n#include \n#include \n\nint main() {\n // Define the number of refinement levels we want for our mesh\n const int reflevels = 7;\n\n // Do the computations for all three possible mesh locations:\n // Above x2 = 0 (top), intersecting it (center), or below it (bottom)\n // Store the data in a Eigen Matrix for nice display later on\n Eigen::MatrixXd h1_seminorms(reflevels + 1, 3), h1_diffs(reflevels + 1, 3);\n\n // 0 for top (-> first column), 1 for center, 2 for bottom\n int type_idx = 0;\n for (auto mesh_type : {\"top\", \"center\", \"bottom\"}) {\n // Get a hierachy of refined meshes\n std::shared_ptr multi_mesh_p =\n UnstableBVP::createMeshHierarchy(reflevels, mesh_type);\n lf::refinement::MeshHierarchy &multi_mesh{*multi_mesh_p};\n\n // Number of levels\n const int L = multi_mesh.NumLevels();\n\n // Computing the difference u_L - u_k, k=0...L-1 is hard, since we would\n // the functions are defined on different meshes.\n // To avoid this caveat we can approximate using the triangle inequality:\n // abs(norm(u_L) - norm(u_k)) <= norm(u_L - u_k)\n // This should also display the right convergence properties.\n\n // H1 seminorm of most refined solution (level L-1)\n double h1_uL =\n UnstableBVP::solveTemperatureDistribution(multi_mesh.getMesh(L - 1));\n\n // Store H1 seminorms and the difference of the seminorms to uL\n h1_seminorms(reflevels, type_idx) = h1_uL;\n h1_diffs(reflevels, type_idx) = 0;\n\n // Compute H1 seminorm for all levels 0..L-2\n for (int level = 0; level < L - 1; ++level) {\n // Get the mesh pointer\n std::shared_ptr mesh_p = multi_mesh.getMesh(level);\n\n // Get the seminorm\n double h1 = UnstableBVP::solveTemperatureDistribution(mesh_p);\n\n // Store\n h1_seminorms(level, type_idx) = h1;\n h1_diffs(level, type_idx) = std::abs(h1_uL - h1);\n }\n ++type_idx;\n }\n\n // Print to terminal\n std::cout << std::left << std::setfill('-');\n std::cout << std::setw(39) << \"# -- Above x2 = 0 \" << std::setw(30)\n << \"|-- Intersecting x2 = 0 \" << std::setw(30)\n << \"|-- Below x2 = 0 \"\n << \"\\n\"\n << std::right << std::setfill(' ');\n std::cout << \"#\" << std::setw(8) << \"Level\" << std::setw(10) << \"|u_k|\"\n << std::setw(20) << \"||u_L| - |u_k||\" << std::setw(10) << \"|u_k|\"\n << std::setw(20) << \"||u_L| - |u_k||\" << std::setw(10) << \"|u_k|\"\n << std::setw(20) << \"||u_L| - |u_k||\"\n << \"\\n\";\n\n for (int l = 0; l < reflevels; ++l) {\n std::cout << std::setw(9) << l << std::setw(10) << h1_seminorms(l, 0)\n << std::setw(20) << h1_diffs(l, 0) << std::setw(10)\n << h1_seminorms(l, 1) << std::setw(20) << h1_diffs(l, 1)\n << std::setw(10) << h1_seminorms(l, 2) << std::setw(20)\n << h1_diffs(l, 2) << \"\\n\";\n }\n std::cout << std::setw(9) << reflevels << std::setw(10)\n << h1_seminorms(reflevels, 0) << std::setw(20) << 0 << std::setw(10)\n << h1_seminorms(reflevels, 1) << std::setw(20) << 0 << std::setw(10)\n << h1_seminorms(reflevels, 2) << std::setw(20) << 0 << \"\\n\";\n\n return 0;\n}\n", "meta": {"hexsha": "b1cc1c3d11a71c156609cfa6cdb918c7bc2c825b", "size": 3704, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/UnstableBVP/templates/unstablebvp_main.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "homeworks/UnstableBVP/templates/unstablebvp_main.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "homeworks/UnstableBVP/templates/unstablebvp_main.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 37.4141414141, "max_line_length": 80, "alphanum_fraction": 0.593412527, "num_tokens": 1179, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8198933271118221, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6502622770685278}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"GPs.h\"\n\n// Include CppOptLib files\n#include \"./include/cppoptlib/meta.h\"\n#include \"./include/cppoptlib/boundedproblem.h\"\n#include \"./include/cppoptlib/solver/lbfgsbsolver.h\"\n\n// Retrieve aliases from GP namescope\nusing Matrix = GP::Matrix;\nusing Vector = GP::Vector;\n\n\n// Compute pairwise distance between lists of points\nvoid GP::pdist(Matrix & Dv, Matrix & X1, Matrix & X2)\n{\n auto n = static_cast(X1.rows());\n int k = 0;\n auto entryCount = static_cast( (n*(n-1))/2);\n Dv.resize(entryCount, 1);\n for ( auto i : boost::irange(0,n-1) )\n { \n for ( auto j : boost::irange(i+1,n) )\n Dv(k++) = (static_cast(X1.row(i) - X2.row(j))).squaredNorm();\n }\n}\n\n// Re-assemble pairwise distances into a dense matrix\nvoid GP::squareForm(Matrix & D, Matrix & Dv, int n, double diagVal)\n{\n\n D.resize(n,n);\n\n int k = 0;\n for ( auto i : boost::irange(0,n-1) )\n {\n for ( auto j : boost::irange(i+1,n) )\n D(i,j) = D(j,i) = Dv(k++,0);\n }\n\n D.diagonal() = diagVal * Eigen::MatrixXd::Ones(n,1);\n}\n\n\n// Compute covariance matrix (and gradients) from a vector of squared pairwise distances Dv\nstd::vector GP::RBF::computeCov(Matrix & K, Matrix & Dv, Vector & params, double jitter, bool evalGrad)\n{\n auto n = static_cast(K.rows());\n int lengthIndex;\n if ( params.size() > paramCount )\n {\n Kv.noalias() = ( (-0.5 / std::pow(params(1),2)) * Dv ).array().exp().matrix();\n squareForm(K, Kv, n, 1.0 + params(0) + jitter);\n lengthIndex = 1;\n }\n else\n {\n Kv.noalias() = ( (-0.5 / std::pow(params(0),2)) * Dv ).array().exp().matrix();\n squareForm(K, Kv, n, 1.0 + noiseLevel + jitter);\n lengthIndex = 0;\n }\n\n // Compute gradient list if \"evalGrad=true\"\n std::vector gradList;\n if ( evalGrad )\n {\n dK_iv.noalias() = 1/std::pow(params(lengthIndex),2) * ( Dv.array() * Kv.array() ).matrix();\n squareForm(dK_i, dK_iv, n); // Note: diagVal = 0.0\n gradList.push_back(dK_i);\n }\n\n return gradList;\n \n};\n\n\n// Compute cross covariance between two input vectors using kernel parameters params\nvoid GP::RBF::computeCrossCov(Matrix & K, Matrix & X1, Matrix & X2, Vector & params)\n{\n // Get prediction count\n auto m = static_cast(X2.rows());\n\n // Define lambda function to create unary operator (by clamping kernelParams argument) \n auto lambda = [=,¶ms](double d)->double { return evalDistKernel(d, params, 0); };\n for ( auto j : boost::irange(0,m) )\n {\n K.col(j) = ((X1.rowwise() - X2.row(j)).rowwise().squaredNorm()).unaryExpr(lambda); \n }\n \n};\n\n\n// Precompute distance matrix to avoid repeated calculations during optimization procedure\nvoid GP::GaussianProcess::computeDistMat()\n{\n pdist(distMatrix, obsX, obsX);\n}\n\n\n// Evaluate NLML for specified kernel hyperparameters p\ndouble GP::GaussianProcess::evalNLML(const Vector & p, Vector & g, bool evalGrad)\n{\n // Get matrix input observation count\n auto n = static_cast(obsX.rows());\n\n // ASSUME OPTIMIZATION OVER LOG VALUES\n auto params = static_cast(p);\n params = params.array().exp().matrix();\n\n // Compute covariance matrix and store Cholesky factor\n K.resize(n,n);\n //time start = high_resolution_clock::now();\n auto gradList = (*kernel).computeCov(K, distMatrix, params, jitter, evalGrad);\n //time end = high_resolution_clock::now();\n //time_computecov += getTime(start, end);\n\n //start = high_resolution_clock::now();\n cholesky = K.llt();\n //end = high_resolution_clock::now();\n //time_cholesky_llt += getTime(start, end);\n\n // Store alpha for DNLML calculation\n _alpha.noalias() = cholesky.solve(obsY);\n\n // Compute NLML value\n //start = high_resolution_clock::now();\n double NLML_value = 0.5*(obsY.transpose()*_alpha)(0);\n NLML_value += static_cast(cholesky.matrixL()).diagonal().array().log().sum();\n NLML_value += 0.5*n*std::log(2*PI);\n //end = high_resolution_clock::now();\n //time_NLML += getTime(start, end);\n\n\n if ( evalGrad )\n {\n\n //\n // Precompute the multiplicative term in derivative expressions\n //\n // [ THIS APPEARS TO BE A COMPUTATIONAL BOTTLE-NECK ]\n //\n\n //start = high_resolution_clock::now();\n // Direct evaluation of inverse matrix\n term.noalias() = cholesky.solve(Matrix::Identity(n,n)) - _alpha*_alpha.transpose();\n\n\n /*\n //\n // --- PARALLEL IMPLEMENTATION ---\n //\n // [ Typically much slower; possibly not thread-safe... ]\n //\n term.resize(n,n);\n //Matrix ei = Eigen::MatrixXd::Zero(n,1);\n int i = 0;\n //#pragma omp parallel for private(i) shared(cholesky, term, n)\n#pragma omp parallel for private(i) shared(cholesky, _alpha, term, n)\n for ( i=0 ; i(lbs.rows());\n\n Vector sampleVector = ((ubs-lbs).array()*( 0.5*Eigen::MatrixXd::Random(n,1) + 0.5*Eigen::MatrixXd::Ones(n,1) ).array()).matrix() + (lbs.array()*Eigen::MatrixXd::Ones(n,1).array()).matrix();\n \n return sampleVector;\n}\n\n// Define function for sampling from standard normal distribution\nMatrix GP::sampleNormal(int N)\n{\n // Note: Boost random is currently throwing deprecated header warnings...\n //boost::random::mt19937 rng;\n //boost::random::normal_distribution<> normalDist;\n std::default_random_engine rng;\n std::normal_distribution normalDist(0.0,1.0);\n Matrix sampleVals(N,1);\n for ( auto i : boost::irange(0,N) )\n sampleVals(i) = normalDist(rng);\n return sampleVals;\n}\n\n\n// Generate equally spaced points on an interval or square region\nMatrix GP::linspace(double a, double b, int N, int dim)\n{\n\n Matrix linspaceVals;\n if ( dim == 1 )\n {\n linspaceVals.resize(N,1);\n linspaceVals = Eigen::Array::LinSpaced(N, a, b);\n }\n else if ( dim == 2 )\n {\n linspaceVals.resize(N*N,2);\n Matrix linspaceVals1D = Eigen::Array::LinSpaced(N, a, b);\n int k = 0;\n for ( auto i : boost::irange(0,N) )\n {\n for ( auto j : boost::irange(0,N) )\n {\n linspaceVals(k,0) = linspaceVals1D(i);\n linspaceVals(k,1) = linspaceVals1D(j);\n k++;\n }\n }\n }\n else\n std::cout << \"[*] GP::linspace has not been implemented for dim > 2\\n\";\n \n return linspaceVals;\n}\n\n\n// Define utility function for formatting hyperparameter bounds\nvoid GP::GaussianProcess::parseBounds(Vector & lbs, Vector & ubs, int augParamCount)\n{\n lbs.resize(augParamCount);\n ubs.resize(augParamCount);\n\n double defaultLowerBound = 0.00001;\n double defaultUpperBound = 10.0;\n \n if ( fixedBounds )\n {\n // Check if bounds for noise parameter were provided\n if ( lowerBounds.size() < augParamCount )\n {\n // Set noise bounds to defaults\n lbs(0) = std::log( defaultLowerBound );\n ubs(0) = std::log( defaultUpperBound );\n\n // Convert specified bounds to log-scale\n for ( auto bi : boost::irange(1,augParamCount) )\n {\n lbs(bi) = std::log(lowerBounds(bi-1));\n ubs(bi) = std::log(upperBounds(bi-1));\n }\n }\n else\n {\n // Convert specified bounds to log-scale\n lbs = (lowerBounds.array().log()).matrix();\n ubs = (upperBounds.array().log()).matrix();\n }\n }\n else\n {\n // Set noise and hyperparameter bounds to defaults\n lbs = ( defaultLowerBound * Eigen::MatrixXd::Ones(augParamCount,1) ).array().log().matrix();\n ubs = ( defaultUpperBound * Eigen::MatrixXd::Ones(augParamCount,1) ).array().log().matrix();\n }\n\n /*\n std::cout << \"Bounds:\\n\";\n std::cout << lbs.array().exp().matrix().transpose() << std::endl;\n std::cout << ubs.array().exp().matrix().transpose() << std::endl;\n std::cout << \"\\nLog Bounds:\\n\";\n std::cout << lbs.transpose() << std::endl;\n std::cout << ubs.transpose() << std::endl << std::endl;\n */\n\n}\n\n\n// Fit model hyperparameters\nvoid GP::GaussianProcess::fitModel()\n{\n\n // Get combined parameter/noise vector size\n paramCount = (*kernel).getParamCount();\n augParamCount = (fixedNoise) ? static_cast(paramCount) : static_cast(paramCount) + 1 ;\n\n // Pass noise level to kernel when 'fixedNoise=true'\n if ( fixedNoise )\n (*kernel).setNoise(noiseLevel);\n \n // Precompute distance matrix\n computeDistMat();\n\n // Declare vector for storing gradient calculations\n Vector g(augParamCount);\n\n // Initialize gradient vector size\n cppOptLibgrad.resize(augParamCount);\n\n // Convert hyperparameter bounds to log-scale\n Vector lbs, ubs;\n parseBounds(lbs, ubs, augParamCount);\n\n Vector optParams = Eigen::MatrixXd::Zero(augParamCount,1);\n \n this->setLowerBound(lbs);\n this->setUpperBound(ubs);\n cppoptlib::LbfgsbSolver solver;\n\n // Specify stopping criteria\n cppoptlib::Criteria crit = cppoptlib::Criteria::defaults();\n //crit.iterations = 5000;\n //crit.gradNorm = 10.0; //!< Minimum norm of gradient vector\n //crit.xDelta = 0; //!< Minimum change in parameter vector\n //crit.fDelta = 0; //!< Minimum change in cost function\n //crit.condition = 0;\n solver.setStopCriteria(crit);\n\n solver.minimize(*this, optParams);\n\n // ASSUME OPTIMIZATION OVER LOG VALUES\n optParams = optParams.array().exp().matrix();\n\n\n //start = high_resolution_clock::now();\n ///* [ This is included in the SciKit Learn model.fit() call as well ]\n\n // Recompute covariance and Cholesky factor\n auto nullGradList = (*kernel).computeCov(K, distMatrix, optParams);\n cholesky = K.llt();\n _alpha.noalias() = cholesky.solve(obsY);\n \n //*/\n //end = high_resolution_clock::now();\n //time_final_chol += getTime(start, end);\n \n \n // Assign tuned parameters to model\n if (!fixedNoise)\n {\n noiseLevel = static_cast((optParams.head(1))[0]);\n optParams = static_cast(optParams.tail(augParamCount - 1));\n }\n \n (*kernel).setParams(optParams);\n\n\n // DISPLAY TIMING INFORMATION\n /*\n std::cout << \"\\n\\n Time Diagnostics |\\n\";\n std::cout << \"------------------\\n\";\n std::cout << \"computeCov():\\t \" << time_computecov << std::endl;\n std::cout << \"cholesky.llt():\\t \" << time_cholesky_llt << std::endl;\n std::cout << \"NLML:\\t \\t \" << time_NLML << std::endl;\n std::cout << \"Grad term:\\t \" << time_term << std::endl;\n std::cout << \"Gradient:\\t \" << time_grad << std::endl;\n std::cout << \"\\n\" << std::endl;\n std::cout << \"paramSearch:\\t \" << time_paramsearch << std::endl;\n std::cout << \"Minimize:\\t \" << time_minimize << std::endl;\n std::cout << \"Final Cholesky:\\t \" << time_final_chol << std::endl;\n */\n \n};\n\n// Compute predicted values\nvoid GP::GaussianProcess::predict()\n{\n // Get matrix input observation count\n auto n = static_cast(obsX.rows());\n auto m = static_cast(predX.rows());\n \n // Get optimized kernel hyperparameters\n Vector params = (*kernel).getParams();\n\n // Compute cross covariance for test points\n Matrix kstar;\n kstar.resize(n,m);\n (*kernel).computeCrossCov(kstar, obsX, predX, params);\n\n // Compute covariance matrix for test points\n Matrix kstarmat;\n kstarmat.resize(m,m);\n (*kernel).computeCrossCov(kstarmat, predX, predX, params);\n\n // Possible redundant calculations; should simplify...\n Matrix cholMat(cholesky.matrixL());\n //Matrix alpha = cholesky.solve(obsY);\n Matrix v = kstar;\n cholMat.triangularView().solveInPlace(v);\n\n // Set predictive means/variances and compute negative log marginal likelihood\n //predMean = kstar.transpose() * alpha;\n predMean = kstar.transpose() * _alpha;\n predCov = kstarmat - v.transpose() * v;\n\n}\n\n\n// Draw sample paths from posterior distribution\nMatrix GP::GaussianProcess::getSamples(int count)\n{\n // Get number of target points\n auto n = static_cast(predX.rows());\n \n // Construct simple random generator engine from a time-based seed\n unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();\n std::default_random_engine generator (seed);\n std::normal_distribution normal (0.0,1.0);\n\n // Assign i.i.d. random normal values to uVals\n Matrix uVals(n,count);\n for (auto i : boost::irange(0,n))\n {\n for (auto j : boost::irange(0,count))\n uVals(i,j) = normal(generator);\n }\n\n // Compute Cholesky factor L\n Matrix L = ( predCov + (noiseLevel+jitter)*Matrix::Identity(static_cast(predCov.cols()), static_cast(predCov.cols())) ).llt().matrixL();\n\n // Draw samples using the formula: y = m + L*u\n Matrix samples = predMean.replicate(1,count) + L*uVals;\n \n return samples;\n}\n\n\n// Evaluate NLML [public interface]\ndouble GP::GaussianProcess::computeNLML(const Vector & p, double noise)\n{\n // Compute log-hyperparameters\n Vector logparams(augParamCount);\n\n if ( !fixedNoise )\n {\n logparams(0) = std::log(noise);\n for ( auto i : boost::irange(1,augParamCount) )\n logparams(i) = std::log(p(i-1));\n }\n else\n {\n logparams = logparams.array().log().matrix();\n }\n\n // Evaluate NLML using log-hyperparameters\n return evalNLML(logparams);\n}\n\n// Evaluate NLML with default noise level [public interface]\ndouble GP::GaussianProcess::computeNLML(const Vector & p)\n{\n return computeNLML(p, noiseLevel);\n}\n\n// Evaluate NLML with default noise level [public interface]\ndouble GP::GaussianProcess::computeNLML()\n{\n auto params = (*kernel).getParams();\n return computeNLML(params, noiseLevel);\n}\n\n\n// Define function for retrieving time from chrono\nfloat GP::getTime(std::chrono::high_resolution_clock::time_point start, std::chrono::high_resolution_clock::time_point end)\n{\n return static_cast(std::chrono::duration_cast( end - start ).count() / 1000000.0);\n};\n\n\n// Define kernel function for RBF\ndouble GP::RBF::evalKernel(Matrix & x, Matrix & y, Vector & params, int n)\n{\n switch (n)\n {\n case 0: return std::exp( -(x-y).squaredNorm() / (2.0*std::pow(params(0),2)));\n case 1: return (x-y).squaredNorm() / std::pow(params(0),3) * std::exp( -(x-y).squaredNorm() / (2.0*std::pow(params(0),2)));\n default: std::cout << \"\\n[*] UNDEFINED DERIVATIVE\\n\"; return 0.0;\n }\n};\n\n// Define distance kernel function for RBF\n//\n// REVISION: Optimize w.r.t. theta = log(l) for stability ==> / l^2 instead of / l^3\n//\ndouble GP::RBF::evalDistKernel(double d, Vector & params, int n)\n{\n switch (n)\n {\n case 0: return std::exp( -d / (2.0*std::pow(params(0),2)));\n case 1: return d / std::pow(params(0),2) * std::exp( -d / (2.0*std::pow(params(0),2)));\n default: std::cout << \"\\n[*] UNDEFINED DERIVATIVE\\n\"; return 0.0;\n }\n};\n\n\n\n\n/*\n// POTENTIAL PARALLEL IMPLEMENTATION OF SQUARE FORM; SPEED-UP APPEARS NEGLIGIBLE\n// Re-assemble pairwise distances into a dense matrix\nvoid GP::squareFormParallel(Matrix & D, Matrix & Dv, int n, double diagVal)\n{\n\n D.resize(n,n);\n int i;\n int j;\n#pragma omp parallel for private(i,j) shared(D,Dv,n)\n for ( i = 0 ; i(i*n - (i*(i+1))/2 + j - i -1) ,0);\n }\n }\n D.diagonal() = diagVal * Eigen::MatrixXd::Ones(n,1);\n}\n*/\n\n\n\n\n//\n// ORIGINAL MINIMIZATION IMPLEMENTATION USING RASMUSSEN'S CODE\n//\n\n//\n// NOTE:\n//\n// Remember to include \"utils/minimize.h\" and derive the\n// 'GaussianProcess' class from the 'GradientObj' class:\n//\n// i.e. class GaussianProcess : public minimize::GradientObj\n//\n\n/*\nvoid minimize(...)\n{\n\n\n //\n // Specify the parameters for the minimization algorithm\n //\n \n // HIGH ACCURACY SETTINGS //\n // max of MAX function evaluations per line search\n //int MAX = 30;\n // max number of line searches = length\n //int length = 20;\n // don't reevaluate within INT of the limit of the current bracket\n //double INT = 0.00001;\n // SIG is a constant controlling the Wolfe-Powell conditions\n //double SIG = 0.9;\n // extrapolate maximum EXT times the current step-size\n //double EXT = 5.0;\n\n // EFFICIENT SETTINGS //\n\n\n int MAX = 15;\n int length = 10;\n double INT = 0.00001;\n double SIG = 0.9;\n double EXT = 5.0;\n\n // Define number of exploratory NLML evaluations for specifying\n // a reasonable initial value for the optimization algorithm\n int initParamSearchCount = 30;\n \n // Define restart count for optimizer\n int restartCount = 0;\n \n // Convert hyperparameter bounds to log-scale\n Vector lbs, ubs;\n parseBounds(lbs, ubs, augParamCount);\n\n // Declare variables to store optimization loop results\n double currentVal;\n double optVal = 1e9;\n Vector theta(augParamCount);\n Vector optParams(augParamCount);\n\n //time start = high_resolution_clock::now();\n // First explore hyperparameter space to get a reasonable initializer for optimization\n for ( auto i : boost::irange(0,initParamSearchCount) )\n {\n if ( i == 0 )\n theta = Eigen::MatrixXd::Zero(augParamCount,1);\n else\n theta = sampleUnifVector(lbs, ubs);\n\n // Compute current NLML and store parameters if optimal\n currentVal = evalNLML(theta);\n if ( currentVal < optVal )\n {\n optVal = currentVal;\n optParams = theta;\n }\n //std::cout << \"Theta Search: \" << theta.transpose() << \" [ NLML = \" << currentVal << \" ]\"<< std::endl;\n }\n //time end = high_resolution_clock::now();\n //time_paramsearch += getTime(start, end);\n\n\n // NOTE: THIS NEEDS TO BE RE-WRITTEN TO USE THE PRELIMINARY PARAMETER SEARCH RESULTS\n // Evaluate optimizer with various different initializations\n for ( auto i : boost::irange(0,restartCount) )\n {\n // Avoid compiler warning for unused variable\n //(void)i;\n\n if ( i == 0 )\n {\n // Set initial guess (should make this user specifiable...)\n theta = Eigen::MatrixXd::Zero(augParamCount,1);\n }\n else\n {\n // Sample initial hyperparameter vector\n theta = sampleUnifVector(lbs, ubs);\n }\n\n // Optimize hyperparameters\n minimize::cg_minimize(theta, this, g, length, SIG, EXT, INT, MAX);\n \n // Compute current NLML and store parameters if optimal\n currentVal = evalNLML(theta);\n if ( currentVal < optVal )\n {\n optVal = currentVal;\n optParams = theta;\n }\n }\n\n // Perform one last optimization starting from best parameters so far\n if ( ( initParamSearchCount == 0 ) && ( restartCount == 0 ) )\n optParams = sampleUnifVector(lbs, ubs);\n //std::cout << \"\\n[*] FINAL - Initial Values (log): \" << optParams.transpose() << std::endl;\n //std::cout << \"[*] FINAL - Initial Values (std): \" << optParams.transpose().array().exp().matrix() << std::endl;\n //start = high_resolution_clock::now();\n minimize::cg_minimize(optParams, this, g, length, SIG, EXT, INT, MAX);\n //end = high_resolution_clock::now();\n //time_minimize += getTime(start, end);\n\n}\n*/\n", "meta": {"hexsha": "51ff66542e3ddb6825a771d947cdd17b22525d6b", "size": 20789, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "misc/TEST_CODE/Two_Dimensional/GPs.cpp", "max_stars_repo_name": "nw2190/CppGPs", "max_stars_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2019-06-14T02:16:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-11T16:22:49.000Z", "max_issues_repo_path": "misc/TEST_CODE/Two_Dimensional/GPs.cpp", "max_issues_repo_name": "nw2190/CppGPs", "max_issues_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2020-05-10T07:40:50.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-10T07:40:50.000Z", "max_forks_repo_path": "misc/TEST_CODE/Two_Dimensional/GPs.cpp", "max_forks_repo_name": "nw2190/CppGPs", "max_forks_repo_head_hexsha": "eb707e54dff274596238310a654a715930d62214", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2019-08-12T15:07:18.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-07T12:44:46.000Z", "avg_line_length": 29.7836676218, "max_line_length": 191, "alphanum_fraction": 0.6318726249, "num_tokens": 5804, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314647623016, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6501593467674481}} {"text": "#include \n#include \n#include \n\n#include \"GeometryDerivatives.h\"\n#include \"MeshConnectivity.h\"\n\nEigen::Matrix3d crossMatrix(Eigen::Vector3d v)\n{\n Eigen::Matrix3d ret;\n ret << 0, -v[2], v[1],\n v[2], 0, -v[0],\n -v[1], v[0], 0;\n return ret;\n}\n\nEigen::Matrix2d adjugate(Eigen::Matrix2d M)\n{\n Eigen::Matrix2d ret;\n ret << M(1, 1), -M(0, 1), -M(1, 0), M(0, 0);\n return ret;\n}\n\ndouble angle(const Eigen::Vector3d& v, const Eigen::Vector3d& w, const Eigen::Vector3d& axis,\n Eigen::Matrix* derivative, // v, w, a\n Eigen::Matrix* hessian\n)\n{\n double theta = 2.0 * atan2((v.cross(w).dot(axis) / axis.norm()), v.dot(w) + v.norm() * w.norm());\n\n if (derivative)\n {\n derivative->segment<3>(0) = -axis.cross(v) / v.squaredNorm() / axis.norm();\n derivative->segment<3>(3) = axis.cross(w) / w.squaredNorm() / axis.norm();\n derivative->segment<3>(6).setZero();\n }\n if (hessian)\n {\n hessian->setZero();\n hessian->block<3, 3>(0, 0) += 2.0 * (axis.cross(v)) * v.transpose() / v.squaredNorm() / v.squaredNorm() / axis.norm();\n hessian->block<3, 3>(3, 3) += -2.0 * (axis.cross(w)) * w.transpose() / w.squaredNorm() / w.squaredNorm() / axis.norm();\n hessian->block<3, 3>(0, 0) += -crossMatrix(axis) / v.squaredNorm() / axis.norm();\n hessian->block<3, 3>(3, 3) += crossMatrix(axis) / w.squaredNorm() / axis.norm();\n\n Eigen::Matrix3d dahat = (Eigen::Matrix3d::Identity() / axis.norm() - axis * axis.transpose() / axis.norm() / axis.norm() / axis.norm());\n\n hessian->block<3, 3>(0, 6) += crossMatrix(v) * dahat / v.squaredNorm();\n hessian->block<3, 3>(3, 6) += -crossMatrix(w) * dahat / w.squaredNorm();\n }\n\n return theta;\n}\n\nEigen::Vector3d faceNormal(const MeshConnectivity &mesh,\n const Eigen::MatrixXd &curPos,\n int face, int startidx,\n Eigen::Matrix *derivative,\n std::vector > *hessian)\n{\n if (derivative)\n derivative->setZero();\n\n if (hessian)\n {\n hessian->resize(3);\n for (int i = 0; i < 3; i++) (*hessian)[i].setZero();\n }\n\n int v0 = startidx % 3;\n int v1 = (startidx + 1) % 3;\n int v2 = (startidx + 2) % 3;\n Eigen::Vector3d qi0 = curPos.row(mesh.faceVertex(face, v0)).transpose();\n Eigen::Vector3d qi1 = curPos.row(mesh.faceVertex(face, v1)).transpose();\n Eigen::Vector3d qi2 = curPos.row(mesh.faceVertex(face, v2)).transpose();\n Eigen::Vector3d n = (qi1 - qi0).cross(qi2 - qi0);\n\n if (derivative)\n {\n derivative->block<3, 3>(0, 0) += crossMatrix(qi2 - qi1);\n derivative->block<3, 3>(0, 3) += crossMatrix(qi0 - qi2);\n derivative->block<3, 3>(0, 6) += crossMatrix(qi1 - qi0);\n }\n\n if (hessian)\n {\n for (int j = 0; j < 3; j++)\n {\n Eigen::Vector3d ej(0, 0, 0);\n ej[j] = 1.0;\n Eigen::Matrix3d ejc = crossMatrix(ej);\n (*hessian)[j].block<3, 3>(0, 3) -= ejc;\n (*hessian)[j].block<3, 3>(0, 6) += ejc;\n (*hessian)[j].block<3, 3>(3, 6) -= ejc;\n (*hessian)[j].block<3, 3>(3, 0) += ejc;\n (*hessian)[j].block<3, 3>(6, 0) -= ejc;\n (*hessian)[j].block<3, 3>(6, 3) += ejc;\n }\n }\n\n return n;\n}\n\ndouble triangleAltitude(const MeshConnectivity &mesh,\n const Eigen::MatrixXd &curPos,\n int face,\n int edgeidx,\n Eigen::Matrix *derivative,\n Eigen::Matrix *hessian)\n{\n if (derivative)\n derivative->setZero();\n if (hessian)\n hessian->setZero();\n\n Eigen::Matrix nderiv;\n std::vector > nhess;\n Eigen::Vector3d n = faceNormal(mesh, curPos, face, edgeidx, (derivative || hessian ? &nderiv : NULL), hessian ? &nhess : NULL);\n\n int v2 = (edgeidx + 2) % 3;\n int v1 = (edgeidx + 1) % 3;\n Eigen::Vector3d q2 = curPos.row(mesh.faceVertex(face, v2)).transpose();\n Eigen::Vector3d q1 = curPos.row(mesh.faceVertex(face, v1)).transpose();\n\n Eigen::Vector3d e = q2 - q1;\n double nnorm = n.norm();\n double enorm = e.norm();\n double h = nnorm / enorm;\n\n if (derivative)\n {\n for (int i = 0; i < 3; i++)\n {\n *derivative += nderiv.row(i) * n[i] / nnorm / enorm;\n }\n derivative->block(0, 6, 1, 3) += -nnorm / enorm / enorm / enorm * e.transpose();\n derivative->block(0, 3, 1, 3) += nnorm / enorm / enorm / enorm * e.transpose();\n }\n\n if (hessian)\n {\n for (int i = 0; i < 3; i++)\n {\n *hessian += nhess[i] * n[i] / nnorm / enorm;\n }\n\n Eigen::Matrix3d idMat = Eigen::Matrix3d::Identity();\n\n Eigen::Matrix3d P = idMat / nnorm - n*n.transpose() / nnorm / nnorm / nnorm;\n *hessian += nderiv.transpose() * P * nderiv / enorm;\n hessian->block<3, 9>(6, 0) += -e * n.transpose() * nderiv / nnorm / enorm / enorm / enorm;\n hessian->block<3, 9>(3, 0) += e * n.transpose() * nderiv / nnorm / enorm / enorm / enorm;\n hessian->block<9, 3>(0, 6) += -nderiv.transpose() * n * e.transpose() / nnorm / enorm / enorm / enorm;\n hessian->block<9, 3>(0, 3) += nderiv.transpose() * n * e.transpose() / nnorm / enorm / enorm / enorm;\n hessian->block<3, 3>(6, 6) += -nnorm / enorm / enorm / enorm * idMat;\n hessian->block<3, 3>(6, 3) += nnorm / enorm / enorm / enorm * idMat;\n hessian->block<3, 3>(3, 6) += nnorm / enorm / enorm / enorm * idMat;\n hessian->block<3, 3>(3, 3) += -nnorm / enorm / enorm / enorm * idMat;\n\n Eigen::Matrix3d outer = e*e.transpose() * 3.0 * nnorm / enorm / enorm / enorm / enorm / enorm;\n hessian->block(6, 6, 3, 3) += outer;\n hessian->block(6, 3, 3, 3) += -outer;\n hessian->block(3, 6, 3, 3) += -outer;\n hessian->block(3, 3, 3, 3) += outer;\n }\n\n return h;\n}\n\nEigen::Matrix2d firstFundamentalForm(\n const MeshConnectivity &mesh,\n const Eigen::MatrixXd &curPos,\n int face,\n Eigen::Matrix *derivative, // F(face, i)\n std::vector > *hessian)\n{\n Eigen::Vector3d q0 = curPos.row(mesh.faceVertex(face, 0));\n Eigen::Vector3d q1 = curPos.row(mesh.faceVertex(face, 1));\n Eigen::Vector3d q2 = curPos.row(mesh.faceVertex(face, 2));\n Eigen::Matrix2d result;\n result << (q1 - q0).dot(q1 - q0), (q1 - q0).dot(q2 - q0),\n (q2 - q0).dot(q1 - q0), (q2 - q0).dot(q2 - q0);\n\n if (derivative)\n {\n derivative->setZero();\n derivative->block<1, 3>(0, 3) += 2.0 * (q1 - q0).transpose();\n derivative->block<1, 3>(0, 0) -= 2.0 * (q1 - q0).transpose();\n derivative->block<1, 3>(1, 6) += (q1 - q0).transpose();\n derivative->block<1, 3>(1, 3) += (q2 - q0).transpose();\n derivative->block<1, 3>(1, 0) += -(q1 - q0).transpose() - (q2 - q0).transpose();\n derivative->block<1, 3>(2, 6) += (q1 - q0).transpose();\n derivative->block<1, 3>(2, 3) += (q2 - q0).transpose();\n derivative->block<1, 3>(2, 0) += -(q1 - q0).transpose() - (q2 - q0).transpose();\n derivative->block<1, 3>(3, 6) += 2.0 * (q2 - q0).transpose();\n derivative->block<1, 3>(3, 0) -= 2.0 * (q2 - q0).transpose();\n }\n\n if (hessian)\n {\n hessian->resize(4);\n for (int i = 0; i < 4; i++)\n {\n (*hessian)[i].setZero();\n }\n Eigen::Matrix3d I = Eigen::Matrix3d::Identity();\n (*hessian)[0].block<3, 3>(0, 0) += 2.0*I;\n (*hessian)[0].block<3, 3>(3, 3) += 2.0*I;\n (*hessian)[0].block<3, 3>(0, 3) -= 2.0*I;\n (*hessian)[0].block<3, 3>(3, 0) -= 2.0*I;\n\n (*hessian)[1].block<3, 3>(3, 6) += I;\n (*hessian)[1].block<3, 3>(6, 3) += I;\n (*hessian)[1].block<3, 3>(0, 3) -= I;\n (*hessian)[1].block<3, 3>(0, 6) -= I;\n (*hessian)[1].block<3, 3>(3, 0) -= I;\n (*hessian)[1].block<3, 3>(6, 0) -= I;\n (*hessian)[1].block<3, 3>(0, 0) += 2.0*I;\n\n (*hessian)[2].block<3, 3>(3, 6) += I;\n (*hessian)[2].block<3, 3>(6, 3) += I;\n (*hessian)[2].block<3, 3>(0, 3) -= I;\n (*hessian)[2].block<3, 3>(0, 6) -= I;\n (*hessian)[2].block<3, 3>(3, 0) -= I;\n (*hessian)[2].block<3, 3>(6, 0) -= I;\n (*hessian)[2].block<3, 3>(0, 0) += 2.0*I;\n\n (*hessian)[3].block<3, 3>(0, 0) += 2.0*I;\n (*hessian)[3].block<3, 3>(6, 6) += 2.0*I;\n (*hessian)[3].block<3, 3>(0, 6) -= 2.0*I;\n (*hessian)[3].block<3, 3>(6, 0) -= 2.0*I;\n }\n\n return result;\n}\n", "meta": {"hexsha": "9b05a7ba10777b01147525d8db02c6b54a0c2e1c", "size": 8554, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "GeometryDerivatives.cpp", "max_stars_repo_name": "csyzzkdcz/effective-garbanzo", "max_stars_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "GeometryDerivatives.cpp", "max_issues_repo_name": "csyzzkdcz/effective-garbanzo", "max_issues_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "GeometryDerivatives.cpp", "max_forks_repo_name": "csyzzkdcz/effective-garbanzo", "max_forks_repo_head_hexsha": "87223ecfc26371a9b251a70a0111ca4e0d95b594", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.4, "max_line_length": 144, "alphanum_fraction": 0.5234977788, "num_tokens": 3158, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178994073575, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6500470427213318}} {"text": "/*=================================================================================\n *\t Copyleft! 2018 William Yu\n * Some rights reserved:CC(creativecommons.org)BY-NC-SA\n * Copyleft! 2018 William Yu\n * 版权部分所有,遵循CC(creativecommons.org)BY-NC-SA协议授权方式使用\n *\n * Filename : \n * Description : 视觉SLAM十四讲/ch3/useGeometry/eigenGeometry.cpp 学习记录\n\t\t\t\t\t\t\t\t矩阵库 \n * Reference : \n * Programmer(s) : William Yu, windmillyucong@163.com\n * Company : HUST, DMET国家重点实验室FOCUS团队\n * Modification History\t : ver1.0, 2018.03.26, William Yu\n \n=================================================================================*/\n/// Include Files\n#include \n#include \n#include \n// Eigen 几何模块\n#include \nusing namespace std;\n\n\n/// Global Variables\n\n\n\n/// Function Definitions\n\n\n/**\n * @function main\n * @author William Yu\n * @brief Eigen几何模块的使用方法\n * @param None\n * @retval None\n */\nint main ( int argc, char** argv )\n{\n //---------------------------------------------------------------------------\n // 旋转平移表示\n //----------------------------------------------------------------\n // Eigen/Geometry 几何模块提供了各种旋转和平移的表示\n // 3D 旋转矩阵直接使用 Matrix3d 或 Matrix3f\n Eigen::Matrix3d rotation_matrix = Eigen::Matrix3d::Identity();\n // 旋转向量使用 AngleAxis, 它底层不直接是Matrix,但运算可以当作矩阵(因为重载了运算符)\n Eigen::AngleAxisd rotation_vector ( M_PI/4, Eigen::Vector3d ( 0,0,1 ) ); //沿 Z 轴旋转 45 度\n cout .precision(3);\n cout<<\"rotation matrix =\\n\"<