{"text": "//\n// Created by Vlad Argunov on 03/01/2022.\n//\n\n#include \"Simulation.h\"\n\n#include \n#include \n#include \n#include \n\nEigen::VectorXd Simulation::generate_uniform_variable(int n) {\n std::random_device rd;\n std::mt19937 gen(rd());\n Eigen::VectorXd uniform_numbers;\n uniform_numbers.resize(n);\n std::uniform_real_distribution uniform(0.0, 1.0);\n for (int i = 0; i < n; ++i) {\n uniform_numbers(i) = uniform(gen);\n }\n return uniform_numbers;\n}\n\nEigen::VectorXd Simulation::generate_normal_variable(int n, double mu, double sigma) {\n std::random_device rd;\n std::mt19937 gen(rd());\n Eigen::VectorXd normal_numbers;\n normal_numbers.resize(n);\n std::normal_distribution<> normal{mu,sigma};\n for (int i = 0; i < n; ++i) {\n normal_numbers(i) = normal(gen);\n }\n return normal_numbers;\n}\n\nEigen::MatrixXd Simulation::generate_gbm(int n_processes, double tn, double stock_price, double mu, double sigma, int n_steps) {\n// Generates the matrix of Geometric brownian motions for each row and a time step for each column\n double time_step = tn / n_steps;\n Eigen::MatrixXd simulated_processes;\n Eigen::Index n_rows = n_processes;\n Eigen::Index n_cols = n_steps + 1;\n simulated_processes.resize(n_rows, n_cols);\n simulated_processes.leftCols(1) = Eigen::MatrixXd::Constant(n_rows, 1, stock_price);\n\n Eigen::VectorXd normal_rv;\n normal_rv.resize(n_processes);\n for (int col = 0; col < n_cols - 1; ++col) {\n normal_rv = generate_normal_variable(n_processes, 0, 1);\n for (int row = 0; row < n_rows; ++row) {\n simulated_processes(row, col + 1) = simulated_processes(row, col)\n * exp(mu - 0.5 * sigma * sigma * time_step + sigma * sqrt(time_step) * normal_rv(row) );\n }\n\n }\n\n return simulated_processes;\n}\n\nstd::tuple\nSimulation::generate_heston_process(int n_processes, double tn, double stock_price, double mu, double variance,\n double kappa, double theta, double sigma, double rho, int n_steps) {\n // Generates the matrix of Heston processes for each row and a time step for each column\n // Here variance is the starting value_matrix of the volatility, theta is the long-term level,\n // kappa is the speed of convergence, and sigma is the volatility of volatility\n double time_step = tn / n_steps;\n Eigen::MatrixXd simulated_stock_processes, simulated_var_process;\n Eigen::Index n_rows = n_processes;\n Eigen::Index n_cols = n_steps + 1;\n\n simulated_stock_processes.resize(n_rows, n_cols);\n simulated_var_process.resize(n_rows, n_cols);\n\n simulated_stock_processes.leftCols(1) = Eigen::MatrixXd::Constant(n_rows, 1, stock_price);\n simulated_var_process.leftCols(1) = Eigen::MatrixXd::Constant(n_rows, 1, variance);\n\n Eigen::VectorXd normal_rv1, normal_rv2;\n normal_rv1.resize(n_processes);\n normal_rv2.resize(n_processes);\n for (int col = 0; col < n_cols - 1; ++col) {\n normal_rv1 = generate_normal_variable(n_processes, 0, 1);\n for (int row = 0; row < n_rows; ++row) {\n simulated_var_process(row, col + 1) = simulated_var_process(row, col) +\n kappa * (theta - simulated_var_process(row, col)) * time_step\n + sigma * sqrt(simulated_var_process(row, col) * time_step)\n * (rho * normal_rv1(row) + sqrt(1 - rho * rho) * normal_rv2(row));\n\n\n simulated_stock_processes(row, col + 1) = simulated_stock_processes(row, col) * (1 + mu * time_step)\n + simulated_stock_processes(row, col) * sqrt(simulated_var_process(row, col) * time_step) * normal_rv1(row);\n }\n\n }\n return {simulated_stock_processes, simulated_var_process};\n}\n", "meta": {"hexsha": "ed8277dfdfd6d2871ce4b189f3d83cda411f7b0f", "size": 3956, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Simulation.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/Simulation.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/Simulation.cpp", "max_forks_repo_name": "vladargunov/QuantKit", "max_forks_repo_head_hexsha": "858f58f6ed6f3ed2b55a618639bcbb82e9ef5bb9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.6421052632, "max_line_length": 128, "alphanum_fraction": 0.6481294237, "num_tokens": 954, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891392358015, "lm_q2_score": 0.7905303137346446, "lm_q1q2_score": 0.6499654381892955}} {"text": "#include \n\n#include \n\n#include \"LSLOpt/BFGS.hpp\"\n\n\nstruct Parabola {\n double value(const Eigen::VectorXd& x)\n {\n return x.dot(x);\n }\n\n Eigen::VectorXd gradient(const Eigen::VectorXd& x)\n {\n return 2 * x;\n }\n\n double initial_step_length(const Eigen::VectorXd& x, const Eigen::VectorXd& p)\n {\n double max_change = p.array().abs().maxCoeff();\n\n return 0.2 / max_change;\n }\n\n double change_acceptable(const Eigen::VectorXd& x, const Eigen::VectorXd& xp) {\n return (xp - x).array().abs().maxCoeff() - (0.2 + 1e-6);\n }\n};\n\n\nint main()\n{\n Parabola parabola;\n Eigen::VectorXd x0 = Eigen::VectorXd::Constant(2, 1.0);\n LSLOpt::OptimizationParameters params\n = LSLOpt::getOptimizationParameters();\n LSLOpt::OstreamOutput output{LSLOpt::OutputLevel::Status, std::cerr};\n\n auto result = LSLOpt::lsl_bfgs(parabola, x0, params, output);\n\n std::cout << \"STATUS \" << result.status << std::endl;\n std::cout << \"F \" << result.function_value << std::endl;\n std::cout << \"X \" << result.x << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "f1fd6996b2be61b08c6cac9d8e1cd05651698ec8", "size": 1116, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/Examples/Example.cpp", "max_stars_repo_name": "flachsenberg/LSLOpt", "max_stars_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-03-18T02:42:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-15T14:09:06.000Z", "max_issues_repo_path": "src/Examples/Example.cpp", "max_issues_repo_name": "flachsenberg/LSLOpt", "max_issues_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Examples/Example.cpp", "max_forks_repo_name": "flachsenberg/LSLOpt", "max_forks_repo_head_hexsha": "20dd15b343e117a6b129e3bdeea2ea02f5d7c829", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-03-08T12:12:51.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-08T12:12:51.000Z", "avg_line_length": 23.25, "max_line_length": 83, "alphanum_fraction": 0.6245519713, "num_tokens": 323, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297914570319, "lm_q2_score": 0.7217432122827968, "lm_q1q2_score": 0.6499512644425554}} {"text": "#include \"NMatrixOperations.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define print(something) {std::stringstream ss; ss << something; qDebug() << ss.str().c_str(); }\n\n// This was based on https://ef.gy/linear-algebra:normal-vectors-in-higher-dimensional-spaces\nEigen::VectorXd getNormalVector(Eigen::MatrixXd vectors) {\n\tassert(vectors.rows() == vectors.cols() + 1);\n\tconst unsigned int N = vectors.rows();\n\n\tEigen::MatrixXd pM = vectors.transpose();\n\tpM.conservativeResize(pM.rows() + 1, Eigen::NoChange);\n\tpM.row(N - 1) = Eigen::VectorXd::Zero(N);\n\tEigen::MatrixXd baseVectors = Eigen::MatrixXd::Identity(N, N);\n\n\tEigen::VectorXd result = Eigen::VectorXd::Zero(N);\n\n\tint signal = 1;\n\tfor (unsigned int i = 0; i < N; i++) {\n\t\tEigen::MatrixXd pS(N - 1, N - 1);\n\n\t\tfor (unsigned int j = 0; j < (N - 1); j++) {\n\t\t\tpS.block(j, 0, 1, i) = pM.block(j, 0, 1, i);\n\t\t\tpS.block(j, i, 1, N - i - 1) = pM.block(j, i + 1, 1, N - i - 1);\n\t\t}\n\t\t\n\t\tresult += signal * baseVectors.row(i) * pS.determinant();\n\t\tsignal *= -1;\n\t}\n\n\treturn result;\n}\n\nEigen::MatrixXd translateMatrixN(int N, Eigen::VectorXd point) {\n\tassert(N > 0);\n\n\tEigen::MatrixXd m = Eigen::MatrixXd::Identity(N + 1, N + 1);\n\tm.topRightCorner(N, 1) = point;\n\treturn m;\n}\n\n// This was based on https://ef.gy/linear-algebra:perspective-projections\n// However, he makes this in a different way than every other LookAt I could find\n// Therefor it has been silightly adjusted to conform to the others\nEigen::MatrixXd lookAtMatrixN(const int N, Eigen::VectorXd from, Eigen::VectorXd to, Eigen::MatrixXd ups) {\n\tassert(N > 2);\n\n\t//print(\"LookAt Double Calculation:\");\n\t//print(\"FROM:\");\n\t//print(from.transpose());\n\t//print(\"TO:\");\n\t//print(to.transpose());\n\t//print(\"UPS\");\n\t//print(ups);\n\n\tEigen::MatrixXd m(N, N);\n\n\tm.rightCols(1) = (to - from).normalized();\n\n\tint numLoops = 0;\n\tfor (int currentColumn = N - 2; currentColumn > 0; currentColumn--) {\n\t\tEigen::MatrixXd vectorsToCross(N, N - 1);\n\t\tint currentColumnOnVectorsToCross = 1;\n\n\t\t//First, cross product all ups, in order\n\t\tvectorsToCross.col(0) = ups.col(numLoops);\n\t\tfor (int i = 1; i < currentColumn; i++) {\n\t\t\tvectorsToCross.col(currentColumnOnVectorsToCross) = ups.col(numLoops + i);\n\t\t\tcurrentColumnOnVectorsToCross++;\n\t\t}\n\n\t\tnumLoops++;\n\t\tfor (int i = 0; i < numLoops; i++) {\n\t\t\tvectorsToCross.col(currentColumnOnVectorsToCross) = m.col(currentColumn + i + 1);\n\t\t\tcurrentColumnOnVectorsToCross++;\n\t\t}\n\n\t\t//print(\"vectorsToCross\\n\" << vectorsToCross << \"\\n\");\n\n\t\tauto normal = getNormalVector(vectorsToCross);\n\t\t//print(\"Normal:\\n\" << normal << \"\\n\");\n\t\t//print(\"Normal Normalized:\\n\" << normal.normalized() << \"\\n\");\n\n\t\tm.col(currentColumn) = normal.normalized();\n\n\t\t//print(\"Current Matrix:\\n\" << m << \"\\n\");\n\t}\n\n\tm.col(0) = getNormalVector(m.rightCols(N - 1)).normalized();\n\n\t//print(\"m\");\n\t//print(m);\n\n\tEigen::MatrixXd temp = Eigen::MatrixXd::Identity(N + 1, N + 1);\n\t//m.leftCols(N - 1).rowwise().reverseInPlace();\n\ttemp.topLeftCorner(N, N) = m;\n\n\treturn temp.transpose();\n}\n\nEigen::MatrixXd perspectiveMatrixN(const int N, double eye_radians_angle, double nearPlane, double farPlane, double aspectRatio) {\n\tassert(N > 2);\n\n\tif (N == 3) {\n\t\tEigen::MatrixXd m = Eigen::MatrixXd::Zero(N + 1, N + 1);\n\n\t\tdouble f_tan = 1 / tan(eye_radians_angle / 2);\n\t\tm(0, 0) = f_tan / aspectRatio;\n\t\tm(1, 1) = f_tan;\n\t\tm(2, 2) = (nearPlane + farPlane) / (nearPlane - farPlane);\n\t\tm(2, 3) = -1.f;\n\t\tm(3, 2) = 2 * (nearPlane*farPlane) / (nearPlane - farPlane);\n\n\t\treturn m.transpose();\n\t}\n\telse {\n\t\tEigen::MatrixXd m = Eigen::MatrixXd::Identity(N + 1, N + 1);\n\n\t\tdouble f_tan = 1 / tan(eye_radians_angle / 2);\n\t\tm = m*f_tan;\n\t\tm(N - 1, N - 1) = 1;\n\t\tm(N, N) = 1;\n\n\t\treturn m;\n\t}\n}\n\n// N > 3\nEigen::MatrixXd viewMatrixN(\n\tconst int N,\n\tEigen::VectorXd from,\n\tEigen::VectorXd to,\n\tEigen::MatrixXd ups,\n\tdouble eyeRadiansAngle,\n\tdouble nearPlane,\n\tdouble farPlane,\n\tdouble aspectRatio) {\n\n\tauto tr = translateMatrixN(N, -from);\n\n\tauto la = lookAtMatrixN(N, from, to, ups);\n\n\tauto pm = perspectiveMatrixN(N, eyeRadiansAngle, nearPlane, farPlane, aspectRatio);\n\n\tEigen::MatrixXd result = pm * la * tr;\n\t\n\t//Axis direction correction\n\tEigen::MatrixXd aux = Eigen::MatrixXd::Identity(N + 1, N + 1);\n\t//X correction\n\taux(0, 0) = -1;\n\t//Z correction\n\taux(2, 2) = N != 4 ? -1 : 1;\n\tresult = aux * result;\n\n\t//Z correction\n\t\n\treturn result;\n}\n\n//This assumes that point is an N+1 dimensional vector and that point(N) == 1\nEigen::VectorXd projectPointLosingDimension(Eigen::VectorXd point, Eigen::MatrixXd m) {\n\t//std::cout << \"point\\n\" << point << \"\\n\";\n\n\tEigen::VectorXd pointWith1(point.rows() + 1);\n\tpointWith1.topRightCorner(point.rows(), 1) = point;\n\tpointWith1(point.rows()) = 1;\n\n\t//std::cout << \"pointWith1\\n\" << pointWith1 << \"\\n\";\n\n\tEigen::VectorXd v = m * pointWith1;\n\t//std::cout << \"v\\n\" << v << \"\\n\";\n\tv = v / v(v.rows() - 2, 0);\n\t//std::cout << \"v\\n\" << v << \"\\n\";\n\tauto result = v.topLeftCorner(v.rows() - 1, 1);\n\t//std::cout << \"result\\n\" << result << \"\\n\";\n\n\treturn result;\n}\n\n//This assumes that each point is an N+1 dimensional column in a matrix and that point(N) == 1\nEigen::MatrixXd projectPointsLosingDimension(Eigen::MatrixXd points, Eigen::MatrixXd m, bool usePerspective) {\n\t//std::cout << \"point\\n\" << points << \"\\n\";\n\n\tEigen::MatrixXd pointWith1(points.rows() + 1, points.cols());\n\tpointWith1.topRightCorner(points.rows(), points.cols()) = points;\n\tpointWith1.row(points.rows()) = Eigen::VectorXd::Ones(points.cols());\n\n\t//std::cout << \"pointWith1\\n\" << pointWith1 << \"\\n\";\n\n\tEigen::MatrixXd v = m * pointWith1;\n\t//std::cout << \"v\\n\" << v << \"\\n\";\n\n\tif (usePerspective) {\n\t\tfor (int i = 0; i < v.cols(); i++) {\n\t\t\tif (v.col(i)(v.rows() - 2, 0) == 0 || v.col(i)(v.rows() - 2, 0) == -0) {\n\t\t\t\tv.col(i) = v.col(i) / (0.000001);\n\t\t\t} else {\n\t\t\t\tv.col(i) = v.col(i) / v.col(i)(v.rows() - 2, 0);\n\t\t\t}\n\t\t}\n\t}else{\n\t\tfor (int i = 0; i < v.cols(); i++) {\n\t\t\tif (v.col(i)(v.rows() - 1, 0) == 0 || v.col(i)(v.rows() - 1, 0) == -0) {\n\t\t\t\tv.col(i) = v.col(i) / (0.000001);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tv.col(i) = v.col(i) / v.col(i)(v.rows() - 1, 0);\n\t\t\t}\n\t\t}\n\t}\n\n\tEigen::MatrixXd result = v.topRows(v.rows() - 2);\n\n\treturn result;\n}\n\nEigen::MatrixXd rotateMatrixN(const unsigned int N, unsigned int axis1, unsigned int axis2, double radians_angle) {\n\tassert(axis1 != axis2);\n\n\tEigen::MatrixXd rot_aa = Eigen::MatrixXd::Identity(N, N);\n\n\trot_aa(axis1, axis1) = cos(radians_angle);\n\trot_aa(axis1, axis2) = sin(radians_angle);\n\trot_aa(axis2, axis1) = -sin(radians_angle);\n\trot_aa(axis2, axis2) = cos(radians_angle);\n\n\treturn rot_aa.transpose();\n}\n\nstd::string generateNDimensionalShader(int n) {\n\tstd::stringstream ss;\n\tss << \"#version 330 core\\nlayout (location = 0) in double[\" << n << \"] position;\\n\";\n\n\tfor (int i = n; i >= 3; i--) {\n\t\tss << \"uniform double m\" << i << \"[\" << ((i + 1) * (i + 1)) << \"];\\n\";\n\t}\n\n\tss << \"\\nvoid main() {\\n\";\n\n\tss << \"\tdouble[\" << (n + 1) << \"] positionWithOne;\\n\";\n\tss << \"\tfor (int i = 0; i < \" << n << \"; i++){\\n\";\n\tss << \"\t\tpositionWithOne[i] = position[i];\\n\";\n\tss << \"\t}\\n\";\n\tss << \"\tpositionWithOne[\" << n << \"] = 1;\\n\\n\";\n\n\tss << \"\tdouble[\" << (n + 1) << \"] newPos\" << n << \";\\n\";\n\n\tfor (int i = n; i >= 3; i--) {\n\t\tss << \"\tfor (int i = 0; i <= \" << i << \"; i++) {\\n\";\n\t\tss << \"\t\tdouble newVal = 0;\\n\";\n\t\tss << \"\t\tfor (int j = 0; j <= \" << i << \"; j++){\\n\";\n\t\tss << \"\t\t\tnewVal += m\" << i << \"[j * \" << i << \" + i] * positionWithOne[j];\\n\";\n\t\tss << \"\t\t}\\n\";\n\t\tss << \"\t\tnewPos\" << i << \"[i] = newVal;\\n\";\n\t\tss << \"\t}\\n\";\n\t\tss << \"\t\\n\";\n\t\tif (i != 3) {\n\t\t\tss << \"\tfor (int i = 0; i < \" << i << \"; i++) {\\n\";\n\t\t\tss << \"\t\tpositionWithOne[i] = newPos\" << i << \"[i] / newPos\" << i << \"[\" << (i - 1) << \"];\\n\";\n\t\t\tss << \"\t}\\n\";\n\t\t\tss << \"\t\\n\";\n\t\t\tss << \"\tdouble[\" << i << \"] newPos\" << i - 1 << \";\\n\";\n\t\t}\n\t}\n\n\tss << \"\tgl_Position.x = newPos3[0]/newPos3[3];\\n\";\n\tss << \"\tgl_Position.y = newPos3[1]/newPos3[3];\\n\";\n\tss << \"\tgl_Position.z = newPos3[2]/newPos3[3];\\n\";\n\tss << \"\tgl_Position.w = newPos3[3]/newPos3[3];\\n\";\n\tss << \"}\\n\";\n\n\tstd::string str = ss.str();\n\treturn str;\n}\n\nEigen::MatrixXd makeVectorsHomogeneous(Eigen::MatrixXd points) {\n\tpoints.conservativeResize(points.rows() + 1, Eigen::NoChange);\n\tpoints.row(points.rows() - 1) = Eigen::VectorXd::Ones(points.cols());\n\n\treturn points;\n}\n\nEigen::MatrixXd makeMatrixHomogeneous(Eigen::MatrixXd matrix) {\n\tmatrix.conservativeResize(matrix.rows() + 1, matrix.cols() + 1);\n\tmatrix.row(matrix.rows() - 1) = Eigen::VectorXd::Zero(matrix.cols());\n\tmatrix.col(matrix.cols() - 1) = Eigen::VectorXd::Zero(matrix.rows());\n\tmatrix(matrix.rows() - 1, matrix.cols() - 1) = 1;\n\n\treturn matrix;\n}\n\n#define print(something) {std::stringstream ss; ss << something; qDebug() << ss.str().c_str(); }\n\nEigen::MatrixXd rotateShapeToLowerDimension(Eigen::MatrixXd m) {\n\tconst int D = m.rows();\n\n\t// First we move the first vertex of the shape to the origin\n\tm = translateMatrixN(D, -m.col(0).cast()).cast() * makeVectorsHomogeneous(m);\n\tm.conservativeResize(m.rows() - 1, Eigen::NoChange);\n\n\t//Then, we find a new base created from the points of the polytope\n\t//And also a vector that is simply the last dimension\n\tEigen::MatrixXd newBase = Eigen::MatrixXd::Zero(D, D);\n\tint currentSizeBase = 1;;\n\t{\n\t\tEigen::VectorXd aux = Eigen::VectorXd::Zero(D);\n\t\taux(D - 1) = 1;\n\t\tnewBase.col(0) = aux;\n\n\t\tfor (int i = 0; i < m.cols() && currentSizeBase < 2; i++) {\n\t\t\tfor (int j = i + 1; j < m.cols() && currentSizeBase < 2; j++) {\n\t\t\t\tEigen::VectorXd newVectorOfBase = m.col(j) - m.col(i);\n\t\t\t\tnewVectorOfBase.normalize();\n\t\t\t\tif (newVectorOfBase(0) < 0) {\n\t\t\t\t\tnewVectorOfBase = newVectorOfBase * -1;\n\t\t\t\t}\n\n\t\t\t\tif (newVectorOfBase != newBase.col(0)) {\n\t\t\t\t\tnewBase.col(currentSizeBase) = newVectorOfBase;\n\t\t\t\t\tcurrentSizeBase++;\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (int i = 0; i < m.cols() && currentSizeBase < D; i++) {\n\t\tfor (int j = i + 1; j < m.cols() && currentSizeBase < D; j++) {\n\t\t\tEigen::VectorXd newVectorOfBase = m.col(j) - m.col(i);\n\t\t\tnewVectorOfBase.normalize();\n\t\t\tif (newVectorOfBase(0) < 0) {\n\t\t\t\tnewVectorOfBase = newVectorOfBase * -1;\n\t\t\t}\n\n\t\t\tEigen::VectorXd x = newBase.colPivHouseholderQr().solve(newVectorOfBase);\n\n\t\t\tEigen::VectorXd check = (newBase * x) - newVectorOfBase;\n\t\t\tdouble error = 0;\n\t\t\tfor (int k = 0; k < x.size(); k++) {\n\t\t\t\terror += check(k) * check(k);\n\t\t\t}\n\n\t\t\tif (error > 1e-5f) {\n\t\t\t\tnewBase.col(currentSizeBase) = newVectorOfBase;\n\t\t\t\tcurrentSizeBase++;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tif (currentSizeBase != newBase.cols()) {\n\t\tfor (int i = 0; i < newBase.rows(); i++) {\n\t\t\tif (newBase.row(i).isZero(1e-10)) {\n\t\t\t\tm.row(i) = m.row(m.rows() - 1);\n\t\t\t\treturn m.topRows(D - 1);\n\t\t\t}\n\t\t}\n\t} else {\n\t\t//We set the coordinate we want to exclude as the last one\n\t\tfor (int i = 0; i < D - 1; i++) {\n\t\t\tEigen::VectorXd aux = newBase.col(i);\n\t\t\tnewBase.col(i) = newBase.col(i + 1);\n\t\t\tnewBase.col(i + 1) = aux;\n\t\t}\n\n\t\t//We change the base\n\t\tEigen::MatrixXd transformationMatrix = newBase.inverse();\n\t\tEigen::MatrixXd newVertices = transformationMatrix * m;\n\n\t\t//Return only the top rows, excluding the last one\n\t\treturn newVertices.topRows(D - 1);\n\t}\n\n\treturn Eigen::MatrixXd(0, 0);\n}", "meta": {"hexsha": "d33b56966ffada110939078e244924f6d6b6b344", "size": 11142, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "TrueNgine/NMatrixOperations.cpp", "max_stars_repo_name": "GSBicalho/TrueNgine", "max_stars_repo_head_hexsha": "069ac9acc1558ae0b549e15eba67dfc646da9200", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2017-12-06T20:47:29.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-06T23:54:50.000Z", "max_issues_repo_path": "TrueNgine/NMatrixOperations.cpp", "max_issues_repo_name": "GSBicalho/TrueNgine", "max_issues_repo_head_hexsha": "069ac9acc1558ae0b549e15eba67dfc646da9200", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "TrueNgine/NMatrixOperations.cpp", "max_forks_repo_name": "GSBicalho/TrueNgine", "max_forks_repo_head_hexsha": "069ac9acc1558ae0b549e15eba67dfc646da9200", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2020-02-24T18:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-19T03:15:35.000Z", "avg_line_length": 29.3210526316, "max_line_length": 130, "alphanum_fraction": 0.6042003231, "num_tokens": 3673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9207896802383029, "lm_q2_score": 0.7057850402140659, "lm_q1q2_score": 0.6498795814956875}} {"text": "//\n//#include \n//#include \n//#include \n//#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nextern \"C\"\n{\n\tdouble randValue(double max, double min) {\n\t\t\treturn min + ((rand() / (double)RAND_MAX) * (max - min));\n\t}\n\n\t__declspec(dllexport) void cleanModel(double * model)\n\t{\n\t\tfree(model);\n\t}\n\n\t__declspec(dllexport) double * lineaire_model(int nbInput)\n\t{\n\t\tdouble * model = (double *)malloc((nbInput + 1) * sizeof(double));\n\t\tmodel[0] = 1;\n\n\t\tfor (int i = 1; i <= nbInput; ++i)\n\t\t{\n\t\t\tmodel[i] = randValue(1, -1);\n\t\t}\n\t\treturn model;\n\t}\n\n\t__declspec(dllexport) double classifyRegression(double* model, double* input, int inputSize)\n\t{\n\t\tdouble sum = model[0];\n\t\tfor (int i = 0; i < inputSize; ++i)\n\t\t{\n\t\t\tsum += model[i + 1] * input[i];\n\t\t}\n\t\treturn sum;\n\t}\n\n\t__declspec(dllexport) void regression(double* model, double* valueSend, int size, int inputSize, double* waitValue)\n\t{\n\t\tEigen::Matrix entry(size, inputSize + 1);\n\t\tEigen::Matrix waited(size, 1);\n\n\t\tfor (int i = 0; i < size; ++i)\n\t\t{\n\t\t\twaited(i, 0) = *waitValue;\n\t\t\t++waitValue;\n\t\t}\n\n\t\tfor (int i = 0; i < size; ++i)\n\t\t{\n\t\t\tentry(i, 0) = 1.0;\n\t\t\tfor (int j = 1; j < inputSize + 1; ++j)\n\t\t\t{\n\t\t\t\tentry(i, j) = *valueSend;\n\t\t\t\t++valueSend;\n\t\t\t}\n\t\t}\n\n\t\tEigen::MatrixXd transposedMatrix = entry.transpose();\n\t\tEigen::MatrixXd inverseMatrix = (transposedMatrix*entry).inverse();\n\t\tEigen::MatrixXd final = inverseMatrix*transposedMatrix;\n\t\tEigen::MatrixXd weight = final*waited;\n\n\t\tfor (int i = 0; i < weight.rows(); ++i)\n\t\t{\n\t\t\t*model = weight(i, 0);\n\t\t\t++model;\n\t\t}\n\t}\n}", "meta": {"hexsha": "ca668ab3a85c98e060f2fe715a30ddb9aed224e8", "size": 1796, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "linear regression/LinearRegressionCpp/ConsoleApplication1/Source.cpp", "max_stars_repo_name": "DamienBidaud/machine_learning_esgi", "max_stars_repo_head_hexsha": "657aaa00957c29b4db74079b1dda96f3e70c2455", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear regression/LinearRegressionCpp/ConsoleApplication1/Source.cpp", "max_issues_repo_name": "DamienBidaud/machine_learning_esgi", "max_issues_repo_head_hexsha": "657aaa00957c29b4db74079b1dda96f3e70c2455", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear regression/LinearRegressionCpp/ConsoleApplication1/Source.cpp", "max_forks_repo_name": "DamienBidaud/machine_learning_esgi", "max_forks_repo_head_hexsha": "657aaa00957c29b4db74079b1dda96f3e70c2455", "max_forks_repo_licenses": ["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.1728395062, "max_line_length": 116, "alphanum_fraction": 0.6319599109, "num_tokens": 573, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587875995482, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.649734730799777}} {"text": "#include\n#include\n#include\n#include \n\nconst int X=0;\nconst int O2=1;\nconst int G=2;\nconst int Xy=3;\nconst int A=4;\nconst int B=5;\n\nvoid get_rhs(std::vector& rhs,std::vector solnvec,double t,int nvars)\n{\n // ------- MODEL CONSTANTS -------\n double y_xs = 0.009;\n double y_as = 1.01;\n double y_bs = 0.88;\n double y_os = 0.0467;\n\n double x_max = 11;\n double qs_max = 17;\n double o2_max = 0.214;\n\n double K_e = 0.0214;\n double K_s = 31;\n\n double alpha_s = 3;\n double beta_s = 12;\n double alpha_e = 1;\n double beta_e = 1e3;\n\n double kLa = 5;\n\n // calculate chi_i\n // A word of explanation about the form of the gamma incomplete call. This function\n // is usually expressed as g(a, x), where a and x are obligate positive. Therefore, we need\n // to restrict x to be no lower than 0. Additionally, we need to make sure we don't hit a\n // divide by zero error, so we condition use of the gamma function on the denominator being\n // non-zero.\n double chi_s = 1;\n double chi_e = 1;\n\n if (solnvec[Xy]>1e-8) {\n double sRatio = std::max(solnvec[G]/(solnvec[Xy]), 0.0);\n chi_s = boost::math::gamma_p(alpha_s, beta_s*sRatio);\n }\n \n if (solnvec[A]>1e-8) {\n double eRatio = std::max(solnvec[O2]/(solnvec[A]), 0.0);\n chi_e = boost::math::gamma_p(alpha_e, beta_e*eRatio);\n }\n \n double chi_p = 0.3;\n\n // calculate q_s\n double F_s = (solnvec[G] + solnvec[Xy])/(solnvec[G] + solnvec[Xy] + K_s);\n double F_e = (solnvec[O2] + solnvec[A]/beta_e)/(solnvec[O2] + solnvec[A]/beta_e + K_e);\n double q_s = qs_max*F_s*F_e;\n\n // calculate intermediate rates\n double rar = chi_p*y_as*q_s*solnvec[X];\n double rbr = (1-chi_p)*y_bs*q_s*solnvec[X];\n\n double our = -chi_e*y_os*q_s*solnvec[X];\n double otr = kLa *(o2_max - solnvec[O2]);\n double rae = -(1-chi_e)*y_as*q_s*solnvec[X];\n double rbe = -rae;\n\n\n // calculate final rates\n rhs[X] = y_xs*q_s*solnvec[X]*(1 - solnvec[X]/x_max);\n //rhs[O2] = our+otr;\n rhs[02] = 0;\n rhs[G] = -chi_s *q_s*solnvec[X];\n rhs[Xy] = -(1-chi_s) *q_s*solnvec[X];\n rhs[A] = rar+rae;\n rhs[B] = rbr+rbe;\n\n}\n\ndouble get_our(std::vector solnvec,double t,int nvars)\n{\n // ------- MODEL CONSTANTS -------\n double y_os = 0.0467;\n\n double x_max = 11;\n double qs_max = 17;\n double o2_max = 0.214;\n\n double K_e = 0.0214;\n double K_s = 31;\n\n double alpha_s = 3;\n double beta_s = 12;\n double alpha_e = 1;\n double beta_e = 1e3;\n\n\n // calculate chi_i\n double chi_s = 1;\n double chi_e = 1;\n\n if (solnvec[Xy]>1e-8) {\n double sRatio = std::max(solnvec[G]/(solnvec[Xy]), 0.0);\n chi_s = boost::math::gamma_p(alpha_s, beta_s*sRatio);\n }\n \n if (solnvec[A]>1e-8) {\n double eRatio = std::max(solnvec[O2]/(solnvec[A]), 0.0);\n chi_e = boost::math::gamma_p(alpha_e, beta_e*eRatio);\n }\n \n double chi_p = 0.3;\n\n // calculate q_s\n double F_s = (solnvec[G] + solnvec[Xy])/(solnvec[G] + solnvec[Xy] + K_s);\n double F_e = (solnvec[O2] + solnvec[A]/beta_e)/(solnvec[O2] + solnvec[A]/beta_e + K_e);\n double q_s = qs_max*F_s*F_e;\n\n double our = -chi_e*y_os*q_s*solnvec[X];\n\n return our;\n}\n\n\n\nvoid advance(std::vector& solnvec,int nvars,double t_now,double t_adv,double dt)\n{\n double current_time=t_now;\n double final_time=t_now+t_adv;\n\n std::vector rhs(nvars);\n std::vector solnvec_n(nvars);\n\n while(current_time < final_time)\n {\n current_time += dt;\n\n //at current time level n\n solnvec_n=solnvec;\n\n //Doing RK23\n\n //stage 1\n get_rhs(rhs,solnvec,current_time,nvars);\n for(int i=0;i solnvec(nvars);\n\n\n double final_time=24.0;\n double advance_time=0.5;\n double current_time=0.0;\n double dt=advance_time/50.0;\n\n std::ofstream outfile(\"timehist.dat\");\n\n //set initial conditions\n solnvec[X] = 0.5;\n solnvec[O2] = 0.214;\n solnvec[G] = 500.0;\n solnvec[Xy] = 250.0;\n solnvec[A] = 0.0;\n solnvec[B] = 0.0;\n\n //write initial condition\n outfile<\n\n#include \"xregAssert.h\"\n#include \"xregRotUtils.h\"\n#include \"xregPointCloudUtils.h\"\n#include \"xregLandmarkMapUtils.h\"\n\nxreg::FrameTransform\nxreg::PairedPointRegi3D3D(const Pt3List& pts1, const Pt3List& pts2, const CoordScalar scale)\n{\n const size_type num_pts = pts1.size();\n xregASSERT(num_pts == pts2.size());\n\n FrameTransform xform = FrameTransform::Identity();\n\n // These calls are threaded\n const Pt3 cent1 = ComputeCentroid(pts1);\n const Pt3 cent2 = ComputeCentroid(pts2);\n\n // These calls are threaded\n const Pt3List pts1_prime = OffsetPoints(-cent1, pts1);\n const Pt3List pts2_prime = OffsetPoints(-cent2, pts2);\n\n CoordScalar s = scale;\n if (s <= 0)\n {\n s = 0;\n\n const CoordScalar s1 = SumOfNormsSquared(pts1_prime); // threaded\n\n if (std::abs(s1) > 1.0e-6)\n {\n const CoordScalar s2 = SumOfNormsSquared(pts2_prime); // threaded\n\n s = std::sqrt(s2 / s1);\n }\n }\n\n CoordScalar S[9];\n\n CoordScalar* S_dst = S;\n for (size_type i = 0; i < 3; ++i)\n {\n for (size_type j = 0; j < 3; ++j, ++S_dst)\n {\n // This call is threaded\n *S_dst = InnerProductAboutDimsOfPts(pts1_prime, pts2_prime, i, j);\n }\n }\n\n const CoordScalar S_xx = S[0];\n const CoordScalar S_xy = S[1];\n const CoordScalar S_xz = S[2];\n const CoordScalar S_yx = S[3];\n const CoordScalar S_yy = S[4];\n const CoordScalar S_yz = S[5];\n const CoordScalar S_zx = S[6];\n const CoordScalar S_zy = S[7];\n const CoordScalar S_zz = S[8];\n\n Mat4x4 N_matrix;\n N_matrix(0,0) = S_xx + S_yy + S_zz;\n N_matrix(0,1) = S_yz - S_zy;\n N_matrix(0,2) = S_zx - S_xz;\n N_matrix(0,3) = S_xy - S_yx;\n N_matrix(1,0) = N_matrix(0,1);\n N_matrix(1,1) = S_xx - S_yy - S_zz;\n N_matrix(1,2) = S_xy + S_yx;\n N_matrix(1,3) = S_zx + S_xz;\n N_matrix(2,0) = N_matrix(0,2);\n N_matrix(2,1) = N_matrix(1,2);\n N_matrix(2,2) = -S_xx + S_yy - S_zz;\n N_matrix(2,3) = S_yz + S_zy;\n N_matrix(3,0) = N_matrix(0,3);\n N_matrix(3,1) = N_matrix(1,3);\n N_matrix(3,2) = N_matrix(2,3);\n N_matrix(3,3) = -S_xx - S_yy + S_zz;\n\n Eigen::EigenSolver eig_dec(N_matrix, true);\n\n size_type max_index = 0;\n eig_dec.eigenvalues().real().maxCoeff(&max_index);\n xform.linear().matrix() = QuatToRotMat(eig_dec.eigenvectors().col(max_index).real());\n\n xform.linear().matrix() *= s;\n\n xform.matrix().block(0,3,3,1) = cent2 - (xform.linear() * cent1);\n \n return xform;\n}\n\nxreg::FrameTransform\nxreg::PairedPointRegi3D3D(const LandMap3& pts1, const LandMap3& pts2, const CoordScalar scale)\n{\n const auto corr_lists = CreateCorrespondencePointLists(pts1, pts2);\n\n return PairedPointRegi3D3D(std::get<0>(corr_lists), std::get<1>(corr_lists), scale);\n}\n\n", "meta": {"hexsha": "730951984b2ba2426388f80ab38c3b69b76534a7", "size": 3850, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "lib/regi/xregPairedPointRegi3D3D.cpp", "max_stars_repo_name": "rg2/xreg", "max_stars_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 30.0, "max_stars_repo_stars_event_min_datetime": "2020-09-29T18:36:13.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T09:25:13.000Z", "max_issues_repo_path": "lib/regi/xregPairedPointRegi3D3D.cpp", "max_issues_repo_name": "gaocong13/Orthopedic-Robot-Navigation", "max_issues_repo_head_hexsha": "bf36f7de116c1c99b86c9ba50f111c3796336af0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-10-09T01:21:27.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-10T15:39:44.000Z", "max_forks_repo_path": "lib/regi/xregPairedPointRegi3D3D.cpp", "max_forks_repo_name": "rg2/xreg", "max_forks_repo_head_hexsha": "c06440d7995f8a441420e311bb7b6524452843d3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2021-05-25T05:14:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-26T12:29:50.000Z", "avg_line_length": 30.5555555556, "max_line_length": 94, "alphanum_fraction": 0.6914285714, "num_tokens": 1232, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6496659803672258}} {"text": "// (C) Copyright Nick Thompson 2021.\n// (C) Copyright Matt Borland 2022.\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0. (See accompanying file\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if !__has_include(\"lodepng.h\")\n #error \"lodepng.h is required to run this example.\"\n#endif\n#include \"lodepng.h\"\n#include \n#include \n#include \n\n\n// In lodepng, the vector is expected to be row major, with the top row\n// specified first. Note that this is a bit confusing sometimes as it's more\n// natural to let y increase moving *up*.\nunsigned write_png(const std::string &filename,\n const std::vector &img, std::size_t width,\n std::size_t height) {\n unsigned error = lodepng::encode(filename, img, width, height,\n LodePNGColorType::LCT_RGBA, 8);\n if (error) {\n std::cerr << \"Error encoding png: \" << lodepng_error_text(error) << \"\\n\";\n }\n return error;\n}\n\n\n// Computes ab - cd.\n// See: https://pharr.org/matt/blog/2019/11/03/difference-of-floats.html\ntemplate \ninline Real difference_of_products(Real a, Real b, Real c, Real d)\n{\n Real cd = c * d;\n Real err = std::fma(-c, d, cd);\n Real dop = std::fma(a, b, -cd);\n return dop + err;\n}\n\ntemplate\nauto fifth_roots(std::complex z)\n{\n std::complex v = std::pow(z,4);\n std::complex dw = Real(5)*v;\n std::complex w = v*z - Real(1);\n return std::make_pair(w, dw);\n}\n\ntemplate\nauto g(std::complex z)\n{\n std::complex z2 = z*z;\n std::complex z3 = z*z2;\n std::complex z4 = z2*z2;\n std::complex w = z4*(z4 + Real(15)) - Real(16);\n std::complex dw = Real(4)*z3*(Real(2)*z4 + Real(15));\n return std::make_pair(w, dw);\n}\n\ntemplate\nstd::complex complex_newton(std::function,std::complex>(std::complex)> f, std::complex z)\n{\n // f(x(1+e)) = f(x) + exf'(x)\n bool close = false;\n do\n {\n auto [y, dy] = f(z);\n z -= y/dy;\n close = (abs(y) <= 1.4*std::numeric_limits::epsilon()*abs(z*dy));\n } while(!close);\n return z;\n}\n\ntemplate\nclass plane_pixel_map\n{\npublic:\n plane_pixel_map(int64_t image_width, int64_t image_height, Real xmin, Real ymin)\n {\n image_width_ = image_width;\n image_height_ = image_height;\n xmin_ = xmin;\n ymin_ = ymin;\n }\n\n std::complex to_complex(int64_t i, int64_t j) const {\n Real x = xmin_ + 2*abs(xmin_)*Real(i)/Real(image_width_ - 1);\n Real y = ymin_ + 2*abs(ymin_)*Real(j)/Real(image_height_ - 1);\n return std::complex(x,y);\n }\n\n std::pair to_pixel(std::complex z) const {\n Real x = z.real();\n Real y = z.imag();\n Real ii = (image_width_ - 1)*(x - xmin_)/(2*abs(xmin_));\n Real jj = (image_height_ - 1)*(y - ymin_)/(2*abs(ymin_));\n\n return std::make_pair(std::round(ii), std::round(jj));\n }\n\nprivate:\n int64_t image_width_;\n int64_t image_height_;\n Real xmin_;\n Real ymin_;\n};\n\nint main(int argc, char** argv)\n{\n using Real = double;\n using boost::math::tools::viridis;\n using std::sqrt;\n\n std::function(Real)> color_map = viridis;\n std::string requested_color_map = \"viridis\";\n if (argc == 2) {\n requested_color_map = std::string(argv[1]);\n if (requested_color_map == \"smooth_cool_warm\") {\n color_map = boost::math::tools::smooth_cool_warm;\n }\n else if (requested_color_map == \"plasma\") {\n color_map = boost::math::tools::plasma;\n }\n else if (requested_color_map == \"black_body\") {\n color_map = boost::math::tools::black_body;\n }\n else if (requested_color_map == \"inferno\") {\n color_map = boost::math::tools::inferno;\n }\n else if (requested_color_map == \"kindlmann\") {\n color_map = boost::math::tools::kindlmann;\n }\n else if (requested_color_map == \"extended_kindlmann\") {\n color_map = boost::math::tools::extended_kindlmann;\n }\n else {\n std::cerr << \"Could not recognize color map \" << argv[1] << \".\";\n return 1;\n }\n }\n constexpr int64_t image_width = 1024;\n constexpr int64_t image_height = 1024;\n constexpr const Real two_pi = 6.28318530718;\n\n std::vector img(4*image_width*image_height, 0);\n plane_pixel_map map(image_width, image_height, Real(-2), Real(-2));\n\n for (int64_t j = 0; j < image_height; ++j)\n {\n std::cout << \"j = \" << j << \"\\n\";\n for (int64_t i = 0; i < image_width; ++i)\n {\n std::complex z0 = map.to_complex(i,j);\n auto rt = complex_newton(g, z0);\n // The root is one of exp(2*pi*ij/5). Therefore, it can be classified by angle.\n Real theta = std::atan2(rt.imag(), rt.real());\n // Now theta in [-pi,pi]. Get it into [0,2pi]:\n if (theta < 0) {\n theta += two_pi;\n }\n theta /= two_pi;\n if (std::isnan(theta)) {\n std::cerr << \"Theta is a nan!\\n\";\n }\n auto c = boost::math::tools::to_8bit_rgba(color_map(theta));\n int64_t idx = 4 * image_width * (image_height - 1 - j) + 4 * i;\n img[idx + 0] = c[0];\n img[idx + 1] = c[1];\n img[idx + 2] = c[2];\n img[idx + 3] = c[3];\n }\n }\n\n std::array, 8> roots;\n roots[0] = -Real(1);\n roots[1] = Real(1);\n roots[2] = {Real(0), Real(1)};\n roots[3] = {Real(0), -Real(1)};\n roots[4] = {sqrt(Real(2)), sqrt(Real(2))};\n roots[5] = {sqrt(Real(2)), -sqrt(Real(2))};\n roots[6] = {-sqrt(Real(2)), -sqrt(Real(2))};\n roots[7] = {-sqrt(Real(2)), sqrt(Real(2))};\n\n for (int64_t k = 0; k < 8; ++k)\n {\n auto [ic, jc] = map.to_pixel(roots[k]);\n\n int64_t r = 7;\n for (int64_t i = ic - r; i < ic + r; ++i)\n {\n for (int64_t j = jc - r; j < jc + r; ++j)\n {\n if ((i-ic)*(i-ic) + (j-jc)*(j-jc) > r*r)\n {\n continue;\n }\n int64_t idx = 4 * image_width * (image_height - 1 - j) + 4 * i;\n img[idx + 0] = 0;\n img[idx + 1] = 0;\n img[idx + 2] = 0;\n img[idx + 3] = 0xff;\n }\n }\n }\n\n // Requires lodepng.h\n // See: https://github.com/lvandeve/lodepng for download and compilation instructions\n write_png(requested_color_map + \"_newton_fractal.png\", img, image_width, image_height);\n}\n", "meta": {"hexsha": "22bb0ed78a8a68d50d64accd832e088552f8d958", "size": 7068, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/color_maps_example.cpp", "max_stars_repo_name": "grlee77/math", "max_stars_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/color_maps_example.cpp", "max_issues_repo_name": "grlee77/math", "max_issues_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/color_maps_example.cpp", "max_forks_repo_name": "grlee77/math", "max_forks_repo_head_hexsha": "e8c40e309cc32d43fbe42c49d9ec7da7cdb79418", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.8378378378, "max_line_length": 142, "alphanum_fraction": 0.5609790606, "num_tokens": 2086, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513786759491, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6496659790577558}} {"text": "#include \"problemes.h\"\n#include \"chiffres.h\"\n#include \"utilitaires.h\"\n#include \"mpz_nombre.h\"\n#include \"mpq_fraction.h\"\n\n#include \n\nENREGISTRER_PROBLEME(65, \"Convergents of e\") {\n // The square root of 2 can be written as an infinite continued fraction.\n // \n // The infinite continued fraction can be written, √2 = [1;(2)], (2) indicates that 2 repeats ad infinitum. In a\n // similar way, √23 = [4;(1,3,1,8)].\n //\n // It turns out that the sequence of partial values of continued fractions for square roots provide the best rational\n // approximations. Let us consider the convergents for √2.\n // \n // Hence the sequence of the first ten convergents for √2 are:\n // \n // 1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ...\n // What is most surprising is that the important mathematical constant,\n // e = [2; 1,2,1, 1,4,1, 1,6,1 , ... , 1,2k,1, ...].\n // \n // The first ten terms in the sequence of convergents for e are:\n // \n // 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ...\n // The sum of digits in the numerator of the 10th convergent is 1+4+5+7=17.\n // \n // Find the sum of digits in the numerator of the 100th convergent of the continued fraction for e.\n std::vector fraction_continue;\n fraction_continue.emplace_back(2);\n for (size_t n = 2; n < 101; n += 2) {\n fraction_continue.emplace_back(1);\n fraction_continue.emplace_back(n);\n fraction_continue.emplace_back(1);\n }\n fraction_continue.resize(99);\n mpq_fraction f(1);\n for (const auto &p: boost::adaptors::reverse(fraction_continue)) f = p + 1 / f;\n\n mpz_nombre resultat = f.numerateur().somme_chiffres();\n return resultat.to_string();\n}\n", "meta": {"hexsha": "003ab106dc8c93022bc3ddddbaf5593266c7cd60", "size": 1802, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme065.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme065.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme0xx/probleme065.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.9545454545, "max_line_length": 121, "alphanum_fraction": 0.6498335183, "num_tokens": 570, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6495865741958006}} {"text": "/*\r\n * Copyright 2012 Karsten Ahnert\r\n * Copyright 2012 Mario Mulansky\r\n *\r\n * Distributed under the Boost Software License, Version 1.0.\r\n * (See accompanying file LICENSE_1_0.txt or\r\n * copy at http://www.boost.org/LICENSE_1_0.txt)\r\n */\r\n\r\n\r\n#include \r\n#include \r\n#include \r\n#include \"time.h\"\r\n\r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n\r\nusing namespace std;\r\nusing namespace boost::numeric::odeint;\r\n\r\nnamespace phoenix = boost::phoenix;\r\n\r\n\r\n\r\ntypedef mtl::dense_vector< double > vec_mtl4;\r\ntypedef mtl::compressed2D< double > mat_mtl4;\r\n\r\ntypedef boost::numeric::ublas::vector< double > vec_ublas;\r\ntypedef boost::numeric::ublas::matrix< double > mat_ublas;\r\n\r\n\r\n// two systems defined 1 & 2 both are mostly sparse with the number of element variable\r\nstruct system1_mtl4\r\n{\r\n\r\n void operator()( const vec_mtl4 &x , vec_mtl4 &dxdt , double t )\r\n {\r\n int size = mtl::size(x);\r\n\r\n dxdt[ 0 ] = -0.06*x[0];\r\n\r\n for (int i =1; i< size ; ++i){\r\n\r\n dxdt[ i ] = 4.2*x[i-1]-2.2*x[i]*x[i];\r\n }\r\n\r\n }\r\n};\r\n\r\nstruct jacobi1_mtl4\r\n{\r\n void operator()( const vec_mtl4 &x , mat_mtl4 &J , const double &t )\r\n {\r\n int size = mtl::size(x);\r\n mtl::matrix::inserter ins(J);\r\n\r\n ins[0][0]=-0.06;\r\n\r\n for (int i =1; i< size ; ++i)\r\n {\r\n ins[i][i-1] = + 4.2;\r\n ins[i][i] = -4.2*x[i];\r\n }\r\n }\r\n};\r\n\r\n\r\n\r\nstruct system1_ublas\r\n{\r\n\r\n void operator()( const vec_ublas &x , vec_ublas &dxdt , double t )\r\n {\r\n int size = x.size();\r\n\r\n dxdt[ 0 ] = -0.06*x[0];\r\n\r\n for (int i =1; i< size ; ++i){\r\n\r\n dxdt[ i ] = 4.2*x[i-1]-2.2*x[i]*x[i];\r\n }\r\n\r\n }\r\n};\r\n\r\nstruct jacobi1_ublas\r\n{\r\n void operator()( const vec_ublas &x , mat_ublas &J , const double &t )\r\n {\r\n int size = x.size();\r\n// mtl::matrix::inserter ins(J);\r\n\r\n J(0,0)=-0.06;\r\n\r\n for (int i =1; i< size ; ++i){\r\n//ins[i][0]=120.0*x[i];\r\n J(i,i-1) = + 4.2;\r\n J(i,i) = -4.2*x[i];\r\n\r\n }\r\n }\r\n};\r\n\r\nstruct system2_mtl4\r\n{\r\n\r\n void operator()( const vec_mtl4 &x , vec_mtl4 &dxdt , double t )\r\n {\r\n int size = mtl::size(x);\r\n\r\n\r\n for (int i =0; i< size/5 ; i+=5){\r\n\r\n dxdt[ i ] = -0.5*x[i];\r\n dxdt[i+1]= +25*x[i+1]*x[i+2]-740*x[i+3]*x[i+3]+4.2e-2*x[i];\r\n dxdt[i+2]= +25*x[i]*x[i]-740*x[i+3]*x[i+3];\r\n dxdt[i+3]= -25*x[i+1]*x[i+2]+740*x[i+3]*x[i+3];\r\n dxdt[i+4] = 0.250*x[i]*x[i+1]-44.5*x[i+3];\r\n\r\n }\r\n\r\n }\r\n};\r\n\r\nstruct jacobi2_mtl4\r\n{\r\n void operator()( const vec_mtl4 &x , mat_mtl4 &J , const double &t )\r\n {\r\n int size = mtl::size(x);\r\n mtl::matrix::inserter ins(J);\r\n\r\n for (int i =0; i< size/5 ; i+=5){\r\n\r\n ins[ i ][i] = -0.5;\r\n ins[i+1][i+1]=25*x[i+2];\r\n ins[i+1][i+2] = 25*x[i+1];\r\n ins[i+1][i+3] = -740*2*x[i+3];\r\n ins[i+1][i] =+4.2e-2;\r\n\r\n ins[i+2][i]= 50*x[i];\r\n ins[i+2][i+3]= -740*2*x[i+3];\r\n ins[i+3][i+1] = -25*x[i+2];\r\n ins[i+3][i+2] = -25*x[i+1];\r\n ins[i+3][i+3] = +740*2*x[i+3];\r\n ins[i+4][i] = 0.25*x[i+1];\r\n ins[i+4][i+1] =0.25*x[i];\r\n ins[i+4][i+3]=-44.5;\r\n\r\n\r\n\r\n }\r\n }\r\n};\r\n\r\n\r\n\r\nstruct system2_ublas\r\n{\r\n\r\n void operator()( const vec_ublas &x , vec_ublas &dxdt , double t )\r\n {\r\n int size = x.size();\r\n for (int i =0; i< size/5 ; i+=5){\r\n\r\n dxdt[ i ] = -4.2e-2*x[i];\r\n dxdt[i+1]= +25*x[i+1]*x[i+2]-740*x[i+3]*x[i+3]+4.2e-2*x[i];\r\n dxdt[i+2]= +25*x[i]*x[i]-740*x[i+3]*x[i+3];\r\n dxdt[i+3]= -25*x[i+1]*x[i+2]+740*x[i+3]*x[i+3];\r\n dxdt[i+4] = 0.250*x[i]*x[i+1]-44.5*x[i+3];\r\n\r\n }\r\n\r\n }\r\n};\r\n\r\nstruct jacobi2_ublas\r\n{\r\n void operator()( const vec_ublas &x , mat_ublas &J , const double &t )\r\n {\r\n int size = x.size();\r\n\r\n for (int i =0; i< size/5 ; i+=5){\r\n\r\n J(i ,i) = -4.2e-2;\r\n J(i+1,i+1)=25*x[i+2];\r\n J(i+1,i+2) = 25*x[i+1];\r\n J(i+1,i+3) = -740*2*x[i+3];\r\n J(i+1,i) =+4.2e-2;\r\n\r\n J(i+2,i)= 50*x[i];\r\n J(i+2,i+3)= -740*2*x[i+3];\r\n J(i+3,i+1) = -25*x[i+2];\r\n J(i+3,i+2) = -25*x[i+1];\r\n J(i+3,i+3) = +740*2*x[i+3];\r\n J(i+4,i) = 0.25*x[i+1];\r\n J(i+4,i+1) =0.25*x[i];\r\n J(i+4,i+3)=-44.5;\r\n\r\n\r\n\r\n }\r\n\r\n\r\n }\r\n};\r\n\r\n\r\n\r\n\r\nvoid testRidiculouslyMassiveArray( int size )\r\n{\r\n typedef boost::numeric::odeint::implicit_euler_mtl4 < double > mtl4stepper;\r\n typedef boost::numeric::odeint::implicit_euler< double > booststepper;\r\n\r\n vec_mtl4 x(size , 0.0);\r\n x[0]=1;\r\n\r\n\r\n double dt = 0.02;\r\n double endtime = 10.0;\r\n\r\n clock_t tstart_mtl4 = clock();\r\n size_t num_of_steps_mtl4 = integrate_const(\r\n mtl4stepper() ,\r\n make_pair( system1_mtl4() , jacobi1_mtl4() ) ,\r\n x , 0.0 , endtime , dt );\r\n clock_t tend_mtl4 = clock() ;\r\n\r\n clog << x[0] << endl;\r\n clog << num_of_steps_mtl4 << \" time elapsed: \" << (double)(tend_mtl4-tstart_mtl4 )/CLOCKS_PER_SEC << endl;\r\n\r\n vec_ublas x_ublas(size , 0.0);\r\n x_ublas[0]=1;\r\n\r\n clock_t tstart_boost = clock();\r\n size_t num_of_steps_ublas = integrate_const(\r\n booststepper() ,\r\n make_pair( system1_ublas() , jacobi1_ublas() ) ,\r\n x_ublas , 0.0 , endtime , dt );\r\n clock_t tend_boost = clock() ;\r\n \r\n clog << x_ublas[0] << endl;\r\n clog << num_of_steps_ublas << \" time elapsed: \" << (double)(tend_boost-tstart_boost)/CLOCKS_PER_SEC<< endl;\r\n\r\n clog << \"dt_ublas/dt_mtl4 = \" << (double)( tend_boost-tstart_boost )/( tend_mtl4-tstart_mtl4 ) << endl << endl;\r\n return ;\r\n}\r\n\r\n\r\n\r\nvoid testRidiculouslyMassiveArray2( int size )\r\n{\r\n typedef boost::numeric::odeint::implicit_euler_mtl4 < double > mtl4stepper;\r\n typedef boost::numeric::odeint::implicit_euler< double > booststepper;\r\n\r\n\r\n vec_mtl4 x(size , 0.0);\r\n x[0]=100;\r\n\r\n\r\n double dt = 0.01;\r\n double endtime = 10.0;\r\n\r\n clock_t tstart_mtl4 = clock();\r\n size_t num_of_steps_mtl4 = integrate_const(\r\n mtl4stepper() ,\r\n make_pair( system1_mtl4() , jacobi1_mtl4() ) ,\r\n x , 0.0 , endtime , dt );\r\n\r\n\r\n clock_t tend_mtl4 = clock() ;\r\n \r\n clog << x[0] << endl;\r\n clog << num_of_steps_mtl4 << \" time elapsed: \" << (double)(tend_mtl4-tstart_mtl4 )/CLOCKS_PER_SEC << endl;\r\n\r\n vec_ublas x_ublas(size , 0.0);\r\n x_ublas[0]=100;\r\n\r\n clock_t tstart_boost = clock();\r\n size_t num_of_steps_ublas = integrate_const(\r\n booststepper() ,\r\n make_pair( system1_ublas() , jacobi1_ublas() ) ,\r\n x_ublas , 0.0 , endtime , dt );\r\n\r\n\r\n clock_t tend_boost = clock() ;\r\n \r\n clog << x_ublas[0] << endl;\r\n clog << num_of_steps_ublas << \" time elapsed: \" << (double)(tend_boost-tstart_boost)/CLOCKS_PER_SEC<< endl;\r\n\r\n clog << \"dt_ublas/dt_mtl4 = \" << (double)( tend_boost-tstart_boost )/( tend_mtl4-tstart_mtl4 ) << endl << endl;\r\n return ;\r\n}\r\n\r\n\r\n\r\n \r\nint main( int argc , char **argv )\r\n{\r\n std::vector< size_t > length;\r\n length.push_back( 8 );\r\n length.push_back( 16 );\r\n length.push_back( 32 );\r\n length.push_back( 64 );\r\n length.push_back( 128 );\r\n length.push_back( 256 );\r\n\r\n for( size_t i=0 ; i\n#include \n#include \n\ntypedef unsigned long long nombre;\n\nENREGISTRER_PROBLEME(42, \"Coded triangle numbers\") {\n // The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:\n //\n // 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...\n //\n // By converting each letter in a word to a number corresponding to its alphabetical position and adding these values\n // we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle\n // number then we shall call the word a triangle word.\n //\n // Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words?\n std::ifstream ifs(\"data/p042_words.txt\");\n std::string entree;\n ifs >> entree;\n std::vector names;\n boost::split(names, entree, boost::is_any_of(\",\"));\n\n std::set triangle;\n for (nombre n = 1; n < 50; ++n)\n triangle.insert(n * (n + 1) / 2);\n\n nombre resultat = 0;\n for (const auto &name: names) {\n nombre score = std::accumulate(name.begin(), name.end(), 0ULL, [](const nombre &n, char c) {\n if (c != '\"')\n return n + 1 + static_cast(c - 'A');\n return n;\n });\n if (triangle.find(score) != triangle.end())\n ++resultat;\n }\n return std::to_string(resultat);\n}\n", "meta": {"hexsha": "b0b0cf8508a8e6d03577803fffe9d15f71ffffcf", "size": 1611, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme0xx/probleme042.cpp", "max_stars_repo_name": "ZongoForSpeed/ProjectEuler", "max_stars_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2015-10-13T17:07:21.000Z", "max_stars_repo_stars_event_max_datetime": "2018-05-08T11:50:22.000Z", "max_issues_repo_path": "problemes/probleme0xx/probleme042.cpp", "max_issues_repo_name": "ZongoForSpeed/ProjectEuler", "max_issues_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "problemes/probleme0xx/probleme042.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": 38.3571428571, "max_line_length": 164, "alphanum_fraction": 0.6045934202, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772253241803, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6495862358897504}} {"text": "//\n// gmatrix9float.cpp\n// GCommon\n//\n// Created by David Coen on 2011 06 01\n// Copyright Pleasure seeking morons 2011. All rights reserved.\n//\n\n#include \"gmatrix9float.h\"\n\n#include \"gvector3float.h\"\n#include \"gmathmatrix.h\"\n#include \"gmath.h\"\n\n#include \n\n#define DSC_INLINE_MATRIX_MUL\n\n/*static*/ const GMatrix9Float GMatrix9Float::sIdentity(1.0F, 0.0F, 0.0F,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t 0.0F, 1.0F, 0.0F,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t 0.0F, 0.0F, 1.0F);\n\n\n//constructors\nGMatrix9Float::GMatrix9Float(const GR32 in_data_0_0, const GR32 in_data_0_1, const GR32 in_data_0_2,\n\tconst GR32 in_data_1_0, const GR32 in_data_1_1, const GR32 in_data_1_2,\n\tconst GR32 in_data_2_0, const GR32 in_data_2_1, const GR32 in_data_2_2\n\t)\n{\n\tSetData(in_data_0_0, in_data_0_1, in_data_0_2,\n\t\tin_data_1_0, in_data_1_1, in_data_1_2,\n\t\tin_data_2_0, in_data_2_1, in_data_2_2\n\t\t);\n\treturn;\n}\nGMatrix9Float::GMatrix9Float(const GR32* const in_data)\n{\n\tfor (GS32 index = 0; index < 9; ++index)\n\t{\n\t\tm_data[index] = in_data[index];\n\t}\n\treturn;\n\n}\n\nGMatrix9Float::GMatrix9Float(const GMatrix9Float& in_src)\n{\n\t(*this) = in_src;\n\treturn;\n}\n\nGMatrix9Float::~GMatrix9Float()\n{\n\treturn;\n}\n\t\n//operators\nconst GMatrix9Float& GMatrix9Float::operator=(const GMatrix9Float& in_rhs)\n{\n\tfor (GS32 index = 0; index < 9; ++index)\n\t{\n\t\tm_data[index] = in_rhs.m_data[index];\n\t}\n\treturn (*this);\n}\n\n//public methods\nGMatrix9Float& GMatrix9Float::TransposeSelf()\n{\n\tstd::swap(m_0_1, m_1_0);\n\tstd::swap(m_0_2, m_2_0);\n\tstd::swap(m_1_2, m_2_1);\n\n\treturn (*this);\n}\n\nconst GMatrix9Float GMatrix9Float::ReturnInverse()const\n{\n\tGMatrix9Float result;\n\tGMathMatrix::Inverse4(&result.m_data[0], &m_data[0]);\n\n\treturn result;\n}\n\n//public accessors\nvoid GMatrix9Float::SetData(const GR32 in_data_0_0, const GR32 in_data_0_1, const GR32 in_data_0_2,\n\tconst GR32 in_data_1_0, const GR32 in_data_1_1, const GR32 in_data_1_2,\n\tconst GR32 in_data_2_0, const GR32 in_data_2_1, const GR32 in_data_2_2\n\t)\n{\n\tm_0_0 = in_data_0_0;\n\tm_1_0 = in_data_1_0;\n\tm_2_0 = in_data_2_0;\n\n\tm_0_1 = in_data_0_1;\n\tm_1_1 = in_data_1_1;\n\tm_2_1 = in_data_2_1;\n\n\tm_0_2 = in_data_0_2;\n\tm_1_2 = in_data_1_2;\n\tm_2_2 = in_data_2_2;\n\n\treturn;\n}\n\nconst GVector3Float GMatrix9Float::GetAt()const\n{\n\tconst GVector3Float result(\n\t\tm_0_2,\n\t\tm_1_2,\n\t\tm_2_2\n\t\t);\n\treturn result;\n}\n\nconst GVector3Float GMatrix9Float::GetUp()const\n{\n\tconst GVector3Float result(\n\t\tm_0_1,\n\t\tm_1_1,\n\t\tm_2_1\n\t\t);\n\treturn result;\n}\n\n//global operators\nconst GMatrix9Float operator*(const GMatrix9Float& in_lhs, const GMatrix9Float& in_rhs)\n{\n\tGR32 value[9];\n#ifdef DSC_INLINE_MATRIX_MUL\n\tconst GR32* const lhsData = in_lhs.GetData();\n\tconst GR32* const rhsData = in_rhs.GetData();\n\tvalue[ 0] = (lhsData[ 0] * rhsData[ 0]) + (lhsData[ 1] * rhsData[ 3]) + (lhsData[ 2] * rhsData[ 6]);\n\tvalue[ 1] = (lhsData[ 0] * rhsData[ 1]) + (lhsData[ 1] * rhsData[ 4]) + (lhsData[ 2] * rhsData[ 7]);\n\tvalue[ 2] = (lhsData[ 0] * rhsData[ 2]) + (lhsData[ 1] * rhsData[ 5]) + (lhsData[ 2] * rhsData[ 8]);\n\n\tvalue[ 3] = (lhsData[ 3] * rhsData[ 0]) + (lhsData[ 4] * rhsData[ 3]) + (lhsData[ 5] * rhsData[ 6]);\n\tvalue[ 4] = (lhsData[ 3] * rhsData[ 1]) + (lhsData[ 4] * rhsData[ 4]) + (lhsData[ 5] * rhsData[ 7]);\n\tvalue[ 5] = (lhsData[ 3] * rhsData[ 2]) + (lhsData[ 4] * rhsData[ 5]) + (lhsData[ 5] * rhsData[ 8]);\n\n\tvalue[ 6] = (lhsData[ 6] * rhsData[ 0]) + (lhsData[ 7] * rhsData[ 3]) + (lhsData[ 8] * rhsData[ 6]);\n\tvalue[ 7] = (lhsData[ 6] * rhsData[ 1]) + (lhsData[ 7] * rhsData[ 4]) + (lhsData[ 8] * rhsData[ 7]);\n\tvalue[ 8] = (lhsData[ 6] * rhsData[ 2]) + (lhsData[ 7] * rhsData[ 5]) + (lhsData[ 8] * rhsData[ 8]);\n#else\n\tGMathMatrix::MatrixMul( \n\t\tin_lhs.GetData(),\n\t\tin_rhs.GetData(), \n\t\t3, \n\t\t3, \n\t\t3, \n\t\t&value[0]\n\t\t);\n#endif\n\treturn GMatrix9Float(&value[0]);\n}\n\nconst GVector3Float operator*(const GVector3Float& in_lhs, const GMatrix9Float& in_rhs)\n{\n\tGR32 value[3];\n#ifdef DSC_INLINE_MATRIX_MUL\n\tconst GR32* const lhsData = in_lhs.GetData();\n\tconst GR32* const rhsData = in_rhs.GetData();\n\tvalue[ 0] = (lhsData[ 0] * rhsData[ 0]) + (lhsData[ 1] * rhsData[ 3]) + (lhsData[ 2] * rhsData[ 6]);\n\tvalue[ 1] = (lhsData[ 0] * rhsData[ 1]) + (lhsData[ 1] * rhsData[ 4]) + (lhsData[ 2] * rhsData[ 7]);\n\tvalue[ 2] = (lhsData[ 0] * rhsData[ 2]) + (lhsData[ 1] * rhsData[ 5]) + (lhsData[ 2] * rhsData[ 8]);\n#else\n\tGMathMatrix::MatrixMul( \n\t\tin_lhs.GetData(),\n\t\tin_rhs.GetData(), \n\t\t3, \n\t\t1, \n\t\t3, \n\t\t&value[0]\n\t\t);\n#endif\n\treturn GVector3Float(value[0], value[1], value[2]);\n}\n\nconst GMatrix9Float& operator*=(GMatrix9Float& in_lhs, const GMatrix9Float& in_rhs)\n{\n\tin_lhs = (in_lhs * in_rhs);\n\treturn in_lhs;\n}\t\n\n/*\n from _Mathematics for computer graphics p.171\n mapping a pair of vectors onto another pair, u,x being one pair, a,y being another of unit vectors at same angle\n u.x = a.y = cos(\\), with sin(\\) != 0\n a roation matrix sending u,x to a,y given by\n a \n M = [u v w ][ b ]\n c\n d = | x * u | = | y * a | = | sin(\\) |\n if 90deg = u to x, cos(\\) = 0, sin(\\) = 1\n v = ( x * u ) / d\n b = ( y * a ) / d\n w = ( x - u( cos(\\) ) ) / d\n c = ( y - a( cos(\\) ) ) / d\n*/\nconst GMatrix9Float GMatrix9FloatConstructAtUp( \n\tconst GVector3Float& in_targetAt, \n\tconst GVector3Float& in_targetUp,\n\tconst GVector3Float& in_baseAt, \n\tconst GVector3Float& in_baseUp\n\t)\n{\n\tGMatrix9Float returnMatrix;\n\n\tconst GVector3Float crossBaseUpAt = CrossProduct(in_baseUp, in_baseAt);\n\tconst GVector3Float crossTargetUpAt = CrossProduct(in_targetUp, in_targetAt);\n\n\treturn GMatrix9Float(\n\t\t(in_baseAt.m_x * in_targetAt.m_x) + (crossBaseUpAt.m_x * crossTargetUpAt.m_x) + (in_baseUp.m_x * in_targetUp.m_x),\n\t\t(in_baseAt.m_y * in_targetAt.m_x) + (crossBaseUpAt.m_y * crossTargetUpAt.m_x) + (in_baseUp.m_y * in_targetUp.m_x),\n\t\t(in_baseAt.m_z * in_targetAt.m_x) + (crossBaseUpAt.m_z * crossTargetUpAt.m_x) + (in_baseUp.m_z * in_targetUp.m_x),\n\n\t\t(in_baseAt.m_x * in_targetAt.m_y) + (crossBaseUpAt.m_x * crossTargetUpAt.m_y) + (in_baseUp.m_x * in_targetUp.m_y),\n\t\t(in_baseAt.m_y * in_targetAt.m_y) + (crossBaseUpAt.m_y * crossTargetUpAt.m_y) + (in_baseUp.m_y * in_targetUp.m_y),\n\t\t(in_baseAt.m_z * in_targetAt.m_y) + (crossBaseUpAt.m_z * crossTargetUpAt.m_y) + (in_baseUp.m_z * in_targetUp.m_y),\n\n\t\t(in_baseAt.m_x * in_targetAt.m_z) + (crossBaseUpAt.m_x * crossTargetUpAt.m_z) + (in_baseUp.m_x * in_targetUp.m_z),\n\t\t(in_baseAt.m_y * in_targetAt.m_z) + (crossBaseUpAt.m_y * crossTargetUpAt.m_z) + (in_baseUp.m_y * in_targetUp.m_z),\n\t\t(in_baseAt.m_z * in_targetAt.m_z) + (crossBaseUpAt.m_z * crossTargetUpAt.m_z) + (in_baseUp.m_z * in_targetUp.m_z)\n\t\t);\n}\n\n/*\n http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToMatrix/index.htm\n*/\nconst GMatrix9Float GMatrix9FloatConstructAxisAngle(const GVector3Float& in_axis, const GR32 in_angleRad)\n{\n\tconst GVector3Float localAxis = Normalise(in_axis);\n\tconst GR32 axis_x = localAxis.m_x;\n\tconst GR32 axis_y = localAxis.m_y;\n\tconst GR32 axis_z = localAxis.m_z;\n\n\tconst GR32 c = GMath::Cos( in_angleRad );\n\tconst GR32 s = GMath::Sin( in_angleRad );\n\tconst GR32 t = 1.0F - c;\n\n\tconst GR32 tmp1_01 = axis_x * axis_y * t;\n\tconst GR32 tmp2_01 = axis_z * s;\n\n\tconst GR32 tmp1_02 = axis_x * axis_z * t;\n\tconst GR32 tmp2_02 = axis_y * s;\n \n\tconst GR32 tmp1_21 = axis_y * axis_z * t;\n\tconst GR32 tmp2_21 = axis_x * s;\n\n\treturn GMatrix9Float(\n\t\tc + axis_x * axis_x * t, tmp1_01 - tmp2_01, tmp1_02 + tmp2_02,\n\t\ttmp1_01 + tmp2_01, c + axis_y * axis_y * t, tmp1_21 - tmp2_21,\n\t\ttmp1_02 - tmp2_02, tmp1_21 + tmp2_21, c + axis_z * axis_z * t\n\t\t);\n}\n", "meta": {"hexsha": "30ab6f6cd8914f24b1b694af60936e1e91f583d1", "size": 7476, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gcommon/source/gmatrix9float.cpp", "max_stars_repo_name": "DavidCoenFish/ancient-code-0", "max_stars_repo_head_hexsha": "243fb47b9302a77f9b9392b6e3f90bba2ef3c228", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gcommon/source/gmatrix9float.cpp", "max_issues_repo_name": "DavidCoenFish/ancient-code-0", "max_issues_repo_head_hexsha": "243fb47b9302a77f9b9392b6e3f90bba2ef3c228", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gcommon/source/gmatrix9float.cpp", "max_forks_repo_name": "DavidCoenFish/ancient-code-0", "max_forks_repo_head_hexsha": "243fb47b9302a77f9b9392b6e3f90bba2ef3c228", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.203125, "max_line_length": 116, "alphanum_fraction": 0.6775013376, "num_tokens": 2877, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.874077222043951, "lm_q2_score": 0.7431680029241321, "lm_q1q2_score": 0.6495862235078762}} {"text": "/* ---------------------------------------------------------------------\n *\n * Copyright (C) 1999 - 2019 by the deal.II authors\n *\n * This file is part of the deal.II library.\n *\n * The deal.II library is free software; you can use it, redistribute\n * it, and/or modify it under the terms of the GNU Lesser General\n * Public License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * The full text of the license can be found in the file LICENSE.md at\n * the top level of the deal.II distribution.\n *\n * ---------------------------------------------------------------------\n *\n * based on deal.II step-1\n */\n\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace dealii;\n\n\n//! Generate a hypercube, and output it as an svg file.\nvoid first_grid(Triangulation<2> &triangulation)\n{\n GridGenerator::hyper_cube(triangulation);\n triangulation.refine_global(4);\n\n std::ofstream out(\"grid-1.svg\");\n GridOut grid_out;\n grid_out.write_svg(triangulation, out);\n std::cout << \"Grid written to grid-1.svg\" << std::endl;\n}\n\n\n//! Generate a locally refined hyper_shell, and output it as an svg file.\nvoid second_grid(Triangulation<2> &triangulation)\n{\n const Point<2> center(1, 0);\n const double inner_radius = 0.5, outer_radius = 1.0;\n GridGenerator::hyper_shell(\n triangulation, center, inner_radius, outer_radius, 10);\n\n\n // triangulation.reset_manifold(0);\n\n for (unsigned int step = 0; step < 5; ++step)\n {\n for (auto &cell : triangulation.active_cell_iterators())\n {\n for (const auto v : cell->vertex_indices())\n {\n const double distance_from_center =\n center.distance(cell->vertex(v));\n\n if (std::fabs(distance_from_center - inner_radius) <=\n 1e-6 * inner_radius)\n {\n cell->set_refine_flag();\n break;\n }\n }\n }\n\n triangulation.execute_coarsening_and_refinement();\n }\n\n\n std::ofstream out(\"grid-2.svg\");\n GridOut grid_out;\n grid_out.write_svg(triangulation, out);\n\n std::cout << \"Grid written to grid-2.svg\" << std::endl;\n}\n\n\n//! Create an L-shaped domain with one global refinement, and write it on\n// `third_grid.vtk`. Refine the L-shaped mesh adaptively around the re-entrant\n// corner three times (after the global refinement you already did), but with a\n// twist: refine all cells with the distance between the center of the cell and\n// re-entrant corner is smaller than 1/3.\nvoid third_grid(Triangulation<2> &tria)\n{\n // Insert code here\n // last year code in comments\n /* Triangulation<2> tr1,tr2,tr3,tr_final;\n const Point<2> p1(0, 0);\n const Point<2> p2(1,2);\n const Point<2> p3(2,1);\n const Point<2> p4(1,0);\n const Point<2> p5(1,1);\n const Point<2> p6(0,1);\n GridGenerator::hyper_rectangle(tr1,p1,p5);\n GridGenerator::hyper_rectangle(tr2,p6,p2);\n GridGenerator::hyper_rectangle(tr3,p4,p3);\n //they cannot be refined!\n GridGenerator::merge_triangulations ({&tr1,&tr2,&tr3},tr_final);*/\n GridGenerator::hyper_L(tria);\n tria.refine_global(1);\n const Point<2> p5(0, 0);\n for (unsigned int step = 0; step < 3; ++step)\n {\n // Active cells are those that are not further refined\n // we need to mark cells for refinement\n for (auto &cell : tria.active_cell_iterators())\n {\n const double distance_from_corner = cell->center().distance({0, 0});\n // choose whatever refinement condition\n if (distance_from_corner < 2.0 / 3.0)\n {\n cell->set_refine_flag();\n }\n }\n // refine global calls this function too\n tria.execute_coarsening_and_refinement();\n } // for steps loop\n\n // tr_final.refine_global(2); //we want a nice picture :)\n\n std::ofstream file_var(\"grid-3.vtk\");\n GridOut grid_out;\n grid_out.write_vtk(tria, file_var);\n std::cout << \"Grid written to grid-3.vtk\" << std::endl;\n}\n\n//! Returns a tuple with number of levels, number of cells, number of active\n// cells. Test this with all of your meshes.\nstd::tuple\nget_info(const Triangulation<2> &tria)\n{\n // Insert code here\n return std::make_tuple(tria.n_levels(),\n tria.n_cells(),\n tria.n_active_cells());\n}\n\nvoid\ntorus_grid()\n{\n Triangulation<2, 3> tria;\n GridGenerator::torus(tria, 2, 1);\n tria.refine_global(2);\n\n std::ofstream out(\"grid-torus.vtk\");\n GridOut grid_out;\n grid_out.write_vtk(tria, out);\n std::cout << \"Grid written to grid-torus.vtk\" << std::endl;\n}\n\n\nint\nmain()\n{\n Triangulation<2> triangulation;\n first_grid(triangulation);\n triangulation.clear();\n second_grid(triangulation);\n triangulation.clear();\n third_grid(triangulation);\n\n torus_grid();\n}\n", "meta": {"hexsha": "8fdaff5ce263e915fc0beb877939e504e7dcef22", "size": 5072, "ext": "cc", "lang": "C++", "max_stars_repo_path": "source/step-1.cc", "max_stars_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-davydenk", "max_stars_repo_head_hexsha": "3353fa9cd3aca4e100e4bae1de6331265755147d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source/step-1.cc", "max_issues_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-davydenk", "max_issues_repo_head_hexsha": "3353fa9cd3aca4e100e4bae1de6331265755147d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source/step-1.cc", "max_forks_repo_name": "dealii-courses/triangulation-dofhandler-and-finiteelement-davydenk", "max_forks_repo_head_hexsha": "3353fa9cd3aca4e100e4bae1de6331265755147d", "max_forks_repo_licenses": ["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.3179190751, "max_line_length": 79, "alphanum_fraction": 0.6360410095, "num_tokens": 1336, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7772998611746912, "lm_q2_score": 0.8354835350552604, "lm_q1q2_score": 0.6494212358121941}} {"text": "#include \n#include \n\n#include \n#include \n\n\nnamespace poisson\n{\n\nvoid reconstructBrightnessFromGradientMap(const cv::Mat& grad_map,\n cv::Mat* map_reconstructed)\n{\n CHECK_EQ(grad_map.type(), CV_32FC2);\n CHECK_GT(grad_map.cols, 0);\n CHECK_GT(grad_map.rows, 0);\n const cv::Size img_size = grad_map.size();\n\n // Compute the right hand side of Poisson eq.\n // F = dgx/dx + dgy/dy and put it into a boost::multi_array\n const size_t height = img_size.height;\n const size_t width = img_size.width;\n boost::multi_array M(boost::extents[height][width]);\n boost::multi_array F(boost::extents[height][width]);\n\n // Compute right hand side (rhs) using one-sided finite differences\n for(size_t i=0; i < height-1; ++i)\n {\n for(size_t j=0; j < width-1; ++j)\n {\n F[i][j] = double( grad_map.at(i,j+1)[0] - grad_map.at(i,j)[0]\n + grad_map.at(i+1,j)[1] - grad_map.at(i,j)[1] );\n }\n }\n F[height-1][width-1] = 0.0;\n\n // Solve for M_xx + M_yy = F using Poisson solver,\n // with constant intensity (zero) boundary conditions\n const double gradient_on_boundary = 0.0;\n pde::poisolve(M, F, 1.0, 1.0, 1.0, 1.0,\n gradient_on_boundary,\n pde::types::boundary::Neumann,false);\n\n // Fill in output variable\n *map_reconstructed = cv::Mat(img_size, CV_32FC1);\n // FILL IN ...\n\n}\n\n}\n", "meta": {"hexsha": "2731ae4740baadace44f47ab308d44eb17985ad3", "size": 1544, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/reconstruction.cpp", "max_stars_repo_name": "tub-rip/dvs_mosaic_skeleton", "max_stars_repo_head_hexsha": "ee3fc860eb312bcb0167a97b6b9f241096ab4179", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-12-27T02:06:39.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-02T09:06:31.000Z", "max_issues_repo_path": "src/reconstruction.cpp", "max_issues_repo_name": "tub-rip/dvs_mosaic_skeleton", "max_issues_repo_head_hexsha": "ee3fc860eb312bcb0167a97b6b9f241096ab4179", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/reconstruction.cpp", "max_forks_repo_name": "tub-rip/dvs_mosaic_skeleton", "max_forks_repo_head_hexsha": "ee3fc860eb312bcb0167a97b6b9f241096ab4179", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-25T01:56:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-25T01:56:10.000Z", "avg_line_length": 30.2745098039, "max_line_length": 92, "alphanum_fraction": 0.6334196891, "num_tokens": 475, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6492867653501584}} {"text": "#include \n#include \n\nusing namespace boost::numeric::ublas;\n\nint main()\n{\n\t// op(Matrix)\n\tmatrix > m (3, 3);\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) = std::complex (3 * i + j, 3 * i + j);\n\n\tstd::cout << \"minus \\t\" << - m << std::endl;\n\tstd::cout << \"conj \\t\" << conj (m) << std::endl;\n\tstd::cout << \"real \\t\" << real (m) << std::endl;\n\tstd::cout << \"imag \\t\" << imag (m) << std::endl;\n\tstd::cout << \"trans \\t\" << trans (m) << std::endl;\n\tstd::cout << \"herm \\t\" << herm (m) << std::endl;\n\n\t// Matrix +/- Matrix\n\tmatrix m1 (3, 3), m2 (3, 3);\n\tfor (unsigned i = 0; i < std::min (m1.size1 (), m2.size1 ()); ++ i)\n\t\tfor (unsigned j = 0; j < std::min (m1.size2 (), m2.size2 ()); ++ j)\n\t\t\tm1 (i, j) = m2 (i, j) = 3 * i + j;\n\n\tstd::cout << \"add \\t\" << m1 + m2 << std::endl;\n\tstd::cout << \"subt \\t\" << m1 - m2 << std::endl;\n\n\t// scalar * Matrix\n\tmatrix mm (3, 3);\n\tfor (unsigned i = 0; i < mm.size1 (); ++ i)\n\t\tfor (unsigned j = 0; j < mm.size2 (); ++ j)\n\t\t\tmm (i, j) = 3 * i + j;\n\n\tstd::cout << \"2 * matrix \\t\" << 2.0 * mm << std::endl;\n\tstd::cout << \"matrix * 2 \\t\" << mm * 2.0 << std::endl;\n\n\t// Matrix * Vector\n\tmatrix m_ (3, 3);\n\tvector v (3);\n\tfor (unsigned i = 0; i < std::min (m_.size1 (), v.size ()); ++ i) {\n\t\tfor (unsigned j = 0; j < m_.size2 (); ++ j)\n\t\t\tm_ (i, j) = 3 * i + j;\n\t\tv (i) = i;\n\t}\n\n\tstd::cout << \"matrix * vector (A * b) \\t\" << prod (m_, v) << std::endl;\n\tstd::cout << \"vector * matrix (A' * b)\\t\" << prod (v, m_) << std::endl; \n\n\t// Matrix * Matrix\n\tmatrix m11 (3, 3), m22 (3, 3);\n\tfor (unsigned i = 0; i < std::min (m11.size1 (), m22.size1 ()); ++ i)\n\t\tfor (unsigned j = 0; j < std::min (m11.size2 (), m22.size2 ()); ++ j)\n\t\t\tm11 (i, j) = m22 (i, j) = 3 * i + j;\n\n\tstd::cout << \"matrix * matrix (A * B) \\t\" << prod (m11, m22) << std::endl;\n\treturn 0;\n}", "meta": {"hexsha": "fbfd54151dbb5632a24eec4b8aabacf287c5c25c", "size": 1962, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "basic_operation.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": "basic_operation.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": "basic_operation.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": 33.2542372881, "max_line_length": 75, "alphanum_fraction": 0.498470948, "num_tokens": 786, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6492867500919898}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"naive_bayes.cpp\"\n#include \"eigen_space.cpp\"\n\n#define PI 3.141592653589793238462643383279502884L\n#define REGULARIZATION_FACTOR 0.5\n#define IDEAL_NUM_PRINCIPLE_COMPONENTS 16\n\n\n#define _l_ std::cout<<__LINE__<\nReadData(\n const std::string& fileName,\n const unsigned featureDim,\n const unsigned numItems) {\n\n std::ifstream fin;\n fin.clear(); fin.open(fileName.c_str());\n\n if (!fin.good()) {\n throw std::exception();\n }\n\n std::vector data; data.reserve(numItems);\n\n for (unsigned i = 0; i < numItems; ++i) {\n ClassificationObject classificationObject;\n double dummy;\n fin >> dummy;\n classificationObject.label = (unsigned) dummy;\n\n classificationObject.features.resize(featureDim);\n for (unsigned j = 0; j < featureDim; ++j) {\n fin >> classificationObject.features(j);\n }\n data.push_back(classificationObject);\n }\n\n return data;\n}\n\n\nEigen::MatrixXi\nPerformClassifications(const std::vector& labelSet,\n const std::vector& classSummaries,\n const std::vector& testObjects) {\n\n Eigen::MatrixXi confusionMatrix(labelSet.size(), labelSet.size());\n confusionMatrix.setZero(labelSet.size(), labelSet.size());\n\n unsigned i = 1;\n unsigned onePercent = testObjects.size() / 100;\n for (const ClassificationObject& object : testObjects) {\n if (i % onePercent == 0) {\n std::cout << i << \"%% processed.\" << std::endl;\n }\n i++;\n\n unsigned classifiedAs = ClassifyObject(object, classSummaries);\n confusionMatrix(object.label, classifiedAs)++;\n }\n\n return confusionMatrix;\n}\n\nEigen::MatrixXi\nPerformPcaClassifications(const std::vector& labelSet,\n const std::vector& classSummaries,\n const std::vector& testObjects) {\n\n Eigen::MatrixXi confusionMatrix(labelSet.size(), labelSet.size());\n confusionMatrix.setZero(labelSet.size(), labelSet.size());\n\n unsigned i = 1;\n unsigned onePercent = testObjects.size() / 100;\n for (const ClassificationObject& object : testObjects) {\n if (i % onePercent == 0) {\n std::cout << (double)i * 100.0 / testObjects.size() << \"% processed.\" << std::endl;\n }\n i++;\n\n unsigned classifiedAs = PcaClassifyObject(object, classSummaries);\n confusionMatrix(object.label, classifiedAs)++;\n }\n\n return confusionMatrix;\n}\n\n\nint\nmain(const int argc, const char** argv) {\n std::cout << \"Reading Data...\" << std::endl;\n std::vector trainingData = ReadData(\n TRAINING_FILE_NAME,\n 256,\n 7291\n );\n std::vector testData = ReadData(\n TEST_FILE_NAME,\n 256,\n 2007\n );\n\n std::cout << \"Training Models...\" << std::endl;\n std::vector classSummaries; classSummaries.reserve(10);\n for (unsigned label = 0; label <= 9; ++label) {\n classSummaries.push_back(ComputeClassInfo(trainingData, label, 256));\n }\n\n std::cout << \"Training Reduced Dimensionality Models...\" << std::endl;\n std::vector reducedClassSummaries; reducedClassSummaries.reserve(10);\n for (unsigned label = 0; label <= 9; ++label) {\n reducedClassSummaries.push_back(\n ComputeClassInfoInPcaDimensionReducedSpace(\n trainingData,\n classSummaries[label],\n 16\n )\n );\n }\n \n std::cout << \"Classifying Objects...\" << std::endl;\n Eigen::MatrixXi confusionMatrix = PerformPcaClassifications(\n {0,1,2,3,4,5,6,7,8,9},\n reducedClassSummaries,\n testData\n );\n\n std::cout << \"Results:\" << std::endl;\n std::cout << confusionMatrix << std::endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "9212f88d81a2da7a27e2b47aca7a3234a792d337", "size": 3923, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "STAT775/HW03/Exercise03.cpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "STAT775/HW03/Exercise03.cpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "STAT775/HW03/Exercise03.cpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 26.3288590604, "max_line_length": 92, "alphanum_fraction": 0.6923273005, "num_tokens": 1021, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970654616711, "lm_q2_score": 0.7371581568543044, "lm_q1q2_score": 0.6492867413384056}} {"text": "\n#include \"camsim.hpp\"\n\n#include \"gtsam/inference/Symbol.h\"\n#include \n#include \n#include \n#include \n\nusing namespace gtsam;\nusing namespace gtsam::noiseModel;\nusing symbol_shorthand::X;\n\n/**\n * Unary factor on the unknown pose, resulting from measuring the projection of\n * a known 3D point in the image\n */\nclass ResectioningFactor_xxx : public NoiseModelFactor1\n{\n typedef NoiseModelFactor1 Base;\n\n Cal3_S2::shared_ptr K_; ///< camera's intrinsic parameters\n Point3 P_; ///< 3D point on the calibration rig\n Point2 p_; ///< 2D measurement of the 3D point\n\npublic:\n\n /// Construct factor given known point P and its projection p\n ResectioningFactor_xxx(const SharedNoiseModel &model, const Key &key,\n const Cal3_S2::shared_ptr &calib, const Point2 &p, const Point3 &P) :\n Base(model, key), K_(calib), P_(P), p_(p)\n {\n }\n\n /// evaluate the error\n virtual Vector evaluateError(const Pose3 &pose, boost::optional H =\n boost::none) const\n {\n SimpleCamera camera(pose, *K_);\n return camera.project(P_, H, boost::none, boost::none) - p_;\n }\n};\n\n/*******************************************************************************\n * Camera: f = 1, Image: 100x100, center: 50, 50.0\n * Pose (ground truth): (Xw, -Yw, -Zw, [0,0,2.0]')\n * Known landmarks:\n * 3D Points: (10,10,0) (-10,10,0) (-10,-10,0) (10,-10,0)\n * Perfect measurements:\n * 2D Point: (55,45) (45,45) (45,55) (55,55)\n *******************************************************************************/\n\nint gtsam_resection()\n{\n /* read camera intrinsic parameters */\n Cal3_S2::shared_ptr calib(new Cal3_S2(1, 1, 0, 50, 50));\n\n /* 1. create graph */\n NonlinearFactorGraph graph;\n\n /* 2. add factors to the graph */\n // add measurement factors\n SharedDiagonal measurementNoise = Diagonal::Sigmas(Vector2(5., .5));\n graph.emplace_shared(measurementNoise, X(1), calib,\n Point2(55, 45), Point3(10, 10, 0));\n graph.emplace_shared(measurementNoise, X(1), calib,\n Point2(45, 45), Point3(-10, 10, 0));\n graph.emplace_shared(measurementNoise, X(1), calib,\n Point2(45, 55), Point3(-10, -10, 0));\n graph.emplace_shared(measurementNoise, X(1), calib,\n Point2(55, 55), Point3(10, -10, 0));\n\n /* 3. Create an initial estimate for the camera pose */\n Values initial;\n initial.insert(X(1),\n// Pose3(Rot3(1, 1, 0, 0, -1, 0, 0, 0, -1), Point3(0, 0, 2)));\n Pose3(Rot3(1, 0, 0, 0, -1, 0, 0, 0, -1), Point3(0, 0, 2)));\n\n graph.print(\"full graph\");\n\n /* 4. Optimize the graph using Levenberg-Marquardt*/\n Values result = LevenbergMarquardtOptimizer(graph, initial).optimize();\n result.print(\"Final result:\\n\");\n\n auto camera_f_marker = result.at(X(1));\n std::cout << camera_f_marker.rotation() << camera_f_marker.rotation().xyz() << std::endl;\n\n std::cout.precision(2);\n Marginals marginals(graph, result);\n std::cout << \"x1 covariance:\\n\" << marginals.marginalCovariance(X(1)) << std::endl;\n\n std::cout << \"initial error = \" << graph.error(initial) << std::endl;\n std::cout << \"final error = \" << graph.error(result) << std::endl;\n\n return EXIT_SUCCESS;\n}\n", "meta": {"hexsha": "ea2e4142643944f2cbc252085d286bfa47153d5f", "size": 3572, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/gtsam_resection.cpp", "max_stars_repo_name": "ptrmu/camsim", "max_stars_repo_head_hexsha": "2d79bf2eff32a33aca81cc205cb9256937abcbed", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-12-12T16:51:58.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-12T16:51:58.000Z", "max_issues_repo_path": "src/gtsam_resection.cpp", "max_issues_repo_name": "ptrmu/camsim", "max_issues_repo_head_hexsha": "2d79bf2eff32a33aca81cc205cb9256937abcbed", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/gtsam_resection.cpp", "max_forks_repo_name": "ptrmu/camsim", "max_forks_repo_head_hexsha": "2d79bf2eff32a33aca81cc205cb9256937abcbed", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.824742268, "max_line_length": 94, "alphanum_fraction": 0.6007838746, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916205190225, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6492813499105727}} {"text": "// Copyright (c) 2018-2019, University of Bremen, M. Farzalipour Tabriz\r\n// Copyrights licensed under the 2-Clause BSD License.\r\n// See the accompanying LICENSE.txt file for terms.\r\n\r\n#pragma once\r\n#include \r\n#include \"arma_io.hpp\"\r\n#include \r\n#include \"general_io.hpp\"\r\n#include \"spline.hpp\"\r\n\r\n#define PI datum::pi\r\n\r\n\r\n//These functions extend the functionality of the included Armadillo library by providing:\r\n// (arma,iostream) << and >> operators for reading from iostreams to armadillo types and vice versa\r\n// fft/ifft functions for cube files: Wrappers for FFTW with MATLAB/Octave scaling convention\r\n//\t\t\t\tin FFT functions the forward FFT scales by 1, and the reverse scales by 1/N. \r\n// 3D ndgrid and 3D meshgrid\r\n// 3D spline interpolation\r\n// 3D shift: by number of the elements along one axis or with a relative 3D shift vector\r\n// irowvec to matrix/cube size conversion\r\n// scalar triple product\r\n\r\n\r\nusing namespace arma;\r\n\r\n// a (very inefficient) 3D spline interpolation!\r\ncube interp3(const rowvec& x, const rowvec& y, const rowvec& z, const cube& v, const rowvec& xi, const rowvec& yi, const rowvec& zi);\r\ncube interp3(const cube& v, const rowvec& xi, const rowvec& yi, const rowvec& zi);\r\n\r\n//Rectangular grid in 3D space\r\ntuple ndgrid(const rowvec& v1, const rowvec& v2, const rowvec& v3);\r\n\r\n//3D meshgrid\r\ntuple meshgrid(const rowvec& v1, const rowvec& v2, const rowvec& v3);\r\n\r\n//shifts a cube by a relative 3D vector [0 1]\r\ncube shift(cube cube_in, rowvec3 shifts);\r\n\r\n//Planar average of a cube in the defined direction\r\n//direction: 0,1,2 > x,y,z\r\nvec planar_average(const uword& direction, const cube& cube_in);\r\n\r\n\r\n//1D FFT of complex data.\r\n//no normalization for forward FFT\r\ncx_vec fft(cx_vec X);\r\n\r\n//1D FFT of real data.\r\n//no normalization for forward FFT\r\ncx_vec fft(vec X);\r\n\r\n\r\n//3D FFT of complex data.\r\n//no normalization for forward FFT\r\ncx_cube fft(cx_cube X);\r\n\r\n//3D FFT of real data.\r\n//no normalization for forward FFT\r\ncx_cube fft(cube X);\r\n\r\n//1D inverse FFT of complex data.\r\n//normalized by N = X.n_elem\r\ncx_vec ifft(cx_vec X);\r\n\r\n//3D inverse FFT of complex data.\r\n//normalized by N = X.n_elem\r\ncx_cube ifft(cx_cube X);\r\n\r\n//returns a cube size object from the values inside a vector\r\nSizeCube as_size(const urowvec3& vec);\r\n\r\n//returns a matrix size object from the values inside a vector\r\nSizeMat as_size(const urowvec2& vec);\r\n\r\n//element-wise fmod\r\nmat fmod(mat mat_in, const double& denom) noexcept;\r\n\r\n//element-wise positive fmod\r\nmat fmod_p(mat mat_in, const double& denom) noexcept;\r\n\r\n//positive fmod\r\ndouble fmod_p(double num, const double& denom) noexcept;\r\n\r\n//just a simple square! May cause overflows!!\r\ninline double square(const double& input) noexcept {\r\n\treturn input * input;\r\n}\r\n\r\n\r\n//Poisson solver in 3D with anisotropic dielectric profiles\r\n//diel is the N*3 matrix of variations in dielectric tensor elements in direction normal to the surface\r\ncx_cube poisson_solver_3D(const cx_cube& rho, mat diel, rowvec3 lengths, uword normal_direction);\r\n\r\n\r\n\r\n//generate a copy of the cube with the elements shifted by N positions along:\r\n//dim=0: each row\r\n//dim=1: each column\r\n//dim=2: each slice\r\ntemplate \r\nCube shift(const Cube& A, const sword& N, const uword& dim) {\r\n\tCube B(arma::size(A));\r\n\tconst auto index_init = regspace(0, A.n_elem - 1);\r\n\timat sub_shift = conv_to::from(ind2sub(arma::size(A), index_init));\r\n\tconst uword size = arma::size(A)(dim);\r\n\tsub_shift.row(dim).for_each([&N, &size](sword& i) noexcept {\r\n\t\ti += N;\r\n\t\twhile (i < 0) i += size;\r\n\t\ti = i % size;\r\n\t});\r\n\r\n\tB(sub2ind(arma::size(A), conv_to::from(sub_shift))) = A(index_init);\r\n\r\n\treturn B;\r\n}\r\n\r\n//Undo a fftshift\r\ntemplate \r\nRow ifftshift(const Row &A) {\r\n\treturn shift(A, -1 * (A.n_elem / 2));\r\n}\r\n\r\n//Undo a fftshift\r\ntemplate \r\nCube ifftshift(Cube A) {\r\n\tfor (uword i = 0; i < 3; ++i) {\r\n\t\tA = shift(A, -1 * (arma::size(A)(i) / 2), i);\r\n\t}\r\n\r\n\treturn A;\r\n}\r\n\r\n//returns the size of a cube as a rowvec\r\ntemplate\r\nurowvec3 SizeVec(const Cube& c) {\r\n\tconst SizeCube size = arma::size(c);\r\n\treturn urowvec({ size(0), size(1), size(2) });\r\n}\r\n\r\n//returns the size of a matrix as a rowvec\r\ntemplate\r\nurowvec2 SizeVec(const Mat& c) {\r\n\tconst SizeMat size = arma::size(c);\r\n\treturn urowvec({ size(0), size(1) });\r\n}\r\n\r\n\r\n//sign of the val as -1/0/+1\r\ntemplate int sgn(T val) {\r\n\treturn (T(0) < val) - (val < T(0));\r\n}\r\n\r\n", "meta": {"hexsha": "94d6f56bedb7fb53d3983ab3d26b2fd82eeeb3bc", "size": 4544, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/slabcc_math.hpp", "max_stars_repo_name": "Anower120/slabcc", "max_stars_repo_head_hexsha": "8b8d17224314ad4c37c6c57d3c613592572870f8", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-09-02T01:11:56.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-02T01:11:56.000Z", "max_issues_repo_path": "src/slabcc_math.hpp", "max_issues_repo_name": "Anower120/slabcc", "max_issues_repo_head_hexsha": "8b8d17224314ad4c37c6c57d3c613592572870f8", "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/slabcc_math.hpp", "max_forks_repo_name": "Anower120/slabcc", "max_forks_repo_head_hexsha": "8b8d17224314ad4c37c6c57d3c613592572870f8", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3161290323, "max_line_length": 134, "alphanum_fraction": 0.6899207746, "num_tokens": 1287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391599428538, "lm_q2_score": 0.7520125793176222, "lm_q1q2_score": 0.6492813436474222}} {"text": "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace crest\n{\n namespace detail\n {\n /**\n * Returns the coefficients of the three linear Lagrange basis functions\n * associated with the triangle.\n *\n * Given basis function l_i for i = 0, 1, 2, then\n * l_i = a_i x + b_i y + c_i\n * where\n * [ a_0 a_1 a_2 ]\n * B = [ b_0 b_1 b_2 ]\n * [ c_0 c_1 c_2 ]\n * @param triangle\n * @return\n */\n template \n Eigen::Matrix basis_coefficients_for_triangle(const Triangle & triangle)\n {\n constexpr Scalar one = static_cast(1.0);\n Eigen::Matrix X;\n X <<\n triangle.a.x, triangle.a.y, one,\n triangle.b.x, triangle.b.y, one,\n triangle.c.x, triangle.c.y, one;\n\n return X.partialPivLu().solve(Eigen::Matrix::Identity());\n };\n /**\n * The interpolation of a fine-scale finite element space in the (possibly discontinuous) space of\n * affine functions on a coarse finite element space can be computed by the relation\n * Py = Bx, where y represent the weights in the affine coarse space and x represents the weights\n * in the fine-scale finite element space. This function computes B.\n * @param coarse\n * @param fine\n * @return\n */\n template \n Eigen::SparseMatrix build_affine_interpolator_rhs(\n const BiscaleMesh & mesh)\n {\n std::vector> triplets;\n\n for (int coarse_index = 0; coarse_index < mesh.coarse_mesh().num_elements(); ++coarse_index)\n {\n // The basis functions p_h in the affine space can be expressed as\n // p_h(x, y) = a x + b y + c\n // for some coefficients a, b, c.\n const auto coarse_triangle = mesh.coarse_mesh().triangle_for(coarse_index);\n const Eigen::Matrix coarse_coeff = basis_coefficients_for_triangle(coarse_triangle);\n for (const auto fine_index : mesh.descendants_for(coarse_index))\n {\n const auto vertex_indices = mesh.fine_mesh().elements()[fine_index].vertex_indices;\n const auto fine_triangle = mesh.fine_mesh().triangle_for(fine_index);\n const Eigen::Matrix fine_coeff = basis_coefficients_for_triangle(fine_triangle);\n\n // Local coarse basis function i\n for (size_t i = 0; i < 3; ++i)\n {\n // Local fine basis function j\n for (size_t j = 0; j < 3; ++j)\n {\n const auto vertex_index = vertex_indices[j];\n const auto product = [&](auto x, auto y)\n {\n const auto coarse_basis_value =\n coarse_coeff(0, i) * x + coarse_coeff(1, i) * y + coarse_coeff(2, i);\n const auto fine_basis_value =\n fine_coeff(0, j) * x + fine_coeff(1, j) * y + fine_coeff(2, j);\n return coarse_basis_value * fine_basis_value;\n };\n const auto inner_product = triquad<2>(product,\n fine_triangle.a,\n fine_triangle.b,\n fine_triangle.c);\n const auto row = 3 * coarse_index + i;\n triplets.push_back(Eigen::Triplet(row, vertex_index, inner_product));\n }\n }\n }\n }\n\n const auto num_dof_affine_space = 3 * mesh.coarse_mesh().num_elements();\n Eigen::SparseMatrix B(num_dof_affine_space, mesh.fine_mesh().num_vertices());\n B.setFromTriplets(triplets.cbegin(), triplets.cend());\n return B;\n };\n\n template \n Eigen::SparseMatrix build_affine_interpolator_lhs_inverse(\n const IndexedMesh & coarse)\n {\n const auto num_dof_affine_space = 3 * coarse.num_elements();\n Eigen::SparseMatrix P(num_dof_affine_space, num_dof_affine_space);\n\n // P will be block diagonal with 3x3 blocks, so we can reserve space in advance.\n P.reserve(Eigen::VectorXi::Constant(num_dof_affine_space, 3));\n\n Eigen::Matrix P_ref;\n P_ref << 2.0 / 24.0, 1.0 / 24.0, 1.0 / 24.0,\n 1.0 / 24.0, 2.0 / 24.0, 1.0 / 24.0,\n 1.0 / 24.0, 1.0 / 24.0, 2.0 / 24.0;\n\n for (int t = 0; t < coarse.num_elements(); ++t)\n {\n const auto triangle = coarse.triangle_for(t);\n const auto determinant = static_cast(2.0) * crest::area(triangle);\n assert(determinant != static_cast(0));\n Eigen::Matrix P_local = determinant * P_ref.template cast();\n P_local = P_local.inverse().eval();\n\n for (int j = 0; j < 3; ++j)\n {\n for (int i = 0; i < 3; ++i)\n {\n const auto row = 3 * t + i;\n const auto col = 3 * t + j;\n P.insert(row, col) = P_local(i, j);\n }\n }\n }\n\n return P;\n };\n\n /**\n * Given a coarse and fine mesh where the coarse mesh is a subset of the fine mesh (when interpreted as a forest),\n * build a matrix that interpolates functions in the fine finite element space in the\n * (possibly discontinuous) space of affine functions on the coarse space.\n * @param coarse\n * @param fine\n * @return\n */\n template \n Eigen::SparseMatrix affine_interpolator(\n const BiscaleMesh & mesh)\n {\n const Eigen::SparseMatrix B = build_affine_interpolator_rhs(mesh);\n const Eigen::SparseMatrix P = build_affine_interpolator_lhs_inverse(mesh.coarse_mesh());\n return P * B;\n };\n\n template \n std::vector count_vertex_occurrences(const IndexedMesh & mesh)\n {\n auto count = std::vector(mesh.num_vertices(), static_cast(0));\n for (const auto & element : mesh.elements())\n {\n for (const auto & v : element.vertex_indices)\n {\n ++count[v];\n }\n }\n return count;\n }\n\n /**\n * Given a triangulation T, returns a matrix of dimensions N(T) x [3 * card(T)] which maps functions in the\n * (possibly discontinuous) affine space P_1 to functions in the standard linear finite element space\n * on the mesh.\n * Here, N(T) denotes the number of vertices in T, and card(T) denotes the number of elements in T.\n * @param mesh\n * @return\n */\n template \n Eigen::SparseMatrix nodal_average_interpolator(const IndexedMesh & mesh)\n {\n const auto occurrences = count_vertex_occurrences(mesh);\n\n // Reserve space for 1 non-zero per column, since each basis function in the affine space\n // maps to exactly one vertex in the standard finite element space.\n const auto num_dof_affine_space = 3 * mesh.num_elements();\n Eigen::SparseMatrix J(mesh.num_vertices(), num_dof_affine_space);\n J.reserve(Eigen::VectorXi::Constant(num_dof_affine_space, 1));\n\n for (int t = 0; t < mesh.num_elements(); ++t)\n {\n const auto vertices = mesh.elements()[t].vertex_indices;\n\n for (size_t v = 0; v < 3; ++v)\n {\n const auto col = 3 * t + v;\n const auto vertex_index = vertices[v];\n const auto cardinality = occurrences[vertex_index];\n J.insert(vertex_index, col) = static_cast(1.0) / static_cast(cardinality);\n }\n }\n\n return J;\n };\n }\n\n template \n Eigen::SparseMatrix quasi_interpolator(const BiscaleMesh & mesh)\n {\n const auto P = detail::affine_interpolator(mesh);\n const auto J = detail::nodal_average_interpolator(mesh.coarse_mesh());\n return J * P;\n }\n\n}\n", "meta": {"hexsha": "420eaaf5387b640a99a5316f19f4272007b0f429", "size": 9366, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/crest/basis/quasi_interpolation.hpp", "max_stars_repo_name": "Andlon/crest", "max_stars_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/crest/basis/quasi_interpolation.hpp", "max_issues_repo_name": "Andlon/crest", "max_issues_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 5.0, "max_issues_repo_issues_event_min_datetime": "2017-01-24T10:45:27.000Z", "max_issues_repo_issues_event_max_datetime": "2017-01-27T16:21:37.000Z", "max_forks_repo_path": "include/crest/basis/quasi_interpolation.hpp", "max_forks_repo_name": "Andlon/crest", "max_forks_repo_head_hexsha": "f79bf5a68f3eb86f5e3422881678bc6f9011730a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7663551402, "max_line_length": 122, "alphanum_fraction": 0.5269058296, "num_tokens": 2041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418158002492, "lm_q2_score": 0.7025300573952052, "lm_q1q2_score": 0.6492374028954583}} {"text": "/**\n * @file kalmen.hpp\n * @author Vahid Bastani\n *\n * Implementation of Kalman filter\n */\n#ifndef SSMPACK_FILTER_KALMAN_HPP\n#define SSMPACK_FILTER_KALMAN_HPP\n\n#include \"ssmkit/distribution/gaussian.hpp\"\n#include \"ssmkit/distribution/conditional.hpp\"\n#include \"ssmkit/process/markov.hpp\"\n#include \"ssmkit/process/memoryless.hpp\"\n#include \"ssmkit/process/hierarchical.hpp\"\n#include \"ssmkit/filter/recursive_bayesian_base.hpp\"\n#include \n\nnamespace ssmkit {\nnamespace filter {\n\nusing process::Hierarchical;\nusing process::Markov;\nusing process::Memoryless;\nusing distribution::Conditional;\nusing distribution::Gaussian;\n\n/** Kalman filter\n */\ntemplate \nclass Kalman\n : public RecursiveBayesianBase> {\n\n public:\n //! Type of process object\n using TProcess =\n Hierarchical,\n Memoryless>;\n //! Type of the posterior state \\f$(\\hat{\\mathbf{x}}, \\hat{\\mathbf{P}})\\f$ \n using TCompeleteState =\n std::tuple;\n\n private:\n //! The process object\n TProcess process_;\n //! The state transition matrix \\f$\\mathbf{F}\\f$\n const arma::mat &dyn_mat_;\n //! The measurement matrix \\f$\\mathbf{H}\\f$\n const arma::mat &mes_mat_;\n //! The covariance of dynamic noise \\f$\\mathbf{Q}\\f$\n const arma::mat &dyn_cov_;\n //! The covariance of measurement noise \\f$\\mathbf{R}\\f$\n const arma::mat &mes_cov_;\n //! The corrected state vector \\f$\\mathbf{x}_{t|t}\\f$\n arma::vec state_vec_;\n //! The corrected state covariance \\f$\\mathbf{P}_{t|t}\\f$\n arma::mat state_cov_;\n //! The predicted state vector \\f$\\mathbf{x}_{t|t-1}\\f$\n arma::vec p_state_vec_;\n //! The predicted state covariance \\f$\\mathbf{P}_{t|t-1}\\f$\n arma::mat p_state_cov_;\n\n public:\n /** Construct a Kalman filter\n *\n * Construct a Kalman filter with parameters taken from \\p process argument.\n */\n Kalman(const TProcess &process)\n : process_(process),\n dyn_mat_(\n process_.template getProcess<0>().getCPDF().getParamMap().transfer),\n mes_mat_(\n process_.template getProcess<1>().getCPDF().getParamMap().transfer),\n dyn_cov_(process_.template getProcess<0>()\n .getCPDF()\n .getParamMap()\n .covariance),\n mes_cov_(process_.template getProcess<1>()\n .getCPDF()\n .getParamMap()\n .covariance) {}\n\n \n /** Prediction\n *\n * Performs the prediction step.\n *\n * \\f{equation}{\\hat{\\mathbf{x}}_{t|t-1} = \\mathbf{F}\\hat{\\mathbf{x}}_{t-1|t-1}+u_d(y^d_1,\n * \\cdots, y^d_{N_d}) \\f}\n * \\f{equation}{\\mathbf{P}_{t|t-1} = \\mathbf{F}\\mathbf{P}_{t-1|t-1}\\mathbf{F}^T+\\mathbf{Q}\\f}\n *\n * @param args... Control variables \\f$y^d_1, \\cdots, y^d_{N_d}\\f$ of the dynamic process, if any.\n */\n template \n void predict(const TArgs &... args) {\n // use the map function to pass controls, avoiding control definition\n // is move used here??\n p_state_vec_ =\n std::get<0>(process_.template getProcess<0>().getCPDF().getParamMap()(\n state_vec_, args...));\n p_state_cov_ = dyn_mat_ * state_cov_ * dyn_mat_.t() + dyn_cov_;\n }\n \n /** Correction\n *\n * Performs correction step.\n *\n * \\f{equation}{\\tilde{\\mathbf{z}}_t=\\mathbf{z}_t-\\mathbf{H}\\hat{\\mathbf{x}}_{t|t-1}-u_m(y^m_1, \\cdots, y^m_{N_m})\\f}\n * \\f{equation}{\\mathbf {S}_t=\\mathbf{H}\\mathbf{P}_{t|t-1}\\mathbf{H}^T+\\mathbf{R} \\f}\n * \\f{equation}{\\mathbf{K}_t=\\mathbf{P}_{t|t-1}\\mathbf{H}^T\\mathbf{S}_t^{-1} \\f}\n * \\f{equation}{\\hat{\\mathbf{x}}_{t|t}=\\hat{\\mathbf{x}}_{t|t-1}+\\mathbf{K}_{t}\\tilde{\\mathbf{z}}_t \\f}\n * \\f{equation}{\\mathbf{P}_{t|t}=(I-\\mathbf{K}_t\\mathbf{H})\\mathbf{P}_{t|t-1}\\f}\n *\n * @param measurement Measurement vector \\f$\\mathbf{z}_t\\f$.\n * @param args... Control variables \\f$y^m_1, \\cdots, y^m_{N_m}\\f$ of the measurement process, if any.\n * @return Estimated state \\f$(\\hat{\\mathbf{x}}_{t|t}, \\mathbf{P}_{t|t})\\f$\n */\n template \n TCompeleteState correct(const arma::vec &measurement,\n const TArgs &... args) {\n arma::vec inovation =\n measurement -\n std::get<0>(process_.template getProcess<1>().getCPDF().getParamMap()(\n p_state_vec_, args...));\n\n arma::mat inovation_cov = mes_mat_ * p_state_cov_ * mes_mat_.t() + mes_cov_;\n arma::mat kalman_gain =\n p_state_cov_ * mes_mat_.t() * arma::inv_sympd(inovation_cov);\n\n state_vec_ = p_state_vec_ + kalman_gain * inovation;\n state_cov_ = p_state_cov_ - kalman_gain * mes_mat_ * p_state_cov_;\n return std::make_tuple(state_vec_, state_cov_);\n }\n /** Initialization\n *\n * @return Initial state \\f$(\\hat{\\mathbf{x}}_{0|0}, \\mathbf{P}_{0|0})\\f$\n */\n TCompeleteState initialize() {\n state_vec_ = process_.template getProcess<0>().getInitialPDF().getMean();\n state_cov_ =\n process_.template getProcess<0>().getInitialPDF().getCovariance();\n return std::make_tuple(state_vec_, state_cov_);\n }\n};\n\ntemplate \nKalman makeKalman(\n Hierarchical,\n Memoryless> process) {\n return Kalman(process);\n}\n\n} // namespace filter\n} // namespace ssmkit\n\n#endif // SSMPACK_FILTER_KALMAN_HPP\n", "meta": {"hexsha": "063c9966482529e6b180704131e68fa42f9ea9e5", "size": 5416, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/ssmkit/filter/kalman.hpp", "max_stars_repo_name": "vahid-bastani/ssmpack", "max_stars_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2016-07-08T09:18:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-10T06:46:55.000Z", "max_issues_repo_path": "src/ssmkit/filter/kalman.hpp", "max_issues_repo_name": "vahidbas/ssmkit", "max_issues_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/ssmkit/filter/kalman.hpp", "max_forks_repo_name": "vahidbas/ssmkit", "max_forks_repo_head_hexsha": "68aed98b1c661a7d1c9e5610656de57f6a967532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2018-01-03T17:46:08.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-03T17:46:08.000Z", "avg_line_length": 34.7179487179, "max_line_length": 119, "alphanum_fraction": 0.6419867061, "num_tokens": 1687, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9241418137109955, "lm_q2_score": 0.702530051167069, "lm_q1q2_score": 0.6492373956720136}} {"text": "//\n// Created by kellerberrin on 5/08/18.\n//\n\n#include \"kel_exec_env.h\"\n#include \"kel_distribution.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace bm = boost::math;\nnamespace kel = kellerberrin;\n\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////\n//\n// Distribution functions use boost special functions.\n//\n////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\n\ndouble kel::NormalDistribution::pdf(double x, double mean, double std_dev) {\n\n static const double inv_sqrt_2pi = 0.3989422804014327;\n\n double a = (x - mean) / std_dev;\n\n return (inv_sqrt_2pi / std_dev) * std::exp(-0.5 * a * a);\n\n}\n\n\ndouble kel::GammaDistribution::pdf(double x) const {\n\n return bm::pdf(bm::gamma_distribution<>(_a, _b), x);\n\n}\n\ndouble kel::GammaDistribution::cdf(double x) const {\n\n return bm::cdf(bm::gamma_distribution<>(_a, _b), x);\n\n}\n\ndouble kel::GammaDistribution::quantile(double p) const {\n\n return bm::quantile(bm::gamma_distribution<>(_a, _b), p);\n\n}\n\n\n\ndouble kel::BetaDistribution::logInverseBetaFunction(double a, double b) {\n\n assert(a > 0.0);\n assert(b > 0.0);\n\n double log_gamma = bm::lgamma(a + b) - bm::lgamma(a) - bm::lgamma(b);\n\n return log_gamma;\n\n}\n\n\ndouble kel::BetaDistribution::logPartialPdf(double x, double a, double b) {\n\n assert(x >= 0 && x <= 1);\n assert(a >= 0);\n assert(b >= 0);\n\n double ret = (b - 1) * std::log(1 - x) + (a - 1) * std::log(x);\n\n return ret;\n\n}\n\n\ndouble kel::BetaDistribution::logPdf(double x, double a, double b) {\n\n assert(x >= 0 && x <= 1);\n assert(a > 0);\n assert(b > 0);\n\n double ret = logInverseBetaFunction(a, b) + logPartialPdf(x, a, b);\n\n return ret;\n\n}\n\ndouble kel::BetaDistribution::pdf(double x, double a, double b) {\n\n assert(x >= 0 && x <= 1);\n assert(a > 0);\n assert(b > 0);\n\n double p = bm::tgamma(a + b) / (bm::tgamma(a) * bm::tgamma(b));\n double q = std::pow(1 - x, b - 1) * std::pow(x, a - 1);\n return p * q;\n\n}\n\n\ndouble kel::BetaDistribution::mean(double a, double b) {\n\n assert(a > 0);\n assert(b > 0);\n\n return a / (a + b);\n\n}\n\n\ndouble kel::BetaDistribution::var(double a, double b) {\n\n assert(a > 0);\n assert(b > 0);\n\n return (a * b) / ((a + b) * (a + b) * (a + b + 1.0));\n\n}\n\n\ndouble kel::BetaDistribution::mode(double a, double b) {\n\n assert(a > 1);\n assert(b > 1);\n\n return (a - 1.0) / (a + b - 2.0);\n\n}\n\ndouble kel::BetaBinomialDistribution::pdf(size_t n, size_t k, double alpha, double beta) {\n\n assert(k <= n);\n assert(alpha > 0);\n assert(beta > 0);\n\n double coeff = bm::binomial_coefficient(n, k);\n\n double a1 = static_cast(k) + alpha;\n double b1 = static_cast(n-k) + beta;\n\n double p = bm::beta(a1, b1);\n double q = bm::beta(alpha, beta);\n\n return coeff * (p / q);\n\n}\n\n\ndouble kel::BetaBinomialDistribution::partialPdf(double n, double k, double alpha, double beta) {\n\n assert(k <= n);\n assert(alpha > 0);\n assert(beta > 0);\n\n double a1 = k + alpha;\n double b1 = n - k + beta;\n\n double p = bm::beta(a1, b1);\n double q = bm::beta(alpha, beta);\n\n return (p / q);\n\n}\n\n\ndouble kel::BetaBinomialDistribution::logPartialPdf(double n, double k, double alpha, double beta) {\n\n assert(k <= n);\n assert(alpha > 0.0);\n assert(beta > 0.0);\n\n double r = n - k;\n double a1 = k + alpha;\n double b1 = r + beta;\n\n double beta_n = bm::lgamma(a1) + bm::lgamma(b1) - bm::lgamma(a1 + b1);\n double beta_d = bm::lgamma(alpha) + bm::lgamma(beta) - bm::lgamma(alpha + beta);\n double prob = beta_n - beta_d;\n\n return prob;\n\n}\n\n\ndouble kel::BetaBinomialDistribution::logPdf(double n, double k, double alpha, double beta) {\n\n assert(k <= n);\n assert(alpha > 0.0);\n assert(beta > 0.0);\n\n double r = n - k;\n double a1 = k + alpha;\n double b1 = r + beta;\n\n double beta_coeff = bm::lgamma(r + 1.0) + bm::lgamma(k + 1.0) - bm::lgamma(n + 2.0);\n double inverse_log_binonimal_coeff = std::log(n + 1.0) + beta_coeff;\n double beta_n = bm::lgamma(a1) + bm::lgamma(b1) - bm::lgamma(a1 + b1);\n double beta_d = bm::lgamma(alpha) + bm::lgamma(beta) - bm::lgamma(alpha + beta);\n double prob = beta_n - beta_d - inverse_log_binonimal_coeff;\n\n return prob;\n\n}\n\n\n// .first is alpha, .second is beta. The raw moments are calculated from the observations and used to calculate alpha and beta.\n[[nodiscard]] std::pair kel::BetaBinomialDistribution::methodOfMoments(const std::vector& observations, size_t n_trials) {\n\n // calculate the first moment\n size_t obs_sum = std::accumulate(observations.begin(), observations.end(), static_cast(0));\n const double m1 = static_cast(obs_sum) / static_cast(observations.size());\n\n // calculate the 2nd moment\n auto sqr_lambda = [](size_t accumulate, size_t obs)->size_t { return accumulate + (obs * obs); };\n size_t sqr_sum = std::accumulate(observations.begin(), observations.end(), static_cast(0), sqr_lambda);\n const double m2 = static_cast(sqr_sum) / static_cast(observations.size());\n\n const double n = static_cast(n_trials);\n\n const double a_numer = (n * m1) - m2;\n const double ab_denom = n * ((m2 / m1) - m1 - 1) + m1;\n const double a = a_numer / ab_denom;\n\n const double b_numer = (n - m1) * (n - (m2/m1));\n const double b = b_numer / ab_denom;\n\n return {a, b};\n\n}\n\n\n\ndouble kel::BinomialDistribution::pdf(size_t n, size_t k, double prob_success) {\n\n assert(k <= n and k >= 0);\n assert(prob_success >= 0 and prob_success <= 1.0);\n\n double coeff = bm::binomial_coefficient(n, k);\n\n double p = std::pow(prob_success, static_cast(k));\n\n double q = std::pow((1.0 - prob_success), static_cast(n - k));\n\n return coeff * p * q;\n\n}\n\n\ndouble kel::BinomialDistribution::cdf(size_t n, double k, double prob_success) {\n\n assert(k <= n and k >= 0);\n assert(prob_success >= 0 and prob_success <= 1.0);\n\n size_t integer_k = std::floor(k);\n double sum_pdf = 0.0;\n\n for (size_t index = 0; index <= integer_k; ++index) {\n\n sum_pdf += cdf(n, index, prob_success);\n\n }\n\n return sum_pdf;\n\n}\n\n\nkel::HypergeometricDistribution::HypergeometricDistribution(size_t pop_successes_K, size_t sample_size_n, size_t population_N) {\n\n\n if (pop_successes_K > population_N) {\n\n ExecEnv::log().warn(\"HypergeometricDistribution::HypergeometricDistribution; Population Successes K:{} exceeds population size :{}\",\n pop_successes_K, population_N);\n pop_successes_K = population_N;\n }\n\n if (sample_size_n > population_N) {\n\n ExecEnv::log().warn(\"HypergeometricDistribution::HypergeometricDistribution; Sample size n:{} exceeds population size :{}\",\n sample_size_n, population_N);\n sample_size_n = population_N;\n }\n\n pop_successes_K_ = pop_successes_K;\n sample_size_n_ = sample_size_n;\n population_N_ = population_N;\n\n}\n\ndouble kel::HypergeometricDistribution::pdf(size_t successes_k) const {\n\n if (successes_k > upperSuccesses_k()) {\n\n ExecEnv::log().warn(\"HypergeometricDistribution::pdf; r_successes k:{} exceeds upper limit :{}\",\n successes_k, upperSuccesses_k());\n successes_k = upperSuccesses_k();\n\n }\n\n if (successes_k < lowerSuccesses_k()) {\n\n ExecEnv::log().warn(\"HypergeometricDistribution::pdf; r_successes k:{} below lower limit :{}\",\n successes_k, lowerSuccesses_k());\n successes_k = lowerSuccesses_k();\n\n }\n\n bm::hypergeometric_distribution hypergeometric(pop_successes_K_, sample_size_n_, population_N_);\n\n return bm::pdf(hypergeometric, successes_k);\n\n}\n\ndouble kel::HypergeometricDistribution::cdf(size_t successes_k) const {\n\n if (successes_k > upperSuccesses_k()) {\n\n ExecEnv::log().warn(\"HypergeometricDistribution(N:{},K:{},n:{},k:{})::cdf; r_successes k exceeds upper limit :{}\",\n population_N_, pop_successes_K_, sample_size_n_, successes_k, upperSuccesses_k());\n successes_k = upperSuccesses_k();\n\n }\n\n if (successes_k < lowerSuccesses_k()) {\n\n ExecEnv::log().warn(\"HypergeometricDistribution(N:{},K:{},n:{},k:{})::cdf; r_successes k exceeds upper limit :{}\",\n population_N_, pop_successes_K_, sample_size_n_, successes_k, lowerSuccesses_k());\n successes_k = lowerSuccesses_k();\n\n }\n\n bm::hypergeometric_distribution hypergeometric(pop_successes_K_, sample_size_n_, population_N_);\n\n return bm::cdf(hypergeometric, successes_k);\n\n}\n\ndouble kel::HypergeometricDistribution::quantile(size_t successes_k) const {\n\n if (successes_k > upperSuccesses_k()) {\n\n ExecEnv::log().warn(\"HypergeometricDistribution::quantile; r_successes k:{} exceeds upper limit :{}\",\n successes_k, upperSuccesses_k());\n successes_k = upperSuccesses_k();\n\n }\n\n if (successes_k < lowerSuccesses_k()) {\n\n ExecEnv::log().warn(\"HypergeometricDistribution::quantile; r_successes k:{} below lower limit :{}\",\n successes_k, lowerSuccesses_k());\n successes_k = lowerSuccesses_k();\n\n }\n\n bm::hypergeometric_distribution hypergeometric(pop_successes_K_, sample_size_n_, population_N_);\n\n return bm::quantile(hypergeometric, successes_k);\n\n}\n\n\nsize_t kel::HypergeometricDistribution::lowerSuccesses_k() const {\n\n int64_t lower_success = static_cast(sample_size_n_ + pop_successes_K_) - static_cast(population_N_);\n return static_cast(std::max(0, lower_success));\n\n}\n\n\ndouble kel::HypergeometricDistribution::upperSingleTailTest(size_t test_value_k) const {\n\n if (test_value_k > 0) {\n\n test_value_k = test_value_k - 1;\n\n }\n\n return 1.0 - cdf(test_value_k);\n\n}\n\ndouble kel::HypergeometricDistribution::lowerSingleTailTest(size_t test_value_k) const {\n\n return cdf(test_value_k);\n\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// The Poisson distribution. Uses boost for implementation.\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\ndouble kel::Poisson::pdf(size_t count) const {\n\n return bm::pdf(bm::poisson_distribution<>(lambda_), count);\n\n}\n\ndouble kel::Poisson::cdf(size_t count) const {\n\n return bm::cdf(bm::poisson_distribution<>(lambda_), count);\n\n}\n\nsize_t kel::Poisson::quantile(double quantile) const {\n\n return bm::quantile(bm::poisson_distribution<>(lambda_), quantile);\n\n}\n\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n// The Negative Binomial distribution. Uses boost for implementation.\n/////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\ndouble kel::NegativeBinomial::pdf(size_t count) const {\n\n return bm::pdf(bm::negative_binomial_distribution<>(r_successes_, p_prob_success_), count);\n\n}\n\ndouble kel::NegativeBinomial::cdf(size_t count) const {\n\n return bm::cdf(bm::negative_binomial_distribution<>(r_successes_, p_prob_success_), count);\n\n}\n\nsize_t kel::NegativeBinomial::quantile(double quantile) const {\n\n return bm::quantile(bm::negative_binomial_distribution<>(r_successes_, p_prob_success_), quantile);\n\n}\n\ndouble kel::NegativeBinomial::mean() const {\n\n return bm::mean(bm::negative_binomial_distribution<>(r_successes_, p_prob_success_));\n\n}\n", "meta": {"hexsha": "059dc7bece2bdf1b74826decabbb6f50c1fa4e2b", "size": 11832, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "kel_utility/kel_distribution.cpp", "max_stars_repo_name": "kellerberrin/OSM_Gene_Cpp", "max_stars_repo_head_hexsha": "4ec4d1244f3f1b16213cf05f0056d8e5f85d68c4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "kel_utility/kel_distribution.cpp", "max_issues_repo_name": "kellerberrin/OSM_Gene_Cpp", "max_issues_repo_head_hexsha": "4ec4d1244f3f1b16213cf05f0056d8e5f85d68c4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "kel_utility/kel_distribution.cpp", "max_forks_repo_name": "kellerberrin/OSM_Gene_Cpp", "max_forks_repo_head_hexsha": "4ec4d1244f3f1b16213cf05f0056d8e5f85d68c4", "max_forks_repo_licenses": ["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.4697986577, "max_line_length": 146, "alphanum_fraction": 0.6423258959, "num_tokens": 3128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425267730008, "lm_q2_score": 0.7057850278370112, "lm_q1q2_score": 0.6490699263585817}} {"text": "\n#include \n#include \n#include \nusing namespace Eigen;\nusing namespace std;\n\n\n\ntemplate\nEIGEN_DONT_INLINE Q nlerp(const Q& a, const Q& b, typename Q::Scalar t)\n{\n return Q((a.coeffs() * (1.0-t) + b.coeffs() * t).normalized());\n}\n\ntemplate\nEIGEN_DONT_INLINE Q slerp_eigen(const Q& a, const Q& b, typename Q::Scalar t)\n{\n return a.slerp(t,b);\n}\n\ntemplate\nEIGEN_DONT_INLINE Q slerp_legacy(const Q& a, const Q& b, typename Q::Scalar t)\n{\n typedef typename Q::Scalar Scalar;\n static const Scalar one = Scalar(1) - dummy_precision();\n Scalar d = a.dot(b);\n Scalar absD = internal::abs(d);\n if (absD>=one)\n return a;\n\n // theta is the angle between the 2 quaternions\n Scalar theta = std::acos(absD);\n Scalar sinTheta = internal::sin(theta);\n\n Scalar scale0 = internal::sin( ( Scalar(1) - t ) * theta) / sinTheta;\n Scalar scale1 = internal::sin( ( t * theta) ) / sinTheta;\n if (d<0)\n scale1 = -scale1;\n\n return Q(scale0 * a.coeffs() + scale1 * b.coeffs());\n}\n\ntemplate\nEIGEN_DONT_INLINE Q slerp_legacy_nlerp(const Q& a, const Q& b, typename Q::Scalar t)\n{\n typedef typename Q::Scalar Scalar;\n static const Scalar one = Scalar(1) - epsilon();\n Scalar d = a.dot(b);\n Scalar absD = internal::abs(d);\n\n Scalar scale0;\n Scalar scale1;\n\n if (absD>=one)\n {\n scale0 = Scalar(1) - t;\n scale1 = t;\n }\n else\n {\n // theta is the angle between the 2 quaternions\n Scalar theta = std::acos(absD);\n Scalar sinTheta = internal::sin(theta);\n\n scale0 = internal::sin( ( Scalar(1) - t ) * theta) / sinTheta;\n scale1 = internal::sin( ( t * theta) ) / sinTheta;\n if (d<0)\n scale1 = -scale1;\n }\n\n return Q(scale0 * a.coeffs() + scale1 * b.coeffs());\n}\n\ntemplate\ninline T sin_over_x(T x)\n{\n if (T(1) + x*x == T(1))\n return T(1);\n else\n return std::sin(x)/x;\n}\n\ntemplate\nEIGEN_DONT_INLINE Q slerp_rw(const Q& a, const Q& b, typename Q::Scalar t)\n{\n typedef typename Q::Scalar Scalar;\n\n Scalar d = a.dot(b);\n Scalar theta;\n if (d<0.0)\n theta = /*M_PI -*/ Scalar(2)*std::asin( (a.coeffs()+b.coeffs()).norm()/2 );\n else\n theta = Scalar(2)*std::asin( (a.coeffs()-b.coeffs()).norm()/2 );\n\n // theta is the angle between the 2 quaternions\n// Scalar theta = std::acos(absD);\n Scalar sinOverTheta = sin_over_x(theta);\n\n Scalar scale0 = (Scalar(1)-t)*sin_over_x( ( Scalar(1) - t ) * theta) / sinOverTheta;\n Scalar scale1 = t * sin_over_x( ( t * theta) ) / sinOverTheta;\n if (d<0)\n scale1 = -scale1;\n\n return Quaternion(scale0 * a.coeffs() + scale1 * b.coeffs());\n}\n\ntemplate\nEIGEN_DONT_INLINE Q slerp_gael(const Q& a, const Q& b, typename Q::Scalar t)\n{\n typedef typename Q::Scalar Scalar;\n\n Scalar d = a.dot(b);\n Scalar theta;\n// theta = Scalar(2) * atan2((a.coeffs()-b.coeffs()).norm(),(a.coeffs()+b.coeffs()).norm());\n// if (d<0.0)\n// theta = M_PI-theta;\n\n if (d<0.0)\n theta = /*M_PI -*/ Scalar(2)*std::asin( (-a.coeffs()-b.coeffs()).norm()/2 );\n else\n theta = Scalar(2)*std::asin( (a.coeffs()-b.coeffs()).norm()/2 );\n\n\n Scalar scale0;\n Scalar scale1;\n if(theta*theta-Scalar(6)==-Scalar(6))\n {\n scale0 = Scalar(1) - t;\n scale1 = t;\n }\n else\n {\n Scalar sinTheta = std::sin(theta);\n scale0 = internal::sin( ( Scalar(1) - t ) * theta) / sinTheta;\n scale1 = internal::sin( ( t * theta) ) / sinTheta;\n if (d<0)\n scale1 = -scale1;\n }\n\n return Quaternion(scale0 * a.coeffs() + scale1 * b.coeffs());\n}\n\nint main()\n{\n typedef double RefScalar;\n typedef float TestScalar;\n\n typedef Quaternion Qd;\n typedef Quaternion Qf;\n\n unsigned int g_seed = (unsigned int) time(NULL);\n std::cout << g_seed << \"\\n\";\n// g_seed = 1259932496;\n srand(g_seed);\n\n Matrix maxerr(7);\n maxerr.setZero();\n\n Matrix avgerr(7);\n avgerr.setZero();\n\n cout << \"double=>float=>double nlerp eigen legacy(snap) legacy(nlerp) rightway gael's criteria\\n\";\n\n int rep = 100;\n int iters = 40;\n for (int w=0; w());\n Qd br(b.cast());\n Qd cr;\n\n\n\n cout.precision(8);\n cout << std::scientific;\n for (int i=0; i();\n c[0] = nlerp(a,b,t);\n c[1] = slerp_eigen(a,b,t);\n c[2] = slerp_legacy(a,b,t);\n c[3] = slerp_legacy_nlerp(a,b,t);\n c[4] = slerp_rw(a,b,t);\n c[5] = slerp_gael(a,b,t);\n\n VectorXd err(7);\n err[0] = (cr.coeffs()-refc.cast().coeffs()).norm();\n// std::cout << err[0] << \" \";\n for (int k=0; k<6; ++k)\n {\n err[k+1] = (c[k].coeffs()-refc.coeffs()).norm();\n// std::cout << err[k+1] << \" \";\n }\n maxerr = maxerr.cwise().max(err);\n avgerr += err;\n// std::cout << \"\\n\";\n b = cr.cast();\n br = cr;\n }\n// std::cout << \"\\n\";\n }\n avgerr /= RefScalar(rep*iters);\n cout << \"\\n\\nAccuracy:\\n\"\n << \" max: \" << maxerr.transpose() << \"\\n\";\n cout << \" avg: \" << avgerr.transpose() << \"\\n\";\n\n // perf bench\n Quaternionf a,b;\n a.coeffs().setRandom();\n a.normalize();\n b.coeffs().setRandom();\n b.normalize();\n //b = a;\n float s = 0.65;\n\n #define BENCH(FUNC) {\\\n BenchTimer t; \\\n for(int k=0; k<2; ++k) {\\\n t.start(); \\\n for(int i=0; i<1000000; ++i) \\\n FUNC(a,b,s); \\\n t.stop(); \\\n } \\\n cout << \" \" << #FUNC << \" => \\t \" << t.value() << \"s\\n\"; \\\n }\n\n cout << \"\\nSpeed:\\n\" << std::fixed;\n BENCH(nlerp);\n BENCH(slerp_eigen);\n BENCH(slerp_legacy);\n BENCH(slerp_legacy_nlerp);\n BENCH(slerp_rw);\n BENCH(slerp_gael);\n}\n", "meta": {"hexsha": "d715de75d2a229c3ce097abbbb16ef82f06516e8", "size": 5937, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/quat_slerp.cpp", "max_stars_repo_name": "eundersander/bps-nav", "max_stars_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 22.0, "max_stars_repo_stars_event_min_datetime": "2021-03-15T01:49:05.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T23:17:14.000Z", "max_issues_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/quat_slerp.cpp", "max_issues_repo_name": "eundersander/bps-nav", "max_issues_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2021-06-27T21:41:25.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-18T21:46:40.000Z", "max_forks_repo_path": "simulator/external/habitat-sim-geodesic/habitat_sim_geodesic/csrc/eigen/bench/quat_slerp.cpp", "max_forks_repo_name": "eundersander/bps-nav", "max_forks_repo_head_hexsha": "a33bac7d10dc077baa596a76790b4fc829d332f7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2021-03-27T17:17:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-19T12:00:06.000Z", "avg_line_length": 24.036437247, "max_line_length": 143, "alphanum_fraction": 0.577901297, "num_tokens": 1971, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8056321983146848, "lm_q2_score": 0.8056321959813275, "lm_q1q2_score": 0.6490432370815239}} {"text": "//\n// Created by hhy on 2022/3/11.\n//\n#include \"OsqpEigen/OsqpEigen.h\"\n#include \n#include \n\nusing namespace std;\n\nint main() {\n OsqpEigen::Solver solver;\n\n // assert(InitMat(solver));\n int numOfVar = 3;\n int numOfCons = 4;\n\n Eigen::SparseMatrix hessian(numOfVar, numOfVar);\n hessian.insert(0, 0) = 1;\n hessian.insert(0, 1) = -1;\n hessian.insert(0, 2) = 1;\n hessian.insert(1, 0) = -1;\n hessian.insert(1, 1) = 2;\n hessian.insert(1, 2) = -2;\n hessian.insert(2, 0) = 1;\n hessian.insert(2, 1) = -2;\n hessian.insert(2, 2) = 4;\n std::cout << \"hessian:\" << hessian << std::endl;\n /* hessian << 1, -1, 1,\n -1, 2, -2,\n 1, -2, 4;*/\n\n Eigen::SparseMatrix linearMatrix(numOfCons, numOfVar);\n linearMatrix.insert(0, 0) = 1;\n linearMatrix.insert(1, 1) = 1;\n linearMatrix.insert(2, 2) = 1;\n linearMatrix.insert(3, 0) = 1;\n linearMatrix.insert(3, 1) = 1;\n linearMatrix.insert(3, 2) = 1;\n std::cout << \" linearMatrix:\" << linearMatrix << std::endl;\n /*linearMatrix << 1, 0, 0,\n 0, 1, 0,\n 0, 0, 1,\n 1, 1, 1;*/\n\n Eigen::Vector3d gradient;\n gradient << 2, -3, 1;\n std::cout << \"gradient:\\n\" << gradient << std::endl;\n\n Eigen::VectorXd lowerBound;\n lowerBound.resize(4, 1);\n lowerBound << 0, 0, 0, 0.4;\n std::cout << \"lowerBound:\\n\" << lowerBound << std::endl;\n\n Eigen::VectorXd upperBound;\n upperBound.resize(4, 1);\n upperBound << 1, 1, 1, 0.5;\n\n solver.settings()->setVerbosity(true);\n solver.settings()->setAlpha(1.0);\n\n // assert(solver.data()->setHessianMatrix(H_s)== true);\n solver.data()->setNumberOfVariables(numOfVar);\n solver.data()->setNumberOfConstraints(numOfCons);\n\n assert(solver.data()->setHessianMatrix(hessian));\n assert(solver.data()->setGradient(gradient));\n assert(solver.data()->setLinearConstraintsMatrix(linearMatrix));\n assert(solver.data()->setLowerBound(lowerBound));\n assert(solver.data()->setUpperBound(upperBound));\n\n assert(solver.initSolver());\n\n // assert(solver.solve() == true);\n assert(solver.solveProblem() == OsqpEigen::ErrorExitFlag::NoError);\n\n std::cout << solver.getSolution() << std::endl;\n}", "meta": {"hexsha": "ee289d3df42a3f50ca5f13da8af23e16b8a52615", "size": 2167, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "osqp_eigen/test/test_osqp2.cpp", "max_stars_repo_name": "HaiYangLib/Tools", "max_stars_repo_head_hexsha": "7cd6be3545574b8431bf404163d24202bda3e621", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "osqp_eigen/test/test_osqp2.cpp", "max_issues_repo_name": "HaiYangLib/Tools", "max_issues_repo_head_hexsha": "7cd6be3545574b8431bf404163d24202bda3e621", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "osqp_eigen/test/test_osqp2.cpp", "max_forks_repo_name": "HaiYangLib/Tools", "max_forks_repo_head_hexsha": "7cd6be3545574b8431bf404163d24202bda3e621", "max_forks_repo_licenses": ["Apache-2.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.1428571429, "max_line_length": 69, "alphanum_fraction": 0.6262113521, "num_tokens": 734, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438951025545426, "lm_q2_score": 0.7690802423634961, "lm_q1q2_score": 0.6490230500020151}} {"text": "/**\n * Copyright (C) Omar Thor - All Rights Reserved\n * Unauthorized copying of this file, via any medium is strictly prohibited\n * Proprietary and confidential\n *\n * Written by Omar Thor , 2017\n */\n#ifndef SP_ALGO_NN_LOSS_MEAN_SQUARE_ERROR_HPP\n#define SP_ALGO_NN_LOSS_MEAN_SQUARE_ERROR_HPP\n\n#include \n#include \"../config.hpp\"\n#include \"../matrix.hpp\"\n#include \"../types.hpp\"\n#include \"sp/util/hints.hpp\"\n\n\nSP_ALGO_NN_NAMESPACE_BEGIN\n\n/**\n * \\brief Mean Square Error Derivative\n */\nstruct mean_square_error_derivative {\n\n sp_hot void operator()( const size_t& si,\n const tensor_4& predicted,\n const tensor_4& observed,\n tensor_4& result) {\n\n BOOST_ASSERT(predicted.dimensions() == observed.dimensions());\n\n const size_t m = predicted.dimension(1) * predicted.dimension(2) * predicted.dimension(3);\n\n float_t factor = float_t(2.0f) / static_cast (m);\n\n result.chip(si, 0) = factor * (predicted.chip(si, 0) - observed.chip(si, 0));\n }\n};\n\n/**\n * \\brief Mean Square Error\n */\nstruct mean_square_error {\n\n using derivative_type = mean_square_error_derivative;\n\n auto operator()( const size_t& si,\n const tensor_4& predicted,\n const tensor_4& observed) {\n BOOST_ASSERT(predicted.dimensions() == observed.dimensions());\n\n tensor_0 d = (\n (predicted.chip(si, 0) - observed.chip(si, 0))\n *\n (predicted.chip(si, 0) - observed.chip(si, 0))\n ).sum();\n\n return d(0) / static_cast (predicted.size());\n }\n\n derivative_type derivative;\n};\n\n\nSP_ALGO_NN_NAMESPACE_END\n\n#endif\t/* SP_ALGO_NN_LOSS_MEAN_SQUARE_ERROR_HPP */\n\n", "meta": {"hexsha": "11629f3087f90757e21a3fe64923a2fce54717e2", "size": 1904, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/sp/algo/nn/loss/mean_square_error.hpp", "max_stars_repo_name": "thorigin/sp", "max_stars_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_stars_repo_licenses": ["FSFAP"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/sp/algo/nn/loss/mean_square_error.hpp", "max_issues_repo_name": "thorigin/sp", "max_issues_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_issues_repo_licenses": ["FSFAP"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/sp/algo/nn/loss/mean_square_error.hpp", "max_forks_repo_name": "thorigin/sp", "max_forks_repo_head_hexsha": "a837b4fcb5b7184591585082012942bbdb8f11f9", "max_forks_repo_licenses": ["FSFAP"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.5942028986, "max_line_length": 98, "alphanum_fraction": 0.6050420168, "num_tokens": 432, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8438950947024555, "lm_q2_score": 0.7690802423634963, "lm_q1q2_score": 0.6490230439631302}} {"text": "// Copyright(c) 2019-present, Alexander Silva Barbosa & bflib contributors.\r\n// Distributed under the MIT License (http://opensource.org/licenses/MIT)\r\n\r\n/**\r\n * @author Alexander Silva Barbosa \r\n * @date 2019\r\n * Kalman Filter\r\n */\r\n\r\n#pragma once\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace Eigen;\r\n\r\ntemplate \r\nclass KF\r\n{\r\n private:\r\n typedef Matrix MatNx1;\r\n typedef Matrix MatNxN;\r\n typedef Matrix MatNxM;\r\n typedef Matrix MatNxP;\r\n typedef Matrix MatPxN;\r\n typedef Matrix MatPxP;\r\n typedef Matrix MatMx1;\r\n typedef Matrix MatPx1;\r\n typedef Matrix Mat3x1;\r\n\r\n public:\r\n typedef MatNx1 State;\r\n typedef MatMx1 Input;\r\n typedef MatPx1 Output;\r\n typedef Input Control;\r\n typedef Output Sensor;\r\n typedef MatNxN ModelCovariance;\r\n typedef MatPxP SensorCovariance;\r\n typedef MatNxN StateMatrix;\r\n typedef MatNxM InputMatrix;\r\n typedef MatPxN OutputMatrix;\r\n typedef Mat3x1 Uncertainty;\r\n \r\n private:\r\n typedef void (*ProcessFunction)(StateMatrix &A, InputMatrix &B, OutputMatrix &C, double dt);\r\n\r\n std::default_random_engine gen;\r\n std::normal_distribution distr{0.0, 1.0};\r\n std::chrono::time_point start;\r\n\r\n State x;\r\n StateMatrix A;\r\n ModelCovariance Q;\r\n InputMatrix B;\r\n OutputMatrix C;\r\n SensorCovariance R;\r\n \r\n MatNx1 randX;\r\n MatPx1 randY;\r\n\r\n MatNxN P;\r\n MatNxN Qsqrt;\r\n MatPxP Rsqrt;\r\n\r\n Output z, yError;\r\n MatPxP S;\r\n MatNxP K;\r\n MatNxN I;\r\n\r\n\r\n ProcessFunction processFn;\r\n\r\n void init()\r\n {\r\n processFn = NULL;\r\n P = Q;\r\n I.setIdentity();\r\n\r\n Qsqrt = Q.cwiseSqrt();\r\n Rsqrt = R.cwiseSqrt();\r\n\r\n start = std::chrono::high_resolution_clock::now();\r\n }\r\n public:\r\n KF()\r\n {\r\n Q.setIdentity();\r\n R.setIdentity();\r\n x.setZero();\r\n init();\r\n }\r\n\r\n KF(State X) : x(X)\r\n {\r\n Q.setIdentity();\r\n R.setIdentity();\r\n init();\r\n }\r\n\r\n KF(ModelCovariance Q, SensorCovariance R) : Q(Q), R(R)\r\n {\r\n x.setZero();\r\n init();\r\n }\r\n\r\n KF(State X, ModelCovariance Q, SensorCovariance R) : x(X), Q(Q), R(R)\r\n {\r\n init();\r\n }\r\n\r\n virtual ~KF()\r\n {\r\n\r\n }\r\n\r\n void seed()\r\n {\r\n gen = std::default_random_engine(std::chrono::system_clock::now().time_since_epoch().count());\r\n }\r\n\r\n void seed(long long s)\r\n {\r\n gen = std::default_random_engine(s);\r\n }\r\n\r\n State state()\r\n {\r\n State x;\r\n x.setZero();\r\n return x;\r\n }\r\n\r\n Input input()\r\n {\r\n Input u;\r\n u.setZero();\r\n return u;\r\n }\r\n\r\n Output output()\r\n {\r\n Output y;\r\n y.setZero();\r\n return y;\r\n }\r\n\r\n ModelCovariance createQ()\r\n {\r\n ModelCovariance Q;\r\n Q.setZero();\r\n return Q;\r\n }\r\n\r\n SensorCovariance createR()\r\n {\r\n SensorCovariance R;\r\n R.setZero();\r\n return R;\r\n }\r\n\r\n ModelCovariance getP()\r\n {\r\n return P;\r\n }\r\n\r\n Uncertainty getUncertainty(unsigned int x1, unsigned int x2)\r\n {\r\n Uncertainty C;\r\n C.setZero();\r\n if(x1 >= states || x2 >= states)\r\n return C;\r\n \r\n Matrix p;\r\n p(0, 0) = P(x1, x1);\r\n p(0, 1) = P(x1, x2);\r\n p(1, 0) = P(x2, x1);\r\n p(1, 1) = P(x2, x2);\r\n\r\n EigenSolver< Matrix > es(p);\r\n Matrix eValue = es.pseudoEigenvalueMatrix();\r\n Matrix eVector = es.pseudoEigenvectors();\r\n\r\n C[0] = eValue(0,0);\r\n C[1] = eValue(1,1);\r\n C[2] = std::atan2(eVector(0, 1), eVector(0, 0));\r\n\r\n return C;\r\n }\r\n\r\n void setQ(ModelCovariance Q)\r\n {\r\n this->Q = Q;\r\n P = Q;\r\n Qsqrt = Q.cwiseSqrt();\r\n }\r\n\r\n void setR(SensorCovariance R)\r\n {\r\n this->R = R;\r\n Rsqrt = R.cwiseSqrt();\r\n }\r\n\r\n double time()\r\n {\r\n auto end = std::chrono::high_resolution_clock::now();\r\n std::chrono::duration diff = end - start;\r\n start = std::chrono::high_resolution_clock::now();\r\n return diff.count();\r\n }\r\n\r\n double delay(double s)\r\n {\r\n double ellapsed = time();\r\n double remain = s - ellapsed;\r\n if(remain < 0)\r\n return ellapsed;\r\n std::this_thread::sleep_for(std::chrono::nanoseconds((long long)(remain * 1e9)));\r\n ellapsed += time();\r\n return ellapsed;\r\n }\r\n\r\n void setProcess(ProcessFunction fn)\r\n {\r\n processFn = fn;\r\n }\r\n\r\n virtual void process(StateMatrix &A, InputMatrix &B, OutputMatrix &C, double dt)\r\n {\r\n\r\n }\r\n\r\n void simulate(State &x, Output &y, Input &u, double dt)\r\n {\r\n doProcess(dt);\r\n\r\n randn(randX);\r\n randn(randY);\r\n\r\n x = A * x + B * u + Qsqrt * randX;\r\n y = C * x + Rsqrt * randY;\r\n }\r\n\r\n void run(State &xK, Output &y, Input &u, double dt)\r\n {\r\n predict(u, dt);\r\n update(y);\r\n xK = x;\r\n }\r\n\r\n private:\r\n void predict(Input &u, double dt)\r\n {\r\n doProcess(dt);\r\n x = A * x + B * u;\r\n P = A * P * A.transpose() + Q;\r\n }\r\n\r\n void update(Output &y)\r\n {\r\n z = C * x;\r\n yError = y - z;\r\n\r\n S = C * P * C.transpose() + R;\r\n K = P * C.transpose() * S.inverse();\r\n x = x + K * yError;\r\n\r\n P = (I - K * C) * P;\r\n }\r\n\r\n void doProcess(double dt)\r\n {\r\n if(processFn != NULL)\r\n processFn(A, B, C, dt);\r\n else\r\n process(A, B, C, dt);\r\n }\r\n\r\n template\r\n void randn(T &mat)\r\n {\r\n for (size_t i = 0; i < mat.rows(); i++)\r\n {\r\n for (size_t j = 0; j < mat.cols(); j++)\r\n {\r\n mat(i, j) = distr(gen);\r\n }\r\n }\r\n }\r\n\r\n};", "meta": {"hexsha": "7ffc21396f9f0d93ea59be82a5a3920d137a9127", "size": 7217, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "bflib/KF.hpp", "max_stars_repo_name": "AlexanderSilvaB/KFs", "max_stars_repo_head_hexsha": "b5eb3692ebc88d158a5210c714b7e7ac1fe3ee32", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-08-30T07:46:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-02-06T10:35:29.000Z", "max_issues_repo_path": "bflib/KF.hpp", "max_issues_repo_name": "AlexanderSilvaB/KFs", "max_issues_repo_head_hexsha": "b5eb3692ebc88d158a5210c714b7e7ac1fe3ee32", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bflib/KF.hpp", "max_forks_repo_name": "AlexanderSilvaB/KFs", "max_forks_repo_head_hexsha": "b5eb3692ebc88d158a5210c714b7e7ac1fe3ee32", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T08:35:01.000Z", "max_forks_repo_forks_event_max_datetime": "2020-08-30T09:06:35.000Z", "avg_line_length": 24.6313993174, "max_line_length": 107, "alphanum_fraction": 0.4465844534, "num_tokens": 1706, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998822, "lm_q2_score": 0.7122321964553657, "lm_q1q2_score": 0.648971524509422}} {"text": "#include \n#include \n\nint main() {\n // definitions\n {\n // compile time sized matrix\n dlib::matrix y;\n // dynamically sized matrix\n dlib::matrix m(3, 3);\n // later we can change size of this matrix\n m.set_size(6, 6);\n }\n // initializations\n {\n // comma operator\n dlib::matrix m(3, 3);\n m = 1., 2., 3., 4., 5., 6., 7., 8., 9.;\n std::cout << \"Matix from comma operator\\n\" << m << std::endl;\n\n // wrap array\n double data[] = {1, 2, 3, 4, 5, 6};\n auto m2 = dlib::mat(data, 2, 3); // create matrix with size 2x3\n std::cout << \"Matix from array\\n\" << m2 << std::endl;\n\n // Matrix elements can be accessed with () operator\n m(1, 2) = 300;\n std::cout << \"Matix element updated\\n\" << m << std::endl;\n\n // Also you can initialize matrix with some predefined values\n auto a = dlib::identity_matrix(3);\n std::cout << \"Identity matix \\n\" << a << std::endl;\n\n auto b = dlib::ones_matrix(3, 4);\n std::cout << \"Ones matix \\n\" << b << std::endl;\n\n auto c = dlib::randm(3, 4); // matrix with random values with size 3x3\n std::cout << \"Random matix \\n\" << c << std::endl;\n }\n // arithmetic operations\n {\n dlib::matrix a(2, 2);\n a = 1, 1, 1, 1;\n dlib::matrix b(2, 2);\n b = 2, 2, 2, 2;\n\n auto c = a + b;\n std::cout << \"c = a + b \\n\" << c << std::endl;\n\n auto e = a * b; // real matrix multiplication\n std::cout << \"e = a dot b \\n\" << e << std::endl;\n\n a += 5;\n std::cout << \"a += 5 \\n\" << a << std::endl;\n\n auto d = dlib::pointwise_multiply(a, b); // element wise multiplication\n std::cout << \"d = a * b \\n\" << e << std::endl;\n\n auto t = dlib::trans(a); // transpose matrix\n std::cout << \"transposed matrix a \\n\" << t << std::endl;\n }\n // partial access\n {\n dlib::matrix m;\n m = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;\n auto sm =\n dlib::subm(m, dlib::range(1, 2),\n dlib::range(1, 2)); // original matrix can't be updated\n std::cout << \"Sub matrix \\n\" << sm << std::endl;\n\n dlib::set_subm(m, dlib::range(1, 2), dlib::range(1, 2)) = 100;\n std::cout << \"Updated sub matrix \\n\" << m << std::endl;\n }\n // there are no implicit broadcasting in dlib\n {\n // we can simulate broadcasting with partial access\n dlib::matrix v;\n v = 10, 10;\n dlib::matrix m;\n m = 1, 2, 3, 4, 5, 6;\n for (int i = 0; i < m.nc(); ++i) {\n dlib::set_colm(m, i) += v;\n }\n std::cout << \"Matrix with updated columns \\n\" << m << std::endl;\n }\n return 0;\n}\n", "meta": {"hexsha": "14c4880ed5160ef13f49d9eed25ffa70307c6933", "size": 2644, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter01/dlib_samples/linalg_dlib.cc", "max_stars_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_stars_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 201.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T12:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:56:11.000Z", "max_issues_repo_path": "Chapter01/dlib_samples/linalg_dlib.cc", "max_issues_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_issues_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T10:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T19:35:05.000Z", "max_forks_repo_path": "Chapter01/dlib_samples/linalg_dlib.cc", "max_forks_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_forks_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T15:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:07:09.000Z", "avg_line_length": 30.0454545455, "max_line_length": 76, "alphanum_fraction": 0.5321482602, "num_tokens": 975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673359709796, "lm_q2_score": 0.7981867729389246, "lm_q1q2_score": 0.6488199557261368}} {"text": "/* \n * Copyright (c) 2021, Tetsuro Nagai\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nconstexpr int BUF_MAX=100000;\n\nconstexpr int DIM_DATA=2 ;\n\nusing std::string;\nusing std::vector;\nusing std::array;\nusing std::cout;\nusing std::cerr;\nusing std::endl;\n\n\nint main(int argc, char** argv)\n{\n\n if(argc != 1){\n cerr << \"ERROR: no arguments allowed\" < pdf;\n vector x;\n\n string buf;\n while (std::getline(std::cin, buf))\n {\n char tmp1[BUF_MAX];\n char tmp2[BUF_MAX];\n auto bsscanf = std::sscanf(buf.c_str(), \"%s %s\" , tmp1,tmp2);\n if(bsscanf != DIM_DATA){\n cerr << \"ERROR: not enough columns\\n\" << \"Exit!!\" < x_tmp){\n cerr << \"ERROR: x should be in ascending (increasing) order\\nExit!!\" < residual_sq(pdf.size(), 0);\n std::transform(x.begin(), x.end(), residual_sq.begin(), [&ave_x](double x){return (x-ave_x)*(x-ave_x);});\n\n double variance = std::inner_product(residual_sq.begin(), residual_sq.end(), pdf.begin(), 0.0) ;\n double stddev = sqrt(variance);\n\n vector residual_3th(pdf.size(), 0);\n std::transform(x.begin(), x.end(), residual_3th.begin(), [&ave_x](double x){return (x-ave_x)*(x-ave_x)*(x-ave_x);});\n\n auto skew = std::inner_product(residual_3th.begin(), residual_3th.end(), pdf.begin(), 0.0) / pow(stddev, 3) ;\n\n vector residual_4th(pdf.size(), 0);\n std::transform(x.begin(), x.end(), residual_4th.begin(), [&ave_x](double x){return (x-ave_x)*(x-ave_x)*(x-ave_x)*(x-ave_x);});\n\n auto kurtosis = std::inner_product(residual_4th.begin(), residual_4th.end(), pdf.begin(), 0.0) / pow(variance, 2) -3.0 ;\n\n auto at_max = std::max_element(pdf.begin(), pdf.end());\n auto mode = x[std::distance(pdf.begin(), at_max)];\n\n //auto median = x[std::distance(pdf.begin(), at_max)];\n vector cdf(pdf.size(), 0);\n std::partial_sum(pdf.begin(), pdf.end(), cdf.begin());\n\n auto at_Q1 = find_if(cdf.begin(), cdf.end(), [](double x){return x>0.25? true : false;});\n auto at_Q2 = find_if(cdf.begin(), cdf.end(), [](double x){return x>0.50? true : false;});\n auto at_Q3 = find_if(cdf.begin(), cdf.end(), [](double x){return x>0.75? true : false;});\n\n auto Q1 = x[std::distance(cdf.begin(), at_Q1)];\n auto Q2 = x[std::distance(cdf.begin(), at_Q2)];\n auto Q3 = x[std::distance(cdf.begin(), at_Q3)];\n\n\n std::cout << boost::format(\"#%12s %12s %12s %12s %12s\") % \"ave_x\"%\"stddev\" % \"variance\" % \"skew\" % \"kurtosis\" << std::endl;\n std::cout << boost::format(\" %12.8g %12.8g %12.8g %12.8g %12.8g\\n\") % ave_x % stddev % variance % skew % kurtosis;\n\n std::cout << boost::format(\"#%12s %12s %12s\") % \"1Q\"%\"2Q(median)\" % \"3Q\" << std::endl;\n std::cout << boost::format(\" %12.8g %12.8g %12.8g \\n\") % Q1 % Q2 % Q3 ;\n\n std::cout << boost::format(\"#%12s %12s %12s\") % \"mode \"%\"normalization\" % \"\" << std::endl;\n std::cout << boost::format(\" %12.8g %12.8g\\n\") % mode % sum_pdf ;\n\n return EXIT_SUCCESS ;\n}\n", "meta": {"hexsha": "17acce8a2ad3d37409aad1812438e153060ca89d", "size": 4341, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/pdf_anlyzer.cpp", "max_stars_repo_name": "tnagai-github/pdf_analyzer", "max_stars_repo_head_hexsha": "dd31d84094166e6d23317f5861a7605afc60a250", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/pdf_anlyzer.cpp", "max_issues_repo_name": "tnagai-github/pdf_analyzer", "max_issues_repo_head_hexsha": "dd31d84094166e6d23317f5861a7605afc60a250", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/pdf_anlyzer.cpp", "max_forks_repo_name": "tnagai-github/pdf_analyzer", "max_forks_repo_head_hexsha": "dd31d84094166e6d23317f5861a7605afc60a250", "max_forks_repo_licenses": ["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.1374045802, "max_line_length": 128, "alphanum_fraction": 0.5966367196, "num_tokens": 1394, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128672997041659, "lm_q2_score": 0.7981867825403177, "lm_q1q2_score": 0.6488199345831044}} {"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#if SOLUTION\n // Area of the cell\n double area;\n // Midpoints of edges in the reference cell\n Eigen::MatrixXd midpoints(2, num_nodes);\n switch (num_nodes) {\n case 3: {\n // Compute cell area for triangles\n area = 0.5 * ((vertices(0, 1) - vertices(0, 0)) *\n (vertices(1, 2) - vertices(1, 0)) -\n (vertices(1, 1) - vertices(1, 0)) *\n (vertices(0, 2) - vertices(0, 0)));\n // clang-format off\n midpoints << vertices(0, 0) + vertices(0, 1),\n\tvertices(0, 1) + vertices(0, 2),\n\tvertices(0, 2) + vertices(0, 0),\n\tvertices(1, 0) + vertices(1, 1),\n\tvertices(1, 1) + vertices(1, 2),\n\tvertices(1, 2) + vertices(1, 0);\n // clang-format on\n break;\n }\n case 4: {\n // Compute cell area for rectangles\n area =\n (vertices(0, 1) - vertices(0, 0)) * (vertices(1, 3) - vertices(1, 0));\n // clang-format off\n midpoints << vertices(0, 0) + vertices(0, 1),\n\tvertices(0, 1) + vertices(0, 2),\n\tvertices(0, 2) + vertices(0, 3),\n\tvertices(0, 3) + vertices(0, 0),\n\tvertices(1, 0) + vertices(1, 1),\n\tvertices(1, 1) + vertices(1, 2),\n\tvertices(1, 2) + vertices(1, 3),\n\tvertices(1, 3) + vertices(1, 0);\n // clang-format on\n break;\n }\n default: {\n LF_ASSERT_MSG(false, \"Illegal entity type!\");\n break;\n }\n } // end switch\n midpoints *= 0.5; // The factor 1/2\n // Evaluate f(x) at the quadrature points, i.e. the midpoints of the edges\n Eigen::VectorXd fvals = Eigen::VectorXd::Zero(4);\n for (int i = 0; i < num_nodes; ++i) {\n fvals(i) = f(midpoints.col(i));\n }\n // Midpoint quadrature for all nodes of the element\n for (int k = 0; k < num_nodes; k++) {\n // Contribution from one end of an edge\n elem_vec[k] += 0.5 * fvals(k);\n // Contribution from the other end of the end\n elem_vec[(k + 1) % num_nodes] += 0.5 * fvals(k);\n }\n // Rescale with quadrature weights\n elem_vec *= (area / num_nodes);\n#else\n\n //====================\n // Your code goes here\n //====================\n\n#endif\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": "1270c6350ddebd4145826243f1ecb62aeb30d90e", "size": 3440, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/ElementMatrixComputation/mastersolution/mylinearloadvector.cc", "max_stars_repo_name": "padomu/NPDECODES", "max_stars_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/ElementMatrixComputation/mastersolution/mylinearloadvector.cc", "max_issues_repo_name": "padomu/NPDECODES", "max_issues_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/ElementMatrixComputation/mastersolution/mylinearloadvector.cc", "max_forks_repo_name": "padomu/NPDECODES", "max_forks_repo_head_hexsha": "d2bc5b0d2d5e76e4d5b8ab6948c82f902211182e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 29.4017094017, "max_line_length": 80, "alphanum_fraction": 0.6171511628, "num_tokens": 1037, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8376199633332891, "lm_q2_score": 0.774583389368527, "lm_q1q2_score": 0.6488065102014404}} {"text": "//\n// Created by chen-tian on 7/24/17.\n//\n\n#include \"pose_estimate_3d3d.h\"\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace cv;\n\nvoid pose_estimate_3d3d::pose_estimation_3d3d\n (const vector &pts1,\n const vector &pts2,\n Mat &R, Mat &t)\n{\n Point3f p1, p2; //center of mass\n int N = pts1.size();\n for ( int i = 0; i < N; i++ )\n {\n p1 += pts1[i];\n p2 += pts2[i];\n }\n\n p1 /= N;\n p2 /= N;\n vector q1(N), q2(N);//remove the center\n for ( int i = 0; i < N; i++ )\n {\n q1[i] = pts1[i] - p1;\n q2[i] = pts2[i] - p2;\n }\n\n //compute q1*q2^T\n Eigen::Matrix3d W = Eigen::Matrix3d::Zero();\n for ( int i = 0; i svd(W, Eigen::ComputeFullU|Eigen::ComputeFullV);\n Eigen::Matrix3d U = svd.matrixU();\n Eigen::Matrix3d V = svd.matrixV();\n cout<<\"U=\"<(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 t = ( Mat_(3,1)<< t_(0,0),t_(1,0),t_(2,0));\n}", "meta": {"hexsha": "8f234d1c559df513ac12f96cf1f2d33a2d3b4d5d", "size": 1628, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch7_VO1/pose_estimation_3d3d/src/pose_estimate_3d3d.cpp", "max_stars_repo_name": "ClovisChen/slam14", "max_stars_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ch7_VO1/pose_estimation_3d3d/src/pose_estimate_3d3d.cpp", "max_issues_repo_name": "ClovisChen/slam14", "max_issues_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ch7_VO1/pose_estimation_3d3d/src/pose_estimate_3d3d.cpp", "max_forks_repo_name": "ClovisChen/slam14", "max_forks_repo_head_hexsha": "35fad23a491f2dd7666edab55ae849ac937d44c2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 26.6885245902, "max_line_length": 116, "alphanum_fraction": 0.5245700246, "num_tokens": 621, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9149009596336303, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.64868229714921}} {"text": "/* \n* Copyright 2017-2018 Simon Raschke\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http://www.apache.org/licenses/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#if __has_include()\n#include \n#elif __has_include()\n#include \n#endif\n \n\n\nnamespace enhance\n{\n // number of digits\n template \n std::uint16_t numDigits(T number)\n {\n std::uint16_t digits = 0;\n if (number < 0) digits = 1; // remove this line if '-' counts as a digit\n std::uint32_t helper = static_cast(number);\n while (helper) \n {\n helper /= 10;\n digits++;\n }\n return digits;\n }\n \n\n\n // angle between two eigen vectors\n // vectors dont have to be normalized\n // will give signed result\n template\n constexpr float directed_angle(const DERIVED1& v1, const DERIVED2& v2)\n {\n assert(std::isfinite(std::atan2(v2.normalized()(1), v2.normalized()(0)) - std::atan2(v1.normalized()(1), v1.normalized()(0))));\n return std::atan2(v2.normalized()(1), v2.normalized()(0)) - std::atan2(v1.normalized()(1), v1.normalized()(0));\n }\n \n\n\n // will give unsigned result\n template\n constexpr float absolute_angle(const DERIVED1& v1, const DERIVED2& v2)\n {\n return std::abs(directed_angle(v1,v2));\n }\n \n\n \n //directed angle normalized to 0 to 360°\n template\n constexpr float normalized_angle(const DERIVED1& v1, const DERIVED2& v2)\n {\n const float angle = directed_angle(v1,v2);\n return angle < 0.f ? angle+M_PI : angle;\n }\n \n \n \n // calculate rad from given deg\n // expects floating pioint type\n template::value>::type>\n constexpr T deg_to_rad(const T& __deg) noexcept\n {\n return __deg*M_PI/180;\n }\n \n \n \n // calculate deg from given rad\n // expects floating pioint type\n template::value>::type>\n constexpr T rad_to_deg(const T& __rad) noexcept\n {\n return __rad/M_PI*180;\n }\n \n \n \n // calculates the volume of a sphere given its radius\n // may throw if radius is negative\n template\n constexpr T sphere_volume(const T& __rad) \n {\n if(__rad < 0) throw std::logic_error(\"radius must not be negative\");\n return M_PI*__rad*__rad*__rad*4.f/3.f;\n }\n \n \n \n // calculates the surface of a sphere given its radius\n // may throw if radius is negative\n template\n constexpr T sphere_surface(const T& __rad) \n {\n if(__rad < 0) throw std::logic_error(\"radius must not be negative\");\n return M_PI*__rad*__rad*4.f;\n }\n \n \n \n // calculates the area of a circle given its radius\n // may throw if radius is negative\n template\n constexpr T circle_area(const T& __rad) \n {\n if(__rad < 0) throw std::logic_error(\"radius must not be negative\");\n return M_PI*__rad*__rad;\n }\n \n \n \n // calculates the radius of a circle given its area\n // may throw if area is negative\n template\n constexpr T circle_area_to_radius(const T& __area)\n {\n if(__area < 0) throw std::logic_error(\"area must not be negative\");\n return std::sqrt( __area/M_PI );\n }\n \n \n \n // calculates the volume of a cone given its base radius and heigt\n // may throw if area is negative\n // may throw if height is negative\n template\n constexpr T cone_volume(const T& __rad, const T& __height) \n {\n if(__rad < 0) throw std::logic_error(\"radius must not be negative\");\n if(__height < 0) throw std::logic_error(\"height must not be negative\");\n return enhance::circle_area(__rad)*__height/(static_cast(3));\n }\n\n\n\n template\n constexpr typename std::enable_if::value,T>::type nth_root(const T& __val )\n {\n return std::pow(__val, 1.0/N);\n }\n}", "meta": {"hexsha": "5e65e65e7f8849fc1882c8f85c3175b4e8f83520", "size": 4812, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "enhance/math_utility.hpp", "max_stars_repo_name": "simonraschke/vesicle", "max_stars_repo_head_hexsha": "3b9b5529c3f36bdeff84596bc59509781b103ead", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-03-15T17:24:52.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-15T17:24:52.000Z", "max_issues_repo_path": "enhance/math_utility.hpp", "max_issues_repo_name": "simonraschke/vesicle", "max_issues_repo_head_hexsha": "3b9b5529c3f36bdeff84596bc59509781b103ead", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "enhance/math_utility.hpp", "max_forks_repo_name": "simonraschke/vesicle", "max_forks_repo_head_hexsha": "3b9b5529c3f36bdeff84596bc59509781b103ead", "max_forks_repo_licenses": ["Apache-2.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.5214723926, "max_line_length": 135, "alphanum_fraction": 0.6417290108, "num_tokens": 1207, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894745194283, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6486062881967635}} {"text": "//==================================================================================================\n/*!\n @file\n\n @copyright 2016 NumScale SAS\n @copyright 2016 J.T. Lapreste\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_LOGSPACE_SUB_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_LOGSPACE_SUB_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n @ingroup group-exponential\n Function object implementing logspace_sub capabilities\n\n Compute the log of a sum from logs of terms\n properly compute \\f$\\log (\\exp (\\log x) - \\exp (\\log y))\\f$\n\n @par Semantic:\n\n For every parameters of floating type T:\n\n @code\n T r = logspace_sub(x, y);\n @endcode\n\n is similar to:\n\n @code\n T r = log(exp(log(x)) - exp(log(y)));\n @endcode\n\n **/\n const boost::dispatch::functor logspace_sub = {};\n} }\n#endif\n\n#include \n#include \n\n#endif\n", "meta": {"hexsha": "2824f102bd70e4240a5217a91ff2d4d6340656a1", "size": 1220, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/function/logspace_sub.hpp", "max_stars_repo_name": "yaeldarmon/boost.simd", "max_stars_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/function/logspace_sub.hpp", "max_issues_repo_name": "yaeldarmon/boost.simd", "max_issues_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/function/logspace_sub.hpp", "max_forks_repo_name": "yaeldarmon/boost.simd", "max_forks_repo_head_hexsha": "561316cc54bdc6353ca78f3b6d7e9120acd11144", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4, "max_line_length": 100, "alphanum_fraction": 0.5860655738, "num_tokens": 273, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045996818987, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6485985283988829}} {"text": "#pragma once\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 vpp;\nusing namespace std;\nusing namespace cv;\nusing namespace Eigen;\n\n// Inhomogeneous coordinates\nclass point_3d\n{\npublic: double x,y,z;\n\n point_3d()\n {x=y=z=0.0;}\n\n point_3d(double xx, double yy, double zz)\n {x=xx;y=yy;z=zz;}\n\n friend ostream & operator << (ostream & os, const point_3d p)\n {\n os<<\"[\"<\n\n#include \n\ntypedef unsigned long long nombre;\ntypedef std::vector vecteur;\n\nnamespace {\n nombre cycle(nombre p, nombre m) {\n nombre n = p, i = 1;\n while (n != 1) {\n ++i;\n n = (n * p) % m;\n }\n return i;\n }\n}\n\nENREGISTRER_PROBLEME(188, \"The hyperexponentiation of a number\") {\n // The hyperexponentiation or tetration of a number a by a positive integer b, denoted by a↑↑b or ba, \n // is recursively defined by:\n //\n // a↑↑1 = a,\n // a↑↑(k+1) = a(a↑↑k).\n //\n // Thus we have e.g. 3↑↑2 = 33 = 27, hence 3↑↑3 = 327 = 7625597484987 and 3↑↑4 is roughly \n // 10^(3.6383346400240996*10^12).\n //\n // Find the last 8 digits of 1777↑↑1855.\n vecteur masques{100000000};\n while (masques.back() > 2)\n masques.push_back(cycle(1777, masques.back()));\n\n nombre resultat = 1;\n for (const auto &m : boost::adaptors::reverse(masques))\n resultat = puissance::puissance_modulaire(1777, resultat, m);\n\n return std::to_string(resultat);\n}\n", "meta": {"hexsha": "6f443b9a31a1735568656b83ca43f90a7cb2f577", "size": 1150, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme188.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/probleme188.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/probleme188.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": 26.7441860465, "max_line_length": 106, "alphanum_fraction": 0.5973913043, "num_tokens": 363, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.940789754239075, "lm_q2_score": 0.6893056104028799, "lm_q1q2_score": 0.6484916558065409}} {"text": "#include \r\n#include \r\n#include \r\n#include \"nv_core.h\"\r\n#include \"nv_ml_mlp.h\"\r\n\r\n\r\n// 多層パーセプトロン\r\n// 2 Layer\r\n\r\nstatic float nv_mlp_sigmoid(float a) {\r\n\treturn 1.0F / (1.0F + expf(-a));\r\n}\r\n\r\n// クラス分類\r\n\r\nint nv_mlp_predict_label(const nv_mlp_t *mlp, const Eigen::Ref > x)\r\n{\r\n\tEigen::Map input_bias(mlp->input_bias->v, mlp->hidden);\r\n\tEigen::Map > input_w(mlp->input_w->v, mlp->hidden, mlp->input);\r\n\tEigen::Map hidden_bias(mlp->hidden_bias->v, mlp->output);\r\n\tEigen::Map > hidden_w(mlp->hidden_w->v, mlp->output, mlp->hidden);\r\n\tEigen::VectorXf y = hidden_w*(input_w*x + input_bias).unaryExpr(&nv_mlp_sigmoid) + hidden_bias;\r\n\tint l;\r\n\ty.maxCoeff(&l);\r\n\treturn (y[l] > 0.F) ? l : -1;\r\n}\r\n\r\ndouble nv_mlp_predict_d(const nv_mlp_t *mlp, const Eigen::Ref > x)\r\n{\r\n\tEigen::Map input_bias(mlp->input_bias->v, mlp->hidden);\r\n\tEigen::Map > input_w(mlp->input_w->v, mlp->hidden, mlp->input);\r\n\tfloat hidden_bias = *mlp->hidden_bias->v;\r\n\tEigen::Map hidden_w(mlp->hidden_w->v, mlp->hidden);\r\n\treturn 1./(1.+exp(-hidden_w.dot((input_w*x + input_bias).unaryExpr(&nv_mlp_sigmoid)) - hidden_bias));\r\n}\r\n\r\ndouble nv_mlp_bagging_predict_d(const nv_mlp_t **mlp, int nmlp, const Eigen::Ref > x)\r\n{\r\n\tdouble p = 0.0F;\r\n\tdouble factor = 1.0 / nmlp;\r\n\tint i;\r\n\t\r\n\tfor (i = 0; i < nmlp; ++i) {\r\n\t\tp += factor * nv_mlp_predict_d(mlp[i], x);\r\n\t}\r\n\r\n\treturn p;\r\n}\r\n\r\n// 非線形重回帰\r\n\r\nvoid nv_mlp_regression(const nv_mlp_t *mlp, const Eigen::Ref > x, nv_matrix_t *out)\r\n{\r\n\tEigen::Map input_bias(mlp->input_bias->v, mlp->hidden);\r\n\tEigen::Map > input_w(mlp->input_w->v, mlp->hidden, mlp->input);\r\n\tEigen::Map hidden_bias(mlp->hidden_bias->v, mlp->output);\r\n\tEigen::Map > hidden_w(mlp->hidden_w->v, mlp->output, mlp->hidden);\r\n\tEigen::Map y(out->v, out->n);\r\n\ty = hidden_w*(input_w*x + input_bias).unaryExpr(&nv_mlp_sigmoid) + hidden_bias;\r\n}\r\n", "meta": {"hexsha": "0476a1a20f9dc2eeba62c8de6b8582d02591a8f6", "size": 2501, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nvxs/nv_ml/nv_mlp.cpp", "max_stars_repo_name": "aliakseis/animeface-2009", "max_stars_repo_head_hexsha": "ca633bf3623c2aac1823657bb5004c5ec2b46723", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nvxs/nv_ml/nv_mlp.cpp", "max_issues_repo_name": "aliakseis/animeface-2009", "max_issues_repo_head_hexsha": "ca633bf3623c2aac1823657bb5004c5ec2b46723", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nvxs/nv_ml/nv_mlp.cpp", "max_forks_repo_name": "aliakseis/animeface-2009", "max_forks_repo_head_hexsha": "ca633bf3623c2aac1823657bb5004c5ec2b46723", "max_forks_repo_licenses": ["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.3387096774, "max_line_length": 138, "alphanum_fraction": 0.6881247501, "num_tokens": 864, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9407897475985937, "lm_q2_score": 0.6893056040203134, "lm_q1q2_score": 0.6484916452245668}} {"text": "// TestMatrixExcel.cpp\n//\n// Test output of a matrix in Excel. Here we \n// use the Excel Driver object directly.\n//\n// The output is in cell/numeric format.\n//\n// (C) Datasim Education BV 2006-2017\n//\n\n\n#include \"ExcelDriverlite.hpp\"\n#include \"Utilities.hpp\"\n\n#include \n#include \"UtilitiesDJD/VectorsAndMatrices/NestedMatrix.hpp\"\n\n#include \n#include \n#include \n\ndouble rho = 0.5;\ndouble NormalPdf2d(double x, double y)\n{ // Bivariate normal density function\n\t\n\tdouble fac = 1.0 / (2.0 * 3.14159265359 * std::sqrt(1.0 - rho*rho));\n\tdouble t = x*x - 2.0*rho*x*y + y*y;\n\tt /= 2.0 * (1.0 - rho*rho);\n\n\treturn fac * std::exp(-t);\n}\n\ntemplate \n\tMatrix DiscreteNormalPdf2d(const std::vector& x, const std::vector& y)\n{\n\treturn CreateDiscreteFunction2d(x, y, NormalPdf2d);\n}\n\nint main()\n{\n\t\t//\tusing NumericMatrix = boost::numeric::ublas::matrix;\n\t\t// C++11 syntax\n\t\t//using NumericMatrix = NestedMatrix;\n\t\t// using Vector = std::vector\n\t\ttypedef NestedMatrix NumericMatrix;\n\t\ttypedef std::vector Vector;\n\n\t\tstd::size_t N = 10; std::size_t M = 6; // rows and columns\n\t\tNumericMatrix matrix(N + 1, M + 1);\n\t\tfor (std::size_t i = 0; i < matrix.size1(); ++i)\n\t\t{\n\t\t\tfor (std::size_t j = 0; j < matrix.size2(); ++j)\n\t\t\t{\n\t\t\t\tmatrix(i, j) = static_cast(i + j);\n\t\t\t}\n\t\t}\n\t\n\t\t// Start Excel\n\t\tExcelDriver& excel = ExcelDriver::Instance();\n\t\texcel.MakeVisible(true);\t\t// Default is INVISIBLE!\n\n\t\t// Call Excel print function\n\t\tstd::string sheetName(\"Test Case 101 Matrix\");\n\t\tlong row = 4; long col = 2;\n\t//\texcel.AddMatrix(matrix, sheetName, row, col);\n\t\n\n\t\tstd::string sheetName2(\"Matrix Labels Case\");\n\n\t//\tExcelDriver& excel = ExcelDriver::Instance();\n\t//\texcel.MakeVisible(true);\t\t// Default is INVISIBLE!\n\n\t\t// Labels for rows and columns of the Excel matrix.\n\t\t// Only labelled values are printed!!\n\t\tstd::list rowLabels; // C++11: {\"A\",\"B\",\"C\",\"D\",\"E\", \"F\",\"K\",\"L\"};\n\t\trowLabels.push_back(\"A\");\n\t\trowLabels.push_back(\"B\");\n\t\trowLabels.push_back(\"C\");\n\t\trowLabels.push_back(\"D\");\n\t\trowLabels.push_back(\"E\");\n\t\trowLabels.push_back(\"F\");\n\t\trowLabels.push_back(\"K\");\n\t\trowLabels.push_back(\"L\");\n\n\t\tstd::list colLabels; // C++11: {\"C1\", \"C2\", \"C3\", \"C4\",\"C5\"};\n\t\tcolLabels.push_back(\"C1\");\n\t\tcolLabels.push_back(\"C2\");\n\t\tcolLabels.push_back(\"C3\");\n\t\tcolLabels.push_back(\"C4\");\n\t\tcolLabels.push_back(\"C5\");\n\n\t\tlong rowPos = 4; long colPos = 3;\n\t//\texcel.AddMatrix(matrix, sheetName2, rowLabels, colLabels, \n\t\t//\t\t\t\t\t\t\t\t\t\trowPos, colPos);\n\t\t\n\t\t{\n\t\t\t// Using mapping continuous space to discrete space\n\t\t\tstd::size_t N = 20; std::size_t M = 10;\n\t\t\tauto x = CreateMesh(N, -4.0, 4.0);\n\t\t\tauto y = CreateMesh(M, -4.0, 4.0);\n\n\t\t\tNumericMatrix matrix = DiscreteNormalPdf2d(x, y);\n\t\t\n\t\t//\tExcelDriver& excel = ExcelDriver::Instance();\n\t\t\tstd::string sheetName(\"Bivariate Normal pdf\");\n\t\t\tlong row = 1; long col = 1;\n\t\t\texcel.AddMatrix(matrix, sheetName, row, col);\n\t}\n\n\n\treturn 0;\n}\n", "meta": {"hexsha": "a1a24a98157eae97a7a45708e8e9253eb79f0440", "size": 3090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Level_9/myUtilities/ExcelDriver/TestMatrixExcel.cpp", "max_stars_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_stars_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Level_9/myUtilities/ExcelDriver/TestMatrixExcel.cpp", "max_issues_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_issues_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Level_9/myUtilities/ExcelDriver/TestMatrixExcel.cpp", "max_forks_repo_name": "ZhehaoLi9705/QuantNet_CPP", "max_forks_repo_head_hexsha": "a889f4656e757842f4163b0cda7e098cc6ad1193", "max_forks_repo_licenses": ["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.3451327434, "max_line_length": 87, "alphanum_fraction": 0.657605178, "num_tokens": 969, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7931059511841119, "lm_q2_score": 0.8175744761936437, "lm_q1q2_score": 0.6484231826054118}} {"text": "#include \n#include \n#include \n#include \n\n#include \n\nnamespace mp = boost::multiprecision;\nusing float_huge = mp::number>;\nusing timer_value_type = float;\nusing std::chrono::high_resolution_clock;\n\ntemplate \nstruct scoped_timer\n{\n explicit scoped_timer(T& t) : t_(t), start_(high_resolution_clock::now()) { }\n ~scoped_timer()\n {\n t_ = std::chrono::duration(high_resolution_clock::now() -\n start_).count();\n }\n\nprivate:\n T& t_;\n high_resolution_clock::time_point start_;\n};\n\nfloat_huge pi_gauss_legendre()\n{\n float_huge a = static_cast(1);\n float_huge b = static_cast(1) /\n mp::sqrt(static_cast(2));\n float_huge t = static_cast(.25);\n float_huge p = static_cast(1);\n\n for (int correct_digits = 3;\n correct_digits < std::numeric_limits::digits;\n correct_digits *= 2)\n {\n float_huge a_n = (a + b) / static_cast(2);\n b = mp::sqrt(a * b);\n t -= p * mp::pow(a - a_n, static_cast(2));\n p *= static_cast(2);\n a = a_n;\n }\n\n float_huge pi = mp::pow(a + b, 2) / (static_cast(4) * t);\n\n return pi;\n}\n\nint main()\n{\n timer_value_type t = 0;\n {\n scoped_timer timer(t);\n\n std::cout <<\n std::setprecision(std::numeric_limits::max_digits10)\n << \"pi = \" << pi_gauss_legendre() << '\\n';\n }\n std::cout << \"Gauss-Legendre took \" << std::fixed << std::setprecision(4)\n << t << \"(ms)\\n\";\n\n return 0;\n}\n/*\nPartial Output (Windows, x64, Release, VC 15):\nAbout to run Gauss-Legendre, t is 0(ms)\npi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062...\nGauss-Legendre took 6674.4258(ms)\n*/\n", "meta": {"hexsha": "bd65245d4385820f9e3f644b4b299e9502c9e898", "size": 1998, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "pi.cpp", "max_stars_repo_name": "parsa/pi-day", "max_stars_repo_head_hexsha": "90eeadefdfeffc520e60924e60b73ea092502949", "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": "pi.cpp", "max_issues_repo_name": "parsa/pi-day", "max_issues_repo_head_hexsha": "90eeadefdfeffc520e60924e60b73ea092502949", "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": "pi.cpp", "max_forks_repo_name": "parsa/pi-day", "max_forks_repo_head_hexsha": "90eeadefdfeffc520e60924e60b73ea092502949", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0, "max_line_length": 83, "alphanum_fraction": 0.6326326326, "num_tokens": 563, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267830311354, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.6482655410089982}} {"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2019 Tinko Bartels, Berlin, Germany.\n\n// Contributed and/or modified by Tinko Bartels,\n// as part of Google Summer of Code 2019 program.\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_STRATEGIES_CARTESIAN_SIDE_ROBUST_HPP\n#define BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_STRATEGIES_CARTESIAN_SIDE_ROBUST_HPP\n\n#include \n#include \n#include \n\nnamespace boost { namespace geometry\n{\n\nnamespace strategy { namespace side\n{\n\n/*!\n\\brief Adaptive precision predicate to check at which side of a segment a point lies:\n left of segment (>0), right of segment (< 0), on segment (0).\n\\ingroup strategies\n\\tparam CalculationType \\tparam_calculation (numeric_limits::epsilon() and numeric_limits::digits must be supported for calculation type ct)\n\\tparam Robustness std::size_t value from 0 (fastest) to 3 (default, guarantees correct results).\n\\details This predicate determines at which side of a segment a point lies using an algorithm that is adapted from orient2d as described in \"Adaptive Precision Floating-Point Arithmetic and Fast Robust Geometric Predicates\" by Jonathan Richard Shewchuk ( https://dl.acm.org/citation.cfm?doid=237218.237337 ). More information and copies of the paper can also be found at https://www.cs.cmu.edu/~quake/robust.html . It is designed to be adaptive in the sense that it should be fast for inputs that lead to correct results with plain float operations but robust for inputs that require higher precision arithmetics.\n */\ntemplate\n<\n typename CalculationType = void,\n std::size_t Robustness = 3\n>\nstruct side_robust\n{\npublic:\n //! \\brief Computes double the signed area of the CCW triangle p1, p2, p\n template\n <\n typename PromotedType,\n typename P1,\n typename P2,\n typename P\n >\n static inline PromotedType side_value(P1 const& p1, P2 const& p2,\n P const& p)\n {\n typedef ::boost::geometry::detail::precise_math::vec2d vec2d;\n vec2d pa { get<0>(p1), get<1>(p1) };\n vec2d pb { get<0>(p2), get<1>(p2) };\n vec2d pc { get<0>(p), get<1>(p) };\n return ::boost::geometry::detail::precise_math::orient2d\n (pa, pb, pc);\n }\n\n#ifndef DOXYGEN_SHOULD_SKIP_THIS\n template\n <\n typename P1,\n typename P2,\n typename P\n >\n static inline int apply(P1 const& p1, P2 const& p2, P const& p)\n {\n typedef typename select_calculation_type_alt\n <\n CalculationType,\n P1,\n P2,\n P\n >::type coordinate_type;\n typedef typename select_most_precise\n <\n coordinate_type,\n double\n >::type promoted_type;\n\n promoted_type sv = side_value(p1, p2, p);\n return sv > 0 ? 1\n : sv < 0 ? -1\n : 0;\n }\n#endif\n\n};\n\n}} // namespace strategy::side\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_EXTENSIONS_TRIANGULATION_STRATEGIES_CARTESIAN_SIDE_ROBUST_HPP\n", "meta": {"hexsha": "59228c06033355764edd3b7a4eabfddb5f0cfd61", "size": 3486, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/geometry/extensions/triangulation/strategies/cartesian/side_robust.hpp", "max_stars_repo_name": "Siddharth-coder13/geometry", "max_stars_repo_head_hexsha": "ff1f245f21215ddcbd2d350702c2da47fccc0f2d", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-05-15T20:30:38.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-31T08:14:05.000Z", "max_issues_repo_path": "include/boost/geometry/extensions/triangulation/strategies/cartesian/side_robust.hpp", "max_issues_repo_name": "Siddharth-coder13/geometry", "max_issues_repo_head_hexsha": "ff1f245f21215ddcbd2d350702c2da47fccc0f2d", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/geometry/extensions/triangulation/strategies/cartesian/side_robust.hpp", "max_forks_repo_name": "Siddharth-coder13/geometry", "max_forks_repo_head_hexsha": "ff1f245f21215ddcbd2d350702c2da47fccc0f2d", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 4.0, "max_forks_repo_forks_event_min_datetime": "2020-12-03T13:22:49.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T10:43:59.000Z", "avg_line_length": 36.3125, "max_line_length": 613, "alphanum_fraction": 0.6910499139, "num_tokens": 866, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.875787001374006, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6482350850240679}} {"text": "#include \n#include \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\n// As we only consider finite vertices and edges\n// we need the following filter\n\ntemplate \nstruct Is_finite {\n\n const T* t_;\n\n Is_finite()\n : t_(NULL)\n {}\n\n Is_finite(const T& t)\n : t_(&t)\n { }\n\n template \n bool operator()(const VertexOrEdge& voe) const {\n return ! t_->is_infinite(voe);\n }\n};\n\ntypedef Is_finite Filter;\ntypedef boost::filtered_graph Finite_triangulation;\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;\nVertexIndexMap vertex_id_map;\n\n// A std::map is not a property map, because it is not lightweight\ntypedef boost::associative_property_map VertexIdPropertyMap;\nVertexIdPropertyMap vertex_index_pmap(vertex_id_map);\n\nint\nmain(int argc,char* argv[])\n{\n const char* filename = (argc > 1) ? argv[1] : \"data/points.xy\";\n std::ifstream input(filename);\n Triangulation t;\n Filter is_finite(t);\n Finite_triangulation ft(t, is_finite, is_finite);\n\n Point p ;\n while(input >> p){\n t.insert(p);\n }\n\n vertex_iterator vit, ve;\n // Associate indices to the vertices\n int index = 0;\n // boost::tie assigns the first and second element of the std::pair\n // returned by boost::vertices to the variables vit and ve\n for(boost::tie(vit,ve)=boost::vertices(ft); vit!=ve; ++vit ){\n vertex_descriptor vd = *vit;\n vertex_id_map[vd]= index++;\n }\n\n\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(ft,\n\t\t\t\t\tstd::back_inserter(mst),\n\t\t\t\t\tvertex_index_map(vertex_index_pmap));\n\n\n std::cout << \"The edges of the Euclidean mimimum spanning tree:\" << std::endl;\n\n for(std::list::iterator it = mst.begin(); it != mst.end(); ++it){\n edge_descriptor ed = *it;\n vertex_descriptor svd = source(ed,t);\n vertex_descriptor tvd = target(ed,t);\n Triangulation::Vertex_handle sv = svd;\n Triangulation::Vertex_handle tv = tvd;\n std::cout << \"[ \" << sv->point() << \" | \" << tv->point() << \" ] \" << std::endl;\n }\n\n return 0;\n}\n", "meta": {"hexsha": "ca8282d31954a7551a27be808cecc2d17d2e10cc", "size": 3041, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_triangulation_2/emst.cpp", "max_stars_repo_name": "liminchen/OptCuts", "max_stars_repo_head_hexsha": "cb85b06ece3a6d1279863e26b5fd17a5abb0834d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 187.0, "max_stars_repo_stars_event_min_datetime": "2019-01-23T04:07:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T03:44:58.000Z", "max_issues_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_triangulation_2/emst.cpp", "max_issues_repo_name": "xiaoxie5002/OptCuts", "max_issues_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2019-03-22T13:27:38.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-18T13:23:23.000Z", "max_forks_repo_path": "ext/libigl/external/cgal/src/CGAL_Project/examples/BGL_triangulation_2/emst.cpp", "max_forks_repo_name": "xiaoxie5002/OptCuts", "max_forks_repo_head_hexsha": "1f4168fc867f47face85fcfa3a572be98232786f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 34.0, "max_forks_repo_forks_event_min_datetime": "2019-02-13T01:11:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-28T03:29:40.000Z", "avg_line_length": 30.7171717172, "max_line_length": 87, "alphanum_fraction": 0.7300230187, "num_tokens": 801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6481283015839473}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"pixel2cam.h\"\n#include \"match.h\"\n#include \"BA.h\"\n\nusing namespace std;\nusing namespace cv;\n\n\nint main( int argc, char** argv ) {\n if ( argc != 5 )\n {\n cout<<\"usage: pose_estimation_3d2d img1 img2 depth1 depth2\"< keypoints_1,keypoints_2;\n vector matches;\n\n\n match ooo;\n\n ooo.find_feature_matches ( img_1, img_2, keypoints_1, keypoints_2, matches );\n cout<<\"totally find \"< (3,3) << 520.9, 0, 325.1, 0, 521.0, 249.7, 0, 0, 1 );\n vectorpts_3d;\n vectorpts_2d;\n for ( DMatch m:matches )\n {\n ushort d = d1.ptr (int(keypoints_1[m.queryIdx].pt.y) )[int(keypoints_1[m.queryIdx].pt.x) ];\n if (d == 0) //bad depth\n continue;\n float dd = d/1000.0;\n pixel2cam mpixel2cam;\n\n Point2d p1 = mpixel2cam.trans( keypoints_1[m.queryIdx].pt, K);\n pts_3d.push_back( Point3f(p1.x*dd, p1.y*dd, dd) );\n pts_2d.push_back( keypoints_2[m.trainIdx].pt );\n }\n\n cout<<\"3d-2d pairs: \"<\n#include \n#include \n\n\nint main() {\n\n\t// This example features 2 frames: an inertial frame of reference \"N\" and a body frame \"B\"\n\n\t// Orienting B with respect to N means\n\tdouble yaw = 0.1;\n\tdouble pitch = 0.1;\n\tdouble roll = 0.1;\n\n\tarma::vec angles_321 = {yaw, pitch, roll};\n\tarma::mat dcm_BN = RBK::euler321_to_dcm(angles_321);\n\n\t// The position of B's origin is also expressed in N\n\tarma::vec origin_B_in_N = {150, 20, 40};\n\n\t// Some vector, for instance representative of a position in the inertial frame\n\tarma::vec pos_N = {150, 120, 20};\n\n\t// This vector is expressed in the B frame\n\tarma::vec pos_B = dcm_BN * (pos_N - origin_B_in_N);\n\n\t\n\n\n\treturn 0;\n\n}", "meta": {"hexsha": "c8cda2c9cbf68958943e0fc78246f50580ec87e9", "size": 1963, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Examples/frames/source/main.cpp", "max_stars_repo_name": "bbercovici/RigidBodyKinematics", "max_stars_repo_head_hexsha": "110d30cc20251081a4558f6851bdfd5abc0fdd82", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Examples/frames/source/main.cpp", "max_issues_repo_name": "bbercovici/RigidBodyKinematics", "max_issues_repo_head_hexsha": "110d30cc20251081a4558f6851bdfd5abc0fdd82", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Examples/frames/source/main.cpp", "max_forks_repo_name": "bbercovici/RigidBodyKinematics", "max_forks_repo_head_hexsha": "110d30cc20251081a4558f6851bdfd5abc0fdd82", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1587301587, "max_line_length": 91, "alphanum_fraction": 0.7554763118, "num_tokens": 495, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8902942144788077, "lm_q2_score": 0.7279754607093178, "lm_q1q2_score": 0.6481123409520503}} {"text": "#include \n#include \n#include \n#include \"../include/layer.h\"\n#include \"../include/activation.h\"\n#include \"../include/loss.h\"\n\nnamespace MyDL\n{\n\n using namespace Eigen;\n using std::cout;\n using std::endl;\n using std::vector;\n\n // -------------------------------------------------\n // AddLayer\n // -------------------------------------------------\n vector AddLayer::forward(vector inputs)\n {\n\n vector outs;\n\n // 本当はここに入力のバリデーションを入れる(要素数が2)\n\n outs.push_back(inputs[0] + inputs[1]);\n return outs;\n }\n\n vector AddLayer::backward(vector douts)\n {\n vector grads;\n MatrixXd dx, dy;\n dx = douts[0];\n dy = douts[0];\n\n grads.push_back(dx);\n grads.push_back(dy);\n return grads;\n }\n\n // -------------------------------------------------\n // MulLayer\n // -------------------------------------------------\n vector MulLayer::forward(vector inputs)\n {\n _x = inputs[0];\n _y = inputs[1];\n\n vector outs;\n MatrixXd out;\n\n out = _x.array() * _y.array();\n\n outs.push_back(out);\n return outs;\n }\n\n vector MulLayer::backward(vector douts)\n {\n vector grads;\n MatrixXd dx, dy;\n\n dx = douts[0].array() * _y.array();\n dy = douts[0].array() * _x.array();\n\n grads.push_back(dx);\n grads.push_back(dy);\n return grads;\n }\n\n // -------------------------------------------------\n // ReLU\n // -------------------------------------------------\n vector ReLU::forward(vector inputs)\n {\n MatrixXd X;\n vector outs;\n X = inputs[0];\n\n _mask = X.unaryExpr([](double p) { return p > 0; }).cast();\n outs.push_back(X.array() * _mask.array()); // 負の数に対して、maskした部分は-0になるのが気がかり\n return outs;\n }\n\n vector ReLU::backward(vector douts)\n {\n vector grads;\n MatrixXd dx;\n\n dx = douts[0].array() * _mask.array();\n\n grads.push_back(dx);\n return grads;\n }\n\n // -------------------------------------------------\n // Sigmoid\n // -------------------------------------------------\n vector Sigmoid::forward(vector inputs)\n {\n MatrixXd X;\n vector outs;\n X = inputs[0];\n\n _y = X.unaryExpr([](double p) { return 1 / (1 + exp(-p)); });\n\n outs.push_back(_y);\n return outs;\n }\n\n vector Sigmoid::backward(vector douts)\n {\n vector grads;\n MatrixXd dx;\n\n dx = douts[0].array() * (MatrixXd::Ones(_y.rows(), _y.cols()) - _y).array();\n\n grads.push_back(dx);\n return grads;\n }\n\n // -------------------------------------------------\n // Affine\n // -------------------------------------------------\n Affine::Affine(MatrixXd& W, MatrixXd& b)\n {\n _W = W;\n _b = b;\n }\n\n Affine::Affine(const shared_ptr W, const shared_ptr b)\n {\n pW = W;\n pb = b;\n }\n\n Affine::Affine(const int input_size, const int output_size, const double weight_init_std)\n {\n auto W = std::make_shared(input_size, output_size);\n auto b = std::make_shared(1, output_size);\n *W = weight_init_std * MatrixXd::Random(input_size, output_size);\n *b = MatrixXd::Zero(1, output_size);\n pW = W;\n pb = b;\n }\n\n vector Affine::forward(vector inputs)\n {\n MatrixXd X, Y, W;\n VectorXd b;\n vector outs;\n X = inputs[0];\n _X = X;\n W = *pW;\n b = pb->row(0);\n // W = _W;\n // b = _b.row(0); // 非推奨 → コピーが走るだけ\n\n Y = (X * W).rowwise() + b.transpose();\n\n outs.push_back(Y);\n return outs;\n }\n\n vector Affine::backward(vector douts)\n {\n vector grads;\n MatrixXd dX, dout;\n MatrixXd W;\n\n dout = douts[0];\n W = *pW;\n // W = _W; // 非推奨 → コピーが走るだけ\n\n dX = dout * W.transpose();\n dW = _X.transpose() * dout;\n db = dout.colwise().sum();\n\n grads.push_back(dX);\n return grads;\n }\n\n // -------------------------------------------------\n // SoftmaxWithLoss\n // -------------------------------------------------\n vector SoftmaxWithLoss::forward(vector inputs)\n {\n vector outs;\n MatrixXd out = MatrixXd::Zero(1,1);\n MatrixXd X = inputs[0];\n _Y = softmax(X);\n _t = inputs[1];\n\n _loss = cross_entropy_error(_Y, _t);\n\n out << _loss;\n outs.push_back(out);\n return outs;\n }\n\n vector SoftmaxWithLoss::backward(vector dout)\n {\n vector grads;\n\n // 出力のバリデーション\n if (!(dout[0].rows() == 1 && dout[0].cols() == 1))\n {\n cout << \"dout shape is not valid @ SoftmaxWithLoss Layer!!\" << endl;\n cout << \"Please Check Your DNN Architecture.\" << endl;\n return grads;\n }\n\n double batch_size = _t.rows();\n MatrixXd dx;\n\n dx = (_Y - _t) / batch_size;\n\n grads.push_back(dx);\n return grads;\n }\n\n // -------------------------------------------------\n // BatchNormalization\n // -------------------------------------------------\n BatchNorm::BatchNorm(const shared_ptr gamma, const shared_ptr beta, double momentum)\n {\n int cols;\n\n pgamma = gamma;\n pbeta = beta;\n _momentum = momentum;\n\n cols = pgamma->cols();\n\n // pgamma, pbetaが横ベクトルであることをここでバリデーションしておく?(rows()==1を確認とか。)\n\n // ここで初期化しておく。ミニバッチにおける平均なので、横ベクトルになる。\n _avg_mean = VectorXd::Zero(cols);\n _avg_var = VectorXd::Zero(cols);\n }\n\n\n BatchNorm::BatchNorm(const int input_size, const double momentum)\n {\n auto gamma = std::make_shared(1, input_size);\n auto beta = std::make_shared(1, input_size);\n *gamma = MatrixXd::Ones(1, input_size); // Onesで初期化する方が良い?\n *beta = MatrixXd::Zero(1, input_size); // Zerosで初期化する方が良い?\n\n pgamma = gamma;\n pbeta = beta;\n _momentum = momentum;\n\n _avg_mean = VectorXd::Zero(input_size);\n _avg_var = VectorXd::Zero(input_size);\n }\n\n\n vector BatchNorm::forward(vector inputs)\n {\n MatrixXd X = inputs[0];\n MatrixXd Xn, Xc, out;\n VectorXd gamma, beta;\n VectorXd mu, var, std;\n vector outs;\n double momentum = _momentum;\n\n gamma = pgamma->row(0);\n beta = pbeta->row(0);\n\n bool train_flg = Config::getInstance().get_flag(); // SingletonのConfigクラスからモード取得\n\n if (train_flg){\n mu = X.colwise().mean(); // ミニバッチにおけるデータの平均値(各次元ごと)\n Xc = X.rowwise() - mu.transpose(); // 入力データの各次元から平均値を引き、中心化\n var = Xc.array().pow(2).colwise().mean(); // ミニバッチにおける標本分散(各次元ごと)\n std = var.unaryExpr([](double p){return sqrt(p + 1e-7);}); // ミニバッチにおける標準偏差(各次元ごと)\n\n Xn = Xc.array().rowwise() / std.transpose().array();\n\n _batch_size = X.rows();\n _Xc = Xc;\n _Xn = Xn;\n _std = std;\n _avg_mean = (momentum * _avg_mean.array() + (1 - momentum) * mu.array()).matrix();\n _avg_var = (momentum * _avg_var.array() + (1 - momentum) * var.array()).matrix();\n }\n else\n {\n Xc = X.rowwise() - _avg_mean.transpose(); // broadcast演算\n std = _avg_var.unaryExpr([](double p) { return sqrt(p + 1e-7); });\n Xn = Xc.array().rowwise() / std.transpose().array();\n }\n\n // gammaとbetaはVectorXdに変換するため、row(0)を使用している。\n out = (Xn * gamma.asDiagonal()).rowwise() + beta.transpose();\n outs.push_back(out);\n\n return outs;\n }\n\n\n\n vector BatchNorm::backward(vector douts)\n {\n vector grads;\n MatrixXd dout = douts[0];\n MatrixXd dXn, dXc;\n MatrixXd Xn = _Xn;\n MatrixXd Xc = _Xc;\n VectorXd std = _std;\n VectorXd var;\n MatrixXd dX;\n VectorXd gamma, beta, dmu, dstd, dvar;\n\n gamma = pgamma->row(0); // ブロードキャスト演算用にVectorXd化\n beta = pbeta->row(0); // 同上\n\n // parameter's gradient\n dbeta = dout.colwise().sum();\n dgamma = (dout.array() * Xn.array()).colwise().sum();\n\n // For inputs' gradient\n dXn = dout * gamma.asDiagonal(); // ブロードキャスト演算\n dXc = dXn.array().rowwise() / _std.transpose().array(); // ブロードキャスト演算\n\n // colwise()を忘れないように -> shapeが合わない\n dstd = ((-1.0 * dXn).array() * Xc.array()).colwise().sum().array().rowwise()\n / (std.transpose().array().pow(2)); // ブロードキャスト演算\n\n\n dvar = (0.5 * dstd).array() * std.array().inverse(); // Vector同士の要素積はarray()を使用。要素商はarray().inverse()とする。\n dXc += (((2.0 / _batch_size)*Xc).array().rowwise() * dvar.transpose().array()).matrix(); // 左辺と右辺でmatrix型かarray型かを合わせる\n dmu = dXc.colwise().sum();\n dX = dXc.rowwise() - ((1/_batch_size) * dmu.transpose());\n\n grads.push_back(dX);\n\n return grads;\n }\n\n // -------------------------------------------------\n // Dropout\n // -------------------------------------------------\n Dropout::Dropout(const double dropout_ratio)\n {\n _dropout_ratio = dropout_ratio;\n }\n\n Dropout::Dropout(const int row, const int col, const double dropout_ratio)\n {\n _dropout_ratio = dropout_ratio;\n _mask = MatrixXd::Zero(row, col).cast();\n }\n\n vector Dropout::forward(vector inputs)\n {\n MatrixXd X = inputs[0];\n MatrixXd out;\n vector outs;\n bool train_flg = Config::getInstance().get_flag();\n int col, row;\n col = X.cols(); // サイズの取得\n row = X.rows(); // サイズの取得\n _mask = MatrixXd::Zero(row, col).cast();\n\n // Eigen MatrixXd::Random は -1 ~ 1 の範囲で乱数生成するので、これを0~1の範囲に変更する\n double HI = 1.0;\n double LO = 0;\n double range = HI - LO;\n\n if (train_flg)\n {\n // 乱数の範囲調整 → 自作関数にし、utilとして使用?\n MatrixXd rand = MatrixXd::Random(row, col);\n rand = (rand + MatrixXd::Constant(row, col, 1.)*range/2.);\n rand = (rand + MatrixXd::Constant(row, col, LO));\n _mask = rand.array() < _dropout_ratio;\n MatrixXd mask = _mask.cast();\n out = X.array() * mask.array();\n } else {\n out = X * (1.0 - _dropout_ratio);\n }\n\n outs.push_back(out);\n return outs;\n }\n\n vector Dropout::backward(vector douts)\n {\n vector grads;\n MatrixXd dout = douts[0];\n MatrixXd grad;\n\n grad = dout.array() * _mask.cast().array();\n\n grads.push_back(grad);\n return grads;\n }\n\n // -------------------------------------------------\n // Convolution\n // -------------------------------------------------\n\n Conv2D::Conv2D(int C, int H, int W, int Fh, int Fw, int Fn, int stride, int pad, double weight_init_std)\n :_C(C), _H(H), _W(W), _Fh(Fh), _Fw(Fw), _Fn(Fn), _stride(stride), _pad(pad)\n {\n pW = std::make_shared(C*Fh*Fw, Fn);\n pb = std::make_shared(1, Fn);\n *pW = weight_init_std * MatrixXd::Random(C*Fh*Fw, Fn);\n *pb = MatrixXd::Zero(1, Fn);\n }\n\n vector Conv2D::forward(vector inputs)\n {\n MatrixXd X, Y, W;\n VectorXd b;\n vector outs;\n X = inputs[0];\n _N = X.rows(); // batch size\n \n W = *pW;\n b = pb->row(0);\n\n int Oh = 1 + (_H + 2 * _pad - _Fh) / _stride;\n int Ow = 1 + (_W + 2 * _pad - _Fw) / _stride;\n\n im2col(X, _col);\n\n Y = (_col * W).rowwise() + b.transpose();\n Map Y_reshaped(Y.data(), _N, _Fn*Oh*Ow);\n\n outs.push_back(Y_reshaped);\n return outs;\n }\n\n vector Conv2D::backward(vector douts)\n {\n vector grads;\n // doutとして入ってくるのは、(N, Fn*Oh*Ow) という形状が前提\n\n MatrixXd dout = douts[0];\n MatrixXd W, dcol, dX;\n VectorXd b;\n W = *pW;\n\n\n int Oh = (2*_pad+_H-_Fh) / _stride + 1;\n int Ow = (2*_pad+_W-_Fw) / _stride + 1;\n\n Map reshaped_dout(dout.data(), _N*Oh*Ow, _Fn);\n\n db = reshaped_dout.colwise().sum();\n dW = _col.transpose() * reshaped_dout;\n\n dcol = reshaped_dout * W.transpose(); // (N×Oh×Ow) × (C×Fh×Fw)\n\n col2im(dcol, dX);\n\n grads.push_back(dX);\n\n return grads;\n }\n\n void Conv2D::padding(MatrixXd& img, MatrixXd& pad_img)\n {\n pad_img = MatrixXd::Zero(_N, _C * (_H + 2 * _pad) * (_W + 2 * _pad));\n\n int pad_H_elems = _H + 2 * _pad;\n int pad_W_elems = _W + 2 * _pad;\n int pad_C_elems = pad_H_elems * pad_W_elems;\n\n for (int n = 0; n < _N; n++)\n {\n for (int c = 0; c < _C; c++)\n {\n for (int h = 0; h < _H; h++)\n {\n for (int w = 0; w < _W; w++)\n {\n // 1pixelずつ置き換え\n pad_img(n, c * pad_C_elems + (h + _pad) * pad_W_elems + (w + _pad)) = img(n, c * (_H * _W) + _W * h + w);\n }\n }\n }\n }\n }\n\n void Conv2D::im2col(MatrixXd& img, MatrixXd& col)\n {\n MatrixXd pad_img;\n\n padding(img, pad_img);\n\n int Oh = (2 * _pad + _H - _Fh) / _stride + 1;\n int Ow = (2 * _pad + _W - _Fw) / _stride + 1;\n\n col = MatrixXd::Zero(_N * Oh * Ow, _Fh * _Fw * _C);\n\n int h_start = 0;\n int w_start = 0;\n\n int pad_H = _H + 2 * _pad;\n int pad_W = _W + 2 * _pad;\n\n int tmp_col_row, tmp_col_width;\n int tmp_img_start; \n\n for (int n = 0; n < _N; n++)\n {\n for (int c = 0; c < _C; c++)\n {\n for (int h_start = 0; h_start < Oh; h_start++)\n {\n for (int w_start = 0; w_start < Ow; w_start++)\n {\n for (int h_offset = 0; h_offset < _Fh; h_offset++)\n {\n tmp_col_row = n * Oh * Ow + h_start * Ow + w_start;\n tmp_col_width = c * _Fh * _Fw + h_offset * _Fw;\n tmp_img_start = c * pad_H * pad_W + (h_start * _stride + h_offset) * pad_W + w_start * _stride;\n col.block(tmp_col_row, tmp_col_width, 1, _Fw) = pad_img.block(n, tmp_img_start, 1, _Fw);\n }\n }\n }\n }\n }\n }\n\n void Conv2D::col2im(MatrixXd& col, MatrixXd& img)\n {\n int pad_H = _H + 2 * _pad;\n int pad_W = _W + 2 * _pad;\n\n MatrixXd pad_img = MatrixXd::Zero(_N, _C*pad_H*pad_W);\n\n int Oh = (2 * _pad + _H - _Fh) / _stride + 1;\n int Ow = (2 * _pad + _W - _Fw) / _stride + 1;\n\n int tmp_img_start;\n int tmp_col_row, tmp_col_width;\n\n for (int n = 0; n < _N; n++)\n {\n for (int c = 0; c < _C; c++)\n {\n for (int h = 0; h < Oh; h++)\n {\n for (int w = 0; w < Ow; w++)\n {\n for (int h_offset = 0; h_offset < _Fh; h_offset++)\n {\n tmp_img_start = pad_H*pad_W*c+(h*_stride+h_offset)*pad_W+w*_stride;\n tmp_col_row = Oh*Ow*n+Ow*h+w;\n tmp_col_width = c*_Fh*_Fw+h_offset*_Fw;\n pad_img.block(n, tmp_img_start, 1, _Fw) += col.block(tmp_col_row, tmp_col_width, 1, _Fw);\n }\n }\n }\n }\n }\n\n suppress(pad_img, img);\n\n }\n\n void Conv2D::suppress(MatrixXd& pad_img, MatrixXd& img)\n {\n img = MatrixXd::Zero(_N, _C*_H*_W);\n int pad_H = 2*_pad + _H;\n int pad_W = 2*_pad + _W;\n\n for (int n = 0; n < _N; n++)\n {\n for (int c = 0; c < _C; c++)\n {\n for (int h = 0; h < _H; h++)\n {\n for (int w = 0; w < _W; w++)\n {\n // 1pixelずつ置き換え\n img(n, c*_H*_W+h*_W+w) = pad_img(n, c*pad_H*pad_W+(h+_pad)*pad_W+(_pad+w));\n }\n }\n }\n }\n }\n\n // -------------------------------------------------\n // Pooling\n // -------------------------------------------------\n\n Pooling::Pooling(int c, int h, int w, int Ph, int Pw, int stride, int pad)\n :_C(c), _H(h), _W(w), _Ph(Ph), _Pw(Pw), _stride(stride), _pad(pad)\n {\n }\n\n vector Pooling::forward(vector inputs)\n {\n MatrixXd X, col, vec_out;\n vector outs;\n\n X = inputs[0];\n _X = X;\n _N = X.rows();\n\n int Oh = (2*_pad + _H - _Ph) / _stride + 1;\n int Ow = (2*_pad + _W - _Pw) / _stride + 1;\n\n im2col(X, col); // colは N*Oh*Ow × C*Ph*Pw のshapeをもつ\n\n MatrixXd reshaped_col = MatrixXd::Zero(_C*_N*Oh*Ow, _Ph*_Pw);\n MatrixXd tmp_c_col = MatrixXd::Zero(_N*Oh*Ow, _Ph*_Pw);\n\n // column majorなので、直接reshapeすると意図した挙動にならない\n // 各チャネルごとにreshapeをかけなおす\n for (int c = 0; c < _C; c++)\n {\n tmp_c_col = col.block(0, c*_Ph*_Pw, _N*Oh*Ow, _Ph*_Pw);\n reshaped_col.block(c*_Ph*_Pw, 0, _N*Oh*Ow, _Ph*_Pw) = tmp_c_col;\n }\n\n int num_rows = reshaped_col.rows();\n _argmax = MatrixXi::Zero(num_rows, 1);\n vec_out = MatrixXd::Zero(num_rows, 1);\n MatrixXi::Index dummy_row = 0;\n MatrixXi::Index max_col = 0;\n\n for (int r = 0; r < num_rows; r++)\n {\n vec_out(r, 0) = reshaped_col.row(r).maxCoeff(&dummy_row, &max_col);\n _argmax(r, 0) = max_col;\n }\n \n Map out(vec_out.data(), _N, Oh*Ow*_C);\n\n outs.push_back(out);\n\n return outs;\n }\n\n vector Pooling::backward(vector douts)\n {\n MatrixXd dout; // size: N × (C×Oh×Ow)\n MatrixXd dX;\n vector grads;\n\n int Oh = (2 * _pad + _H - _Ph) / _stride + 1;\n int Ow = (2 * _pad + _W - _Pw) / _stride + 1;\n\n dout = douts[0];\n Map vec_dout(dout.data(), _N*Oh*Ow*_C, 1);\n\n MatrixXd dmax = MatrixXd::Zero(_N*_C*Oh*Ow, _Ph*_Pw);\n int argmax_index = 0;\n\n for (int r = 0; r < dmax.rows(); r++)\n {\n argmax_index = _argmax(r, 0);\n dmax(r, argmax_index) = vec_dout(r, 0);\n }\n\n MatrixXd tmp_c_dmax = MatrixXd::Zero(_N*Oh*Ow, _Ph*_Pw);\n MatrixXd dcol = MatrixXd::Zero(_N*Oh*Ow, _C*_Ph*_Pw);\n\n for (int c = 0; c < _C; c++)\n {\n tmp_c_dmax = dmax.block(c*_N*Oh*Ow, 0, _N*Oh*Ow, _Ph*_Pw);\n dcol.block(0, c*_Ph*_Pw, _N*Oh*Ow, _Ph*_Pw) = tmp_c_dmax;\n }\n\n col2im(dcol, dX);\n\n grads.push_back(dX);\n\n return grads;\n }\n\n void Pooling::im2col(MatrixXd& img, MatrixXd& col)\n {\n MatrixXd pad_img;\n\n padding(img, pad_img);\n\n int Oh = (2 * _pad + _H - _Ph) / _stride + 1;\n int Ow = (2 * _pad + _W - _Pw) / _stride + 1;\n\n col = MatrixXd::Zero(_N * Oh * Ow, _Ph * _Pw * _C);\n\n int h_start = 0;\n int w_start = 0;\n\n int pad_H = _H + 2 * _pad;\n int pad_W = _W + 2 * _pad;\n\n int tmp_col_row, tmp_col_width;\n int tmp_img_start;\n\n for (int n = 0; n < _N; n++)\n {\n for (int c = 0; c < _C; c++)\n {\n for (int h_start = 0; h_start < Oh; h_start++)\n {\n for (int w_start = 0; w_start < Ow; w_start++)\n {\n for (int h_offset = 0; h_offset < _Ph; h_offset++)\n {\n tmp_col_row = n * Oh * Ow + h_start * Ow + w_start;\n tmp_col_width = c * _Ph * _Pw + h_offset * _Pw;\n tmp_img_start = c * pad_H * pad_W + (h_start * _stride + h_offset) * pad_W + w_start * _stride;\n col.block(tmp_col_row, tmp_col_width, 1, _Pw) = pad_img.block(n, tmp_img_start, 1, _Pw);\n }\n }\n }\n }\n }\n }\n\n void Pooling::col2im(MatrixXd& col, MatrixXd& img)\n {\n int pad_H = _H + 2 * _pad;\n int pad_W = _W + 2 * _pad;\n\n MatrixXd pad_img = MatrixXd::Zero(_N, _C*pad_H*pad_W);\n\n int Oh = (2 * _pad + _H - _Ph) / _stride + 1;\n int Ow = (2 * _pad + _W - _Pw) / _stride + 1;\n\n int tmp_img_start;\n int tmp_col_row, tmp_col_width;\n\n for (int n = 0; n < _N; n++)\n {\n for (int c = 0; c < _C; c++)\n {\n for (int h = 0; h < Oh; h++)\n {\n for (int w = 0; w < Ow; w++)\n {\n for (int h_offset = 0; h_offset < _Ph; h_offset++)\n {\n tmp_img_start = pad_H*pad_W*c+(h*_stride+h_offset)*pad_W+w*_stride;\n tmp_col_row = Oh*Ow*n+Ow*h+w;\n tmp_col_width = c*_Ph*_Pw+h_offset*_Pw;\n pad_img.block(n, tmp_img_start, 1, _Pw) += col.block(tmp_col_row, tmp_col_width, 1, _Pw);\n }\n }\n }\n }\n }\n\n suppress(pad_img, img);\n }\n\n void Pooling::padding(MatrixXd &img, MatrixXd &pad_img)\n {\n pad_img = MatrixXd::Zero(_N, _C * (_H + 2 * _pad) * (_W + 2 * _pad));\n\n int pad_H_elems = _H + 2 * _pad;\n int pad_W_elems = _W + 2 * _pad;\n int pad_C_elems = pad_H_elems * pad_W_elems;\n\n for (int n = 0; n < _N; n++)\n {\n for (int c = 0; c < _C; c++)\n {\n for (int h = 0; h < _H; h++)\n {\n for (int w = 0; w < _W; w++)\n {\n // 1pixelずつ置き換え\n pad_img(n, c * pad_C_elems + (h + _pad) * pad_W_elems + (w + _pad)) = img(n, c * (_H * _W) + _W * h + w);\n }\n }\n }\n }\n }\n\n void Pooling::suppress(MatrixXd &pad_img, MatrixXd &img)\n {\n img = MatrixXd::Zero(_N, _C * _H * _W);\n int pad_H = 2 * _pad + _H;\n int pad_W = 2 * _pad + _W;\n\n for (int n = 0; n < _N; n++)\n {\n for (int c = 0; c < _C; c++)\n {\n for (int h = 0; h < _H; h++)\n {\n for (int w = 0; w < _W; w++)\n {\n // 1pixelずつ置き換え\n img(n, c * _H * _W + h * _W + w) = pad_img(n, c * pad_H * pad_W + (h + _pad) * pad_W + (_pad + w));\n }\n }\n }\n }\n }\n}", "meta": {"hexsha": "0f476f8693c588beb81b85a6e643f5cd60a704d8", "size": 23608, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/layer.cpp", "max_stars_repo_name": "potedo/zeroDL_cpp", "max_stars_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-05-22T15:26:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-22T15:26:20.000Z", "max_issues_repo_path": "src/layer.cpp", "max_issues_repo_name": "potedo/zeroDL_cpp", "max_issues_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/layer.cpp", "max_forks_repo_name": "potedo/zeroDL_cpp", "max_forks_repo_head_hexsha": "4d5b376d2cc3d0d8e1180662e906957c4a142bb4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4364089776, "max_line_length": 129, "alphanum_fraction": 0.4573873263, "num_tokens": 7041, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146780175245, "lm_q2_score": 0.7371581741774411, "lm_q1q2_score": 0.6480702353079597}} {"text": "/* copied from the article:\nhttp://amitsaha.github.io/site/notes/articles/c_scientific/article.html\n*/\n\n/*Listing-5: array_demo.cc*/\n\n/* Simple demonstration of using Array\n in Blitz++*/\n\n#include \n\nusing namespace blitz;\n\nint main()\n{\n\n cout << \">>>> 1-D Array Demonstration >>>>\" << endl << endl;\n\n Array a(5);\n a=1,2,3,4,5;\n cout << \"a = \" << a < b(5);\n b=2,1,3,4,1;\n cout << \"b = \" << b <> Basic Arithmetic Operations >>\" << endl << endl;\n\n Array c(5);\n c = a+b;\n cout << \"c = a+b = \" << c <>>> 2-D Array Demonstration >>>>\" << endl << endl;\n\n Array A(3,3);\n A = 1, 2, 3,\n 3, 5, 1,\n 1, 1, 4;\n\n cout << \"A = \" << A << endl;\n\n Array B(3,3);\n B = 1, 2, 3,\n 3, 5, 1,\n 1, 1, 4;\n\n cout << \"B = \" << B << endl;\n\n cout << \" >> Basic Arithmetic Operations >>\" << endl << endl;\n\n Array C(3,3);\n C = A+B;\n cout << \"C = A+B = \" << C <\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#include \n#include \n\ntemplate\nclass func {\npublic:\n typedef T real_t;\n func(real_t s) : s_(s) {}\n real_t operator()(real_t x) const {\n using std::exp; using std::pow; using std::sqrt;\n if ((exp(x) - 1) > sqrt(std::numeric_limits::epsilon())) {\n return pow(x, s_ - 1) / (exp(x) - 1);\n } else {\n return pow(x, s_ - 1) / (x + x * x / 2);\n }\n }\n real_t result() const {\n return boost::math::tgamma(s_) * boost::math::zeta(s_);\n }\nprivate:\n real_t s_;\n};\n\nint main() {\n using std::abs; \n typedef double real_t;\n \n boost::math::quadrature::exp_sinh integrator;\n real_t termination = sqrt(std::numeric_limits::epsilon());\n real_t error, L1;\n size_t levels;\n\n real_t values[5] = { 1.1, 1.5, 2, 2.5, 3 };\n for (auto s : values) {\n func f(s);\n real_t q = integrator.integrate(f, termination, &error, &L1, &levels);\n\n std::cout << std::scientific << std::setprecision(std::numeric_limits::digits10)\n << \"value of s: \" << s << std::endl\n << \"result: \" << q << std::endl\n << \"estimated error: \" << error << std::endl\n << \"real error: \" << abs(q - f.result()) << std::endl\n << \"L1 * error: \" << L1 * error << std::endl\n << \"levels: \" << levels << std::endl;\n }\n}\n", "meta": {"hexsha": "4cda2bb30191a35ae3f13ef92d654f06f6859863", "size": 1909, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exp_sinh/zeta.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": "exp_sinh/zeta.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": "exp_sinh/zeta.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": 31.2950819672, "max_line_length": 92, "alphanum_fraction": 0.5489785228, "num_tokens": 543, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519527944504227, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.6480384445263876}} {"text": "/*****************************************************************\n* Inversion of a symmetric matrix by Cholesky decomposition. *\n* The matrix must be positive definite. * \n* -------------------------------------------------------------- *\n* REFERENCE: *\n* From a Java Library Created by Vadim Kutsyy, *\n* \"http://www.kutsyy.com\". *\n* -------------------------------------------------------------- * \n* SAMPLE RUN: *\n* *\n* Inversion of a square real symetric matrix by Cholevsky method *\n* (The matrix must positive definite). *\n* *\n* Size = 4 *\n* *\n* Determinant = 432.000000 *\n* *\n* Matrix A: *\n* 5.000000 -1.000000 -1.000000 -1.000000 *\n* -1.000000 5.000000 -1.000000 -1.000000 *\n* -1.000000 -1.000000 5.000000 -1.000000 *\n* -1.000000 -1.000000 -1.000000 5.000000 *\n* *\n* Matrix Inv(A): *\n* 0.250000 0.083333 0.083333 0.083333 *\n* 0.083333 0.250000 0.083333 0.083333 *\n* 0.083333 0.083333 0.250000 0.083333 *\n* 0.083333 0.083333 0.083333 0.250000 *\n* *\n* C++ Release By Jean-Pierre Moreau, Paris. *\n* (www.jpmoreau.fr) *\n* -------------------------------------------------------------- *\n* Release 1.1 : added verification Inv(A) * A = I. *\n*****************************************************************/\n#include \n#include \n#include \n#include \n\n#define SIZE 25\n\n\ntypedef double MAT[SIZE][SIZE], VEC[SIZE];\n\nvoid choldc1(int,MAT,VEC); \n\n//print a square real matrix A of size n with caption s\n//(n items per line).\nvoid MatPrint(const char *s, int n, MAT A) {\n\tint i, j; printf(\"\\n %s\\n\", s);\n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < n; j++)\n\t\t\tprintf(\" %10.6f\", A[i][j]);\n\t\tprintf(\"\\n\");\n\t}\n}\n\n/* -----------------------------------------------\n Cholesky decomposition.\n\n input n size of matrix\n input A Symmetric positive def. matrix\n output a lower deomposed matrix\n uses choldc1(int,MAT,VEC)\n ----------------------------------------------- */\nvoid choldc(int n,MAT A, MAT a) {\n\tint i,j;\n\tVEC p;\n\tfor (i = 0; i < n; i++) \n\t\tfor (j = 0; j < n; j++) \n\t\t\ta[i][j] = A[i][j];\n\tcholdc1(n, a, p);\n\tfor (i = 0; i < n; i++) {\n\t\ta[i][i] = p[i];\n\t\tfor (j = i + 1; j < n; j++) {\n\t\t\ta[i][j] = 0;\n\t\t}\n\t}\n}\n \n/* -----------------------------------------------------\n Inverse of Cholesky decomposition.\n\n input n size of matrix\n input A Symmetric positive def. matrix\n output a inverse of lower decomposed matrix\n uses choldc1(int,MAT,VEC) \n ----------------------------------------------------- */\n void choldcsl(int n, MAT A, MAT a) {\n\t int i,j,k; double sum;\n\t VEC p;\n for (i = 0; i < n; i++) \n\t for (j = 0; j < n; j++) \n\t a[i][j] = A[i][j];\n \n\t choldc1(n, a, p);\n for (i = 0; i < n; i++) {\n a[i][i] = 1 / p[i];\n for (j = i + 1; j < n; j++) {\n sum = 0;\n for (k = i; k < j; k++) {\n sum -= a[j][k] * a[k][i];\n\t }\n a[j][i] = sum / p[j];\n\t }\n\t }\n\t}\n \n/* -----------------------------------------------------------------------------\n Computation of Determinant of the matrix using Cholesky decomposition\n\n input n size of matrix\n input a Symmetric positive def. matrix\n return det(a)\n uses choldc(int,MAT,MAT)\n ------------------------------------------------------------------------------ */\n double choldet(int n, MAT a) {\n\t MAT c; \n\t double d=1; \n\t int i;\n choldc(n,a,c);\n\t MatPrint(\"choldet calls choldc:\\n\", n, c);\n for (i = 0; i < n; i++) d *= c[i][i];\n return d * d;\n\t}\n \n/* ---------------------------------------------------\n Matrix inverse using Cholesky decomposition\n\n input n size of matrix\n input\t A Symmetric positive def. matrix\n output a inverse of A\n uses choldc1(MAT, VEC)\n --------------------------------------------------- */\nvoid cholsl(int n, MAT A, MAT a) {\n\tint i,j,k;\n\tMatPrint(\"a\", n, a);\n choldcsl(n,A,a);\n\tMatPrint(\"first a\", n, a);\n\n for (i = 0; i < n; i++) {\n\t\tfor (j = i + 1; j < n; j++) {\n\t\t\ta[i][j] = 0.0;\n\t\t}\n\t}\n\tMatPrint(\"2nd a\", n, a);\n for (i = 0; i < n; i++) {\n\t\ta[i][i] *= a[i][i];\n\t\tfor (k = i + 1; k < n; k++) {\n\t\t\ta[i][i] += a[k][i] * a[k][i];\n\t\t}\n\t\tfor (j = i + 1; j < n; j++) {\n\t\t\tfor (k = j; k < n; k++) {\n\t\t\t\ta[i][j] += a[k][i] * a[k][j];\n\t\t\t}\n\t\t}\n\t}\n\tMatPrint(\"3rd a\", n, a);\n\tfor (i = 0; i < n; i++) {\n\t\tfor (j = 0; j < i; j++) {\n\t\t\ta[i][j] = a[j][i];\n\t\t}\n\t}\n\tMatPrint(\"final a\", n, a);\n}\n\n/* ----------------------------------------------------\n main method for Cholesky decomposition.\n\n input n size of matrix\n input/output a Symmetric positive def. matrix\n output p vector of resulting diag of a\n author: \n ----------------------------------------------------- */\n void choldc1(int n, MAT a, VEC p) {\n int i,j,k;\n double sum;\n\n\t for (i = 0; i < n; i++) {\n for (j = i; j < n; j++) {\n sum = a[i][j];\n for (k = i - 1; k >= 0; k--) {\n sum -= a[i][k] * a[j][k];\n\t }\n if (i == j) {\n if (sum <= 0) {\n printf(\" a is not positive definite!\\n\");\n\t\t}\n p[i] = sqrt(sum);\n\t }\n else {\n a[j][i] = sum / p[i];\n\t }\n\t }\n\t }\n\t}\n\n\n\n//check if matrix A is positive definite (return 1)\n//or not positive definite (return 0) \nint Check_Matrix(int n, MAT A) {\n int i,j,k,result; double sum;\n result=1;\n\tfor (i=0; i=0; k--)\n sum -= A[i][k] * A[j][k];\n if (i == j)\n if (sum <= 0.0) result=0;\n\t }\n }\n\treturn result;\n}\n\n/******************************************\n* MULTIPLICATION OF TWO SQUARE REAL * \n* MATRICES *\n* --------------------------------------- * \n* INPUTS: A MATRIX N*N * \n* B MATRIX N*N * \n* N INTEGER * \n* --------------------------------------- * \n* OUTPUTS: C MATRIX N*N PRODUCT A*B * \n* *\n******************************************/\nvoid MatMult(int n, MAT A,MAT B, MAT C) {\n double SUM;\n int I,J,K;\n for (I=0; I B(4, 4); B = 0;\n\tMAT C;\n\tif (Check_Matrix(n,A)) {\n\t\t//MatPrint(\"Matrix B:\", n, B);\n\t\tstd::cout << \"B:\\n\" << B << std::endl;\n\t\tMatPrint(\"Matrix C:\", n, C);\n\n\t\tdouble det = choldet(n, A);\n\t\t//MatPrint(\"Matrix B:\", n, B);\n\t\tstd::cout << \"B:\\n\" << B << std::endl;\n\t\tprintf(\"\\n Determinant = %f\\n\", det);\n\t\tMatPrint(\"Matrix A:\", n, A);\n\t\t// MatPrint(\"Matrix B:\", n, B);\n\t\tstd::cout << \"B:\\n\" << B << std::endl;\n\t\tMatPrint(\"Matrix C:\", n, C);\n\t\tcholsl(n,A,C);\n\t\tMatPrint(\"Matrix Inv(A):\",n,C);\n\t\tstd::cout << \"B:\\n\" << B << std::endl;\n\t}\n\telse {\n\t\tprintf(\"\\n Sorry, this matrix is not positive definite !\\n\");\n\t\treturn EXIT_FAILURE;\n\t}\n\n\tMAT Bprime;\n\tMatCopy(n, C, Bprime);\n\tprintf(\"\\n Verification: \");\n\tMatMult(n,A1,Bprime,C);\n\tMatPrint(\"Verification A * Inv(A) = I:\",n,C);\n\tprintf(\"\\n\");\n}\ncatch (char const* msg) {\n\tstd::cerr << msg << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const sw::universal::posit_arithmetic_exception& err) {\n\tstd::cerr << \"Uncaught posit arithmetic exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const sw::universal::quire_exception& err) {\n\tstd::cerr << \"Uncaught quire exception: \" << err.what() << std::endl;\n\treturn EXIT_FAILURE;\n}\ncatch (const sw::universal::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": "2ece9fa0ebde68b1d74317368fb9631f282e72bc", "size": 10556, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "applications/blas/cholesky.cpp", "max_stars_repo_name": "stillwater-sc/hpr-blas", "max_stars_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2019-02-13T10:53:51.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-21T20:30:58.000Z", "max_issues_repo_path": "applications/blas/cholesky.cpp", "max_issues_repo_name": "stillwater-sc/hpr-blas", "max_issues_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-07-20T16:45:52.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-17T11:19:32.000Z", "max_forks_repo_path": "applications/blas/cholesky.cpp", "max_forks_repo_name": "stillwater-sc/hpr-blas", "max_forks_repo_head_hexsha": "06236fa2b5069cd467f53aeb12b4ca21ec0192ae", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2020-03-12T21:20:54.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T05:35:35.000Z", "avg_line_length": 32.48, "max_line_length": 87, "alphanum_fraction": 0.3703107238, "num_tokens": 2840, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8976952811593496, "lm_q2_score": 0.7217432182679956, "lm_q1q2_score": 0.6479054812479421}} {"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_RASTERIZATION_CIRCLE_HPP\n#define BOOST_GIL_RASTERIZATION_CIRCLE_HPP\n\n#include \n#include \n#include \n#include \n\nnamespace boost { namespace gil {\n/// \\defgroup CircleRasterization\n/// \\ingroup Rasterization\n/// \\brief Circle rasterization algorithms\n///\n/// The main problems are connectivity and equation following. Circle can be easily moved\n/// to new offset, and rotation has no effect on it (not recommended to do rotation).\n\n/// \\ingroup CircleRasterization\n/// \\brief Rasterize trigonometric circle according to radius by sine and radius by cosine\n///\n/// This rasterizer is the one used that is used in standard Hough circle transform in\n/// the books. It is also quite expensive to compute.\n/// WARNING: the product of this rasterizer does not follow circle equation, even though it\n/// produces quite round like shapes.\nstruct trigonometric_circle_rasterizer\n{\n /// \\brief Calculates minimum angle step that is distinguishable when walking on circle\n ///\n /// It is important to not have disconnected circle and to not compute unnecessarily,\n /// thus the result of this function is used when rendering.\n double minimum_angle_step(std::ptrdiff_t radius) const noexcept\n {\n const auto diameter = radius * 2 - 1;\n return std::atan2(1.0, diameter);\n }\n\n /// \\brief Calculate the amount of points that rasterizer will output\n std::ptrdiff_t point_count(std::ptrdiff_t radius) const noexcept\n {\n return 8 * static_cast(\n std::round(detail::pi / 4 / minimum_angle_step(radius)) + 1);\n }\n\n /// \\brief perform rasterization and output into d_first\n template \n void operator()(std::ptrdiff_t radius, point_t offset, RandomAccessIterator d_first) const\n {\n const double minimum_angle_step = std::atan2(1.0, radius);\n auto translate_mirror_points = [&d_first, offset](point_t p) {\n *d_first++ = point_t{offset.x + p.x, offset.y + p.y};\n *d_first++ = point_t{offset.x + p.x, offset.y - p.y};\n *d_first++ = point_t{offset.x - p.x, offset.y + p.y};\n *d_first++ = point_t{offset.x - p.x, offset.y - p.y};\n *d_first++ = point_t{offset.x + p.y, offset.y + p.x};\n *d_first++ = point_t{offset.x + p.y, offset.y - p.x};\n *d_first++ = point_t{offset.x - p.y, offset.y + p.x};\n *d_first++ = point_t{offset.x - p.y, offset.y - p.x};\n };\n const std::ptrdiff_t iteration_count = point_count(radius) / 8;\n double angle = 0;\n // do note that + 1 was done inside count estimation, thus <= is not needed, only <\n for (std::ptrdiff_t i = 0; i < iteration_count; ++i, angle += minimum_angle_step)\n {\n std::ptrdiff_t x = static_cast(std::round(radius * std::cos(angle)));\n std::ptrdiff_t y = static_cast(std::round(radius * std::sin(angle)));\n translate_mirror_points({x, y});\n }\n }\n};\n\n/// \\ingroup CircleRasterization\n/// \\brief Perform circle rasterization according to Midpoint algorithm\n///\n/// This algorithm givess reasonable output and is cheap to compute.\n/// reference:\n/// https://en.wikipedia.org/wiki/Midpoint_circle_algorithm\nstruct midpoint_circle_rasterizer\n{\n /// \\brief Calculate the amount of points that rasterizer will output\n std::ptrdiff_t point_count(std::ptrdiff_t radius) const noexcept\n {\n // the reason for pulling 8 out is so that when the expression radius * cos(45 degrees)\n // is used, it would yield the same result as here\n // + 1 at the end is because the point at radius itself is computed as well\n return 8 * static_cast(\n std::round(radius * std::cos(boost::gil::detail::pi / 4)) + 1);\n }\n\n /// \\brief perform rasterization and output into d_first\n template \n void operator()(std::ptrdiff_t radius, point_t offset, RAIterator d_first) const\n {\n auto translate_mirror_points = [&d_first, offset](point_t p) {\n *d_first++ = point_t{offset.x + p.x, offset.y + p.y};\n *d_first++ = point_t{offset.x + p.x, offset.y - p.y};\n *d_first++ = point_t{offset.x - p.x, offset.y + p.y};\n *d_first++ = point_t{offset.x - p.x, offset.y - p.y};\n *d_first++ = point_t{offset.x + p.y, offset.y + p.x};\n *d_first++ = point_t{offset.x + p.y, offset.y - p.x};\n *d_first++ = point_t{offset.x - p.y, offset.y + p.x};\n *d_first++ = point_t{offset.x - p.y, offset.y - p.x};\n };\n std::ptrdiff_t iteration_distance = point_count(radius) / 8;\n std::ptrdiff_t y_current = radius;\n std::ptrdiff_t r_squared = radius * radius;\n translate_mirror_points({0, y_current});\n for (std::ptrdiff_t x = 1; x < iteration_distance; ++x)\n {\n std::ptrdiff_t midpoint = x * x + y_current * y_current - y_current - r_squared;\n if (midpoint > 0)\n {\n --y_current;\n }\n translate_mirror_points({x, y_current});\n }\n }\n};\n}} // namespace boost::gil\n#endif\n", "meta": {"hexsha": "31c3cf6caf5f88054ca61f615141e4749e16860c", "size": 5601, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/gil/rasterization/circle.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/rasterization/circle.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/rasterization/circle.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": 44.1023622047, "max_line_length": 97, "alphanum_fraction": 0.6407784324, "num_tokens": 1388, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8615382094310355, "lm_q2_score": 0.7520125682019722, "lm_q1q2_score": 0.6478875614783616}} {"text": "#ifndef STAN_MATH_PRIM_MAT_PROB_DIRICHLET_LPMF_HPP\n#define STAN_MATH_PRIM_MAT_PROB_DIRICHLET_LPMF_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\n namespace math {\n\n /**\n * The log of the Dirichlet density for the given theta and\n * a vector of prior sample sizes, alpha.\n * Each element of alpha must be greater than 0.\n * Each element of theta must be greater than or 0.\n * Theta sums to 1.\n *\n * \\f{eqnarray*}{\n \\theta &\\sim& \\mbox{\\sf{Dirichlet}} (\\alpha_1, \\ldots, \\alpha_k) \\\\\n \\log (p (\\theta \\, |\\, \\alpha_1, \\ldots, \\alpha_k) ) &=& \\log \\left( \\frac{\\Gamma(\\alpha_1 + \\cdots + \\alpha_k)}{\\Gamma(\\alpha_1) \\cdots \\Gamma(\\alpha_k)}\n \\theta_1^{\\alpha_1 - 1} \\cdots \\theta_k^{\\alpha_k - 1} \\right) \\\\\n &=& \\log (\\Gamma(\\alpha_1 + \\cdots + \\alpha_k)) - \\log(\\Gamma(\\alpha_1)) - \\cdots - \\log(\\Gamma(\\alpha_k)) +\n (\\alpha_1 - 1) \\log (\\theta_1) + \\cdots + (\\alpha_k - 1) \\log (\\theta_k)\n \\f}\n *\n * @param theta A scalar vector.\n * @param alpha Prior sample sizes.\n * @return The log of the Dirichlet density.\n * @throw std::domain_error if any element of alpha is less than\n * or equal to 0.\n * @throw std::domain_error if any element of theta is less than 0.\n * @throw std::domain_error if the sum of theta is not 1.\n * @tparam T_prob Type of scalar.\n * @tparam T_prior_sample_size Type of prior sample sizes.\n */\n template \n typename boost::math::tools::promote_args::type\n dirichlet_lpmf(const Eigen::Matrix& theta,\n const Eigen::Matrix\n & alpha) {\n static const char* function(\"dirichlet_lpmf\");\n using boost::math::lgamma;\n using boost::math::tools::promote_args;\n\n typename promote_args::type lp(0.0);\n check_consistent_sizes(function,\n \"probabilities\", theta,\n \"prior sample sizes\", alpha);\n check_positive(function, \"prior sample sizes\", alpha);\n check_simplex(function, \"probabilities\", theta);\n\n if (include_summand::value) {\n lp += lgamma(alpha.sum());\n for (int k = 0; k < alpha.rows(); ++k)\n lp -= lgamma(alpha[k]);\n }\n if (include_summand::value) {\n for (int k = 0; k < theta.rows(); ++k)\n lp += multiply_log(alpha[k] - 1, theta[k]);\n }\n return lp;\n }\n\n template \n inline\n typename boost::math::tools::promote_args::type\n dirichlet_lpmf(const Eigen::Matrix& theta,\n const Eigen::Matrix\n & alpha) {\n return dirichlet_lpmf(theta, alpha);\n }\n\n }\n}\n#endif\n", "meta": {"hexsha": "abca8a0c941e05150b48fe0c5070fc21c694be4c", "size": 3483, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/dirichlet_lpmf.hpp", "max_stars_repo_name": "yizhang-cae/torsten", "max_stars_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/dirichlet_lpmf.hpp", "max_issues_repo_name": "yizhang-cae/torsten", "max_issues_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmdstan/stan/lib/stan_math/stan/math/prim/mat/prob/dirichlet_lpmf.hpp", "max_forks_repo_name": "yizhang-cae/torsten", "max_forks_repo_head_hexsha": "dc82080ca032325040844cbabe81c9a2b5e046f9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9638554217, "max_line_length": 159, "alphanum_fraction": 0.6431237439, "num_tokens": 967, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8824278664544912, "lm_q2_score": 0.734119526900183, "lm_q1q2_score": 0.647807527845109}} {"text": "#include \"PointCloud.hpp\"\n\n#include \n#include \n\n#include \"../KDTreeFlann/KDTreeFlann.hpp\"\n\n\nnamespace pointcloudhandler \n{\n\n\t\tPointCloud& PointCloud::Clear() \n\t\t{\n\t\t\tmPoints.clear();\n\t\t\treturn *this;\n\t\t}\n\n\t\tbool PointCloud::IsEmpty() const \n\t\t{ \n\t\t\treturn !HasPoints(); \n\t\t}\n\n\t\tEigen::Vector3d PointCloud::GetMinBound() const \n\t\t{\n\t\t\treturn ComputeMinBound(mPoints);\n\t\t}\n\n\t\tEigen::Vector3d PointCloud::GetMaxBound() const \n\t\t{\n\t\t\treturn ComputeMaxBound(mPoints);\n\t\t}\n\n\t\tEigen::Vector3d PointCloud::GetCenter() const \n\t\t{ \n\t\t\treturn ComputeCenter(mPoints); \n\t\t}\n\n\t\tPointCloud& PointCloud::Transform(const Eigen::Matrix4d &transformation) \n\t\t{\n\t\t\tTransformPoints(transformation, mPoints);\n\t\t\treturn *this;\n\t\t}\n\n\t\tPointCloud& PointCloud::Translate(const Eigen::Vector3d &translation, bool relative) \n\t\t{\n\t\t\tTranslatePoints(translation, mPoints, relative);\n\t\t\treturn *this;\n\t\t}\n\n\t\tPointCloud& PointCloud::Scale(const double scale, bool center) \n\t\t{\n\t\t\tScalePoints(scale, mPoints, center);\n\t\t\treturn *this;\n\t\t}\n\n\t\tPointCloud& PointCloud::Rotate(const Eigen::Matrix3d &R, bool center) \n\t\t{\n\t\t\tRotatePoints(R, mPoints, center);\n\t\t\treturn *this;\n\t\t}\n\n\t\tPointCloud& PointCloud::operator+=(const PointCloud &cloud) \n\t\t{\n\t\t\tif (cloud.IsEmpty()) \n\t\t\t\treturn (*this);\n\t\t\tsize_t oldVertNum = mPoints.size();\n\t\t\tsize_t addVertNum = cloud.mPoints.size();\n\t\t\tsize_t newVertNum = oldVertNum + addVertNum;\n\t\t\tmPoints.resize(newVertNum);\n\t\t\tfor (size_t i = 0; i < addVertNum; i++)\n\t\t\t\tmPoints[oldVertNum + i] = cloud.mPoints[i];\n\t\t\treturn (*this);\n\t\t}\n\n\t\tPointCloud PointCloud::operator+(const PointCloud &cloud) const \n\t\t{\n\t\t\treturn (PointCloud(*this) += cloud);\n\t\t}\n\n\t\tstd::vector PointCloud::ComputePointCloudDistance(const PointCloud &target) \n\t\t{\n\t\t\tstd::vector distances(mPoints.size());\n\t\t\tKDTreeFlann kdtree;\n\t\t\tkdtree.SetGeometry(target);\n\t\t\tfor (int i = 0; i < (int)mPoints.size(); i++) \n\t\t\t{\n\t\t\t\tstd::vector indices(1);\n\t\t\t\tstd::vector dists(1);\n\t\t\t\tif (kdtree.SearchKNN(mPoints[i], 1, indices, dists) == 0) \n\t\t\t\t{\n\t\t\t\t\t/*Found a point without neighbors.\");*/\n\t\t\t\t\tdistances[i] = 0.0;\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\tdistances[i] = std::sqrt(dists[0]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn distances;\n\t\t}\n\n\t\tPointCloud& PointCloud::RemoveNoneFinitePoints(bool removeNan, bool removeInfinite) {\n\t\t\tsize_t oldPointNum = mPoints.size();\n\t\t\tsize_t k = 0; // new index\n\t\t\tfor (size_t i = 0; i < oldPointNum; i++) \n\t\t\t{ // old index\n\t\t\t\tbool isNan = removeNan &&\n\t\t\t\t\t(std::isnan(mPoints[i](0)) || std::isnan(mPoints[i](1)) || std::isnan(mPoints[i](2)));\n\t\t\t\tbool is_infinite = removeInfinite && \n\t\t\t\t\t(std::isinf(mPoints[i](0)) || std::isinf(mPoints[i](1)) ||std::isinf(mPoints[i](2)));\n\t\t\t\tif (!isNan && !is_infinite) \n\t\t\t\t{\n\t\t\t\t\tmPoints[k] = mPoints[i];\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tmPoints.resize(k);\n\t\t\treturn *this;\n\t\t}\n\n\t\tstd::tuplePointCloud::ComputeMeanAndCovariance() const \n\t\t{\n\t\t\tif (IsEmpty()) \n\t\t\t{\n\t\t\t\treturn std::make_tuple(Eigen::Vector3d::Zero(), Eigen::Matrix3d::Identity());\n\t\t\t}\n\t\t\tEigen::Matrix cumulants;\n\t\t\tcumulants.setZero();\n\t\t\tfor (const auto &point : mPoints) \n\t\t\t{\n\t\t\t\tcumulants(0) += point(0);\n\t\t\t\tcumulants(1) += point(1);\n\t\t\t\tcumulants(2) += point(2);\n\t\t\t\tcumulants(3) += point(0) * point(0);\n\t\t\t\tcumulants(4) += point(0) * point(1);\n\t\t\t\tcumulants(5) += point(0) * point(2);\n\t\t\t\tcumulants(6) += point(1) * point(1);\n\t\t\t\tcumulants(7) += point(1) * point(2);\n\t\t\t\tcumulants(8) += point(2) * point(2);\n\t\t\t}\n\t\t\tcumulants /= (double)mPoints.size();\n\t\t\tEigen::Vector3d mean;\n\t\t\tEigen::Matrix3d covariance;\n\t\t\tmean(0) = cumulants(0);\n\t\t\tmean(1) = cumulants(1);\n\t\t\tmean(2) = cumulants(2);\n\t\t\tcovariance(0, 0) = cumulants(3) - cumulants(0) * cumulants(0);\n\t\t\tcovariance(1, 1) = cumulants(6) - cumulants(1) * cumulants(1);\n\t\t\tcovariance(2, 2) = cumulants(8) - cumulants(2) * cumulants(2);\n\t\t\tcovariance(0, 1) = cumulants(4) - cumulants(0) * cumulants(1);\n\t\t\tcovariance(1, 0) = covariance(0, 1);\n\t\t\tcovariance(0, 2) = cumulants(5) - cumulants(0) * cumulants(2);\n\t\t\tcovariance(2, 0) = covariance(0, 2);\n\t\t\tcovariance(1, 2) = cumulants(7) - cumulants(1) * cumulants(2);\n\t\t\tcovariance(2, 1) = covariance(1, 2);\n\t\t\treturn std::make_tuple(mean, covariance);\n\t\t}\n\n\t\tstd::vector PointCloud::ComputeMahalanobisDistance() const \n\t\t{\n\t\t\tstd::vector mahalanobis(mPoints.size());\n\t\t\tEigen::Vector3d mean;\n\t\t\tEigen::Matrix3d covariance;\n\t\t\tstd::tie(mean, covariance) = ComputeMeanAndCovariance();\n\t\t\tEigen::Matrix3d covInv = covariance.inverse();\n\n\t\t\tfor (int i = 0; i < (int)mPoints.size(); i++) \n\t\t\t{\n\t\t\t\tEigen::Vector3d p = mPoints[i] - mean;\n\t\t\t\tmahalanobis[i] = std::sqrt(p.transpose() * covInv * p);\n\t\t\t}\n\t\t\treturn mahalanobis;\n\t\t}\n\n\t\tstd::vector PointCloud::ComputeNearestNeighborDistance() const \n\t\t{\n\t\t\tstd::vector nnDis(mPoints.size());\n\t\t\tKDTreeFlann kdtree(*this);\n\t\t\tfor (int i = 0; i < (int)mPoints.size(); i++) \n\t\t\t{\n\t\t\t\tstd::vector indices(2);\n\t\t\t\tstd::vector dists(2);\n\t\t\t\tif (kdtree.SearchKNN(mPoints[i], 2, indices, dists) <= 1) \n\t\t\t\t{\n\t\t\t\t\t/*Found a point without neighbors.\");*/\n\t\t\t\t\tnnDis[i] = 0.0;\n\t\t\t\t}\n\t\t\t\telse \n\t\t\t\t{\n\t\t\t\t\tnnDis[i] = std::sqrt(dists[1]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nnDis;\n\t\t}\n\n} // namespace pointcloudhandler", "meta": {"hexsha": "bc55a2bccb222ea6a98dafad8d50c1e82ae61b2d", "size": 5290, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PointCloudHandler/PointCloud/PointCloud.cpp", "max_stars_repo_name": "serjik85kg/PointCloudHandler", "max_stars_repo_head_hexsha": "c3e91ce4ac334cd603dbe03659fd87d661f322fa", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PointCloudHandler/PointCloud/PointCloud.cpp", "max_issues_repo_name": "serjik85kg/PointCloudHandler", "max_issues_repo_head_hexsha": "c3e91ce4ac334cd603dbe03659fd87d661f322fa", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PointCloudHandler/PointCloud/PointCloud.cpp", "max_forks_repo_name": "serjik85kg/PointCloudHandler", "max_forks_repo_head_hexsha": "c3e91ce4ac334cd603dbe03659fd87d661f322fa", "max_forks_repo_licenses": ["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.9897959184, "max_line_length": 91, "alphanum_fraction": 0.6247637051, "num_tokens": 1794, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8577680904463333, "lm_q2_score": 0.7549149758396752, "lm_q1q2_score": 0.647541977275338}} {"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 \"zienkiewiczzhuestimator.h\"\n\n#define _USE_MATH_DEFINES\n#include \n#include \n// Eigen includes\n#include \n#include \n#include \n// Lehrfem++ includes\n#include \n#include \n#include \n#include \n\nnamespace ZienkiewiczZhuEstimator {\n\n/* Implementing member function Eval of class VectorProjectionMatrixProvider*/\n/* SAM_LISTING_BEGIN_1 */\nEigen::MatrixXd VectorProjectionMatrixProvider::Eval(\n const lf::mesh::Entity &entity) {\n Eigen::MatrixXd elMat_vec; // element matrix to be returned\n // Throw error in case cell is not Tria nor Quad\n LF_VERIFY_MSG(entity.RefEl() == lf::base::RefEl::kTria() ||\n entity.RefEl() == lf::base::RefEl::kQuad(),\n \"Unsupported cell type \" << entity.RefEl());\n\n if (entity.RefEl() == lf::base::RefEl::kTria()) {\n elMat_vec = Eigen::MatrixXd::Zero(6, 6);\n // For TRIANGULAR CELLS\n // Compute the area of the triangle cell\n const double area = lf::geometry::Volume(*(entity.Geometry()));\n // Assemble the mass element matrix over the cell\n // clang-format off\n elMat_vec << 2.0, 0.0, 1.0, 0.0, 1.0, 0.0,\n 0.0, 2.0, 0.0, 1.0, 0.0, 1.0,\n\t 1.0, 0.0, 2.0, 0.0, 1.0, 0.0,\n\t 0.0, 1.0, 0.0, 2.0, 0.0, 1.0,\n\t 1.0, 0.0, 1.0, 0.0, 2.0, 0.0,\n\t 0.0, 1.0, 0.0, 1.0, 0.0, 2.0;\n // clang-format on\n elMat_vec *= area / 12.0;\n } else {\n // for QUADRILATERAL CELLS\n elMat_vec = Eigen::MatrixXd::Zero(8, 8);\n Eigen::MatrixXd elMat_scal =\n Eigen::MatrixXd::Zero(4, 4); // element matrix for scalar FEM\n // Tensor product Gauss-Legendre quadrature rule of order 4\n const lf::quad::QuadRule qr{\n lf::quad::make_QuadRule(lf::base::RefEl::kQuad(), 3)};\n // Reference quadrature points\n const Eigen::MatrixXd zeta_ref{qr.Points()};\n // Quadrature weights\n const Eigen::VectorXd w_ref{qr.Weights()};\n // Number of quadrature points\n const lf::base::size_type P = qr.NumPoints();\n\n // Reference tensor product basis functions on quadrilateral ref entity\n std::vector> ref_basis_vec;\n auto b0_ref = [](coord_t x) -> double { return (1 - x(0)) * (1 - x(1)); };\n auto b1_ref = [](coord_t x) -> double { return x(0) * (1 - x(1)); };\n auto b2_ref = [](coord_t x) -> double { return x(0) * x(1); };\n auto b3_ref = [](coord_t x) -> double { return (1 - x(0)) * x(1); };\n ref_basis_vec.push_back(b0_ref);\n ref_basis_vec.push_back(b1_ref);\n ref_basis_vec.push_back(b2_ref);\n ref_basis_vec.push_back(b3_ref);\n\n const lf::geometry::Geometry &geo{*(entity.Geometry())};\n const Eigen::VectorXd gram_dets{geo.IntegrationElement(zeta_ref)};\n for (int i = 0; i < 4; i++) {\n for (int j = 0; j < 4; j++) {\n for (int l = 0; l < P; l++) {\n elMat_scal(i, j) += w_ref[l] * ref_basis_vec[i](zeta_ref.col(l)) *\n ref_basis_vec[j](zeta_ref.col(l)) * gram_dets[l];\n }\n }\n }\n // 8x8 element (mass) matrix for vectorial FEM\n // clang-format off\n elMat_vec << elMat_scal(0, 0), 0.0, elMat_scal(0, 1), 0.0, elMat_scal(0, 2), 0.0, elMat_scal(0, 3), 0.0,\n 0.0, elMat_scal(0, 0), 0.0, elMat_scal(0, 1), 0.0, elMat_scal(0, 2), 0.0, elMat_scal(0, 3),\n elMat_scal(1, 0), 0.0, elMat_scal(1, 1), 0.0, elMat_scal(1, 2), 0.0, elMat_scal(1, 3), 0.0,\n\t 0.0, elMat_scal(1, 0), 0.0, elMat_scal(1, 1), 0.0, elMat_scal(1, 2), 0.0, elMat_scal(1, 3),\n\t elMat_scal(2, 0), 0.0, elMat_scal(2, 1), 0.0, elMat_scal(2, 2), 0.0, elMat_scal(2, 3), 0.0,\n\t 0.0, elMat_scal(2, 0), 0.0, elMat_scal(2, 1), 0.0, elMat_scal(2, 2), 0.0, elMat_scal(2, 3),\n elMat_scal(3, 0), 0.0, elMat_scal(3, 1), 0.0, elMat_scal(3, 2), 0.0, elMat_scal(3, 3), 0.0,\n 0.0, elMat_scal(3, 0), 0.0, elMat_scal(3, 1), 0.0, elMat_scal(3, 2), 0.0, elMat_scal(3, 3);\n // clang-format on\n\n }\n return elMat_vec; // return the local mass element matrix\n} //\n/* SAM_LISTING_END_1 */\n\n/* Implementing member function Eval of class GradientProjectionVectorProvider*/\n/* SAM_LISTING_BEGIN_2 */\nEigen::VectorXd GradientProjectionVectorProvider::Eval(\n const lf::mesh::Entity &entity) {\n Eigen::VectorXd elVec(6); // for returning the element vector\n // Obtain local->global index mapping for current finite element space\n const lf::assemble::DofHandler &dofh{_fe_space_p->LocGlobMap()};\n // Obtain global indices of the vertices of the triangle entity\n auto dof_idx_vec = dofh.GlobalDofIndices(entity);\n LF_ASSERT_MSG(dofh.NumLocalDofs(entity) == 3,\n \"Too many global indices were returned for a triangle entity!\");\n\n // Obtain the gradients of the barycentric coordinate functions\n Eigen::Matrix elgrad_Mat = gradbarycoordinates(entity);\n // Compute the local constant gradient of the finite element solution\n Eigen::Vector2d grad_vec(0.0, 0.0);\n for (int i = 0; i < 3; i++) {\n grad_vec = grad_vec + elgrad_Mat.col(i) * _mu(dof_idx_vec[i]);\n }\n // Assemble local element vector\n // Compute the area of the triangle cell\n const double area = lf::geometry::Volume(*(entity.Geometry()));\n // clang-format off\n elVec << grad_vec(0),\n grad_vec(1),\n grad_vec(0),\n grad_vec(1),\n grad_vec(0),\n grad_vec(1);\n // clang-format on\n elVec *= area / 3.0;\n return elVec;\n} // GradientProjectionVectorProvider::Eval\n/* SAM_LISTING_END_2 */\n\nEigen::Matrix gradbarycoordinates(\n const lf::mesh::Entity &entity) {\n LF_VERIFY_MSG(entity.RefEl() == lf::base::RefEl::kTria(),\n \"Unsupported cell type \" << entity.RefEl());\n\n // Get vertices of the triangle\n auto endpoints = lf::geometry::Corners(*(entity.Geometry()));\n\n Eigen::Matrix X; // temporary matrix\n X.block<3, 1>(0, 0) = Eigen::Vector3d::Ones();\n X.block<3, 2>(0, 1) = endpoints.transpose();\n\n return X.inverse().block<2, 3>(1, 0);\n} // gradbarycoordinates\n\n/* SAM_LISTING_BEGIN_3 */\nEigen::VectorXd computeLumpedProjection(\n const lf::assemble::DofHandler &scal_dofh, const Eigen::VectorXd &mu,\n const lf::assemble::DofHandler &vec_dofh) {\n // Obtain shared_ptr to mesh\n std::shared_ptr mesh_p = scal_dofh.Mesh();\n // Dimension of vector-valued finite element space\n const lf::uscalfe::size_type N_vec_dofs(vec_dofh.NumDofs());\n // Initialize vector FE basis expansion coefficient vector with zeros\n Eigen::VectorXd proj_vec(N_vec_dofs);\n proj_vec.setZero();\n // Initialize temporary helper nodal DataSet (codim 2)\n auto nodal_sum_of_areas =\n lf::mesh::utils::CodimMeshDataSet(mesh_p, 2, 0.0);\n\n // Loop over the triangular cells of the mesh in the spirit of\n // cell oriented assembly\n for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n LF_VERIFY_MSG(cell->RefEl() == lf::base::RefEl::kTria(),\n \"Unsupported cell type \" << cell->RefEl());\n // Obtain global scalar-FE indices of the vertices\n const auto scal_dof_idx_vec = scal_dofh.GlobalDofIndices(*cell);\n // Obtain the gradients of the barycentric coordinate functions\n const Eigen::Matrix elgrad_Mat = gradbarycoordinates(*cell);\n // Obtain area of the triangular cell\n const double area = lf::geometry::Volume(*(cell->Geometry()));\n// Compute the gradient of the passed coefficient vector\n const Eigen::Vector2d grad_mu =\n elgrad_Mat.col(0) * mu(scal_dof_idx_vec[0]) +\n elgrad_Mat.col(1) * mu(scal_dof_idx_vec[1]) +\n elgrad_Mat.col(2) * mu(scal_dof_idx_vec[2]);\n // Local contribution to the area of the cell patch surrounding a node\n for (const lf::mesh::Entity *node : cell->SubEntities(2)) {\n LF_VERIFY_MSG(node->RefEl() == lf::base::RefEl::kPoint(),\n \"Expected kPoint type!\" << node->RefEl());\n auto vec_dofh_idx = vec_dofh.GlobalDofIndices(*node);\n proj_vec[vec_dofh_idx[0]] += area * grad_mu[0];\n proj_vec[vec_dofh_idx[1]] += area * grad_mu[1];\n nodal_sum_of_areas(*node) = nodal_sum_of_areas(*node) + area;\n }\n }\n\n // Scaling of components of vector of dofs\n for (const lf::mesh::Entity *node : mesh_p->Entities(2)) {\n LF_VERIFY_MSG(node->RefEl() == lf::base::RefEl::kPoint(),\n \"Expected kPoint type!\" << node->RefEl());\n const double area_scal_fac = 1.0 / nodal_sum_of_areas(*node);\n auto vec_dofh_idx = vec_dofh.GlobalDofIndices(*node);\n proj_vec[vec_dofh_idx[0]] *= area_scal_fac;\n proj_vec[vec_dofh_idx[1]] *= area_scal_fac;\n }\n return proj_vec;\n}; // computeLumpedProjection\n\n/* SAM_LISTING_END_3 */\n\n/* SAM_LISTING_BEGIN_4 */\ndouble computeL2Deviation(const lf::assemble::DofHandler &scal_dofh,\n const Eigen::VectorXd &eta,\n const lf::assemble::DofHandler &vec_dofh,\n const Eigen::VectorXd &gamma) {\n double deviation_norm_value = 0.0; // For retrurning the result\n // Obtain shared_ptr to mesh\n auto mesh_p = scal_dofh.Mesh();\n // Cell-oriented computation of deviation norm (squared)\n for (const lf::mesh::Entity *cell : mesh_p->Entities(0)) {\n LF_VERIFY_MSG(cell->RefEl() == lf::base::RefEl::kTria(),\n \"Unsupported cell type \" << cell->RefEl());\n // Obtain area of the triangular cell\n const double area = lf::geometry::Volume(*(cell->Geometry()));\n\n // Obtain global scalar-FE indices of the vertices\n auto scal_dof_idx_vec = scal_dofh.GlobalDofIndices(*cell);\n // Obtain the gradients of the barycentric coordinates functions\n Eigen::Matrix elgrad_Mat = gradbarycoordinates(*cell);\n// Compute the gradient of the passed coefficient vector eta\n const Eigen::Vector2d grad_eta =\n elgrad_Mat.col(0) * eta(scal_dof_idx_vec[0]) +\n elgrad_Mat.col(1) * eta(scal_dof_idx_vec[1]) +\n elgrad_Mat.col(2) * eta(scal_dof_idx_vec[2]);\n\n // Obtaining the values of the passed vector at each node\n std::vector r_vec_values;\n for (const lf::mesh::Entity *node : cell->SubEntities(2)) {\n LF_VERIFY_MSG(node->RefEl() == lf::base::RefEl::kPoint(),\n \"Expected kPoint type!\" << node->RefEl());\n auto vec_dofh_idx = vec_dofh.GlobalDofIndices(*node);\n Eigen::Vector2d r_vec_at_node;\n r_vec_at_node[0] = gamma[vec_dofh_idx[0]];\n r_vec_at_node[1] = gamma[vec_dofh_idx[1]];\n r_vec_values.push_back(r_vec_at_node);\n }\n\n // Computing local contribution of the cell to the deviation norm\n double local_norm_value =\n (0.5 * (r_vec_values.at(0) + r_vec_values.at(1)) - grad_eta)\n .squaredNorm() +\n (0.5 * (r_vec_values.at(1) + r_vec_values.at(2)) - grad_eta)\n .squaredNorm() +\n (0.5 * (r_vec_values.at(2) + r_vec_values.at(0)) - grad_eta)\n .squaredNorm();\n local_norm_value *= area / 3.0;\n\n // Adding local contribution to the value of the deviation norm\n deviation_norm_value += local_norm_value;\n }\n return std::sqrt(deviation_norm_value);\n}; // computeL2Deviation\n/* SAM_LISTING_END_4 */\n\nEigen::VectorXd solveBVP(\n const std::shared_ptr> &fe_space_p) {\n Eigen::VectorXd discrete_solution;\n\n // TOOLS AND DATA\n // Pointer to current mesh\n std::shared_ptr mesh_p = fe_space_p->Mesh();\n // Obtain local->global index mapping for current finite element space\n const lf::assemble::DofHandler &dofh{fe_space_p->LocGlobMap()};\n // Dimension of finite element space\n const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n // Obtain specification for shape functions on edges\n std::shared_ptr>\n rsf_edge_p = fe_space_p->ShapeFunctionLayout(lf::base::RefEl::kSegment());\n\n // Dirichlet data\n auto mf_g = lf::mesh::utils::MeshFunctionGlobal(\n [](coord_t x) -> double { return 0.0; });\n // Right-hand side source function f\n auto mf_f = lf::mesh::utils::MeshFunctionGlobal([](coord_t x) -> double {\n return sin(M_PI * x[0]) * sin(2 * M_PI * x[1]);\n });\n\n // I : ASSEMBLY\n // Matrix in triplet format holding Galerkin matrix, zero initially.\n lf::assemble::COOMatrix A(N_dofs, N_dofs);\n // Right hand side vector, must be initialized with 0!\n Eigen::Matrix phi(N_dofs);\n phi.setZero();\n\n // I.i : Computing volume matrix for negative Laplace operator\n // Initialize object taking care of local mass (volume) computations.\n lf::uscalfe::LinearFELaplaceElementMatrix elmat_builder{};\n // Invoke assembly on cells (co-dimension = 0 as first argument)\n // Information about the mesh and the local-to-global map is passed through\n // a Dofhandler object, argument 'dofh'. This function call adds triplets to\n // the internal COO-format representation of the sparse matrix A.\n lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elmat_builder, A);\n\n // I.ii : Computing right-hand side vector\n lf::uscalfe::ScalarLoadElementVectorProvider\n elvec_builder(fe_space_p, mf_f);\n // Invoke assembly on cells (codim == 0)\n AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n // I.iii : Imposing essential boundary conditions\n // Obtain an array of boolean flags for the edges of the mesh, 'true'\n // indicates that the edge lies on the boundary (codim = 1)\n auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 1)};\n // Inspired by the example in the documentation of\n // InitEssentialConditionFromFunction()\n // https://craffael.github.io/lehrfempp/namespacelf_1_1uscalfe.html#a5afbd94919f0382cf3fb200c452797ac\n // Creating a predicate that will guarantee that the computations are carried\n // only on the exterior boundary edges of the mesh using the boundary flags\n auto edges_predicate_Dirichlet =\n [&bd_flags](const lf::mesh::Entity &edge) -> bool {\n return bd_flags(edge);\n };\n // Determine the fixed dofs on the boundary and their values\n // Alternative: See lecturedemoDirichlet() in\n // https://github.com/craffael/lehrfempp/blob/master/examples/lecturedemos/lecturedemoassemble.cc\n auto edges_flag_values_Dirichlet{\n lf::uscalfe::InitEssentialConditionFromFunction(\n dofh, *rsf_edge_p, edges_predicate_Dirichlet, mf_g)};\n // Eliminate Dirichlet dofs from the linear system\n lf::assemble::FixFlaggedSolutionCompAlt(\n [&edges_flag_values_Dirichlet](lf::assemble::glb_idx_t gdof_idx) {\n return edges_flag_values_Dirichlet[gdof_idx];\n },\n A, phi);\n\n // Assembly completed! Convert COO matrix A into CRS format using Eigen's\n // internal conversion routines.\n Eigen::SparseMatrix A_sparse = A.makeSparse();\n\n // II : SOLVING THE LINEAR SYSTEM\n // II.i : Setting up Eigen's sparse direct elimination\n Eigen::SparseLU> solver;\n solver.compute(A_sparse);\n LF_VERIFY_MSG(solver.info() == Eigen::Success, \"LU decomposition failed\");\n // II.ii : Solving\n discrete_solution = solver.solve(phi);\n LF_VERIFY_MSG(solver.info() == Eigen::Success, \"Solving LSE failed\");\n\n return discrete_solution;\n}; // solveBVP\n\nEigen::VectorXd solveGradVP(\n const std::shared_ptr> &fe_space_p,\n const Eigen::VectorXd &mu, const lf::assemble::DofHandler &vec_dofh) {\n Eigen::VectorXd approx_grad;\n\n // TOOLS AND DATA\n // Pointer to current mesh\n std::shared_ptr mesh_p = fe_space_p->Mesh();\n // Dimension of finite vector elements space\n const lf::uscalfe::size_type N_vec_dofs(vec_dofh.NumDofs());\n // Matrix in triplet format holding the Galerkin matrix, zero initially.\n lf::assemble::COOMatrix M_COO(N_vec_dofs, N_vec_dofs);\n // Right-hand side vector has to be set to zero initially\n Eigen::Matrix phi(N_vec_dofs);\n phi.setZero();\n\n // Initialize classes containing the information required for the\n // local computations of the Galerkin matrix and the load vector\n VectorProjectionMatrixProvider elMat_builder;\n GradientProjectionVectorProvider elVec_builder(fe_space_p, mu);\n // Compute the Galerkin matrix and load vector\n lf::assemble::AssembleMatrixLocally(0, vec_dofh, vec_dofh, elMat_builder,\n M_COO);\n lf::assemble::AssembleVectorLocally(0, vec_dofh, elVec_builder, phi);\n\n // Solve the linear problem\n Eigen::SparseMatrix M = M_COO.makeSparse();\n Eigen::SparseLU> solver;\n solver.compute(M);\n LF_VERIFY_MSG(solver.info() == Eigen::Success, \"LU decomposition failed\");\n approx_grad = solver.solve(phi);\n\n return approx_grad;\n}; // solveGradVP\n\ndouble getMeshSize(const std::shared_ptr &mesh_p) {\n double mesh_size = 0.0;\n\n // Find maximal edge length\n double edge_length;\n for (const lf::mesh::Entity *edge : mesh_p->Entities(1)) {\n // Compute the length of the edge\n auto endpoints = lf::geometry::Corners(*(edge->Geometry()));\n edge_length = (endpoints.col(0) - endpoints.col(1)).norm();\n if (mesh_size < edge_length) {\n mesh_size = edge_length;\n }\n }\n\n return mesh_size;\n}; // getMeshSize\n\nvoid progress_bar::write(double fraction) {\n // clamp fraction to valid range [0,1]\n if (fraction < 0)\n fraction = 0;\n else if (fraction > 1)\n fraction = 1;\n\n auto width = bar_width - message.size();\n auto offset = bar_width - static_cast(width * fraction);\n\n std::string sign = \"%\";\n os << '\\r' << message;\n os.write(full_bar.data() + offset, width);\n os << \" [completed: \" << std::setw(3) << static_cast(100 * fraction)\n << sign + \" of meshes]\" << std::flush;\n};\n\n} // namespace ZienkiewiczZhuEstimator\n", "meta": {"hexsha": "a3888b467963e21a775626119032f1826a8c1303", "size": 18005, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/ZienkiewiczZhuEstimator/mastersolution/zienkiewiczzhuestimator.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/ZienkiewiczZhuEstimator/mastersolution/zienkiewiczzhuestimator.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/ZienkiewiczZhuEstimator/mastersolution/zienkiewiczzhuestimator.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": 42.869047619, "max_line_length": 108, "alphanum_fraction": 0.6690919189, "num_tokens": 5344, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933094060543488, "lm_q2_score": 0.7248702880639791, "lm_q1q2_score": 0.6475334464968779}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\nint fired_main(std::string file_path = fire::arg({\"--file-path\",\"-f\"})) {\n std::ifstream file(file_path, std::fstream::binary);\n\n if (!file.good()) {\n std::cerr << \"Couldn't open file!\" << std::endl;\n return 1;\n }\n file >> std::noskipws;\n\n std::map freq;\n\n uint64_t total_bytes;\n\n char buf;\n while (file >> buf) {\n freq[buf]++;\n total_bytes++;\n }\n file.close();\n\n double entropy = 0;\n for (const auto& f : freq) {\n double p=(double)f.second/(double)total_bytes;\n entropy-=p*log2(p);\n }\n\n std::cout << \"Entropy: \" << boost::lexical_cast(entropy) << \"\\n\" << \"Metric entropy: \" << boost::lexical_cast(entropy/total_bytes) << std::endl;\n\n return 0;\n}\n\nFIRE(fired_main, \"Calculate file entropy\")\n", "meta": {"hexsha": "6ddf43b8e18678ae436782e7e54a2eaf8b03c1e5", "size": 1006, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "app/entropy.cxx", "max_stars_repo_name": "northy/huffman-compactor", "max_stars_repo_head_hexsha": "bcb174b0d8e6a97f5a9f6e7f6ce7e94de2ce0bbc", "max_stars_repo_licenses": ["MIT"], "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/entropy.cxx", "max_issues_repo_name": "northy/huffman-compactor", "max_issues_repo_head_hexsha": "bcb174b0d8e6a97f5a9f6e7f6ce7e94de2ce0bbc", "max_issues_repo_licenses": ["MIT"], "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/entropy.cxx", "max_forks_repo_name": "northy/huffman-compactor", "max_forks_repo_head_hexsha": "bcb174b0d8e6a97f5a9f6e7f6ce7e94de2ce0bbc", "max_forks_repo_licenses": ["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.3555555556, "max_line_length": 174, "alphanum_fraction": 0.5994035785, "num_tokens": 269, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8933093946927837, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.6475334170234034}} {"text": "// This file contains my implementation for pose esimtation\n#include \"marker.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n// refer to: https://www.dropbox.com/s/qkulg4j64lyn0qa/2018_proj_geo_for_cv_projcv_assignment.pdf?dl=0\n// update computed rotation matrix\nvoid updateRotationSVD(glm::mat4x3& M)\n{\n Eigen::Matrix3f R;\n R << M[0][0], M[1][0], M[2][0],\n M[0][1], M[1][1], M[2][1],\n M[0][2], M[1][2], M[2][2];\n Eigen::JacobiSVD svdSolver(R, Eigen::ComputeFullV | Eigen::ComputeFullU);\n R = svdSolver.matrixU() * svdSolver.matrixV().transpose();\n M[0][0] = R.col(0)[0];\n M[0][1] = R.col(0)[1];\n M[0][2] = R.col(0)[2];\n M[1][0] = R.col(1)[0];\n M[1][1] = R.col(1)[1];\n M[1][2] = R.col(1)[2];\n M[2][0] = R.col(2)[0];\n M[2][1] = R.col(2)[1];\n M[2][2] = R.col(2)[2];\n}\n\n// refer to https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.895.2324&rep=rep1&type=pdf\n// update to Tait-Bryan rotation matrix\nvoid updateRotationTaitBryan(glm::mat4x3& M)\n{\n float theta = -std::asin(M[2][0]);\n float thetaS = std::sin(theta);\n float thetaC = std::cos(theta);\n float psi = std::asin(M[1][0] / thetaC);\n float psiS = std::sin(psi);\n float psiC = std::cos(psi);\n float phi = std::asin(M[2][1] / thetaC);\n float phiS = std::sin(phi);\n float phiC = std::cos(phi);\n\n M[0][0] = thetaC * psiC;\n M[1][0] = thetaC * psiS;\n M[2][0] = -thetaS;\n\n M[0][1] = phiS * thetaS * psiC - phiC * psiS;\n M[1][1] = phiS * thetaS * psiS + phiC * psiC;\n M[2][1] = phiS * thetaC;\n\n M[0][2] = phiC * thetaS * psiC + phiS * psiS;\n M[1][2] = phiC * thetaS * psiS - phiS * psiC;\n M[2][2] = phiC * thetaC;\n}\n\n// refer to: https://stackoverflow.com/questions/12463487/obtain-rotation-axis-from-rotation-matrix-and-translation-vector-in-opencv\nvoid updateRotationEuclidean(glm::mat4x3& M)\n{\n // obtain rotation angle\n float angle = std::acos(0.5f * (M[0][0] + M[1][1] + M[2][2] - 1.0f));\n // obtain axis\n glm::vec3 axis = glm::vec3(M[1][2] - M[2][1], M[2][0] - M[0][2], M[0][1] - M[1][0]);\n axis = glm::normalize(axis);\n glm::mat4 rot = glm::rotate(glm::mat4(1.0f), glm::degrees(angle), axis);\n M[0][0] = rot[0][0]; M[1][0] = rot[1][0]; M[2][0] = rot[2][0];\n M[0][1] = rot[0][1]; M[1][1] = rot[1][1]; M[2][1] = rot[2][1];\n M[0][2] = rot[0][2]; M[1][2] = rot[1][2]; M[2][2] = rot[2][2];\n}\n\n// compute reprojection error\nfloat reprojectionError(\n const glm::mat3& cameraK, const glm::mat4x3& M,\n const std::vector& objPoints,\n const std::vector& imgPoints\n)\n{\n float error = 0.0f;\n for(size_t i = 0; i < 4; i++)\n {\n // auto projected = M * glm::vec4(objPoints[i], 0.0f, 1.0f);\n auto projected = cameraK * M * glm::vec4(objPoints[i], 0.0f, 1.0f);\n float dx = projected.x - imgPoints[i].x;\n float dy = projected.y - imgPoints[i].y;\n error += dx * dx + dy * dy;\n }\n return std::sqrt(error * 0.125f);\n}\n\n// validate solution based on Zhang's method\nbool validateSolutionZhang(\n const Eigen::Vector3f& tstar, const Eigen::Vector3f& nstar, const Eigen::MatrixXf& H,\n const Eigen::MatrixXf& mstarT, Eigen::Matrix3f& outR, Eigen::Vector3f& outT\n)\n{\n // prepare rotation matrix and translation vector\n // R = H (I + t* n^T)^-1\n outR = H * (Eigen::Matrix3f::Identity() + tstar * nstar.transpose()).inverse();\n if(outR.determinant() < 0.0f)\n {\n // flip surface\n outR *= -1.0f;\n }\n outT = outR * tstar;\n // 1 + n^T R^T t\n float positive = 1.0f + (nstar.transpose() * outR.transpose() * outT)[0];\n if(positive <= 0.0f)\n return false;\n // m*^T n*\n Eigen::Vector4f positives = mstarT * nstar;\n if(positives[0] <= 0.0f || positives[1] <= 0.0f ||\n positives[2] <= 0.0f || positives[3] <= 0.0f)\n return false;\n return true;\n}\n\n// refer to https://hal.inria.fr/inria-00174036v3/document\n// refer to https://github.com/opencv/opencv/blob/4.x/modules/calib3d/src/homography_decomp.cpp#L217\n// decompose homography matrix\nvoid decomposeHomoMatrixZhang(\n const glm::mat3& cameraK, const glm::mat3& cameraInvK, const glm::mat3x4& mstarTransposed,\n const glm::mat3& G, const std::vector& objPoints,\n const std::vector& imgPoints, glm::mat4x3& outputM)\n{\n // normalize H\n // glm::mat3 hHat = cameraInvK * G * cameraK;\n glm::mat3 hHat = cameraInvK * G;\n // retrieve homography matrix H\n Eigen::Matrix H;\n H << hHat[0][0], hHat[1][0], hHat[2][0],\n hHat[0][1], hHat[1][1], hHat[2][1],\n hHat[0][2], hHat[1][2], hHat[2][2];\n Eigen::EigenSolver eigenSolver;\n // eigenSolver.compute(H, false);\n // float gamma = eigenSolver.eigenvalues().real()[1];\n // H = H / gamma; // scale by lambda2\n // H^TH = V A V^T and solve for eigenvalues and eigenvectors\n // H = H.transpose() * H;\n eigenSolver.compute(H, true);\n Eigen::VectorXf lambdas = eigenSolver.eigenvalues().real();\n Eigen::MatrixXf vs = eigenSolver.eigenvectors().real();\n // verify the eigenvectors\n if (vs.rows() < 3 || vs.cols() < 3) return;\n float lambda1 = lambdas[0];\n float lambda3 = lambdas[2];\n // float lambda1 = lambdas[0] >= lambdas[2] ? lambdas[0] : lambdas[2];\n // float lambda3 = lambdas[0] >= lambdas[2] ? lambdas[2] : lambdas[0];\n float lambda1x3 = lambda1 * lambda3;\n float lambda1m3 = lambda1 - lambda3;\n float lambda1m3_2 = lambda1m3 * lambda1m3;\n // prepare zeta\n float tmp1 = 1.0f / (2.0f * lambda1x3);\n float tmp2 = std::sqrt(std::abs(1.0f + 4.0f * lambda1x3 / lambda1m3_2));\n float tmp1x2 = tmp1 * tmp2;\n float zeta1 = -tmp1 + tmp1x2;\n float zeta3 = -tmp1 - tmp1x2;\n float zeta1_2 = zeta1 * zeta1;\n float zeta3_2 = zeta3 * zeta3;\n float zeta1m3 = zeta1 - zeta3;\n float zeta1m3_inv = 1.0f / zeta1m3;\n // compute norms of v'1,3\n float nv1p = std::sqrt(std::abs(zeta1_2 * lambda1m3_2 + 2.0f * zeta1 * (lambda1x3 - 1.0f) + 1.0f));\n float nv3p = std::sqrt(std::abs(zeta3_2 * lambda1m3_2 + 2.0f * zeta3 * (lambda1x3 - 1.0f) + 1.0f));\n // compute v1' and v3'\n Eigen::Vector3f v1p, v3p;\n v1p << vs.col(0)[0]*nv1p, vs.col(0)[1]*nv1p, vs.col(0)[2]*nv1p;\n v3p << vs.col(2)[0]*nv3p, vs.col(2)[1]*nv3p, vs.col(2)[2]*nv3p;\n // 8 solutions in total:\n Eigen::Vector3f tstar[4], nstar[4];\n // solution 1\n tstar[0] = (v1p - v3p) * zeta1m3_inv;\n tstar[1] = -(v1p - v3p) * zeta1m3_inv;\n nstar[0] = (zeta1 * v3p - zeta3 * v1p) * zeta1m3_inv;\n nstar[1] = -(zeta1 * v3p - zeta3 * v1p) * zeta1m3_inv;\n // solution 2\n tstar[2] = (v1p + v3p) * zeta1m3_inv;\n tstar[3] = -(v1p + v3p) * zeta1m3_inv;\n nstar[2] = (zeta1 * v3p + zeta3 * v1p) * zeta1m3_inv;\n nstar[3] = -(zeta1 * v3p + zeta3 * v1p) * zeta1m3_inv;\n // prepare mstar transposed (for validation)\n Eigen::Matrix mstarT;\n mstarT << mstarTransposed[0][0], mstarTransposed[1][0], mstarTransposed[2][0],\n mstarTransposed[0][1], mstarTransposed[1][1], mstarTransposed[2][1],\n mstarTransposed[0][2], mstarTransposed[1][2], mstarTransposed[2][2],\n mstarTransposed[0][3], mstarTransposed[1][3], mstarTransposed[2][3];\n // validate solutions, collect the first one\n Eigen::Matrix3f R; // rotation\n Eigen::Vector3f T; // translation\n std::vector candidates;\n for(int i = 0; i < 2; i++)\n {\n for(int j = 0; j < 2; j++)\n {\n if(validateSolutionZhang(tstar[i], nstar[j], H, mstarT, R, T))\n {\n candidates.push_back(glm::mat4x3(\n glm::vec3(R.col(0)[0], R.col(0)[1], R.col(0)[2]),\n glm::vec3(R.col(1)[0], R.col(1)[1], R.col(1)[2]),\n glm::vec3(R.col(2)[0], R.col(2)[1], R.col(2)[2]),\n glm::vec3(T[0], T[1], T[2])\n ));\n }\n if(validateSolutionZhang(tstar[i+2], nstar[j+2], H, mstarT, R, T))\n {\n candidates.push_back(glm::mat4x3(\n glm::vec3(R.col(0)[0], R.col(0)[1], R.col(0)[2]),\n glm::vec3(R.col(1)[0], R.col(1)[1], R.col(1)[2]),\n glm::vec3(R.col(2)[0], R.col(2)[1], R.col(2)[2]),\n glm::vec3(T[0], T[1], T[2])\n ));\n }\n }\n }\n\n if(candidates.size() == 0)\n {\n outputM = glm::mat4x3(0.0f);\n return;\n }\n // compute reprojection error for each\n float minError = std::numeric_limits::max();\n size_t selectedIdx = 0;\n for(size_t i = 0; i < candidates.size(); i++)\n {\n float error = reprojectionError(cameraK, candidates[i], objPoints, imgPoints);\n if(error < minError)\n {\n minError = error;\n selectedIdx = i;\n }\n }\n // std::cout << \"Reprojection Error: \" << minError << std::endl;\n // set pose matrix\n outputM = candidates[selectedIdx];\n}\n\n// refer to: https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L384\n// undistort image points\nvoid undistortPoints(\n const glm::mat3& cameraK, const glm::vec3& cameraDistK, const glm::vec2& cameraDistP,\n glm::vec2& p1, glm::vec2& p2, glm::vec2& p3, glm::vec2& p4)\n{\n glm::vec2 src[4] = {p1, p2, p3, p4};\n glm::vec2 dst[4];\n float fx = cameraK[0][0], fy = cameraK[1][1];\n float invfx = 1.0f / fx, invfy = 1.0f / fy;\n float cx = cameraK[2][0], cy = cameraK[2][1];\n // prepare coefficient K\n // k1,k2,p1,p2,k3\n float k[5] = {cameraDistK.x, cameraDistK.y, cameraDistP.x, cameraDistP.y, cameraDistK.z};\n for(int i = 0; i < 4; i++)\n {\n float x = src[i].x, y = src[i].y;\n float x0, y0, u, v;\n u = x;\n v = y;\n x = x0 = (x - cx) * invfx;\n y = y0 = (y - cy) * invfy;\n // init error\n float error = std::numeric_limits::max();\n // iteratively reduce distortion error\n const int MAX_ITER = 10;\n const float EPS = 0.0005f;\n int j = 0;\n for(; j < MAX_ITER; j++)\n {\n if(error < EPS) break;\n float r2 = x*x + y*y;\n float icdist = 1.0f / (\n 1.0f + ((k[4] * r2 + k[1]) * r2 + k[0]) * r2\n );\n // if distortion is negative, reset\n if(icdist < 0.0f)\n {\n x = (u - cx) * invfx;\n y = (v - cy) * invfy;\n break;\n }\n float deltaX = 2.0f * k[2] * x * y + k[3] * (r2 + 2.0f * x * x);\n float deltaY = k[2] * (r2 + 2 * y * y) + 2.0f * k[3] * x * y;\n x = (x0 - deltaX) * icdist;\n y = (y0 - deltaY) * icdist;\n // compute error\n {\n float r4, r6;\n float a1, a2, a3;\n float cdist;\n float xd, yd;\n r2 = x * x + y * y;\n r4 = r2 * r2;\n r6 = r4 * r2;\n a1 = 2.0f * x * y;\n a2 = r2 + 2.0f * x * x;\n a3 = r2 + 2.0f * y * y;\n cdist = 1.0f + k[0] * r2 + k[1] * r4 + k[4] * r6;\n xd = x * cdist + k[2] * a1 + k[3] * a2;\n yd = y * cdist + k[2] * a3 + k[3] * a1;\n float xproj, yproj;\n xproj = xd * fx + cx;\n yproj = yd * fy + cy;\n error = std::sqrt((xproj - u) * (xproj - u) + (yproj - v) * (yproj - v));\n }\n }\n // std::cout << j << \",\" << error << std::endl;\n dst[i].x = x * fx + cx;\n dst[i].y = y * fy + cy;\n }\n // retrieve new positions\n p1 = dst[0];\n p2 = dst[1];\n p3 = dst[2];\n p4 = dst[3];\n}\n\n// refer to book: \"Augmented Reality: Principles and Practice\"\n// decompose homography matrix\nvoid decomposeHomoMatrixARBook(\n const glm::mat3& cameraK, const glm::mat3& cameraInvK, glm::mat3 H, glm::mat4x3& outputM\n)\n{\n H = cameraInvK * H;\n // recover rotation matrix and translation vector\n float d = 1.0f / std::sqrt(glm::length(H[0]) * glm::length(H[1]));\n // set translation\n outputM[3] = d * H[2];\n glm::vec3 h1 = H[0];\n glm::vec3 h2 = H[1];\n glm::vec3 h12 = glm::normalize(h1 + h2);\n glm::vec3 h21 = glm::normalize(glm::cross(h12, glm::cross(h1, h2)));\n // set rotations\n d = 1.0f / std::sqrt(2.0f);\n outputM[0] = (h12 + h21) * d; // set R1\n outputM[1] = (h12 - h21) * d; // set R2\n outputM[2] = glm::cross(outputM[0], outputM[1]); // set R3\n}\n\n// refer to https://stackoverflow.com/questions/8927771/computing-camera-pose-with-homography-matrix-based-on-4-coplanar-points\n// decompose homography matrix\nvoid decomposeHomoMatrixInternet(\n const glm::mat3& cameraK, const glm::mat3& cameraInvK, glm::mat3 H, glm::mat4x3& outputM\n)\n{\n H = cameraInvK * H;\n float tnorm = 2.0f / (glm::length(H[0]) + glm::length(H[1]));\n // set translation\n outputM[3] = tnorm * H[2];\n // set rotations\n outputM[0] = glm::normalize(H[0]);\n outputM[1] = glm::normalize(H[1]);\n outputM[2] = glm::cross(outputM[0], outputM[1]);\n}\n\n// refer to https://gist.github.com/inspirit/740979/97f54a63eb5f61f8f2eb578d60eb44839556ff3f\nvoid decomposeHomoMatrixInternet2(\n const glm::mat3& cameraK, const glm::mat3& cameraInvK, glm::mat3 H, glm::mat4x3& outputM\n)\n{\n H = cameraInvK * H;\n float lambda = 1.0f / glm::length(H[0]);\n // set translation\n outputM[3] = lambda * H[2];\n // set rotations\n outputM[0] = lambda * H[0];\n outputM[1] = lambda * H[1];\n outputM[2] = glm::cross(outputM[0], outputM[1]);\n}\n\n\n// refer to https://courses.cs.duke.edu//spring22/compsci527/notes/n_10_reconstruction.pdf\n// decompose homography matrix\nvoid decomposeHomoMatrixDuke(\n const glm::mat3& cameraK, const glm::mat3& cameraInvK,\n const std::vector& objPoints, const std::vector& imgPoints,\n glm::mat3 H, glm::mat4x3& outputM\n)\n{\n H = cameraInvK * H;\n // prepare E\n Eigen::Matrix E;\n E << H[0][0], H[1][0], H[2][0],\n H[0][1], H[1][1], H[2][1],\n H[0][2], H[1][2], H[2][2];\n // decompose E\n Eigen::JacobiSVD svdSolver;\n svdSolver.compute(E, Eigen::ComputeFullV | Eigen::ComputeFullU);\n // estimate two possible t\n auto& U = svdSolver.matrixU();\n auto& V = svdSolver.matrixV();\n Eigen::Vector3f T1 = V.col(2);\n Eigen::Vector3f T2 = -V.col(2);\n // prepare alpha, beta\n Eigen::Matrix3f ab1 = U.col(0) * V.col(0).transpose();\n Eigen::Matrix3f ab2 = U.col(1) * V.col(1).transpose();\n Eigen::Matrix3f ab3 = U.col(2) * V.col(2).transpose();\n // compute Q\n Eigen::Matrix3f Q1 = ab1 + ab2 + ab3;\n Eigen::Matrix3f Q2 = ab1 + ab2 - ab3;\n // compute R\n Eigen::Matrix3f R1 = Q1 * Q1.determinant();\n Eigen::Matrix3f R2 = Q2 * Q2.determinant();\n std::vector candidates;\n candidates.push_back(glm::mat4x3(\n glm::vec3(R1.col(0)[0], R1.col(0)[1], R1.col(0)[2]),\n glm::vec3(R1.col(1)[0], R1.col(1)[1], R1.col(1)[2]),\n glm::vec3(R1.col(2)[0], R1.col(2)[1], R1.col(2)[2]),\n glm::vec3(T1[0], T1[1], T1[2])\n ));\n candidates.push_back(glm::mat4x3(\n glm::vec3(R1.col(0)[0], R1.col(0)[1], R1.col(0)[2]),\n glm::vec3(R1.col(1)[0], R1.col(1)[1], R1.col(1)[2]),\n glm::vec3(R1.col(2)[0], R1.col(2)[1], R1.col(2)[2]),\n glm::vec3(T2[0], T2[1], T2[2])\n ));\n candidates.push_back(glm::mat4x3(\n glm::vec3(R2.col(0)[0], R2.col(0)[1], R2.col(0)[2]),\n glm::vec3(R2.col(1)[0], R2.col(1)[1], R2.col(1)[2]),\n glm::vec3(R2.col(2)[0], R2.col(2)[1], R2.col(2)[2]),\n glm::vec3(T1[0], T1[1], T1[2])\n ));\n candidates.push_back(glm::mat4x3(\n glm::vec3(R2.col(0)[0], R2.col(0)[1], R2.col(0)[2]),\n glm::vec3(R2.col(1)[0], R2.col(1)[1], R2.col(1)[2]),\n glm::vec3(R2.col(2)[0], R2.col(2)[1], R2.col(2)[2]),\n glm::vec3(T2[0], T2[1], T2[2])\n ));\n float minError = std::numeric_limits::max();\n size_t selectedIdx = 0;\n for(size_t i = 0; i < candidates.size(); i++)\n {\n float error = reprojectionError(cameraK, candidates[i], objPoints, imgPoints);\n if(error < minError)\n {\n minError = error;\n selectedIdx = i;\n }\n }\n // set pose matrix\n outputM = candidates[selectedIdx];\n}\n\n// refer to https://stanford.edu/class/ee267/notes/ee267_notes_tracking.pdf\n// decompose homography matrix\nvoid decomposeHomoMatrixStanford(\n const glm::mat3& cameraK, const glm::mat3& cameraInvK, glm::mat3 H, glm::mat4x3& outputM\n)\n{\n H = cameraInvK * H;\n float normCol0 = glm::length(H[0]);\n float normCol1 = glm::length(H[1]);\n float s = 2.0f / (normCol0 + normCol1);\n // set translation\n outputM[3] = s * H[2];\n // set rotations\n outputM[0] = H[0] / normCol0;\n outputM[1] = H[1] - outputM[0] * glm::dot(outputM[0], H[1]);\n outputM[1] = glm::normalize(outputM[1]);\n outputM[2] = glm::cross(outputM[0], outputM[1]);\n}\n\n// scale the estimated projection matrix\nfloat scalePoseM(glm::mat4x3& M)\n{\n float scale = std::abs(M[3][2]);\n M /= scale;\n return scale;\n}\n\nvoid testPoseM(const glm::mat3& cameraK, glm::mat4x3& M, const glm::vec2& q)\n{\n auto tmp = cameraK * M * glm::vec4(q, 0.0f, 1.0f);\n std::cout << tmp.x << \",\" << tmp.y << \",\" << tmp.z << std::endl;\n}\n\n// estimate pose from homography (SVD method)\nvoid Marker::estimatePoseSVD(\n const glm::mat3& cameraK, const glm::mat3& cameraInvK,\n const glm::vec3& cameraDistK, const glm::vec2& cameraDistP\n)\n{\n if(!_new_marker) return;\n if(_marker_borderp1p2.x <= 0.0f)\n {\n _poseM = glm::mat4x3(0.0f);\n _poseMRefined = glm::mat4x3(0.0f);\n return;\n }\n // prepare p\n glm::vec2 p1 = glm::vec2(_marker_borderp1p2.x, _marker_borderp1p2.y);\n glm::vec2 p2 = glm::vec2(_marker_borderp1p2.z, _marker_borderp1p2.w);\n glm::vec2 p3 = glm::vec2(_marker_borderp3p4.x, _marker_borderp3p4.y);\n glm::vec2 p4 = glm::vec2(_marker_borderp3p4.z, _marker_borderp3p4.w);\n // undistort points\n undistortPoints(\n cameraK, cameraDistK, cameraDistP,\n p1, p2, p3, p4\n );\n // glm::mat3x4 mstarT = glm::transpose(\n // cameraInvK * glm::mat4x3(\n // glm::vec3(p1, 1.0f),\n // glm::vec3(p2, 1.0f),\n // glm::vec3(p3, 1.0f),\n // glm::vec3(p4, 1.0f)\n // )\n // );\n // prepare q\n // const glm::vec2 q1 = glm::vec2(0.0f, 0.0f);\n // const glm::vec2 q2 = glm::vec2(0.0f, 1.0f);\n // const glm::vec2 q4 = glm::vec2(1.0f, 0.0f);\n // const glm::vec2 q3 = glm::vec2(1.0f, 1.0f);\n const glm::vec2 q1 = glm::vec2(-1.0f, -1.0f);\n const glm::vec2 q2 = glm::vec2(-1.0f, 1.0f);\n const glm::vec2 q3 = glm::vec2( 1.0f, -1.0f);\n const glm::vec2 q4 = glm::vec2( 1.0f, 1.0f);\n // set up matrix A\n Eigen::Matrix A;\n A << q1.x, q1.y, 1.0f, 0.0f, 0.0f, 0.0f, -p1.x*q1.x, -p1.x*q1.y, -p1.x,\n 0.0f, 0.0f, 0.0f, q1.x, q1.y, 1.0f, -p1.y*q1.x, -p1.y*q1.y, -p1.y,\n\n q2.x, q2.y, 1.0f, 0.0f, 0.0f, 0.0f, -p2.x*q2.x, -p2.x*q2.y, -p2.x,\n 0.0f, 0.0f, 0.0f, q2.x, q2.y, 1.0f, -p2.y*q2.x, -p2.y*q2.y, -p2.y,\n\n q3.x, q3.y, 1.0f, 0.0f, 0.0f, 0.0f, -p3.x*q3.x, -p3.x*q3.y, -p3.x,\n 0.0f, 0.0f, 0.0f, q3.x, q3.y, 1.0f, -p3.y*q3.x, -p3.y*q3.y, -p3.y,\n\n q4.x, q4.y, 1.0f, 0.0f, 0.0f, 0.0f, -p4.x*q4.x, -p4.x*q4.y, -p4.x,\n 0.0f, 0.0f, 0.0f, q4.x, q4.y, 1.0f, -p4.y*q4.x, -p4.y*q4.y, -p4.y;\n // solve SVD for A\n Eigen::JacobiSVD svdSolver(A, Eigen::ComputeFullV);\n auto& matrixV = svdSolver.matrixV();\n auto& h = matrixV.col(matrixV.cols() - 1);\n glm::mat3 H = glm::mat3(\n glm::vec3(h[0], h[3], h[6]),\n glm::vec3(h[1], h[4], h[7]),\n glm::vec3(h[2], h[5], h[8])\n );\n std::vector objPoints = {q1, q2, q3, q4};\n std::vector imgPoints = {p1, p2, p3, p4};\n // decomposeHomoMatrixZhang(cameraK, cameraInvK, mstarT, H, objPoints, imgPoints, _poseM);\n // decomposeHomoMatrixARBook(cameraK, cameraInvK, H, _poseM);\n decomposeHomoMatrixInternet(cameraK, cameraInvK, H, _poseM);\n // decomposeHomoMatrixInternet2(cameraK, cameraInvK, H, _poseM);\n // decomposeHomoMatrixStanford(cameraK, cameraInvK, H, _poseM);\n _err_scale = scalePoseM(_poseM);\n refinePoseM(cameraInvK, objPoints, imgPoints);\n _err_reproj = reprojectionError(cameraK, _poseMRefined, objPoints, imgPoints);\n}\n\n// reference: https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/\n// estimate pose from homography (linear equation method)\nvoid Marker::estimatePoseLinear(\n const glm::mat3& cameraK, const glm::mat3& cameraInvK,\n const glm::vec3& cameraDistK, const glm::vec2& cameraDistP\n)\n{\n if(!_new_marker) return;\n if(_marker_borderp1p2.x <= 0.0f)\n {\n _poseM = glm::mat4x3(0.0f);\n _poseMRefined = glm::mat4x3(0.0f);\n return;\n }\n // prepare p\n glm::vec2 p1 = glm::vec2(_marker_borderp1p2.x, _marker_borderp1p2.y);\n glm::vec2 p2 = glm::vec2(_marker_borderp1p2.z, _marker_borderp1p2.w);\n glm::vec2 p3 = glm::vec2(_marker_borderp3p4.x, _marker_borderp3p4.y);\n glm::vec2 p4 = glm::vec2(_marker_borderp3p4.z, _marker_borderp3p4.w);\n // undistort points\n undistortPoints(\n cameraK, cameraDistK, cameraDistP,\n p1, p2, p3, p4\n );\n // prepare q\n static glm::vec2 q1 = glm::vec2(-1.0f, -1.0f);\n static glm::vec2 q2 = glm::vec2(-1.0f, 1.0f);\n static glm::vec2 q3 = glm::vec2( 1.0f, -1.0f);\n static glm::vec2 q4 = glm::vec2( 1.0f, 1.0f);\n // set up matrix A\n Eigen::Matrix A;\n A << q1.x, q1.y, 1.0f, 0.0f, 0.0f, 0.0f, -p1.x*q1.x, -p1.x*q1.y,\n 0.0f, 0.0f, 0.0f, q1.x, q1.y, 1.0f, -p1.y*q1.x, -p1.y*q1.y,\n\n q2.x, q2.y, 1.0f, 0.0f, 0.0f, 0.0f, -p2.x*q2.x, -p2.x*q2.y,\n 0.0f, 0.0f, 0.0f, q2.x, q2.y, 1.0f, -p2.y*q2.x, -p2.y*q2.y,\n\n q3.x, q3.y, 1.0f, 0.0f, 0.0f, 0.0f, -p3.x*q3.x, -p3.x*q3.y,\n 0.0f, 0.0f, 0.0f, q3.x, q3.y, 1.0f, -p3.y*q3.x, -p3.y*q3.y,\n\n q4.x, q4.y, 1.0f, 0.0f, 0.0f, 0.0f, -p4.x*q4.x, -p4.x*q4.y,\n 0.0f, 0.0f, 0.0f, q4.x, q4.y, 1.0f, -p4.y*q4.x, -p4.y*q4.y;\n\n Eigen::Vector b;\n b << p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y;\n auto h = A.colPivHouseholderQr().solve(b);\n glm::mat3 H = glm::mat3(\n glm::vec3(h[0], h[3], h[6]),\n glm::vec3(h[1], h[4], h[7]),\n glm::vec3(h[2], h[5], 1.0f)\n );\n\n std::vector objPoints = {q1, q2, q3, q4};\n std::vector imgPoints = {p1, p2, p3, p4};\n // decomposeHomoMatrixStanford(cameraK, cameraInvK, H, _poseM);\n // decomposeHomoMatrixARBook(cameraK, cameraInvK, H, _poseM);\n decomposeHomoMatrixInternet(cameraK, cameraInvK, H, _poseM);\n // decomposeHomoMatrixInternet2(cameraK, cameraInvK, H, _poseM);\n // decomposeHomoMatrixDuke(cameraK, cameraInvK, objPoints, imgPoints, H, _poseM);\n _err_scale = scalePoseM(_poseM);\n refinePoseM(cameraInvK, objPoints, imgPoints);\n _err_reproj = reprojectionError(cameraK, _poseMRefined, objPoints, imgPoints);\n}\n\n// use opencv as reference\n// estimate pose (OpenCV method)\nvoid Marker::estimatePoseOpenCV(\n const glm::mat3& cameraK, const glm::mat3& cameraInvK,\n const glm::vec3& cameraDistK, const glm::vec2& cameraDistP\n)\n{\n if(!_new_marker) return;\n if(_marker_borderp1p2.x <= 0.0f)\n {\n _poseM = glm::mat4x3(0.0f);\n _poseMRefined = glm::mat4x3(0.0f);\n return;\n }\n std::vector imgPoints = {\n cv::Point2d(_marker_borderp1p2.x, _marker_borderp1p2.y),\n cv::Point2d(_marker_borderp1p2.z, _marker_borderp1p2.w),\n cv::Point2d(_marker_borderp3p4.x, _marker_borderp3p4.y),\n cv::Point2d(_marker_borderp3p4.z, _marker_borderp3p4.w),\n };\n std::vector objPoints = {\n cv::Point3d(-1.0, -1.0, 0.0),\n cv::Point3d(-1.0, 1.0, 0.0),\n cv::Point3d( 1.0, -1.0, 0.0),\n cv::Point3d( 1.0, 1.0, 0.0),\n };\n // std::vector objPoints = {\n cv::Mat3d cameraMat = (\n cv::Mat_>(3,3) << cameraK[0][0], cameraK[1][0], cameraK[2][0],\n cameraK[0][1], cameraK[1][1], cameraK[2][1],\n cameraK[0][2], cameraK[1][2], cameraK[2][2]\n );\n std::vector cameraDist = {\n cameraDistK.x, cameraDistK.y, cameraDistP.x, cameraDistP.y, cameraDistK.z\n };\n cv::Mat rvec, tvec;\n if(!cv::solvePnP(objPoints, imgPoints, cameraMat, cameraDist, rvec, tvec, false, cv::SOLVEPNP_IPPE))\n {\n _poseM = glm::mat4x3(0.0f);\n return;\n }\n cv::Mat rotMat;\n cv::Rodrigues(rvec, rotMat);\n rotMat.convertTo(rotMat, CV_32F);\n tvec.convertTo(tvec, CV_32F);\n _poseM = glm::mat4x3(\n glm::vec3(rotMat.at(0,0), rotMat.at(1,0), rotMat.at(2,0)),\n glm::vec3(rotMat.at(0,1), rotMat.at(1,1), rotMat.at(2,1)),\n glm::vec3(rotMat.at(0,2), rotMat.at(1,2), rotMat.at(2,2)),\n glm::vec3(tvec.at(0,0), tvec.at(0,1), tvec.at(0,2))\n );\n _err_scale = scalePoseM(_poseM);\n}", "meta": {"hexsha": "5c8238dbf5c74c29334a6ef5160d7361446d4902", "size": 25376, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "PC/src/markerpose.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/markerpose.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/markerpose.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": 38.1021021021, "max_line_length": 132, "alphanum_fraction": 0.5614360025, "num_tokens": 9801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314828740728, "lm_q2_score": 0.7310585903489892, "lm_q1q2_score": 0.6474485034386046}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ros/ros.h\"\n#include \"std_msgs/Float64.h\"\n#include \"std_msgs/Float64MultiArray.h\"\n#include \"sensor_msgs/JointState.h\"\n#include \"gazebo_msgs/LinkStates.h\"\n#include \"define.h\"\n\n#include \n\n#define DESIRED_VEL 40 // RW_qdot_des [rad/s]\n#define NUM_OF_MEASUREMENTS 1000\n\ntypedef Eigen::Matrix Matrix;\n\ntemplate\nusing PseudoInverseType = Eigen::Matrix;\n\ntemplate\nPseudoInverseType pseudoInverse(const MatType &a, double epsilon = std::numeric_limits::epsilon())\n{\n using WorkingMatType = Eigen::Matrix;\n Eigen::BDCSVD svd(a, Eigen::ComputeThinU | Eigen::ComputeThinV);\n svd.setThreshold(epsilon*std::max(a.cols(), a.rows()));\n Eigen::Index rank = svd.rank();\n Eigen::Matrix::MaxDiagSizeAtCompileTime, MatType::MaxRowsAtCompileTime>\n tmp = svd.matrixU().leftCols(rank).adjoint();\n tmp = svd.singularValues().head(rank).asDiagonal().inverse() * tmp;\n return svd.matrixV().leftCols(rank) * tmp;\n}\n\nbool reachedVel = false;\n\nfloat q1; // angle of first joint [rad]\nfloat q2; // angle of second joint [rad]\nfloat q1dot; // rate of first joint [rad/s]\nfloat q2dot; // rate of second joint [rad/s]\nfloat omega0; // base angular velocity [rad/s]\nfloat RW_vel; // reaction wheel velocity [rad/s]\n\nvoid velocityCheckCallback(const sensor_msgs::JointState::ConstPtr& msg) {\n \n q1 = msg->position[0];\n q2 = msg->position[1];\n q1dot = msg->velocity[0];\n q2dot = msg->velocity[1];\n RW_vel = msg->velocity[4];\n \n // ROS_INFO(\"RW_vel: %.5f | q1: %.5f | q2: %.5f | q1dot: %.5f | q2dot: %.5f\", RW_vel, q1, q2, q1dot, q2dot);\n\n if (!reachedVel && RW_vel >= DESIRED_VEL)\n reachedVel = true;\n else if (reachedVel) {\n // ROS_INFO(\"Measurement number: %d\");\n }\n}\n\nvoid positionCheckCallback(const gazebo_msgs::LinkStates::ConstPtr& msg) {\n\n omega0 = msg->twist[3].angular.z;\n // ROS_INFO(\"angular twist z: %.5f\", omega0);\n}\n\n\nint main(int argc, char **argv) {\n\n // calculations\n double EulerConstant = std::exp(1.0);\n\n double M = M0+M1+M2;\n double I0 = ((double)1/2)*(M0*pow(RH, (double)2));\n double I1 = 3.46*pow(EulerConstant, (double)-4);\n double I2 = 3.46*pow(EulerConstant, (double)-4);\n // double R0X = 0.1954*cos(27.9*PI/180);\n // double R0Y = 0.1954*sin(27.9*PI/180);\n\n double frequency = (float)1/DT;\n\n double hrw = Irw * DESIRED_VEL;\n\n /* define the robot 8 inertial parameters */\n double pi1 = M0*R0X*((M1+M2)*L1+M2*R1)/M;\n double pi2 = M0*R0X*M2*L2/M;\n double pi3 = M0*R0Y*((M1+M2)*L1+M2*R1)/M;\n double pi4 = M0*R0Y*M2*L2/M;\n double pi5 = I0+M0*(M1+M2)*(pow(R0X, (double)2) + pow(R0Y, (double)2))/M;\n double pi6 = M2*L2*(M0*L1+(M0+M1)*R1)/M;\n double pi7 = I1+(M0*(M1+M2)*pow(L1, (double)2)+2*M0*M2*L1*R1+M2*(M0+M1)*pow(R1, (double)2))/M;\n double pi8 = I2+(M2*(M0+M1)*pow(L2, (double)2))/M;\n\n Eigen::Matrix robotInertialParameters;\n robotInertialParameters(0, 0) = pi1;\n robotInertialParameters(1, 0) = pi2;\n robotInertialParameters(2, 0) = pi3;\n robotInertialParameters(3, 0) = pi4;\n robotInertialParameters(4, 0) = pi5;\n robotInertialParameters(5, 0) = pi6;\n robotInertialParameters(6, 0) = pi7;\n robotInertialParameters(7, 0) = pi8;\n\n\n q1 = q2 = q1dot = q2dot = omega0 = 0.0;\n \n /* Eigen Matrix */\n Matrix Y;\n Y.resize(NUM_OF_MEASUREMENTS, 8);\n\n /* Define Hrw matrix as a Nx1 column vector and all components equal to hrw */\n Eigen::Matrix Hcm;\n for (int i = 0; i < NUM_OF_MEASUREMENTS; ++i)\n Hcm(i, 0) = hrw;\n\n /* ros init */\n ros::init(argc, argv, \"cepheus_controller_node\");\n ros::NodeHandle n;\n\n /* Create publishers */\n ros::Publisher RW_velocity_pub = n.advertise(\"/cepheus/reaction_wheel_velocity_controller/command\", 1);\n ros::Publisher LE_position_pub = n.advertise(\"/cepheus/left_elbow_position_controller/command\", 1);\n ros::Publisher LS_position_pub = n.advertise(\"/cepheus/left_shoulder_position_controller/command\", 1);\n\n /* messages to publish */\n std_msgs::Float64 msg_RW;\n std_msgs::Float64 msg_LE;\n std_msgs::Float64 msg_LS;\n \n /* init messages */ \n msg_RW.data = 0.1;\n msg_LE.data = 0.1;\n msg_LS.data = 0.1;\n\n int currentMeasurement = 0;\n\n /* Create subscribers */\n ros::Subscriber RW_velocity_sub = n.subscribe(\"/cepheus/joint_states\", 1, velocityCheckCallback);\n ros::Subscriber position_sub = n.subscribe(\"/gazebo/link_states\", 1, positionCheckCallback);\n\n \n ros::Rate loop_rate(frequency);\n\n\n while (ros::ok()) {\n\n RW_velocity_pub.publish(msg_RW);\n LE_position_pub.publish(msg_LE);\n LS_position_pub.publish(msg_LS);\n \n ros::spinOnce();\n\n // arm joins sinusoidal movement\n msg_LE.data = 3 * sin(ros::Time::now().toSec());\n msg_LS.data = -1 * sin(ros::Time::now().toSec());\n\n\n if (reachedVel && (currentMeasurement < NUM_OF_MEASUREMENTS)) {\n \n /* Keep RW desired velocity while taking measurements */\n\n msg_RW.data = DESIRED_VEL;\n \n ROS_INFO(\"-----------------------------------------------------------------\");\n ROS_INFO(\"current measurement number: %d\", currentMeasurement+1);\n ROS_INFO(\"q1: %.3f, q2: %.3f, q1dot: %.3f, q2dot: %.3f, omega0: %.3f\", q1, q2, q1dot, q2dot, omega0);\n\n Y(currentMeasurement, 0) = (2*omega0 + q1dot) * cos(q1);\n Y(currentMeasurement, 1) = (2*omega0 + q1dot + q2dot) * cos(q1+q2);\n Y(currentMeasurement, 2) = (2*omega0 + q1dot) * sin(q1);\n Y(currentMeasurement, 3) = (2*omega0 + q1dot + q2dot) * sin(q1+q2);\n Y(currentMeasurement, 4) = omega0;\n Y(currentMeasurement, 5) = (2*omega0 + 2*q1dot + q2dot) * cos(q2);\n Y(currentMeasurement, 6) = omega0 + q1dot;\n Y(currentMeasurement, 7) = omega0 + q1dot + q2dot;\n\n currentMeasurement++;\n }\n else if (currentMeasurement >= NUM_OF_MEASUREMENTS) {\n\n /* Measurements completed */\n\n RW_velocity_sub.shutdown();\n position_sub.shutdown();\n // std::cout << Y << std::endl;\n \n Eigen::ColPivHouseholderQR qr_decomp(Y);\n // Eigen::FullPivLU lu_decomp(Y);\n // auto fs = Y.colPivHouseholderQr();\n auto rank = qr_decomp.rank();\n ROS_INFO(\"rank = %ld\", rank);\n if (rank == 8) {\n // std::cout << Y << std::endl;\n auto pinv = pseudoInverse(Y);\n // auto pinv = Y.completeOrthogonalDecomposition().pseudoInverse();\n // std::cout << Y.rows() << \" \" << Y.cols() << \" \" << pinv.rows() << \" \" << pinv.cols() <<'\\n';\n\n auto pi_est = pinv*Hcm;\n std::ofstream file;\n file.open(\"/home/pelekoudas/cepheus_simulator/ls_pi_est.txt\");\n if (file.is_open()) {\n double e = 0.0;\n for (int i = 0; i < 8; ++i) {\n e = (robotInertialParameters(i, 0) - pi_est(i, 0))/robotInertialParameters(i, 0)*100;\n file << \"Robot Parameter \" << i << \": \" << robotInertialParameters(i, 0) << \", LS estimation: \" << pi_est(i, 0) << \", error(%): \"<< e << '\\n'; \n }\n file.close();\n } else {\n std::cout << pi_est << std::endl;\n } \n break;\n }\n\n // break;\n }\n else {\n msg_RW.data += 0.1;\n }\n\n loop_rate.sleep();\n }\n\n\n return 0;\n}\n", "meta": {"hexsha": "003134a67d82b60bfd4c5bcda149a02fb6389824", "size": 8384, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cepheus_control/src/cepheus_controller.cpp", "max_stars_repo_name": "pelekoudasq/cepheus_launcher", "max_stars_repo_head_hexsha": "d51ab9441acac00ab95d00352a4d44a6dad61fc1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-08T20:01:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-21T12:31:43.000Z", "max_issues_repo_path": "src/cepheus_control/src/cepheus_controller.cpp", "max_issues_repo_name": "pelekoudasq/cepheus_simulator", "max_issues_repo_head_hexsha": "d51ab9441acac00ab95d00352a4d44a6dad61fc1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2020-08-19T16:10:03.000Z", "max_issues_repo_issues_event_max_datetime": "2020-12-21T12:33:17.000Z", "max_forks_repo_path": "src/cepheus_control/src/cepheus_controller.cpp", "max_forks_repo_name": "pelekoudasq/cepheus_simulator", "max_forks_repo_head_hexsha": "d51ab9441acac00ab95d00352a4d44a6dad61fc1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-12-16T18:49:03.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-16T18:49:03.000Z", "avg_line_length": 36.2943722944, "max_line_length": 171, "alphanum_fraction": 0.5938692748, "num_tokens": 2516, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7310585903489891, "lm_q1q2_score": 0.6474484924046331}} {"text": "// Copyright Matt Overby 2021.\n// Distributed under the MIT License.\n\n#ifndef MCL_NORMAL_HPP\n#define MCL_NORMAL_HPP 1\n\n#include \n\nnamespace mcl\n{\n\ntemplate \nstatic inline Eigen::Matrix triangle_normal(\n\tconst Eigen::Matrix &a,\n\tconst Eigen::Matrix &b,\n\tconst Eigen::Matrix &c,\n\tbool normalize = true)\n{\n\tEigen::Matrix n = (b-a).cross(c-a);\n\tif (normalize) { n.stableNormalize(); }\n\treturn n;\n}\n\ntemplate \nstatic inline Eigen::Matrix edge_normal(\n\tconst Eigen::Matrix &p0,\n\tconst Eigen::Matrix &p1,\n\tbool normalize = true)\n{\n\tEigen::Matrix n(p1[1]-p0[1], -(p1[0]-p0[0]));\n\tif (normalize) { n.stableNormalize(); }\n\treturn n;\n}\n\n} // ns mcl\n\n#endif\n", "meta": {"hexsha": "f90f9aaa0f2d70bbc9ec6495c4873e2012c583fc", "size": 746, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/MCL/Normal.hpp", "max_stars_repo_name": "mattoverby/mclgeom", "max_stars_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/MCL/Normal.hpp", "max_issues_repo_name": "mattoverby/mclgeom", "max_issues_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-12-26T22:44:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-09T02:54:23.000Z", "max_forks_repo_path": "include/MCL/Normal.hpp", "max_forks_repo_name": "mattoverby/mclgeom", "max_forks_repo_head_hexsha": "d3ecd2a878900f33ba1412b8d82e643895201e51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.6315789474, "max_line_length": 53, "alphanum_fraction": 0.6689008043, "num_tokens": 248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8856314677809303, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.647448476836581}} {"text": "#include \n#include \n#include \n\nusing namespace std;\nint main()\n{\n Eigen::Quaterniond q1(0.35,0.2,0.3,0.1);\n q1=q1.normalized();\n Eigen::Quaterniond p(0,0.1,0.2,0.3);\n cout<<\"p\"<\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"controllers/LQR.hpp\"\n\nnamespace frc3512 {\n\n/**\n * Contains the controller coefficients and logic for an implicit model\n * follower.\n *\n * Implicit model following lets us design a feedback controller that erases the\n * dynamics of our system and makes it behave like some other system. This can\n * be used to make a drivetrain more controllable during teleop driving by\n * making it behave like a slower or more benign drivetrain.\n *\n * For more on the underlying math, read appendix C.3 in\n * https://file.tavsys.net/control/controls-engineering-in-frc.pdf.\n */\ntemplate \nclass ImplicitModelFollower {\npublic:\n /**\n * Constructs a controller with the given coefficients and plant.\n *\n * @param plant The plant being controlled.\n * @param plantRef The plant whose dynamics should be followed.\n * @param Qelems The maximum desired error tolerance for each state.\n * @param Relems The maximum desired control effort for each input.\n * @param dt Discretization timestep.\n */\n template \n ImplicitModelFollower(\n const frc::LinearSystem& plant,\n const frc::LinearSystem& plantRef,\n const wpi::array& Qelems,\n const wpi::array& Relems, units::second_t dt)\n : ImplicitModelFollower(plant.A(), plant.B(),\n plantRef.A(), plantRef.B(),\n Qelems, Relems, dt) {}\n\n /**\n * Constructs a controller with the given coefficients and plant.\n *\n * @param A Continuous system matrix of the plant being controlled.\n * @param B Continuous input matrix of the plant being controlled.\n * @param Aref Continuous system matrix whose dynamics should be followed.\n * @param Bref Continuous input matrix whose dynamics should be followed.\n * @param Qelems The maximum desired error tolerance for each state.\n * @param Relems The maximum desired control effort for each input.\n * @param dt Discretization timestep.\n */\n ImplicitModelFollower(const Eigen::Matrix& A,\n const Eigen::Matrix& B,\n const Eigen::Matrix& Aref,\n const Eigen::Matrix& Bref,\n const wpi::array& Qelems,\n const wpi::array& Relems,\n units::second_t dt) {\n // Discretize real dynamics\n Eigen::Matrix discA;\n Eigen::Matrix discB;\n frc::DiscretizeAB(A, B, dt, &discA, &discB);\n\n // Discretize desired dynamics\n Eigen::Matrix discAref;\n Eigen::Matrix discBref;\n frc::DiscretizeAB(Aref, Bref, dt, &discAref, &discBref);\n\n // Find initial Q and R weights\n Eigen::Matrix Q = frc::MakeCostMatrix(Qelems);\n Eigen::Matrix R = frc::MakeCostMatrix(Relems);\n\n Eigen::Matrix Adiff = discA - discAref;\n\n Eigen::Matrix Qimf =\n Adiff.transpose() * Q * Adiff;\n Eigen::Matrix Rimf =\n discB.transpose() * Q * discB + R;\n Eigen::Matrix Nimf =\n Adiff.transpose() * Q * discB;\n\n // Nudge eigenvalues of Qimf slightly more positive if Q <= 0, since\n // this is usually caused by numerical imprecision\n Eigen::SelfAdjointEigenSolver Qeigen{Qimf};\n if (!std::all_of(Qeigen.eigenvalues().data(),\n Qeigen.eigenvalues().data() + States,\n [](const auto& elem) { return elem >= 0.0; })) {\n Qimf += decltype(Qimf)::Identity() * 1e-10;\n }\n\n m_K = LQR(discA, discB, Qimf, Rimf, Nimf);\n\n // Find u_imf that makes real model match reference model.\n //\n // x_k+1 = Ax_k + Bu_imf\n // z_k+1 = Aref z_k + Bref u_k\n //\n // Let x_k = z_k.\n //\n // x_k+1 = z_k+1\n // Ax_k + Bu_imf = Aref x_k + Bref u_k\n // Bu_imf = Aref x_k - Ax_k + Bref u_k\n // Bu_imf = (Aref - A)x_k + Bref u_k\n // u_imf = B^+ ((Aref - A)x_k + Bref u_k)\n // u_imf = -B^+ (A - Aref)x_k + B^+ Bref u_k\n\n // The first term makes the open-loop poles that of the reference\n // system, and the second term makes the input behave like that of the\n // reference system.\n m_B = discB.householderQr().solve(discBref);\n\n Reset();\n }\n\n /**\n * Returns the controller matrix K.\n */\n const Eigen::Matrix& K() const { return m_K; }\n\n /**\n * Returns an element of the controller matrix K.\n *\n * @param i Row of K.\n * @param j Column of K.\n */\n double K(int i, int j) const { return m_K(i, j); }\n\n /**\n * Returns the control input vector u.\n *\n * @return The control input.\n */\n const Eigen::Matrix& U() const { return m_u; }\n\n /**\n * Returns an element of the control input vector u.\n *\n * @param i Row of u.\n *\n * @return The row of the control input vector.\n */\n double U(int i) const { return m_u(i, 0); }\n\n /**\n * Resets the controller.\n */\n void Reset() { m_u.setZero(); }\n\n /**\n * Returns the next output of the controller.\n *\n * @param x The current state x.\n * @param u The current input for the original model.\n */\n Eigen::Matrix Calculate(\n const Eigen::Matrix& x,\n const Eigen::Matrix& u) {\n m_u = -m_K * x + m_B * u;\n return m_u;\n }\n\nprivate:\n // Computed controller output\n Eigen::Matrix m_u;\n\n // Controller gain\n Eigen::Matrix m_K;\n\n // Input space conversion gain\n Eigen::Matrix m_B;\n};\n\n} // namespace frc3512\n", "meta": {"hexsha": "f643aa85e41da25e5c4d4c7b390d32b0ffad2c5e", "size": 6773, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/main/include/controllers/ImplicitModelFollower.hpp", "max_stars_repo_name": "frc3512/Robot-2020", "max_stars_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10.0, "max_stars_repo_stars_event_min_datetime": "2020-02-07T04:13:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T00:13:39.000Z", "max_issues_repo_path": "src/main/include/controllers/ImplicitModelFollower.hpp", "max_issues_repo_name": "frc3512/Robot-2020", "max_issues_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 82.0, "max_issues_repo_issues_event_min_datetime": "2020-02-12T03:05:15.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-18T02:14:38.000Z", "max_forks_repo_path": "src/main/include/controllers/ImplicitModelFollower.hpp", "max_forks_repo_name": "frc3512/Robot-2020", "max_forks_repo_head_hexsha": "c6811155900ccffba93ea9ba131192dcb9fcb1bd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-02-14T16:24:01.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T09:10:01.000Z", "avg_line_length": 35.835978836, "max_line_length": 80, "alphanum_fraction": 0.6051971062, "num_tokens": 1711, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505299595162, "lm_q2_score": 0.7154239897159439, "lm_q1q2_score": 0.6472086914422801}} {"text": "#include \"lib/header.h\"\n#include \"lib/random.h\"\n\n#include \n\n#include \"glog/logging.h\"\n\nstruct Kalman {\n public:\n Kalman(size_t n_out, size_t n_states) : n_out_(n_out) {\n x_ = arma::colvec(n_states, arma::fill::zeros);\n\n a_ = arma::mat(n_states, n_states, arma::fill::zeros);\n for (size_t i = 0; i < n_states; ++i) {\n for (size_t j = i; j < n_states; ++j) {\n a_(i, j) = 1.0 / std::pow(10.0, j - i);\n }\n }\n\n // LOG(INFO) << \"A:\\n\" << a_;\n\n i_ = arma::eye(n_states, n_states);\n\n h_ = arma::mat(n_out, n_states, arma::fill::zeros);\n for (size_t i = 0; i < n_out; ++i) {\n h_(i, i) = 1.0;\n }\n\n q_ = 10.0 * arma::eye(n_states, n_states) + 0.1 * arma::ones(n_states, n_states);\n r_ = 40.0 * arma::eye(n_out, n_out) + 0.1 * arma::ones(n_out, n_out);\n p_ = arma::zeros(n_states, n_states);\n }\n\n void update(const DoubleVector& z) {\n x_hat_ = a_ * x_;\n p_ = a_ * p_ * a_.t() + q_;\n const arma::colvec y = arma::colvec(z) - h_ * x_hat_;\n const arma::mat s = h_ * p_ * h_.t() + r_;\n k_ = p_ * h_.t() * s.i();\n x_hat_ += k_ * y;\n p_ = (i_ - k_ * h_) * p_;\n x_ = x_hat_;\n // LOG(INFO) << \"Z:\\n\" << z;\n // LOG(INFO) << \"X:\\n\" << x_;\n }\n\n DoubleVector state() const {\n DoubleVector result(n_out_);\n const arma::vec s = h_ * x_;\n for (size_t i = 0; i < n_out_; ++i) {\n result[i] = s(i);\n }\n return result;\n }\n\n private:\n size_t n_out_;\n arma::colvec x_;\n arma::colvec x_hat_;\n arma::mat a_;\n arma::mat h_;\n arma::mat q_;\n arma::mat r_;\n arma::mat k_;\n arma::mat p_;\n arma::mat i_;\n};\n\nint main() {\n Kalman k(1, 3);\n double sum1 = 0;\n double sum2 = 0;\n for (size_t i = 0; i < 100000; ++i) {\n const double value = std::sin(static_cast(i) / 1000.);\n const double noise_value = value + 0.01 * randNorm01();\n k.update({noise_value});\n sum1 += std::abs(noise_value - value);\n sum2 += std::abs(k.state()[0] - value);\n std::cout << (noise_value - value) << \" \" << (k.state()[0] - value) << std::endl;\n }\n std::cout << sum2 / sum1 << std::endl;\n return 0;\n}\n", "meta": {"hexsha": "eacb846c91d6682944d16483d369ccf2ab165ddd", "size": 2331, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "eulerKalman/Kalman.cpp", "max_stars_repo_name": "evilmucedin/project-euler", "max_stars_repo_head_hexsha": "08ed51a5ff0d05f60271d99d35b3e601bcddf85d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2020-03-23T04:31:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-17T09:03:09.000Z", "max_issues_repo_path": "eulerKalman/Kalman.cpp", "max_issues_repo_name": "evilmucedin/project-euler", "max_issues_repo_head_hexsha": "08ed51a5ff0d05f60271d99d35b3e601bcddf85d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "eulerKalman/Kalman.cpp", "max_forks_repo_name": "evilmucedin/project-euler", "max_forks_repo_head_hexsha": "08ed51a5ff0d05f60271d99d35b3e601bcddf85d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-03-28T20:53:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-27T07:03:02.000Z", "avg_line_length": 27.75, "max_line_length": 89, "alphanum_fraction": 0.4916344916, "num_tokens": 777, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9046505351008904, "lm_q2_score": 0.7154239836484143, "lm_q1q2_score": 0.6472086896315487}} {"text": "/*\n * Copyright (c) 2015, The Regents of the University of California (Regents).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following\n * disclaimer in the documentation and/or other materials provided\n * with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * Please contact the author(s) of this library if you have any questions.\n * Authors: Erik Nelson ( eanelson@eecs.berkeley.edu )\n * David Fridovich-Keil ( dfk@eecs.berkeley.edu )\n */\n\n#include \"rotation.h\"\n\n#include \n#include \n#include \n\nnamespace bsfm {\n\n// Convert from Euler angles to a rotation matrix. Phi, theta, and psi define the\n// angles of the intermediate rotations about x (R_x), y (R_y), and z (R_z)\n// respectively. See https://en.wikipedia.org/wiki/Rotation_matrix.\nMatrix3d EulerAnglesToMatrix(double phi, double theta, double psi) {\n double c1 = std::cos(phi);\n double c2 = std::cos(theta);\n double c3 = std::cos(psi);\n double s1 = std::sin(phi);\n double s2 = std::sin(theta);\n double s3 = std::sin(psi);\n\n Matrix3d R;\n R(0, 0) = c2*c3;\n R(0, 1) = c3*s1*s2 - c1*s3;\n R(0, 2) = s1*s3 + c1*c3*s2;\n R(1, 0) = c2*s3;\n R(1, 1) = c1*c3 + s1*s2*s3;\n R(1, 2) = c1*s2*s3 - c3*s1;\n R(2, 0) = -s2;\n R(2, 1) = c2*s1;\n R(2, 2) = c1*c2;\n\n return R;\n}\n\n// Same thing as above, but where phi, theta, and psi are specified as a vector.\nMatrix3d EulerAnglesToMatrix(const Vector3d& euler_angles) {\n return EulerAnglesToMatrix(euler_angles(0), euler_angles(1), euler_angles(2));\n}\n\n// Convert from a rotation matrix to Euler angles.\n// From: http://staff.city.ac.uk/~sbbh653/publications/euler.pdf\n// Note that the solution that is returned is only unique when phi, theta, and\n// psi are all <= 0.5 * PI. If this is not the case, they will still be correct,\n// but may not be unique!\nVector3d MatrixToEulerAngles(const Matrix3d& R) {\n // Make sure R is actually a rotation matrix.\n if (std::abs(R.determinant() - 1) > 1e-4) {\n LOG(WARNING) << \"R does not have a determinant of 1.\";\n return Vector3d::Zero();\n }\n\n double theta = -std::asin(R(2, 0));\n\n if (std::abs(cos(theta)) < 1e-8) {\n LOG(WARNING) << \"Theta is approximately +/- PI/2, which yields a \"\n \"singularity. Cannot decompose matrix into Euler angles.\";\n return Vector3d(theta, 0.0, 0.0);\n }\n\n double phi = std::atan2(R(2, 1), R(2, 2));\n double psi = std::atan2(R(1, 0) / std::cos(theta), R(0, 0) / std::cos(theta));\n\n return Vector3d(phi, theta, psi);\n}\n\n// Get roll angle from a rotation matrix.\n// Just like above, the solution will only be unique if roll < 0.5 * PI.\ndouble Roll(const Matrix3d& R) {\n double theta = -std::asin(R(2, 0));\n if (std::abs(std::cos(theta)) < 1e-8)\n return 0.0;\n return std::atan2(R(2, 1), R(2, 2));\n}\n\n// Get pitch angle from a rotation matrix.\n// This solution is unique.\ndouble Pitch(const Matrix3d& R) {\n return -std::asin(R(2, 0));\n}\n\n// Get yaw angle from a rotation matrix.\n// Just like above, the solution will only be unique if yaw < 0.5 * PI.\ndouble Yaw(const Matrix3d& R) {\n double theta = -std::asin(R(2, 0));\n if (std::abs(std::cos(theta)) < 1e-8)\n return 0.0;\n return std::atan2(R(1, 0) / std::cos(theta), R(0, 0) / std::cos(theta));\n}\n\n// Unroll an angle to be \\in [0, 2*PI)\ndouble Unroll(double angle) {\n angle = fmod(angle, 2.0 * M_PI);\n if (angle < 0)\n angle += 2.0 * M_PI;\n return angle;\n}\n\n// Normalize an angle to be \\in [-PI, PI)\ndouble Normalize(double angle) {\n angle = fmod(angle + M_PI, 2.0 * M_PI);\n if (angle < 0)\n angle += 2.0 * M_PI;\n return angle - M_PI;\n}\n\n// Computes the shortest distance between two angles on S^1.\n// Found by manipulating the first answer on:\n// stackoverflow.com/questions/1878907/the-smallest-difference-between-2-angles\ndouble S1Distance(double from, double to) {\n double d = Unroll(Unroll(to) - Unroll(from));\n if (d > M_PI)\n d -= 2.0*M_PI;\n return Normalize(d);\n}\n\n// Convert from degrees to radians.\ndouble D2R(double angle) {\n return angle * M_PI / 180.0;\n}\n\n// Convert from radians to degrees.\ndouble R2D(double angle) {\n return angle * 180.0 / M_PI;\n}\n\n// An error metric between two rotation matrices on SO3.\ndouble SO3Error(const Matrix3d& R1, const Matrix3d& R2) {\n const Matrix3d R_error = R1.transpose()*R2 - R2.transpose()*R1;\n\n // 'vee' is the inverse of the hat operator, and extracts a vector from a\n // cross-product matrix.\n const Vector3d R_vee(R_error(2,1), R_error(0,2), R_error(1,0));\n return (0.5 * R_vee).norm();\n}\n\n} //\\namespace bsfm\n", "meta": {"hexsha": "c4743d1209439dcbef6f5321ec9913b146e2337f", "size": 5917, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/cpp/geometry/rotation.cpp", "max_stars_repo_name": "jamesdsmith/berkeley_sfm", "max_stars_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 21.0, "max_stars_repo_stars_event_min_datetime": "2016-01-14T13:52:11.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T19:30:33.000Z", "max_issues_repo_path": "src/cpp/geometry/rotation.cpp", "max_issues_repo_name": "jamesdsmith/berkeley_sfm", "max_issues_repo_head_hexsha": "de3ae6b104602c006d939b1f3da8c497b86d39ff", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-10-17T17:01:46.000Z", "max_issues_repo_issues_event_max_datetime": "2015-10-22T20:59:43.000Z", "max_forks_repo_path": "src/cpp/geometry/rotation.cpp", "max_forks_repo_name": "erik-nelson/berkeley_sfm", "max_forks_repo_head_hexsha": "5bf0b45fac176ff7abfca0ff690893c1afc73c51", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2016-01-22T06:23:59.000Z", "max_forks_repo_forks_event_max_datetime": "2018-01-16T03:54:33.000Z", "avg_line_length": 34.2023121387, "max_line_length": 81, "alphanum_fraction": 0.6765252662, "num_tokens": 1744, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835452961425, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6471516719295941}} {"text": "//==================================================================================================\n/*!\n @file\n\n @copyright 2016 NumScale SAS\n\n Distributed under the Boost Software License, Version 1.0.\n (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)\n*/\n//==================================================================================================\n#ifndef BOOST_SIMD_FUNCTION_GAMMALN_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_GAMMALN_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n @ingroup group-euler\n Function object implementing gammaln capabilities\n\n Natural logarithm of the absolute value of the Gamma function\n \\f$\\displaystyle \\log |\\Gamma(x)|\\f$\n\n @par Semantic:\n\n For every parameter of floating type T\n\n @code\n T r = gammaln(x);\n @endcode\n\n is similar to:\n\n @code\n T r = log(abs(gamma(x))));\n @endcode\n\n @par Notes\n\n - The accuracy of the function is not uniformly good for negative entries\n The algorithm used is currently an adapted vesion of the cephes one.\n For better accuracy in the negative entry case one can use the extern\n boost_math gammaln functor but at a loss of speed.\n\n However, as stated in boost math:\n\n \"While the relative errors near the positive roots of lgamma are very low,\n the function has an infinite number of irrational roots for negative arguments:\n very close to these negative roots only a low absolute error can be guaranteed.\"\n\n - The call gammaln(x, sgn) also returns the sign of gamma in the output parameter sgn.\n\n Be aware that POSIX version of lgamma is not thread-safe: each execution of the function\n stores the sign of the gamma function of x in the static external variable signgam.\n\n boost.simd also provides @ref signgam which independantly computes the sign.\n\n @par Decorators\n\n std_ for floating entries provides access to @c std::lgamma\n\n @see gamma, signgam\n\n **/\n Value gammaln(Value const & v0);\n} }\n#endif\n\n#include \n#include \n\n#endif\n", "meta": {"hexsha": "3ec693824d6d019395f580f90f54fd830cb7e549", "size": 2171, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/gammaln.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/function/gammaln.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/gammaln.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-12-12T12:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-08T15:55:25.000Z", "avg_line_length": 28.9466666667, "max_line_length": 100, "alphanum_fraction": 0.6508521419, "num_tokens": 476, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8354835289107307, "lm_q2_score": 0.7745833841649233, "lm_q1q2_score": 0.6471516592377264}} {"text": "#include \n#include \nusing namespace Eigen;\nusing namespace std;\nvoid PolygonToEquations(const MatrixX2d& pts, MatrixX2d& ab, VectorXd& c) {\n // ax + by + c <= 0\n // assume polygon is convex\n\n Vector2d p0 = pts.row(0);\n\n for (int i=0; i < pts.rows(); ++i) {\n int i1 = (i+1) % pts.rows();\n double x0 = pts(i,0),\n y0 = pts(i,1),\n x1 = pts(i1,0),\n y1 = pts(i1,1);\n ab(i,0) = -(y1 - y0);\n ab(i,1) = x1 - x0;\n ab.row(i).normalize();\n c(i) = -ab.row(i).dot(pts.row(i));\n }\n\n}\n\nint main() {\n MatrixX2d m(4,2), ab(4,2);\n VectorXd c(4);\n m << 0,0,\n 0,1,\n 1,1,\n 1,0;\n PolygonToEquations(m, ab, c);\n cout << \"ab: \" << ab << endl;\n cout << \"c: \" << c.transpose() << endl;\n}\n", "meta": {"hexsha": "176d0b83e605d5d5c3ec9862f4f5338b3efe44a5", "size": 748, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/sandbox/polygon_expt.cpp", "max_stars_repo_name": "HARPLab/trajopt", "max_stars_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 250.0, "max_stars_repo_stars_event_min_datetime": "2015-01-13T04:38:59.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-09T15:52:54.000Z", "max_issues_repo_path": "src/sandbox/polygon_expt.cpp", "max_issues_repo_name": "HARPLab/trajopt", "max_issues_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": 31.0, "max_issues_repo_issues_event_min_datetime": "2015-08-19T13:14:56.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-22T08:08:26.000Z", "max_forks_repo_path": "src/sandbox/polygon_expt.cpp", "max_forks_repo_name": "HARPLab/trajopt", "max_forks_repo_head_hexsha": "40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 118.0, "max_forks_repo_forks_event_min_datetime": "2015-01-08T16:06:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T11:44:00.000Z", "avg_line_length": 20.7777777778, "max_line_length": 75, "alphanum_fraction": 0.5093582888, "num_tokens": 287, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297861178929, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6471156546473502}} {"text": "#include \"gaussianprocessregressor.h\"\n#include \n#include \n#include \n#include \n#include \"nloptutility.h\"\n#include \"utility.h\"\n\n//#define VERBOSE\n//#define NOISELESS\n\nusing Eigen::MatrixXd;\nusing Eigen::VectorXd;\n\nnamespace\n{\n\nconst bool useLogNormalPrior = true;\nconst double a_prior_mu = std::log(0.500);\nconst double a_prior_sigma_squared = 0.10;\n#ifdef NOISELESS\nconst double b_fixed = 1e-06;\n#else\nconst double b_prior_mu = std::log(0.001);\nconst double b_prior_sigma_squared = 0.10;\n#endif\nconst double r_prior_mu = std::log(0.500);\nconst double r_prior_sigma_squared = 0.10;\n\ndouble calc_grad_a_prior(const double a)\n{\n return (a_prior_mu - a_prior_sigma_squared - std::log(a)) / (a_prior_sigma_squared * a);\n}\n\n#ifndef NOISELESS\ndouble calc_grad_b_prior(const double b)\n{\n return (b_prior_mu - b_prior_sigma_squared - std::log(b)) / (b_prior_sigma_squared * b);\n}\n#endif\n\ndouble calc_grad_r_i_prior(const Eigen::VectorXd &r, const int index)\n{\n return (r_prior_mu - r_prior_sigma_squared - std::log(r(index))) / (r_prior_sigma_squared * r(index));\n}\n\ndouble calc_a_prior(const double a)\n{\n return std::log(Utility::log_normal(a, a_prior_mu, a_prior_sigma_squared));\n}\n\n#ifndef NOISELESS\ndouble calc_b_prior(const double b)\n{\n return std::log(Utility::log_normal(b, b_prior_mu, b_prior_sigma_squared));\n}\n#endif\n\ndouble calc_r_i_prior(const Eigen::VectorXd &r, const int index)\n{\n return std::log(Utility::log_normal(r(index), r_prior_mu, r_prior_sigma_squared));\n}\n\ndouble calc_grad_a(const MatrixXd& X, const MatrixXd& C_inv, const VectorXd& y, const double a, const double b, const VectorXd& r)\n{\n const MatrixXd C_grad_a = Regressor::calc_C_grad_a(X, a, b, r);\n const double term1 = + 0.5 * y.transpose() * C_inv * C_grad_a * C_inv * y;\n const double term2 = - 0.5 * (C_inv * C_grad_a).trace();\n return term1 + term2 + (useLogNormalPrior ? calc_grad_a_prior(a) : 0.0);\n}\n\n#ifndef NOISELESS\ndouble calc_grad_b(const MatrixXd& X, const MatrixXd& C_inv, const VectorXd& y, const double a, const double b, const VectorXd& r)\n{\n const MatrixXd C_grad_b = Regressor::calc_C_grad_b(X, a, b, r);\n const double term1 = + 0.5 * y.transpose() * C_inv * C_grad_b * C_inv * y;\n const double term2 = - 0.5 * (C_inv * C_grad_b).trace();\n return term1 + term2 + (useLogNormalPrior ? calc_grad_b_prior(b) : 0.0);\n}\n#endif\n\ndouble calc_grad_r_i(const MatrixXd& X, const MatrixXd& C_inv, const VectorXd& y, const double a, const double b, const VectorXd& r, const int index)\n{\n const MatrixXd C_grad_r_i = Regressor::calc_C_grad_r_i(X, a, b, r, index);\n const double term1 = + 0.5 * y.transpose() * C_inv * C_grad_r_i * C_inv * y;\n const double term2 = - 0.5 * (C_inv * C_grad_r_i).trace();\n return term1 + term2 + (useLogNormalPrior ? calc_grad_r_i_prior(r, index) : 0.0);\n}\n\nVectorXd calc_grad(const MatrixXd& X, const MatrixXd& C_inv, const VectorXd& y, const double a, const double b, const VectorXd& r)\n{\n const unsigned D = X.rows();\n\n VectorXd grad(D + 2);\n grad(0) = calc_grad_a(X, C_inv, y, a, b, r);\n#ifdef NOISELESS\n grad(1) = 0.0;\n#else\n grad(1) = calc_grad_b(X, C_inv, y, a, b, r);\n#endif\n\n for (unsigned i = 2; i < D + 2; ++ i)\n {\n const unsigned index = i - 2;\n grad(i) = calc_grad_r_i(X, C_inv, y, a, b, r, index);\n }\n\n return grad;\n}\n\nstruct Data\n{\n Data(const MatrixXd& X, const VectorXd& y) : X(X), y(y)\n {\n }\n\n const MatrixXd X;\n const VectorXd y;\n};\n\n// For counting the number of function evaluations\nunsigned count;\n\n// Log likelihood that will be maximized\ndouble objective(const std::vector &x, std::vector& grad, void* data)\n{\n // For counting the number of function evaluations\n ++ count;\n\n const MatrixXd& X = static_cast(data)->X;\n const VectorXd& y = static_cast(data)->y;\n\n const unsigned N = X.cols();\n\n const double a = x[0];\n#ifdef NOISELESS\n const double b = b_fixed;\n#else\n const double b = x[1];\n#endif\n const VectorXd r = [&x]() { std::vector _x = x; return Eigen::Map(&_x[2], _x.size() - 2); }();\n\n const MatrixXd C = Regressor::calc_C(X, a, b, r);\n const MatrixXd C_inv = C.inverse();\n\n // When the algorithm is gradient-based, compute the gradient vector\n if (grad.size() == x.size())\n {\n const VectorXd g = calc_grad(X, C_inv, y, a, b, r);\n for (unsigned i = 0; i < g.rows(); ++ i) grad[i] = g(i);\n }\n\n const double term1 = - 0.5 * y.transpose() * C_inv * y;\n const double term2 = - 0.5 * std::log(C.determinant());\n const double term3 = - 0.5 * N * std::log(2.0 * M_PI);\n\n // Computing the regularization terms from a prior assumptions\n const double a_prior = calc_a_prior(a);\n#ifdef NOISELESS\n const double b_prior = 1.0;\n#else\n const double b_prior = calc_b_prior(b);\n#endif\n const double r_prior = [&r]()\n {\n double sum = 0.0;\n for (unsigned i = 0; i < r.rows(); ++ i) sum += calc_r_i_prior(r, i);\n return sum;\n }();\n const double regularization = useLogNormalPrior ? (a_prior + b_prior + r_prior) : 0.0;\n\n return term1 + term2 + term3 + regularization;\n}\n\n}\n\nGaussianProcessRegressor::GaussianProcessRegressor(const MatrixXd& X, const VectorXd& y)\n{\n this->X = X;\n this->y = y;\n\n compute_MAP();\n\n C = calc_C(X, a, b, r);\n C_inv = C.inverse();\n}\n\nGaussianProcessRegressor::GaussianProcessRegressor(const Eigen::MatrixXd &X, const Eigen::VectorXd &y, double a, double b, const Eigen::VectorXd &r)\n{\n this->X = X;\n this->y = y;\n this->a = a;\n this->b = b;\n this->r = r;\n\n C = calc_C(X, a, b, r);\n C_inv = C.inverse();\n}\n\ndouble GaussianProcessRegressor::estimate_y(const VectorXd &x) const\n{\n const VectorXd k = calc_k(x, X, a, b, r);\n return k.transpose() * C_inv * y;\n}\n\ndouble GaussianProcessRegressor::estimate_s(const VectorXd &x) const\n{\n const VectorXd k = calc_k(x, X, a, b, r);\n return std::sqrt(a + b - k.transpose() * C_inv * k);\n}\n\nvoid GaussianProcessRegressor::compute_MAP()\n{\n const unsigned D = X.rows();\n\n Data data(X, y); // Constant during optimization\n\n#ifdef VERBOSE\n const auto t1 = std::chrono::system_clock::now();\n count = 0;\n#endif\n\n const VectorXd x_ini = VectorXd::Constant(D + 2, 1e+00);\n const VectorXd upper = VectorXd::Constant(D + 2, 5e+01);\n const VectorXd lower = VectorXd::Constant(D + 2, 1e-08);\n\n const VectorXd x_glo = nloptUtility::compute(x_ini, upper, lower, objective, &data, nlopt::GN_DIRECT, 300);\n\n#ifdef VERBOSE\n const auto t2 = std::chrono::system_clock::now();\n const unsigned g_count = count;\n count = 0;\n#endif\n\n const VectorXd x_loc = nloptUtility::compute(x_glo, upper, lower, objective, &data, nlopt::LD_TNEWTON, 1000);\n\n a = x_loc(0);\n b = x_loc(1);\n r = x_loc.block(2, 0, D, 1);\n\n#ifdef NOISELESS\n b = b_fixed;\n#endif\n\n#ifdef VERBOSE\n const auto t3 = std::chrono::system_clock::now();\n const unsigned l_count = count;\n\n std::cout << \"global optimization: \" << std::chrono::duration_cast(t2 - t1).count() << \" ms, \" << g_count << \" evaluations, obj = \" << objective(x_star_global, x_ini, &data) << std::endl;\n std::cout << \"local optimization: \" << std::chrono::duration_cast(t3 - t2).count() << \" ms, \" << l_count << \" evaluations, obj = \" << objective(x_star_local, x_ini, &data) << std::endl;\n std::cout << \"a = \" << a << \", b = \" << b << \", r = \" << r.transpose() << std::endl;\n#endif\n}\n", "meta": {"hexsha": "cf36a7a7870483b83181a8c85971c2aa51064228", "size": 7636, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main/gaussianprocessregressor.cpp", "max_stars_repo_name": "takuma-ya/sequential_bayesian_optimization", "max_stars_repo_head_hexsha": "cf0cc61adb4a66cbf3eb8e5f22e441d5af539f8f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main/gaussianprocessregressor.cpp", "max_issues_repo_name": "takuma-ya/sequential_bayesian_optimization", "max_issues_repo_head_hexsha": "cf0cc61adb4a66cbf3eb8e5f22e441d5af539f8f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main/gaussianprocessregressor.cpp", "max_forks_repo_name": "takuma-ya/sequential_bayesian_optimization", "max_forks_repo_head_hexsha": "cf0cc61adb4a66cbf3eb8e5f22e441d5af539f8f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.062992126, "max_line_length": 218, "alphanum_fraction": 0.6474594028, "num_tokens": 2286, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297754396141, "lm_q2_score": 0.7185943925708561, "lm_q1q2_score": 0.6471156469739989}} {"text": "#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"biggles/detail/random.hpp\"\n#include \"biggles/sampling/metropolis_hastings.hpp\"\n\nextern \"C\" {\n#include \n}\n\ntypedef boost::tuples::tuple point;\n\ninline float rosenbrock(const point& p)\n{\n float x, y;\n boost::tuples::tie(x,y) = p;\n return (1.f-x)*(1.f-x) + 100.f*(y-x*x)*(y-x*x);\n}\n\n// a cooked-up PDF which has a maximum where the Rosenbrock function has a minimum.\ninline float rosenbrock_log_pdf(const point& p)\n{\n return -rosenbrock(p);\n}\n\ntypedef boost::tuples::tuple proposal_result_t;\n\ninline proposal_result_t propose_gaussian(const point& p)\n{\n static boost::normal_distribution norm(0.f, 0.2f);\n static boost::variate_generator > variate(\n biggles::detail::random_generator, norm);\n\n point new_p(p.get<0>() + variate(), p.get<1>() + variate());\n\n return proposal_result_t(new_p, 0.f);\n}\n\nusing namespace biggles::sampling::metropolis_hastings;\n\nint main(int argc, char** argv)\n{\n biggles::detail::seed_prng(0xdeadbeef);\n\n bool verbose = (argc > 1) && (0 == strcmp(argv[1], \"-v\"));\n\n plan_tests(4);\n\n typedef std::pointer_to_unary_function pdf_t;\n typedef std::pointer_to_unary_function proposal_func_t;\n\n // MH sampler for Rosenbrock function. An example of using a function pointer directly.\n sampler s(std::ptr_fun(rosenbrock_log_pdf), std::ptr_fun(propose_gaussian));\n\n point optimum(s.last_sample());\n float optimum_log_density(s.current_sample_log_density());\n\n for(int i=0; i<4096; ++i)\n {\n s.draw();\n\n if(s.current_sample_log_density() > optimum_log_density)\n {\n optimum_log_density = s.current_sample_log_density();\n optimum = s.last_sample();\n }\n\n if(verbose)\n {\n std::stringstream ss;\n ss << \"sample: \" << s.last_sample();\n diag(\"%s\", ss.str().c_str());\n }\n }\n\n {\n std::stringstream ss;\n ss << \"optimum: \" << optimum << \", log-pdf: \" << optimum_log_density\n << \", alpha: \" << s.acceptance_rate() << \", rosenbrock: \" << rosenbrock(optimum);\n diag(\"%s\", ss.str().c_str());\n }\n\n diag(\"acceptance rate = %.2f%%\", s.acceptance_rate()*100.f);\n //ok(fabs(s.acceptance_rate() - 0.25f) < 0.2f, \"acceptance rate within 0.2 of 0.25\");\n ok(fabs(optimum.get<0>() - 1.f) < 0.1f, \"x-co-ordinate within 10%% of optimum\");\n ok(fabs(optimum.get<1>() - 1.f) < 0.1f, \"y-co-ordinate within 10%% of optimum\");\n\n // the same thing using the optimise function\n point optimum2 = optimise(std::ptr_fun(rosenbrock_log_pdf), std::ptr_fun(propose_gaussian));\n\n {\n std::stringstream ss;\n ss << \"optimum via optimise(): \" << optimum2 << \", log-pdf: \" << rosenbrock_log_pdf(optimum2)\n << \", rosenbrock: \" << rosenbrock(optimum2);\n diag(\"%s\", ss.str().c_str());\n }\n\n ok(fabs(optimum2.get<0>() - 1.f) < 0.1f, \"x-co-ordinate within 10%% of optimum\");\n ok(fabs(optimum2.get<1>() - 1.f) < 0.1f, \"y-co-ordinate within 10%% of optimum\");\n\n return exit_status();\n}\n", "meta": {"hexsha": "20dbd818d1945b4645aff8ab1076a54d0a6e35f3", "size": 3398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "test/metropolis_hastings.cpp", "max_stars_repo_name": "fbi-octopus/biggles", "max_stars_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-11-15T14:01:59.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-15T14:01:59.000Z", "max_issues_repo_path": "test/metropolis_hastings.cpp", "max_issues_repo_name": "fbi-octopus/biggles", "max_issues_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/metropolis_hastings.cpp", "max_forks_repo_name": "fbi-octopus/biggles", "max_forks_repo_head_hexsha": "2dac4f1748ab87242951239caf274f302be1143a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.8909090909, "max_line_length": 104, "alphanum_fraction": 0.6362566215, "num_tokens": 958, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127678225575, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.6470902843445976}} {"text": "/*\n * Copyright (c) 2013-2019 Masahide Kashiwagi (kashi@waseda.jp)\n */\n\n#ifndef ODE_MAFFINE_HPP\n#define ODE_MAFFINE_HPP\n\n//\n// ODE using Affine and Mean Value Form\n//\n// (2018/11/28) ode-maffine0 and ode-maffine are integrated by\n// porting maffine's algorithm to ode-autodif.hpp .\n//\n// use -DODE_AUTODIF_NEW=0 to come back the behaviour of maffine0.\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\n\nnamespace kv {\n\nnamespace ub = boost::numeric::ublas;\n\n\ntemplate \nint\node_maffine(F f, ub::vector< affine >& init, const interval& start, interval& end, ode_param p = ode_param() , ub::matrix< interval >* mat = NULL, ub::vector< psa< interval > >* result_psa = NULL)\n{\n\tint n = init.size();\n\tint i, j;\n\n\tub::vector< interval > c;\n\tub::vector< interval > fc;\n\tub::vector< interval > I;\n\tub::vector< autodif< interval > > Iad;\n\n\tub::vector< interval > result_i;\n\tub::matrix< interval > result_d;\n\n\tub::vector< affine > result;\n\n\n\tint maxnum_save;\n\n\tint r;\n\n\tint ret_val;\n\tinterval end2 = end;\n\n\tI.resize(n);\n\tc.resize(n);\n\tfor (i=0; i >::init(I);\n\t// NOTICE: below must be autodif version of ode\n\tr = ode(f, Iad, start, end2, p, result_psa);\n\tif (r == 0) return 0;\n\tret_val = r;\n\tautodif< interval >::split(Iad, result_i, result_d);\n\n\tfc = c;\n\t// Step size should be same as above ode call.\n\t// Because above ode call is with autodif and interval input and\n\t// below ode call is without autodif and point input,\n\t// below ode call is supposed to be easier to succeed than above.\n\t// If below ode call fails, force success by increasing order.\n\tode_param p2 = p;\n\tp2.set_autostep(false);\n\twhile (true) {\n\t\tr = ode(f, fc, start, end2, p2);\n\t\tif (r != 0) break;\n\t\tp2.order++;\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \"ode_maffine: increase order: \" << p.order << \"\\n\";\n\t\t}\n\t}\n\n\tif (p.ep_reduce == 0) {\n\t\tmaxnum_save = affine::maxnum();\n\t}\n\n\tresult = fc + prod(result_d, init - c);\n\n\tif (p.ep_reduce == 0) {\n\t\tepsilon_reduce2(result, maxnum_save);\n\t} else {\n\t\tepsilon_reduce(result, p.ep_reduce, p.ep_reduce_limit);\n\t}\n\n\tinit = result;\n\tif (ret_val == 1) end = end2;\n\tif (mat != NULL) *mat = result_d;\n\n\treturn ret_val;\n}\n\ntemplate \nint\nodelong_maffine(\n\tF f,\n\tub::vector< affine >& init,\n\tconst interval& start,\n\tinterval& end,\n\tode_param p = ode_param(),\n\tconst ode_callback& callback = ode_callback(),\n\tub::matrix< interval >* mat = NULL\n) {\n\n\tint s = init.size();\n\tub::vector< affine > x, x1;\n\tinterval t, t1;\n\tint ret_ode;\n\tub::matrix< interval > M, M_tmp;\n\tub::matrix< interval >* M_p;\n\tint ret_val = 0;\n\tbool ret_callback;\n\n\tub::vector< psa< interval > > result_tmp;\n\n\n\tif (mat == NULL) {\n\t\tM_p = NULL;\n\t} else {\n\t\tM_p = &M_tmp;\n\t\tM = ub::identity_matrix< interval >(s);\n\t}\n\n\tx = init;\n\tt = start;\n\tp.set_autostep(true);\n\n\twhile (true) {\n\t\tx1 = x;\n\t\tt1 = end;\n\n\t\tret_ode = ode_maffine(f, x1, t, t1, p, M_p, &result_tmp);\n\t\tif (ret_ode == 0) {\n\t\t\tif (ret_val == 1) {\n\t\t\t\tinit = x1;\n\t\t\t\tif (mat != NULL) *mat = M;\n\t\t\t\tend = t;\n\t\t\t}\n\t\t\treturn ret_val;\n\t\t}\n\t\tret_val = 1;\n\t\tif (mat != NULL) M = prod(M_tmp, M);\n\t\t#if 0\n\t\tif (result_psa != NULL) {\n\t\t\t(*result_psa).push_back(boost::make_tuple(t, t1, result_tmp));\n\t\t}\n\t\t#endif\n\t\tif (p.verbose == 1) {\n\t\t\tstd::cout << \"t: \" << t1 << \"\\n\";\n\t\t\tstd::cout << to_interval(x1) << \"\\n\";\n\t\t}\n\n\t\tret_callback = callback(t, t1, to_interval(x), to_interval(x1), result_tmp);\n\n\t\tif (ret_callback == false) {\n\t\t\tinit = x1;\n\t\t\tif (mat != NULL) *mat = M;\n\t\t\tend = t1;\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (ret_ode == 2) {\n\t\t\tinit = x1;\n\t\t\tif (mat != NULL) *mat = M;\n\t\t\treturn 2;\n\t\t}\n\n\t\tt = t1;\n\t\tx = x1;\n\t}\n}\n\ntemplate \nint\nodelong_maffine(\n\tF f,\n\tub::vector< interval >& init,\n\tconst interval& start,\n\tinterval& end,\n\tode_param p = ode_param(),\n\tconst ode_callback& callback = ode_callback()\n) {\n\tint s = init.size();\n\tint i;\n\tub::vector< affine > x;\n\tint maxnum_save;\n\tint r;\n\n\tmaxnum_save = affine::maxnum();\n\taffine::maxnum() = 0;\n\n\tx = init;\n\n\tr = odelong_maffine(f, x, start, end, p, callback);\n\n\taffine::maxnum() = maxnum_save;\n\n\tif (r == 0) return 0;\n\n\tfor (i=0; i\nint\nodelong_maffine(\n\tF f,\n\tub::vector< autodif< interval > >& init,\n\tconst interval& start,\n\tinterval& end,\n\tode_param p = ode_param(),\n\tconst ode_callback& callback = ode_callback()\n) {\n\tint s = init.size();\n\tint i, j;\n\tub::vector< interval > xi;\n\tub::vector< affine > x;\n\tub::matrix< interval > M, M_tmp;\n\tint maxnum_save;\n\tint r;\n\n\tautodif< interval >::split(init, xi, M);\n\tint s2 = M.size2();\n\n\tmaxnum_save = affine::maxnum();\n\taffine::maxnum() = 0;\n\n\tx = xi;\n\n\tr = odelong_maffine(f, x, start, end, p, callback, &M_tmp);\n\n\taffine::maxnum() = maxnum_save;\n\n\tif (r == 0) return 0;\n\n\tM = prod(M_tmp, M);\n\n\tfor (i=0; i\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include // -I /home/thenriod/Desktop/cpp_libs/Eigen_lib\n#include \"my_stopwatch.h\"\n\nusing namespace std;\nusing namespace Eigen;\n\n\n\n/*==============================================================================\n======= GLOBAL CONSTANTS ===============================================\n==============================================================================*/\n#define DEBUG 1\n\nconst int STD_STR_LEN = 100;\n\nconst char MATCH = 'X';\nconst char NO_MATCH = '-';\n\nconst string TRAINING_RESULTS_DIRECTORY = \"/training_results/\";\n\nenum Status\n{\n NO_ERRORS = 0,\n ERROR\n};\n\nenum Mode\n{\n TRAINING_MODE = 0,\n TESTING_MODE = 1,\n INVALID = 666\n};\n\n\n/*==============================================================================\n\n======= USER DEFINED TYPES =============================================\n==============================================================================*/\n\n/**\n@struct\n\nDescription\n\n@var\n*/\ntypedef struct\n{\n char** training_image_names;\n int num_training_images;\n char** training_eigenweight_names;\n int num_training_eigenweights;\n char** testing_image_names;\n int num_testing_images;\n int pixels_per_image;\n int width_in_pixels;\n int height_in_pixels;\n} JobInfo;\n\n\ntypedef struct\n{\n char tested_image_name[ STD_STR_LEN ];\n int test_image_index;\n char matched_image_name[ STD_STR_LEN ];\n int matched_image_index;\n double distance_between_images;\n char is_match_by_test;\n char is_actual_match;\n} MatchResult;\n\n/*==============================================================================\n======= GLOBAL VARIABLES ===============================================\n==============================================================================*/\n\n\n/*==============================================================================\n======= FUNCTION PROTOTYPES ============================================\n==============================================================================*/\n/**\nFunctionName\n\nA short description\n\n@param\n\n@return\n\n@pre\n-# \n\n@post\n-# \n\n@detail @bAlgorithm\n-# \n\n@exception\n\n@code\n@endcode\n*/\nint processCommandLineArguments( const int argc, char** argv,\n JobInfo& info );\n\nint trainingMode( JobInfo& info );\n\nint findSampleImageSize( int& image_width, int& image_height,\n const char* file_name );\n\nint allocateArrays( double**& face_data_matrix, double*& mean_face, const JobInfo& info );\n\nint loadTrainingData( Matrix& face_data, const JobInfo& info );\n\nint readPgmToVector( VectorXd& image_vector, const char* file_name, const JobInfo& info );\n\nint trainMeanFace( VectorXd& mean_face, const Matrix& face_data, const JobInfo& info );\n\nint writeVectorToFile( const char* file_name, const VectorXd& data_vector );\n\nint centerFaceData( Matrix& centered_data, Matrix& face_data, const VectorXd& mean_face, const JobInfo& info );\n\nint findFaceCovariance( Matrix& face_covariance,\n const Matrix& centered_data,\n const JobInfo& info );\n\nint findEigenValuesVectors( VectorXd& eigenvalues, MatrixXd& eigenvectors,\n const MatrixXd& A_matrix, const JobInfo& info );\n\nbool compareEigenvalIndexPairs( const pair< double, int >& one,\n const pair< double, int >& other );\n\ndouble getVectorMagnitude( const VectorXd the_vector );\n\nint writePgmImage( const string& file_name, const VectorXd& image_data,\n int image_width, int image_height, int image_shades );\n\nVectorXd scaleImageToPgm( const VectorXd& image_data, const JobInfo& info );\n\nint storeEigenData( const VectorXd& eigenvalues, const MatrixXd& eigenvectors );\n\nint promptForNumEigens( const VectorXd& eigenvalues );\n\nint storeEigenProjections( const int eigens_to_keep, const MatrixXd& centered_data, const MatrixXd& face_eigenvectors, const JobInfo& info );\n\nint writeEigenweightFile( const char* file_name, const VectorXd& eigen_weights );\n\nint testingMode( JobInfo& info );\n\nint loadTrainingOutcomes( VectorXd& mean_face, VectorXd& eigenvalues, MatrixXd& eigenvectors, MatrixXd& training_eigenweights, const JobInfo& info );\n\nint readDataVectorFromTxt( VectorXd& data_vector, const char* file_name );\n\nint readMatrixFromTxt( MatrixXd& data_matrix, const char* file_name );\n\nint loadTestingData( Matrix& face_data, const JobInfo& info );\n\nint centerTestData( MatrixXd& centered_data, MatrixXd& face_data, const VectorXd& mean_face, const JobInfo& info );\n\nint projectDataInEigenspace( MatrixXd& eigenweights, const MatrixXd& data, const MatrixXd& eigenvectors );\n\nVectorXd projectImageInEigenspace( const VectorXd& centered_image, const MatrixXd& eigenvectors );\n\ndouble promptForThreshold();\n\nint matchAllImages( vector< MatchResult >& matching_results,\n const MatrixXd& training_eigenweights,\n const MatrixXd& testing_eigenweights,\n const MatrixXd& eigenvalues,\n const double threshold,\n const int num_eigens_to_use,\n const JobInfo& info );\n\nint matchImage( MatchResult& result, const VectorXd& test_weights, const MatrixXd& training_weights );\n\nint matchImage( MatchResult& result, const VectorXd& test_weights,\n const MatrixXd& training_weights, const VectorXd& eigenvalues,\n const int num_eigens_to_use, const double threshold,\n const JobInfo& info );\n\ndouble computeMahalanobisDistance( const VectorXd& test_weights,\n const VectorXd& training_weights,\n const VectorXd& eigenvalues,\n const int num_eigens_to_use );\n\nint outputDataSummary( vector< MatchResult >& results, double threshold, int num_eigens_to_use, bool explicit_summary );\n\nchar* stripFilePath( char* file_name );\n\n/*==============================================================================\n======= MAIN FUNCTION ==================================================\n==============================================================================*/\n\n/**\nFunctionName\n\nA short description\n\n@param\n\n@return\n\n@pre\n-# \n\n@post\n-# \n\n@detail @bAlgorithm\n-# \n\n@exception\n\n@code\n@endcode\n*/\nint main( int argc, char** argv )\n{\n // variables\n int program_status = NO_ERRORS;\n int program_mode = TRAINING_MODE;\n JobInfo info;\n\n // process the command line arguments\n program_mode = processCommandLineArguments( argc, argv, info );\n\ninfo.pixels_per_image = 2880; // 48 x 60 for hi-res samples\n\n // case: the program is running in training mode\n if( program_mode == TRAINING_MODE )\n {\n // indicate that the program is running in training mode\n cout << char( 0x0C )\n << \" =====================\" << endl\n << \" | TRAINING MODE |\" << endl\n << \" =====================\" << endl << endl;\n\n // run program in training mode\n trainingMode( info );\n }\n // case: the program is running in \"testing\" mode\n else if( program_mode == TESTING_MODE )\n {\n // indicate that the program is running in training mode\n cout << char( 0x0C )\n << \" ====================\" << endl\n << \" | TESTING MODE |\" << endl\n << \" ====================\" << endl << endl;\n\n testingMode( info );\n } \n // case: bad command line arguments were used\n else\n {\n puts( \"Bad command line arguments result in program termination.\\n\" );\n }\n\n // return a program operation status signal\n return program_status;\n}\n\n\n/*==============================================================================\n======= FUNCTION IMPLEMENTATIONS =======================================\n==============================================================================*/\nint processCommandLineArguments( const int argc, char** argv,\n JobInfo& info )\n{\n // variables\n int program_mode = INVALID;\n\n // case: a large enough number of command line arguments were given\n if( argc >= 3 )\n {\n // collect the numerical value of the first command line argument\n program_mode = atoi( argv[1] );\n\n // case: the given mode is not a valid one\n if( !( program_mode == TRAINING_MODE ||\n program_mode == TESTING_MODE ) )\n {\n // set the mode to indicate an invalid mode\n program_mode = INVALID;\n }\n\n if( program_mode == TRAINING_MODE )\n {\n // set up the job information\n info.num_training_images = argc - 2;\n info.training_image_names = argv + 2;\n }\n else if( program_mode == TESTING_MODE )\n {\n // set up the job information\n info.training_image_names = argv + 2;\n info.num_training_images = 0;\n while( strstr( info.training_image_names[ info.num_training_images ], \".pgm\" ) != NULL )\n {\n info.num_training_images++;\n }\n\n info.training_eigenweight_names = info.training_image_names + info.num_training_images;\n info.num_training_eigenweights = 0;\n while( strstr( info.training_eigenweight_names[ info.num_training_eigenweights ], \".txt\" ) != NULL )\n {\n info.num_training_eigenweights++;\n }\n\n info.testing_image_names = info.training_eigenweight_names + info.num_training_eigenweights;\n info.num_testing_images = 0;\n while( ( info.num_testing_images < 1196 ) &&\n ( strstr( info.testing_image_names[ info.num_testing_images ], \".pgm\" ) != NULL ) )\n {\n info.num_testing_images++;\n }\n }\n }\n // case: too few arguments were used\n else\n {\n // give a stern message\n cout << \"Something's wrong there guy... You need more arguments.\"\n << endl << endl;\n }\n\n // return the mode the program will be running in\n return program_mode;\n}\n\n\nint trainingMode( JobInfo& info )\n{\n // variables\n int training_success = NO_ERRORS;\n\n VectorXd mean_face;\n VectorXd face_eigenvalues;\n Matrix< double, Dynamic, Dynamic > face_eigenvectors;\n Matrix< double, Dynamic, Dynamic > face_data;\n Matrix< double, Dynamic, Dynamic > centered_data; // A matrix\n Matrix< double, Dynamic, Dynamic > face_covariance;\n Matrix< double, Dynamic, Dynamic > eigen_faces;\n pair< VectorXd, MatrixXd > eigen_values_vectors;\n\n int eigens_to_keep = 1;\n\n info.pixels_per_image = findSampleImageSize( info.width_in_pixels,\n info.height_in_pixels,\n info.training_image_names[0] );\n\n puts( \"Loading data...\\n\" );\n loadTrainingData( face_data, info );\n\n puts( \"Training mean...\\n\" );\n trainMeanFace( mean_face, face_data, info );\n\n puts( \"\\\"Centering\\\" faces...\\n\" );\n centerFaceData( centered_data, face_data, mean_face, info );\n\n/* puts( \"Training covariance matrix...\\n\" );\n findFaceCovariance( face_covariance, centered_data, info );\n */\n\n // compute the Eigen values/vectors\n puts( \"Finding Eigenvalues/Eigenvectors...\\n\" );\n findEigenValuesVectors( face_eigenvalues, face_eigenvectors,\n centered_data, info );\n\n // create data/coefficients file\n puts( \"Storing the found eigen-data...\\n\" );\n storeEigenData( face_eigenvalues, face_eigenvectors );\n\n // prompt user for the amount of information to keep\n eigens_to_keep = promptForNumEigens( face_eigenvalues );\n\n // create the reduced dimensionality eigenfaces, store them to a file\n puts( \"Storing the training faces projected into eigenspace...\\n\" );\n storeEigenProjections( eigens_to_keep, centered_data, face_eigenvectors, info );\n\n\n // return a signal as to whether or not training was successful\n return training_success;\n}\n\n\nint findSampleImageSize( int& image_width, int& image_height,\n const char* file_name )\n{\n ifstream fin;\n string magic_number;\n int width = 0;\n int height = 0;\n\n fin.clear();\n fin.open( file_name );\n fin >> magic_number >> image_width >> image_height;\n fin.close();\n\n return ( image_width * image_height );\n}\n\n\nint loadTrainingData( Matrix& face_data, const JobInfo& info )\n{\n // variables\n int image_num = 0;\n VectorXd temp;\n\n face_data.resize( info.pixels_per_image, info.num_training_images );\n\n // for every image\n for( image_num = 0; image_num < info.num_training_images; image_num++ )\n {\n readPgmToVector( temp, info.training_image_names[image_num], info );\n face_data.col( image_num ) = temp;\n }\n\n\n#if 0\nwritePgmImage( info.training_image_names[20], face_data.col( 20 ), info.width_in_pixels,\n info.height_in_pixels, 255 );\n#endif\n\n}\n\n\nint readPgmToVector( VectorXd& image_vector, const char* file_name, const JobInfo& info )\n{\n int read_success = NO_ERRORS;\n int pixel_num = 0;\n ifstream fin;\n string magic_number;\n int width;\n int height;\n int granularity;\n unsigned char pixel_byte;\n\n // open the file\n fin.clear();\n fin.open( file_name );\n\n // size the vector appropriately\n image_vector.resize( info.pixels_per_image );\n\n // eat the header\n fin >> magic_number >> width >> height >> granularity;\n fin.get(); // and an endline char\n\n // read in the data to a column vector\n for( pixel_num = 0; pixel_num < info.pixels_per_image; pixel_num++ )\n {\n // read in the byte, convert to float\n pixel_byte = fin.get();\n image_vector( pixel_num ) = (double) pixel_byte;\n }\n\n // close the file\n fin.close();\n\n return read_success;\n}\n\n\nint trainMeanFace( VectorXd& mean_face, const Matrix& face_data, const JobInfo& info )\n{\n int mean_success = NO_ERRORS;\n int image_num = 0, pixel_num = 0;\n\n mean_face.resize( info.pixels_per_image );\n\n for( pixel_num = 0; pixel_num < info.pixels_per_image; pixel_num++ )\n {\n for( image_num = 0, mean_face( pixel_num ) = 0;\n image_num < info.num_training_images;\n image_num++ )\n {\n mean_face( pixel_num ) += face_data( pixel_num, image_num );\n }\n\n mean_face( pixel_num ) /= info.num_training_images;\n }\n\n\n#if 1\nwritePgmImage( \"mean_training_face.pgm\", mean_face, info.width_in_pixels,\n info.height_in_pixels, 255 );\n\nwriteVectorToFile( \"mean_training_face_data.txt\", mean_face );\n#endif\n\n return mean_success;\n}\n\n\nint writeVectorToFile( const char* file_name, const VectorXd& data_vector )\n{\n int write_success = NO_ERRORS;\n ofstream fout;\n int i = 0;\n\n fout.clear();\n fout.open( file_name );\n fout << data_vector.size() << endl;\n fout<< data_vector << endl;\n\n return write_success;\n}\n\n\nint centerFaceData( Matrix& centered_data, Matrix& face_data, const VectorXd& mean_face, const JobInfo& info )\n{\n int centering_success = NO_ERRORS;\n int image_number = 0, pixel_number = 0;\n\n centered_data.resize( face_data.rows(), face_data.cols() );\n\n for( image_number = 0; image_number < info.num_training_images; image_number++ )\n {\n for( pixel_number = 0; pixel_number < info.pixels_per_image; pixel_number++ )\n {\n centered_data( pixel_number, image_number ) = face_data( pixel_number, image_number ) - mean_face( pixel_number );\n }\n }\n\n\n#if 0\nwritePgmImage( \"test_center.pgm\", centered_data.col( 5 ), info.width_in_pixels,\n info.height_in_pixels, 255 );\n#endif\n\n return centering_success;\n}\n\n\nint findFaceCovariance( Matrix& face_covariance,\n const Matrix& centered_data,\n const JobInfo& info )\n{\n int covariance_success = NO_ERRORS;\n double inverse_num_training_images = 1.0 / info.num_training_images;\n\n face_covariance.resize( info.pixels_per_image, info.pixels_per_image );\n\n face_covariance = inverse_num_training_images *\n ( centered_data * centered_data.transpose().eval() );\n\n return covariance_success;\n}\n\n\nbool compareEigenvalIndexPairs( const pair< double, int >& one,\n const pair< double, int >& other )\n{\n // this makes for a high to low sort when used with std::sort\n return ( one.first > other.first );\n}\n\n\ndouble getVectorMagnitude( const VectorXd the_vector )\n{\n double magnitude = 0.0;\n int i = 0;\n\n for( i = 0; i < the_vector.size(); i++ )\n {\n magnitude += ( the_vector( i ) * the_vector( i ) );\n }\n\n return sqrt( magnitude );\n}\n\n\nint writePgmImage( const string& file_name, const VectorXd& image_data, int image_width, int image_height, int image_shades )\n{\n int write_success = NO_ERRORS;\n ofstream fout;\n int pixel_num = 0;\n int row_sizer = 0;\n int num_pixels = image_width * image_height;\n\n fout.clear();\n fout.open( file_name.c_str() );\n\n\n // write header with PGM \"magic number\" for binary type\n fout << \"P5\" << '\\n' << image_width << ' '\n << image_height << '\\n' << image_shades << '\\n';\n\n // write the data\n for( pixel_num = 0; pixel_num < num_pixels; pixel_num++ )\n {\n fout << (unsigned char) ((unsigned int)image_data( pixel_num ) % (image_shades + 1));\n }\n\n#if 0\n // write header with PGM \"magic number\" for ASCII type\n fout << \"P2\" << ' ' << image_width << ' '\n << image_height << ' ' << image_shades << '\\n';\n\n // write the data\n for( pixel_num = 0; pixel_num < num_pixels; pixel_num++ )\n {\n fout << (unsigned int) image_data( pixel_num ) % image_shades;\n row_sizer++;\n if( row_sizer < image_width )\n {\n fout << ' ';\n }\n else\n {\n row_sizer = 0;\n fout << '\\n';\n }\n }\n#endif\n fout.close();\n\n return write_success;\n}\n\n\nint findEigenValuesVectors( VectorXd& eigenvalues, MatrixXd& eigenvectors, const MatrixXd& A_matrix, const JobInfo& info )\n{\n EigenSolver eigen_solver;\n Matrix At_A_matrix; // A^t * A matrix\n Matrix interim_eigenvectors;\n vector< pair< double, int> > eigen_indices;\n pair< double, int > temp;\n int i = 0;\n char buffer[100];\n\n // compute the A^t * A matrix to save on computations vs A * A^t\n At_A_matrix = A_matrix.transpose().eval() * A_matrix;\n\n // compute the eigen-stuff of the matrix\n eigen_solver.compute( At_A_matrix );\n\n // identify the strictly real eigen values and vectors\n for( i = 0; i < eigen_solver.eigenvalues().size(); i++ )\n {\n if( ( eigen_solver.eigenvalues().imag()( i ) == 0.0 ) )\n {\n temp.first = eigen_solver.eigenvalues().real()( i );\n temp.second = i;\n eigen_indices.push_back( temp );\n }\n }\n\n // sort the eigen stuff in descending order by eigen value\n sort( eigen_indices.begin(), eigen_indices.end(),\n compareEigenvalIndexPairs );\n\n // store the eigen-stuff in usable objects\n eigenvalues.resize( eigen_indices.size() );\n interim_eigenvectors.resize( A_matrix.cols(), eigen_indices.size() );\n eigenvectors.resize( A_matrix.rows(), eigen_indices.size() );\n for( i = 0; i < eigen_indices.size(); i++ )\n {\n eigenvalues( i ) = eigen_indices[i].first;\n interim_eigenvectors.col( i ) = eigen_solver.eigenvectors().col( eigen_indices[i].second ).real();\n }\n\n // get from Av to u for actual eigenvectors\n for( i = 0; i < eigenvectors.cols(); i++ )\n {\n // get the u vector\n eigenvectors.col( i ) = (A_matrix * interim_eigenvectors.col( i ));\n\n // make it a unit u vector\n eigenvectors.col( i ) /= getVectorMagnitude( eigenvectors.col( i ) );\n }\n\n for( i = 0; i < eigenvalues.size(); i++ )\n {\n sprintf( buffer, \"eigenfaces/eigenface_%d.pgm\", i );\n\n writePgmImage( buffer, scaleImageToPgm( eigenvectors.col( i ), info ), info.width_in_pixels,\n info.height_in_pixels, 255 );\n }\n\n return 0;\n}\n\n\nVectorXd scaleImageToPgm( const VectorXd& image_data, const JobInfo& info )\n{\n VectorXd scaled_vector;\n double minimum_value = image_data( 0 );\n double maximum_value = image_data( 0 );\n int pixel_num = 0;\n\n scaled_vector.resize( image_data.size() );\n scaled_vector = image_data;\n\n // find the minimum and maximum values for scaling\n for( pixel_num = 0; pixel_num < image_data.size(); pixel_num++ )\n {\n if( image_data( pixel_num ) < minimum_value )\n {\n minimum_value = image_data( pixel_num );\n }\n\n if( image_data( pixel_num ) > maximum_value )\n {\n maximum_value = image_data( pixel_num );\n }\n }\n\n // scale the pixel values properly\n for( pixel_num = 0; pixel_num < image_data.size(); pixel_num++ )\n {\n scaled_vector( pixel_num ) = image_data( pixel_num ) - minimum_value;\n }\n maximum_value -= minimum_value;\n scaled_vector *= ( 255.0 / (maximum_value ));//- minimum_value ));\n\n return scaled_vector;\n}\n\n\nint storeEigenData( const VectorXd& eigenvalues, const MatrixXd& eigenvectors )\n{\n int storage_success = NO_ERRORS;\n ofstream fout;\n int i = 0;\n int j = 0;\n\n fout.clear();\n fout.open( \"EIGENVALUES.txt\" );\n fout << eigenvalues.size() << endl;\n for( i = 0; i < eigenvalues.size(); i++ )\n {\n fout << eigenvalues( i ) << endl;\n }\n fout.close();\n\n fout.clear();\n fout.open( \"EIGENVECTORS.txt\" );\n fout << eigenvectors.rows() << ' ' << eigenvectors.cols() << endl;\n\n fout << eigenvectors << endl;\n\n fout.close();\n\n return storage_success;\n}\n\n\nint promptForNumEigens( const VectorXd& eigenvalues )\n{\n int num_eigens_to_keep = 0;\n double eigenvalue_sum = 0;\n double kept_eigenvalue_sum = 0;\n char response;\n bool keep_prompting = true;\n int i = 0;\n\n for( i = 0; i < eigenvalues.size(); i++ )\n {\n eigenvalue_sum += eigenvalues( i );\n }\n\n while( keep_prompting )\n {\n cout << \"How many eigen values (faces) should be kept? (\"\n << eigenvalues.size() << \" available): \";\n cin >> num_eigens_to_keep;\n // use 16 for ~80%\n\n for( kept_eigenvalue_sum = 0, i = 0; i < num_eigens_to_keep; i++ )\n {\n kept_eigenvalue_sum += eigenvalues( i );\n }\n\n cout << ( kept_eigenvalue_sum * 100 / eigenvalue_sum )\n << \"% of the information will be kept. Is this acceptable? (y/n): \";\n cin >> response;\n\n if( response == 'y' )\n {\n keep_prompting = false;\n }\n }\n\n return num_eigens_to_keep;\n}\n\n\nint storeEigenProjections( const int eigens_to_keep, const MatrixXd& centered_data, const MatrixXd& eigenvectors, const JobInfo& info )\n{\n int eigenprojection_success = NO_ERRORS;\n VectorXd projected_face;\n MatrixXd eigen_weights;\n char buffer[100];\n ofstream fout;\n int i = 0;\n int j = 0;\n\n // initial setup and resizing\n eigen_weights.resize( eigens_to_keep, centered_data.cols() );\n projected_face.resize( info.pixels_per_image );\n\n for( j = 0; j < centered_data.cols(); j++ )\n {\n // eigen_weights.col( j ) = projectImageInEigenspace( centered_data.col( j ), eigenvectors );\n\n for( i = 0; i < eigens_to_keep; i++ )\n {\n eigen_weights( i, j ) = eigenvectors.col( i ).transpose().eval() * centered_data.col( j );\n }\n\n }\n\n for( j = 0; j < centered_data.cols(); j++ )\n {\n projected_face *= 0;\n\n for( i = 0; i < eigens_to_keep; i++ )\n {\n projected_face += eigen_weights( i, j ) * eigenvectors.col( i );\n }\n\n sprintf( buffer, \"training_eigenprojections/projected_face_%d_coefficients.txt\", j );\n writeEigenweightFile( buffer, eigen_weights.col( j ) );\n\n sprintf( buffer, \"training_eigenprojections/projected_face_%d.pgm\", j );\n writePgmImage( buffer, scaleImageToPgm( projected_face, info ), info.width_in_pixels,\n info.height_in_pixels, 255 );\n }\n\n return eigenprojection_success;\n}\n\n\nint writeEigenweightFile( const char* file_name, const VectorXd& eigen_weights )\n{\n int write_success = NO_ERRORS;\n ofstream fout;\n\n fout.clear();\n fout.open( file_name );\n\n fout << eigen_weights.size() << endl;\n fout << eigen_weights << endl;\n \n fout.close();\n\n return write_success;\n}\n\n\nint testingMode( JobInfo& info )\n{\n int testing_success = NO_ERRORS;\n VectorXd mean_face;\n VectorXd eigenvalues;\n MatrixXd eigenvectors;\n MatrixXd testing_faces;\n MatrixXd centered_test_faces;\n MatrixXd training_eigenweights;\n MatrixXd testing_eigenweights;\n int num_eigens_to_use = 0;\n vector< MatchResult > matching_results;\n double threshold = 1.0;\n ofstream fout;\n int i = 0;\n int true_positive = 0, false_positive = 0, total_positive = 0, total_negative = 0;\n\n info.pixels_per_image = findSampleImageSize( info.width_in_pixels,\n info.height_in_pixels,\n info.training_image_names[0] );\n\n puts( \"Loading training outcomes...\\n\" );\n loadTrainingOutcomes( mean_face, eigenvalues, eigenvectors, training_eigenweights, info );\n\n puts( \"Projecting inputs onto eigenspace...\\n\" );\n loadTestingData( testing_faces, info );\n centerTestData( centered_test_faces, testing_faces, mean_face, info );\n projectDataInEigenspace( testing_eigenweights, centered_test_faces, eigenvectors );\n\n puts( \"Matching inputs to training images...\\n\" );\n fout.clear()\n fout.open( \"ROC.txt\" );\n fout << \"True positives, total positives, false negatives, total negatives\" << endl;\n for( threshold = 0.0001, true_positive = 0, false_positive = 0, total_positive = 0, total_negative = 0;\n threshold < 0.004; threshold += 0.0005 )\n {\n num_eigens_to_use = 114; //promptForNumEigens( eigenvalues );\n // threshold = 1.5; // promptForThreshold();\n matchAllImages( matching_results, training_eigenweights, testing_eigenweights, eigenvalues, threshold, num_eigens_to_use, info );\n\n puts( \"Outputting matching data...\\n\" );\n outputDataSummary( matching_results, threshold, num_eigens_to_use, false );\n\n for( i = 0; i < matching_results.size(); i++ );\n \n\n\n }\n\n return testing_success;\n}\n\n\nint loadTrainingOutcomes( VectorXd& mean_face, VectorXd& eigenvalues, MatrixXd& eigenvectors, MatrixXd& training_eigenweights, const JobInfo& info )\n{\n int load_success = NO_ERRORS;\n int i = 0;\n VectorXd temp;\n\n readDataVectorFromTxt( mean_face, \"mean_training_face_data.txt\" );\n readDataVectorFromTxt( eigenvalues, \"EIGENVALUES.txt\" );\n readMatrixFromTxt( eigenvectors, \"EIGENVECTORS.txt\" );\n\ncout << eigenvalues.size() << endl;\n\n training_eigenweights.resize( 1204, eigenvectors.cols() );\n for( i = 0; i < info.num_training_eigenweights; i++ )\n {\n readDataVectorFromTxt( temp, info.training_eigenweight_names[i] );\n training_eigenweights.col( i ) = temp;\n }\n\n return load_success;\n}\n\n\nint readDataVectorFromTxt( VectorXd& data_vector, const char* file_name )\n{\n int read_success = NO_ERRORS;\n ifstream fin;\n int size;\n double value;\n int i;\n\n fin.clear();\n fin.open( file_name );\n\n if( fin.good() )\n {\n fin >> size;\n data_vector.resize( size );\n\n for( i = 0; i < size; i++ )\n {\n fin >> value;\n data_vector( i ) = value;\n }\n }\n\n return read_success;\n}\n\n\nint readMatrixFromTxt( MatrixXd& data_matrix, const char* file_name )\n{\n int read_success = NO_ERRORS;\n ifstream fin;\n int rows, cols;\n double value;\n int i = 0, j = 0;\n\n fin.clear();\n fin.open( file_name );\n\n if( fin.good() )\n {\n fin >> rows >> cols;\n data_matrix.resize( rows, cols );\n\n for( i = 0; i < rows; i++ )\n {\n for( j = 0; j < cols; j++ )\n {\n fin >> value;\n data_matrix( i, j ) = value;\n }\n }\n }\n\n return read_success;\n}\n\n\nint loadTestingData( Matrix& face_data, const JobInfo& info )\n{\n // variables\n int image_num = 0;\n VectorXd temp;\n\n face_data.resize( info.pixels_per_image, info.num_testing_images );\n\n // for every image\n for( image_num = 0; image_num < info.num_testing_images; image_num++ )\n {\n readPgmToVector( temp, info.testing_image_names[image_num], info );\n face_data.col( image_num ) = temp;\n }\n\n\n#if 1\nwritePgmImage( info.training_image_names[20], face_data.col( 20 ), info.width_in_pixels,\n info.height_in_pixels, 255 );\n#endif\n}\n\n\nint centerTestData( MatrixXd& centered_data, MatrixXd& face_data, const VectorXd& mean_face, const JobInfo& info )\n{\n int centering_success = NO_ERRORS;\n int image_number = 0, pixel_number = 0;\n\n centered_data.resize( face_data.rows(), face_data.cols() );\n\n for( image_number = 0; image_number < info.num_testing_images; image_number++ )\n {\n for( pixel_number = 0; pixel_number < info.pixels_per_image; pixel_number++ )\n {\n centered_data( pixel_number, image_number ) = face_data( pixel_number, image_number ) - mean_face( pixel_number );\n }\n }\n\n\n#if 0\n\nwritePgmImage( \"test_center.pgm\", centered_data.col( 5 ), info.width_in_pixels,\n info.height_in_pixels, 255 );\n#endif\n\n return centering_success;\n}\n\nint projectDataInEigenspace( MatrixXd& eigenweights, const MatrixXd& data, const MatrixXd& eigenvectors )\n{\n int eigenprojection_success = NO_ERRORS;\n int j = 0;\n\n // initial setup and resizing\n eigenweights.resize( eigenvectors.cols(), data.cols() );\n\n for( j = 0; j < data.cols(); j++ ) // for each image\n {\n eigenweights.col( j ) = projectImageInEigenspace( data.col( j ), eigenvectors );\n\n/*\n for( i = 0; i < eigenvectors.cols(); i++ ) // for each feature/weight\n {\n eigenweights( i, j ) = eigenvectors.col( i ).transpose().eval() * data.col( j );\n }\n*/\n }\n\n return eigenprojection_success;\n}\n\n\nVectorXd projectImageInEigenspace( const VectorXd& centered_image, const MatrixXd& eigenvectors )\n{\n VectorXd weight_vector;\n int i = 0;\n\n weight_vector.resize( eigenvectors.cols() );\n\n for( i = 0; i < eigenvectors.cols(); i++ ) // for every eigenvector\n {\n weight_vector( i ) = eigenvectors.col( i ).transpose().eval() * centered_image;\n }\n\n return weight_vector;\n}\n\n\ndouble promptForThreshold()\n{\n double threshold;\n\n cout << \"Enter the threshold value to be used: \";\n cin >> threshold;\n\n return threshold; \n}\n\n\nint matchAllImages( vector< MatchResult >& matching_results,\n const MatrixXd& training_eigenweights,\n const MatrixXd& testing_eigenweights,\n const MatrixXd& eigenvalues,\n const double threshold,\n const int num_eigens_to_use,\n const JobInfo& info )\n{\n int matching_success;\n int i = 0;\n int j = 0;\n double temp_distance = 0;\n double distance = 0;\n MatchResult temp;\n\n for( i = 0; i < testing_eigenweights.cols(); i++ )\n {\n strcpy( temp.tested_image_name, stripFilePath( info.testing_image_names[i] ) );\n\n matchImage( temp, testing_eigenweights.col( i ), training_eigenweights, eigenvalues, num_eigens_to_use, threshold, info );\n\n matching_results.push_back( temp );\n }\n\n return matching_success;\n}\n\n\nint matchImage( MatchResult& result, const VectorXd& test_weights,\n const MatrixXd& training_weights, const VectorXd& eigenvalues,\n const int num_eigens_to_use, const double threshold,\n const JobInfo& info )\n{\n int match_function_success = NO_ERRORS;\n int i = 0;\n double temp_distance = 2E64;\n int CMC_counter = 0;\n\n // check against all other sets of weights\n for( i = 0, result.distance_between_images = 2E64; i < training_weights.cols(); i++ )\n {\n // find the distance between the image and a training one\n temp_distance = computeMahalanobisDistance( test_weights, training_weights.col( i ), eigenvalues, num_eigens_to_use );\n\n // case: the distance is better than what was thought to be the previous best\n if( temp_distance < result.distance_between_images )\n {\n // update the index of the match and the new, lower distance\n result.distance_between_images = temp_distance;\n result.matched_image_index = i;\n }\n\n if( atoi(result.tested_image_name) == atoi( stripFilePath( info.training_image_names[ i ] ) )\n && temp_distance < threshold )\n {\n CMC_counter++;\n }\n\n }\n\ncout << \"CMC\" << CMC_counter << endl;\n\n // indicate which image the test one is closest to\n strcpy( result.matched_image_name,\n stripFilePath( info.training_image_names[ result.matched_image_index ] ) );\n\n // case: the best distance could be considered a match\n if( result.distance_between_images < threshold )\n {\n // indicate that there was a match, get matching image's name\n result.is_match_by_test = MATCH;\n }\n // case: the distance does not indicate a match\n else\n {\n result.is_match_by_test = NO_MATCH;\n }\n\n // determine if the images are an actual match\n // NOTE: I expect the atoi to read just the first segment of the image name, up to the first underscore\n if( atoi( result.tested_image_name ) == atoi( result.matched_image_name ) )\n {\n result.is_actual_match = MATCH;\n\ncout << result.tested_image_name << \" \" << result.matched_image_name << \" \" << result.is_actual_match << ' ' << MATCH << endl;\n\n }\n else\n {\n result.is_actual_match = NO_MATCH;\n }\n\n return match_function_success;\n}\n\n\ndouble computeMahalanobisDistance( const VectorXd& test_weights,\n const VectorXd& training_weights,\n const VectorXd& eigenvalues,\n const int num_eigens_to_use )\n{\n double mahalanobis_distance = 0;\n double euclidean_component;\n int i = 0;\n\n for( i = 0; i < num_eigens_to_use; i++ )\n {\n euclidean_component = ( test_weights( i ) - training_weights( i ) );\n euclidean_component *= euclidean_component;\n mahalanobis_distance += euclidean_component / eigenvalues( i );\n }\n\n return mahalanobis_distance;\n}\n\n\nint outputDataSummary( vector< MatchResult >& results, double threshold, int num_eigens_to_use, bool explicit_summary )\n{\n ofstream fout;\n int i = 0;\n\n\n if( explicit_summary )\n {\n fout.clear();\n fout.open( \"RESULTS.txt\" );\n\n fout << \"Test Image Name,\"\n \"Matched Image Name,\"\n \"Distance Between Images,\"\n \"Is Match By Test,\"\n \"Is Actually A Match,\"\n << endl; \n\n for( i = 0; i < results.size(); i++ )\n {\n fout << results[i].tested_image_name << \", \"\n << results[i].matched_image_name << \", \"\n << results[i].distance_between_images << \", \"\n << results[i].is_match_by_test << \", \"\n << results[i].is_actual_match << endl;\n }\n }\n}\n\n\nchar* stripFilePath( char* file_name )\n{\n char* stripped_string = file_name;\n char* temp;\n\n temp = strstr( stripped_string, \"/\" );\n while( temp != NULL )\n {\n stripped_string = temp + 1;\n temp = strstr( stripped_string, \"/\" );\n }\n\n return stripped_string;\n}\n\n\n\n", "meta": {"hexsha": "0e3ce66c9949a757448b1fcae5227d858c81dc24", "size": 37015, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CS479/Project_3/driver_project_3 (2).cpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "CS479/Project_3/driver_project_3 (2).cpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "CS479/Project_3/driver_project_3 (2).cpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 28.940578577, "max_line_length": 163, "alphanum_fraction": 0.6019451574, "num_tokens": 8630, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8539127455162773, "lm_q2_score": 0.7577943658046609, "lm_q1q2_score": 0.647090267441024}} {"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#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n /*!\n\n @ingroup group-constant\n\n GeneratesEuler constant.\n\n\n @par Header \n\n @par Semantic:\n The Euler constant can be defined as \\f$\\displaystyle \\lim_{n \\rightarrow \\infty} \\left(\\sum_1^n \\frac1n -\\log n\\right)\\f$\n\n @code\n T r = Euler();\n @endcode\n\n is similar to:\n\n @code\n r = T(0.577215664901532860606512090082402431042159335939923598805767234884867726777664670936947063291746749);\n @endcode\n\n\n**/\n template T Euler();\n\n namespace functional\n {\n /*!\n @ingroup group-callable-constant\n\n\n GeneratesEuler constant.\n\n Generate the constant euler.\n\n @return The Euler constant for the proper type\n **/\n Value Euler();\n }\n} }\n#endif\n\n#include \n#include \n\n#endif\n", "meta": {"hexsha": "818a3efae8bccd684dc88d1b51ac07c554f78cef", "size": 1401, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/simd/constant/euler.hpp", "max_stars_repo_name": "TobiasLudwig/boost.simd", "max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/simd/constant/euler.hpp", "max_issues_repo_name": "TobiasLudwig/boost.simd", "max_issues_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/simd/constant/euler.hpp", "max_forks_repo_name": "TobiasLudwig/boost.simd", "max_forks_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-02-16T09:58:18.000Z", "max_forks_repo_forks_event_max_datetime": "2020-02-10T14:22:43.000Z", "avg_line_length": 21.890625, "max_line_length": 126, "alphanum_fraction": 0.6002855103, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8267117855317473, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6470363038258053}} {"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2016 Sebastian Schlenkrich\n\n*/\n\n\n\n#ifndef quantlib_templateauxilliaries_choleskyfactorisation_hpp\n#define quantlib_templateauxilliaries_choleskyfactorisation_hpp\n\n//#include \n//#include \n\n#include \n#include \n\n\nnamespace TemplateAuxilliaries {\n\n // This method is unsafe! Memory allocation need to be ensured by user\n // A(i,j) (and L) is stored row-wise as A[i*n+j]\n // L(i,j) is lower triangular matrix with L L^T = A\n template \n inline void cholesky(std::vector< Type >& A, std::vector< Type >& L, size_t n) {\n for (size_t i = 0; i < n; ++i) {\n for (size_t j = 0; j < (i+1); ++j) {\n Type s = 0;\n for (size_t k = 0; k < j; ++k) s += L[i * n + k] * L[j * n + k];\n if (i==j) {\n if (A[i * n + i] < s) throw std::exception();\n L[i * n + j] = sqrt(A[i * n + i] - s);\n }\n else L[i * n + j] = (1.0 / L[j * n + j] * (A[i * n + j] - s));\n }\n } \n }\n\n template \n std::vector< std::vector< Type > > cholesky(const std::vector< std::vector< Type > >& A) {\n std::vector arrayA(A.size()*A.size());\n std::vector arrayL(A.size()*A.size());\n for (size_t i = 0; i < A.size(); ++i) {\n if (A.size()!=A[i].size()) throw std::exception();\n for (size_t j = 0; j < A[i].size(); ++j) arrayA[i*A[i].size() + j] = A[i][j];\n }\n cholesky(arrayA, arrayL, A.size());\n std::vector< std::vector< Type > > L(A.size(), std::vector< Type >(A.size(), 0.0));\n for (size_t i = 0; i < L.size(); ++i) {\n for (size_t j = 0; j <= i; ++j) L[i][j] = arrayL[i*L[i].size() + j];\n }\n return L;\n }\n\n\n // alternative implementation of Cholesky decomposition\n template\n void performCholesky(std::vector< std::vector >& matrix, size_t dimIn, bool flexible) {\n size_t dim = dimIn;\n for (size_t i = 0; i < dim; i++) {\n for (size_t j = i; j < dim; j++) {\n if (abs(matrix[i][j] - matrix[j][i])>QL_EPSILON)\n QL_FAIL(std::string(\"A symmetrix matrix is necessary to apply Cholesky Decomposition\"));\n }\n }\n\n //Perform Decomposition as described in script of Trottenberg (S. 47):\n //Because script delivers Upper right matrix, we interchange indizes in order to end up with lower left matrix.\n\n //First step:\n matrix[0][0] = sqrt(matrix[0][0]);\n if (abs(matrix[0][0]) < QL_EPSILON && !flexible)\n QL_FAIL(\"No positive definite Correlation Matrix because rank is not full.\");\n for (size_t i = 1; i < dim; i++) {\n matrix[i][0] = abs(matrix[0][0]) < QL_EPSILON ? 0.0 : matrix[i][0] / matrix[0][0];\n }\n\n //Now iterate:\n for (size_t i = 1; i < dim; i++) {\n for (size_t k = 0; k < i; k++) {\n matrix[i][i] = matrix[i][i] - matrix[i][k] * matrix[i][k];\n }\n matrix[i][i] = sqrt(matrix[i][i]);\n if (abs(matrix[i][i]) < QL_EPSILON && !flexible)\n QL_FAIL(std::string(\"No positive definite Correlation Matrix because rank is not full.\"));\n if (matrix[i][i] != matrix[i][i] && !flexible) {\n QL_FAIL(std::string(\"No positive definite Correlation Matrix as diagonal square entry is negative.\"));\n }\n matrix[i][i] = (matrix[i][i] != matrix[i][i]) ? 0.0 : matrix[i][i];\n for (size_t j = 0; j < dim; j++) {\n if (j >= i + 1) {\n for (size_t k = 0; k < i; k++) {\n matrix[j][i] = matrix[j][i] - matrix[i][k] * matrix[j][k];\n }\n matrix[j][i] = (abs(matrix[i][i]) < QL_EPSILON || matrix[i][i] != matrix[i][i]) ? 0.0 : matrix[j][i] / matrix[i][i];\n }\n else if (j\n#include \n\nint main()\n{\nusing Eigen::Quaterniond;\nusing Eigen::Vector3d;\nEigen::Quaterniond q(2, 0, 1, -3); \n\n std::cout << \"This quaternion consists of a scalar \" << q.w() << \" and a vector \" << std::endl << q.vec() << std::endl;\n\n\n q.normalize();\n\n std::cout << \"To represent rotation, we need to normalize it such that its length is \" << q.norm() << std::endl;\n\n\n Eigen::Vector3d v(1, 2, -1);\n\n Eigen::Quaterniond p;\n\n p.w() = 0;\n\n p.vec() = v;\n\n Eigen::Quaterniond rotatedP = q * p * q.inverse(); \n\n Eigen::Vector3d rotatedV = rotatedP.vec();\n\n std::cout << \"We can now use it to rotate a vector \" << std::endl << v << \" to \" << std::endl << rotatedV << std::endl;\n\n\n Eigen::Matrix3d R = q.toRotationMatrix(); // convert a quaternion to a 3x3 rotation matrix\n\n std::cout << \"Compare with the result using an rotation matrix \" << std::endl << R * v << std::endl;\n\n \n\n Eigen::Quaterniond a = Eigen::Quaterniond::Identity();\n\n Eigen::Quaterniond b = Eigen::Quaterniond::Identity();\n\n Eigen::Quaterniond c; // Adding two quaternion as two 4x1 vectors is not supported by the EIgen API. That is, c = a + b is not allowed. We have to do this in a hard way\n\n c.w() = a.w() + b.w();\n\n c.x() = a.x() + b.x();\n\n c.y() = a.y() + b.y();\n\n c.z() = a.z() + b.z();\n}\n", "meta": {"hexsha": "b6f83c0bd6836b6b06f1090deaa651a3f85eb4f5", "size": 1308, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "quaternionExample.cpp", "max_stars_repo_name": "nearlab/rover_visual_od", "max_stars_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "quaternionExample.cpp", "max_issues_repo_name": "nearlab/rover_visual_od", "max_issues_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "quaternionExample.cpp", "max_forks_repo_name": "nearlab/rover_visual_od", "max_forks_repo_head_hexsha": "5b945e0ba9694e53bf0533bcf7ba065fd57d4198", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.679245283, "max_line_length": 170, "alphanum_fraction": 0.6039755352, "num_tokens": 401, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.888758793492457, "lm_q2_score": 0.7279754489059774, "lm_q1q2_score": 0.6469945816618062}} {"text": "#include \n#include \n#include \n\nusing namespace std;\nusing namespace arma;\n\nconst double pi =3.141592653589793238462;\nint n,k; // nrow(X),ncol(X)\nmat z,X,y,XXi,Xt;\nconst double a=1;\nconst double b=1;\nconst int B=pow(10,5);\nconst double s2 = 10;\n\ndouble ll(mat be, double sig2) {\n mat c(1,k), out(k,1);\n\n c = y-X*be;\n out = (c.t()*c / sig2 + n*log(sig2))/-2;\n \n return as_scalar(out);\n}\n\ndouble lpb(mat be) {\n return as_scalar(-be.t()*XXi*be/(2*s2));\n}\n\ndouble lps(double sig2) {\n return (a-1) * log(sig2) - sig2/b;\n}\n\nmat mvrnorm(mat M, mat S) {\n int n = M.n_rows;\n mat e = randn(n);\n return M + chol(S).t()*e;\n}\n\nint main(int argc, char** argv) {\n mat mle;\n\n //posteriors:\n mat bb; \n mat ss;\n\n // candidate sigma:\n mat csb;\n const double css = 1;\n\n //candidate values:\n mat candb;\n double cands;\n \n //acceptance rates:\n int accb = 0;\n int accs = 0;\n\n //metropolis ratio:\n double q;\n\n z.load(\"../data/dat.txt\");\n n = z.n_rows;\n k = z.n_cols-1;\n\n y = z.col(0);\n X = z.cols(1,k); // columns 2 to k+1 of z\n Xt = X.t();\n XXi = (Xt*X).i();\n csb = 4*XXi;\n mle = XXi * Xt * y;\n \n bb.set_size(B,k);\n ss.set_size(B,1);\n bb.zeros();\n ss.ones();\n\n //current vals:\n mat bc = bb.row(0);\n double sc = 1.0;\n\n cout << \"Starting Metropolis:\" <log(randu())) {\n bc = candb;\n bb.row(i) = bc.t();\n accb++;\n }\n\n //Update sigma2:\n cands = randn()*sqrt(css)+sc;\n if (cands>0){\n q = ll(bc,cands)+lps(cands) -ll(bc,sc)-lps(sc);\n if (q>log(randu())) {\n sc = cands;\n accs++;\n }\n }\n \n cout << \"\\r\" << i*100/B <<\"%\";\n }\n clock_t t2 = clock();\n double elapsed = double(t2-t1) / CLOCKS_PER_SEC;\n cout << \"Elapsed Time: \" <\n\n#include \n\nnamespace coconut {\nnamespace pulp {\nnamespace math {\n\nconst float PI = static_cast(3.14159264f);\n\nclass Angle :\n\tboost::less_than_comparable>>>\n{\npublic:\n\n\tstatic const Angle RIGHT;\n\n\tstatic const Angle HALF_FULL;\n\n\tstatic const Angle FULL;\n\n\tconstexpr float radians() const noexcept {\n\t\treturn radians_;\n\t}\n\n\tconstexpr float degrees() const noexcept {\n\t\treturn radians_ * (180.0f / PI);\n\t}\n\n\tconstexpr bool operator==(const Angle& rhs) const noexcept {\n\t\treturn radians_ == rhs.radians_;\n\t}\n\n\tconstexpr bool operator<(const Angle& rhs) const noexcept {\n\t\treturn radians_ < rhs.radians_;\n\t}\n\n\tAngle& operator+=(const Angle& rhs) noexcept {\n\t\tradians_ += rhs.radians_;\n\t\treturn *this;\n\t}\n\n\tAngle& operator-=(const Angle& rhs) noexcept {\n\t\tradians_ -= rhs.radians_;\n\t\treturn *this;\n\t}\n\n\tAngle& operator*=(float rhs) noexcept {\n\t\tradians_ *= rhs;\n\t\treturn *this;\n\t}\n\n\tAngle& operator/=(float rhs) noexcept {\n\t\tradians_ /= rhs;\n\t\treturn *this;\n\t}\n\n\tAngle operator-() const noexcept {\n\t\treturn -1.0f * (*this);\n\t}\n\n\tfriend const Angle radians(float radians) noexcept;\n\n\tfriend const Angle degrees(float degrees) noexcept;\n\nprivate:\n\n\tconstexpr explicit Angle(float radians) noexcept :\n\t\tradians_(radians)\n\t{\n\t}\n\nprivate:\n\n\tfloat radians_;\n\n};\n\nstatic_assert(sizeof(Angle) == sizeof(float), \"Angle should have no extra data\");\n\nstd::ostream& operator<<(std::ostream& os, const Angle& angle);\n\ninline const Angle radians(float radians) noexcept {\n\treturn Angle(radians);\n}\n\ninline const Angle degrees(float degrees) noexcept {\n\treturn Angle(degrees * (PI / 180.0f));\n}\n\ninline const Angle operator\"\"_rad(long double r) noexcept {\n\treturn radians(static_cast(r));\n}\n\ninline const Angle operator\"\"_deg(long double d) noexcept {\n\treturn degrees(static_cast(d));\n}\n\n} // namespace math\n\nusing math::PI;\nusing math::Angle;\nusing math::radians;\nusing math::degrees;\n\nnamespace math_literals {\n\nusing math::operator \"\"_deg;\nusing math::operator \"\"_rad;\n\n} // namespace math_literals\n\n} // namespace pulp\n} // namespace coconut\n\n#endif /* _COCONUT_PULP_MATH_ANGLE_HPP_ */\n", "meta": {"hexsha": "6ad7b7e450162ba6077337049b4812f3d797f0ec", "size": 2310, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Angle.hpp", "max_stars_repo_name": "mikosz/coconut", "max_stars_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2017-05-02T12:01:54.000Z", "max_stars_repo_stars_event_max_datetime": "2017-05-02T12:01:54.000Z", "max_issues_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Angle.hpp", "max_issues_repo_name": "mikosz/coconut", "max_issues_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "coconut-pulp-math/src/main/c++/coconut/pulp/math/Angle.hpp", "max_forks_repo_name": "mikosz/coconut", "max_forks_repo_head_hexsha": "547bfd55062f09d7af853043c393fc51e8a7a8b6", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.7804878049, "max_line_length": 81, "alphanum_fraction": 0.7207792208, "num_tokens": 560, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044094, "lm_q2_score": 0.7401743677704878, "lm_q1q2_score": 0.6469695600648488}} {"text": "#include \n#include \n#include \n\ndouble calculate_anisotropy(const arma::mat &m) {\n\n const double iso = arma::mean(arma::eig_sym(m));\n double aniso = arma::accu(m % m);\n aniso = std::sqrt(std::abs(1.5*(aniso - (3.0*iso*iso))));\n\n return aniso;\n}\n\nint main() {\n\n arma::mat tensor(3, 3);\n tensor(0, 0) = 71.96979730;\n tensor(0, 1) = -7.19617988;\n tensor(0, 2) = 1.01470321;\n tensor(1, 0) = -7.19617833;\n tensor(1, 1) = 65.74361807;\n tensor(1, 2) = -5.62003645;\n tensor(2, 0) = 1.01469269;\n tensor(2, 1) = -5.62002592;\n tensor(2, 2) = 65.05385723;\n\n // arma::cx_vec principal_components_cx;\n // arma::cx_mat orientation_cx;\n\n // arma::eig_gen(principal_components_cx, orientation_cx, tensor);\n // principal_components_cx.print(\"principal components (complex)\");\n // orientation_cx.print(\"orientation (complex)\");\n\n arma::vec principal_components;\n arma::mat orientation;\n\n arma::eig_sym(principal_components, orientation, tensor);\n\n principal_components.print(\"principal components (real)\");\n orientation.print(\"orientation (real)\");\n\n double isotropic = arma::mean(principal_components);\n std::cout << \"isotropic : \" << isotropic << std::endl;\n double anisotropic = calculate_anisotropy(tensor);\n std::cout << \"anisotropic: \" << anisotropic << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "63acaf2191456b38dc3fa066180f25cb4eb2dc4f", "size": 1381, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/armadillo/arma_aniso.cpp", "max_stars_repo_name": "berquist/eg", "max_stars_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/armadillo/arma_aniso.cpp", "max_issues_repo_name": "berquist/eg", "max_issues_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/armadillo/arma_aniso.cpp", "max_forks_repo_name": "berquist/eg", "max_forks_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1836734694, "max_line_length": 71, "alphanum_fraction": 0.6473569877, "num_tokens": 429, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772351648677, "lm_q2_score": 0.7401743620390163, "lm_q1q2_score": 0.6469695599109831}} {"text": "#include \n#include \n#include \n\n#include \"crossprod.h\"\n\nint main() {\n double T = 1.;\n int N = 1;\n\n Eigen::Vector3d y0(0.1, 0.2, 0.4);\n\n auto f = [](Eigen::Vector3d y) -> Eigen::Vector3d {\n return Eigen::Vector3d(y(0) * y(1), y(1) * y(2), y(2) - y(0));\n };\n\n auto Jf = [](Eigen::Vector3d y) -> Eigen::Matrix3d {\n Eigen::Matrix3d J;\n J << y(1), y(0), 0, 0, y(2), y(1), -1, 0, 1;\n return J;\n };\n // test implicit midpoint\n std::vector test_imp =\n CrossProd::solve_imp_mid(f, Jf, T, y0, N);\n std::cout << \"Implicit midpoint:\\n\"\n << test_imp.back() << std::endl\n << std::endl;\n\n // test linear implicit midpoint\n std::vector test_lin =\n CrossProd::solve_lin_mid(f, Jf, T, y0, N);\n std::cout << \"Implicit linear midpoint:\\n\"\n << test_lin.back() << std::endl\n << std::endl;\n\n // CrossProd::tab_crossprod();\n\n return 0;\n}\n", "meta": {"hexsha": "90a757468e68ad4cd3a11b2fa3c843c1f51be06e", "size": 958, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/CrossProd/templates/crossprod_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/CrossProd/templates/crossprod_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/CrossProd/templates/crossprod_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": 23.95, "max_line_length": 66, "alphanum_fraction": 0.5553235908, "num_tokens": 330, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6469695550551001}} {"text": "#include \"drake/math/quadratic_form.h\"\n\n#include \n\n#include \n#include \n\n#include \"drake/math/matrix_util.h\"\n\nnamespace drake {\nnamespace math {\nEigen::MatrixXd DecomposePSDmatrixIntoXtransposeTimesX(\n const Eigen::Ref& Y, double zero_tol) {\n if (Y.rows() != Y.cols()) {\n throw std::runtime_error(\"Y is not square.\");\n }\n if (zero_tol < 0) {\n throw std::runtime_error(\"zero_tol should be non-negative.\");\n }\n Eigen::LLT llt_Y(Y);\n if (llt_Y.info() == Eigen::Success) {\n return llt_Y.matrixU();\n } else {\n // TODO(hongkai.dai) Switch to use robust Choleskly decomposition instead\n // of Eigen value decomposition, when the bug in\n // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=1479 is fixed.\n Eigen::SelfAdjointEigenSolver es_Y(Y);\n if (es_Y.info() == Eigen::Success) {\n Eigen::MatrixXd X(Y.rows(), Y.cols());\n int X_row_count = 0;\n for (int i = 0; i < es_Y.eigenvalues().rows(); ++i) {\n if (es_Y.eigenvalues()(i) < -zero_tol) {\n throw std::runtime_error(\"Y is not positive definite.\");\n } else if (es_Y.eigenvalues()(i) > zero_tol) {\n X.row(X_row_count++) = std::sqrt(es_Y.eigenvalues()(i)) *\n es_Y.eigenvectors().col(i).transpose();\n }\n }\n return X.topRows(X_row_count);\n }\n }\n throw std::runtime_error(\"Y is not PSD.\");\n}\n\nstd::pair DecomposePositiveQuadraticForm(\n const Eigen::Ref& Q,\n const Eigen::Ref& b, double c, double tol) {\n if (Q.rows() != Q.cols()) {\n throw std::runtime_error(\"Q should be a square matrix.\");\n }\n if (b.rows() != Q.rows()) {\n throw std::runtime_error(\"b does not have the right size.\");\n }\n // The quadratic form xᵀQx + bᵀx + c can also be written as\n // [x]ᵀ * [Q b/2] * [x]\n // [1] [b/2 c] [1]\n // We will call the matrix in the middle as M\n Eigen::MatrixXd M(Q.rows() + 1, Q.rows() + 1);\n // clang-format on\n M << (Q + Q.transpose()) / 2, b / 2,\n b.transpose() / 2, c;\n // clang-format off\n\n const Eigen::MatrixXd A = DecomposePSDmatrixIntoXtransposeTimesX(M, tol);\n Eigen::MatrixXd R = A.leftCols(Q.cols());\n Eigen::VectorXd d = A.col(Q.cols());\n return std::make_pair(R, d);\n}\n\nEigen::MatrixXd BalanceQuadraticForms(\n const Eigen::Ref& S,\n const Eigen::Ref& P) {\n const double tolerance = 1e-8;\n const int n = S.rows();\n DRAKE_THROW_UNLESS(P.rows() == n);\n DRAKE_THROW_UNLESS(IsPositiveDefinite(S, tolerance));\n DRAKE_THROW_UNLESS(IsSymmetric(P, tolerance));\n\n const Eigen::MatrixXd R =\n S.llt().matrixL().solve(Eigen::MatrixXd::Identity(n, n));\n\n const Eigen::JacobiSVD svd(R * P * R.transpose(),\n Eigen::ComputeThinU);\n // Check that P was full rank (hence RPR' full-rank).\n DRAKE_THROW_UNLESS(svd.singularValues()(svd.singularValues().size()-1) >=\n tolerance*std::max(1., svd.singularValues()(0)));\n\n const Eigen::VectorXd sigmaRootN4 =\n svd.singularValues().array().pow(-0.25).matrix();\n return R.transpose() * svd.matrixU() * sigmaRootN4.asDiagonal();\n}\n\n} // namespace math\n} // namespace drake\n", "meta": {"hexsha": "e1b8d7d1bb1b7a839dd107e676b7eeca58f7202a", "size": 3360, "ext": "cc", "lang": "C++", "max_stars_repo_path": "math/quadratic_form.cc", "max_stars_repo_name": "RobotLocomotion/drake-python3.7", "max_stars_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-02-25T02:01:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-17T04:52:04.000Z", "max_issues_repo_path": "math/quadratic_form.cc", "max_issues_repo_name": "RobotLocomotion/drake-python3.7", "max_issues_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "math/quadratic_form.cc", "max_forks_repo_name": "RobotLocomotion/drake-python3.7", "max_forks_repo_head_hexsha": "ae397a4c6985262d23e9675b9bf3927c08d027f5", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-06-13T12:05:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-13T12:05:39.000Z", "avg_line_length": 35.3684210526, "max_line_length": 77, "alphanum_fraction": 0.6255952381, "num_tokens": 972, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772286044095, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6469695500453513}} {"text": "#include \n#include \n#include \n#include \n#include \n\nEigen::Affine2d get_svd_transform(const Eigen::Matrix &src, const Eigen::Matrix &tgt)\n{\n\n assert(src.rows() == tgt.rows());\n Eigen::Affine2d result = Eigen::Affine2d::Identity();\n Eigen::Matrix src_ = src;\n Eigen::Matrix tgt_ = tgt;\n Eigen::Vector2d centroid_src, centroid_tgt;\n // std::cout << \"getting mean\" << std::endl;\n\n centroid_src = src.colwise().mean();\n centroid_tgt = tgt.colwise().mean();\n\n std::cout << centroid_src << std::endl\n << centroid_tgt << std::endl;\n\n src_.colwise() -= centroid_src;\n tgt_.colwise() -= centroid_tgt;\n // std::cout << \"getting svd\" << std::endl;\n Eigen::Matrix2d mat = tgt_.transpose() * src_;\n Eigen::JacobiSVD svd(mat, Eigen::ComputeFullU | Eigen::ComputeFullV);\n Eigen::Matrix2d u, v;\n u = svd.matrixU();\n v = svd.matrixV();\n // std::cout << \"getting rot\" << std::endl;\n result.linear() = u * v.transpose();\n if (result.linear().determinant() < 0)\n {\n Eigen::Matrix inv;\n inv << 1, 0,\n 0, -1;\n std::cout << \"special case\" << std::endl;\n // v.transpose().rowwise() *= v;\n v = v * inv;\n result.linear() = u * v.transpose();\n }\n // std::cout << \"getting trans\" << std::endl;\n result.translation() = centroid_tgt - result.linear() * centroid_src;\n return result;\n}\n\n// Return l2 distance of transformed points\ndouble compare_point_sets(const Eigen::Matrix &src, const Eigen::Matrix &tgt, Eigen::Affine2d &result)\n{\n int rows = src.rows();\n\n // std::cout << \"src: \\n\" << src << std::endl;\n // std::cout << \"tgt: \\n\" << tgt << std::endl;\n // std::cout << \"getting tf\" << std::endl;\n\n result = get_svd_transform(src, tgt);\n std::cout << \"rot:\" << std::endl\n << result.linear() << std::endl;\n std::cout << \"trans:\" << std::endl\n << result.translation() << std::endl;\n\n Eigen::Matrix transformed_src = (result * src.transpose()).transpose();\n // transformed_src.resize(rows, 2);\n // for(int i=0; i diff = tgt - transformed_src.topLeftCorner(rows, 2);\n Eigen::Matrix err = diff.rowwise().norm();\n\n cv::Mat before = cv::Mat::zeros(cv::Size(640, 480), CV_8UC3);\n cv::Mat after = cv::Mat::zeros(cv::Size(640, 480), CV_8UC3);\n for (int i = 0; i < src.rows(); i++)\n {\n cv::circle(before, cv::Point(src(i, 0), src(i, 1)), 2, cv::Scalar(0, 0, 255), 2);\n }\n\n for (int i = 0; i < tgt.rows(); i++)\n {\n cv::circle(before, cv::Point(tgt(i, 0), tgt(i, 1)), 2, cv::Scalar(255, 255, 0), 2);\n cv::circle(after, cv::Point(tgt(i, 0), tgt(i, 1)), 2, cv::Scalar(255, 255, 0), 2);\n }\n\n for (int i = 0; i < transformed_src.rows(); i++)\n {\n cv::circle(after, cv::Point(transformed_src(i, 0), transformed_src(i, 1)), 2, cv::Scalar(0, 0, 255), 2);\n }\n\n cv::imshow(\"before\", before);\n cv::imshow(\"after\", after);\n cv::waitKey(2);\n return err.sum();\n}", "meta": {"hexsha": "fa6048fddb481a10586532b2078620ded95a216a", "size": 3328, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "examples/point_set_compare.hpp", "max_stars_repo_name": "biomotion/esd-2020-final", "max_stars_repo_head_hexsha": "548a0e9a16372cfc04e77220b347ffcfc54efd2e", "max_stars_repo_licenses": ["MIT"], "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/point_set_compare.hpp", "max_issues_repo_name": "biomotion/esd-2020-final", "max_issues_repo_head_hexsha": "548a0e9a16372cfc04e77220b347ffcfc54efd2e", "max_issues_repo_licenses": ["MIT"], "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/point_set_compare.hpp", "max_forks_repo_name": "biomotion/esd-2020-final", "max_forks_repo_head_hexsha": "548a0e9a16372cfc04e77220b347ffcfc54efd2e", "max_forks_repo_licenses": ["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.6161616162, "max_line_length": 132, "alphanum_fraction": 0.5919471154, "num_tokens": 1091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361580958427, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6469347000574693}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nigl::AABB tree;\n\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\nstruct SPoint2D\n{\n\tdouble x[2];\n};\n\ndouble computeAngle(const Eigen::Vector2d& e_im, const Eigen::Vector2d& e_i)\n{\n\t//compute theta\n\t//when e_im.dot(e_i) = 1.0, theta = pi;\n\tconst double r_sinT = e_im(0)*e_i(1) - e_im(1)*e_i(0);\n\tconst double r_cosT = -e_im.dot(e_i);\n\treturn atan2(r_sinT, r_cosT);\n}\n\ndouble sgn(const double& x)\n{\n\treturn (x >= 0) ? 1.0 : -1.0;\n}\n\n\ndouble computeOmegaFromAngle(const double& theta)\n{\n\tconst double sinT = sin(theta);\n\tconst double cosT = cos(theta);\n\tconst double tan_phi_over_2 = sgn(sinT) * sqrt((1.0+cosT)/(max(0.0, 1.0-cosT) + 1.0e-10));\n\treturn 2.0 * tan_phi_over_2;\n}\n\ndouble computeOmega(const Eigen::Vector2d& e_im, const Eigen::Vector2d& e_i)\n{\n\t//compute 2.0 * tan(phi / 2.0)\n\t//phi = pi - theta\n\treturn computeOmegaFromAngle(computeAngle(e_im, e_i));\t\n}\n\ndouble sampleDistanceField(const SImage& in_DF, const SRegion& in_Region, const Eigen::Vector2d& x)\n{\n\tassert(in_DF.width == in_DF.height);\n\tassert(in_Region.right-in_Region.left == in_Region.top-in_Region.bottom);\n\n\tEigen::Vector2d proj_x = x;\n\tproj_x(0) = std::max(in_Region.left, std::min(in_Region.right, x(0)));\n\tproj_x(1) = std::max(in_Region.bottom, std::min(in_Region.top, x(1)));\n\n\tconst double dist_scale = (in_Region.right-in_Region.left) / in_DF.width;\n\n\tdouble fi = (proj_x(0) - in_Region.left) * in_DF.width / (in_Region.right - in_Region.left);\n\tdouble fj = (proj_x(1) - in_Region.bottom) * in_DF.height / (in_Region.top - in_Region.bottom);\n\tdouble _i = floor(fi);\n\tdouble _j = floor(fj);\n\n\tint i = std::max(0, std::min(in_DF.width-1, int(_i)));\n\tint j = std::max(0, std::min(in_DF.height-1, int(_j)));\n\tint ip = std::min(in_DF.width-1, i+1);\n\tint jp = std::min(in_DF.height-1, j+1);\n\n\tdouble s = fi - _i;\n\tdouble t = fj - _j;\n\n\tdouble dist_proj = (1.0 - t) * (s * in_DF.ptr[j*in_DF.width+ip] + (1.0-s) * in_DF.ptr[j*in_DF.width+i])\n\t\t+ t * (s * in_DF.ptr[jp*in_DF.width+ip] + (1.0-s) * in_DF.ptr[jp*in_DF.width+i]);\n\n\treturn dist_proj * dist_scale + (proj_x - x).norm();\n}\n\ndouble integrateDF2OverSegment(const SParameters* in_Params, const Eigen::Vector2d& x1, const Eigen::Vector2d& x2, const double restL)\n{\n\tdouble tot = 0.0;\n\tconst double len = restL / in_Params->substep_fit;\n\n\t//printf(\"integ_DF: \");\n\tfor(int i=0; isubstep_fit; i++)\n\t{\n\t\tconst Eigen::Vector2d& p1 = x1 + (x2-x1) * double(i)/double(in_Params->substep_fit);\n\t\tconst Eigen::Vector2d& p2 = x1 + (x2-x1) * double(i+1)/double(in_Params->substep_fit);\n\t\t\n\t\tconst double d1 = sampleDistanceField(in_Params->df, in_Params->region, p1);\n\t\tconst double d2 = sampleDistanceField(in_Params->df, in_Params->region, p2);\n\n\t\t//printf(\"[%f, %f, %f], \", d1, d2, len);\n\n\t\tconst double e1 = 0.5 * (exp(d1) + exp(-d1)) - 1.0;\n\t\tconst double e2 = 0.5 * (exp(d2) + exp(-d2)) - 1.0;\n\n\t\t//tot += 0.5 * (d1*d1+d2*d2) * len;\n\t\ttot += 0.5 * (e1*e1+e2*e2) * len;\n\t}\n\t//printf(\"\\n\");\n\n\treturn tot;\n}\n\ninline double computeSegmentElasticEnergy(const Eigen::Vector2d& p1, const Eigen::Vector2d& p2, const double& YA, const double& restLength)\n{\n\tconst Eigen::Vector2d diff = p1 - p2;\n\treturn 0.5 * YA * restLength\n\t\t* (diff.norm() / restLength - 1)\n\t\t* (diff.norm() / restLength - 1);\n}\n\ninline double computeSegmentBendingEnergy(const Eigen::Vector2d& pp, const Eigen::Vector2d& pc, const Eigen::Vector2d& pn, \n\tconst double& alpha, const double& restLengthP, const double& restLengthN, const double& theta)\n{\n\tconst Eigen::Vector2d e_im = pc - pp;\n\tconst Eigen::Vector2d e_i = pn - pc;\n\n\t/*\n\tdouble omega = 2.0 * fabs(e_im(0)*e_i(1)-e_im(1)*e_i(0)) / (e_im.norm()*e_i.norm() + e_im.dot(e_i));\n\tdouble omega_bar = 2.0 * fabs(tan(phi*0.5));\n\t//*/\n\tdouble omega = computeOmega(e_im, e_i);\n\tdouble omega_bar = computeOmegaFromAngle(theta);\n\treturn alpha * (omega - omega_bar) * (omega - omega_bar) / (restLengthP + restLengthN);\n}\n\ndouble computeEnergy_elastic(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\n\tdouble energy = 0.0;\n\n\tfor(int i=0; inVertices;\n\t\tenergy += computeSegmentElasticEnergy(in_Position.col(ip), in_Position.col(i), in_Params->YA, in_Curve->restLengths(i));\n\t}\n\n\treturn energy;\n}\n\ndouble computeEnergy_bending(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position)\n{\n\tint nAngles = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 2; \n\n\tdouble energy = 0.0;\n\n\tfor(int i=0; iclosed ? \n\t\t\t(i + in_Curve->nVertices - 1) % in_Curve->nVertices : i;\n\t\tint ii = in_Curve->closed ? i : i + 1;\n\t\tint iip = in_Curve->closed ? (i + 1) % in_Curve->nVertices : i + 2;\n\n\t\tdouble restL_m = in_Curve->closed ? in_Curve->restLengths((i + in_Curve->nVertices - 1) % in_Curve->nVertices) : \n\t\t\tin_Curve->restLengths(i);\n\t\tdouble restL = in_Curve->closed ? in_Curve->restLengths(i) : \n\t\t\tin_Curve->restLengths(i+1);\n\n\t\tenergy += computeSegmentBendingEnergy(in_Position.col(iim), in_Position.col(ii), in_Position.col(iip),\n\t\t\tin_Params->alpha, restL_m, restL, in_Curve->restAngles(i));\n\t}\n\n\treturn energy;\n}\n\ndouble computeEnergy_fit(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\n\tdouble energy = 0.0;\n\n\tfor(int i=0; inVertices;\n\t\tdouble int_df_seg = integrateDF2OverSegment(in_Params, in_Position.col(i), in_Position.col(ip), in_Curve->restLengths(i));\n\t\tenergy += 0.5 * in_Params->fit * int_df_seg;\n\t}\n\n\treturn energy;\n}\n\ndouble computeEnergy(const SParameters* in_Params, const SCurve* in_Curve, const SVar& in_Vars)\n{\n\tconst double E_elastic = computeEnergy_elastic(in_Params, in_Curve, in_Vars.pos);\n\tconst double E_bending = computeEnergy_bending(in_Params, in_Curve, in_Vars.pos);\n\tconst double E_fit = computeEnergy_fit(in_Params, in_Curve, in_Vars.pos);\n\treturn E_elastic + E_bending + E_fit;\n}\n\nvoid compute_f_elastic(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position, Eigen::VectorXd& io_f, int offset_row)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\n\tassert(io_f.rows() >= nSegs + offset_row);\n\tassert(in_Curve->nVertices == in_Position.cols());\n\n\tfor(int i=0; inVertices;\n\t\tconst Eigen::Vector2d diff = in_Position.col(ip) - in_Position.col(i);\n\t\tio_f(i+offset_row) = sqrt(0.5 * in_Params->YA * in_Curve->restLengths(i)) * (diff.norm() / in_Curve->restLengths(i) - 1);\n\t}\n}\n\nvoid compute_f_bending(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position, Eigen::VectorXd& io_f, int offset_row)\n{\n\tint nAngles = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 2; \n\n\tassert(io_f.rows() >= nAngles + offset_row);\n\tassert(in_Curve->nVertices == in_Position.cols());\n\n\tfor(int i=0; iclosed ? \n\t\t\t(i + in_Curve->nVertices - 1) % in_Curve->nVertices : i;\n\t\tint ii = in_Curve->closed ? i : i + 1;\n\t\tint iip = in_Curve->closed ? (i + 1) % in_Curve->nVertices : i + 2;\n\n\t\tdouble restL_m = in_Curve->closed ? in_Curve->restLengths((i + in_Curve->nVertices - 1) % in_Curve->nVertices) : \n\t\t\tin_Curve->restLengths(i);\n\t\tdouble restL = in_Curve->closed ? in_Curve->restLengths(i) : \n\t\t\tin_Curve->restLengths(i+1);\n\n\t\tconst Eigen::Vector2d e_im = in_Position.col(ii) - in_Position.col(iim);\n\t\tconst Eigen::Vector2d e_i = in_Position.col(iip) - in_Position.col(ii);\n\n\t\t/*\n\t\tdouble omega = 2.0 * fabs(e_im(0)*e_i(1)-e_im(1)*e_i(0)) / (e_im.norm()*e_i.norm() + e_im.dot(e_i));\n\t\tdouble omega_bar = 2.0 * fabs(tan(in_Curve->restAngles(i)*0.5));\n\t\t//*/\n\t\tdouble omega = computeOmega(e_im, e_i);\n\t\tdouble omega_bar = computeOmegaFromAngle(in_Curve->restAngles(i));\n\t\tio_f(i+offset_row) = sqrt(in_Params->alpha/(restL_m + restL)) * (omega - omega_bar);\n\t}\n}\n\nvoid compute_f_fit(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position, Eigen::VectorXd& io_f, int offset_row)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\n\tassert(io_f.rows() >= nSegs + offset_row);\n\tassert(in_Curve->nVertices == in_Position.cols());\n\n\t//printf(\"int_seg: \");\n\tfor(int i=0; inVertices;\n\t\tdouble int_df_seg = integrateDF2OverSegment(in_Params, in_Position.col(i), in_Position.col(ip), in_Curve->restLengths(i));\n\t\t//printf(\"%f, \", int_df_seg);\n\t\tio_f(i+offset_row) = sqrt(in_Params->fit * 0.5) * sqrt(int_df_seg);\n\t}\n\t//printf(\"\\n\");\n}\n\nvoid compute_f(const SParameters* in_Params, const SCurve* in_Curve, const SVar& in_Vars, Eigen::VectorXd& io_f)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\tint nAngles = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 2; \n\n\tint nElems = nSegs + nAngles + nSegs;\n\n\tassert(io_f.rows() == nElems);\n\tassert(in_Curve->nVertices == in_Vars.pos.cols());\n\tassert(in_Curve->nVertices == in_Vars.pos.cols());\n\n\tio_f.setZero();\n\n\tcompute_f_elastic(in_Params, in_Curve, in_Vars.pos, io_f, 0);\n\tcompute_f_bending(in_Params, in_Curve, in_Vars.pos, io_f, nSegs);\n\tcompute_f_fit(in_Params, in_Curve, in_Vars.pos, io_f, nSegs+nAngles);\n\n\t/*\n\tprintf(\"f: [\");\n\tfor(int i=0; iclosed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\n\tassert(io_Jacobian.rows() >= nSegs + offset_row);\n\tassert(io_Jacobian.cols() == in_Curve->nVertices * 2);\n\n\tconst Eigen::Vector2d dx(epsilon, 0.0); \n\tconst Eigen::Vector2d dy(0.0, epsilon);\n\n\t//dJ/dxi, dJ/dyi\n\tfor(int i=0; inVertices;\n\n\t\tconst Eigen::Vector2d xi = in_Position.col(i);\n\t\tconst Eigen::Vector2d xip = in_Position.col(ip);\n\n\t\tconst Eigen::Vector2d diff0 = xip - xi;\n\t\tconst double fi = sqrt(in_Params->YA * in_Curve->restLengths(i) * 0.5) * (diff0.norm() / in_Curve->restLengths(i) - 1);\n\n\t\t//dJ/dxi_i\n\t\tconst Eigen::Vector2d xi_dx = xi + dx;\n\t\tconst Eigen::Vector2d diff1 = xip - xi_dx;\n\t\tconst double fi_i_dx = sqrt(in_Params->YA * in_Curve->restLengths(i) * 0.5) * (diff1.norm() / in_Curve->restLengths(i) - 1);\n\t\tio_Jacobian(i+offset_row, i) = (fi_i_dx - fi) / epsilon;\n\n\t\t//dJ/dyi_i\n\t\tconst Eigen::Vector2d xi_dy = xi + dy;\n\t\tconst Eigen::Vector2d diff2 = xip - xi_dy;\n\t\tconst double fi_i_dy = sqrt(in_Params->YA * in_Curve->restLengths(i) * 0.5) * (diff2.norm() / in_Curve->restLengths(i) - 1);\n\t\tio_Jacobian(i+offset_row, i+in_Curve->nVertices) = (fi_i_dy - fi) / epsilon;\n\n\t\t//dJ/dxi_ip\n\t\tconst Eigen::Vector2d xip_dx = xip + dx;\n\t\tconst Eigen::Vector2d diff3 = xip_dx - xi;\n\t\tconst double fi_ip_dx = sqrt(in_Params->YA * in_Curve->restLengths(i) * 0.5) * (diff3.norm() / in_Curve->restLengths(i) - 1);\n\t\tio_Jacobian(i+offset_row, ip) = (fi_ip_dx - fi) / epsilon;\n\t\t\n\t\t//dJ/dyi_i\n\t\tconst Eigen::Vector2d xip_dy = xip + dy;\n\t\tconst Eigen::Vector2d diff4 = xip_dy - xi;\n\t\tconst double fi_ip_dy = sqrt(in_Params->YA * in_Curve->restLengths(i) * 0.5) * (diff4.norm() / in_Curve->restLengths(i) - 1);\n\t\tio_Jacobian(i+offset_row, ip+in_Curve->nVertices) = (fi_ip_dy - fi) / epsilon;\n\t}\n}\n\nvoid computeNumericalDerivative_bending(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position, double epsilon, Eigen::MatrixXd& io_Jacobian, int offset_row)\n{\n\tint nAngles = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 2; \n\n\tassert(io_Jacobian.rows() >= nAngles + offset_row);\n\tassert(io_Jacobian.cols() == in_Curve->nVertices * 2);\n\n\tconst Eigen::Vector2d dx(epsilon, 0.0); \n\tconst Eigen::Vector2d dy(0.0, epsilon);\n\n\t//dB/dxi, dB/dyi\n\tfor(int i=0; iclosed ? \n\t\t\t(i + in_Curve->nVertices - 1) % in_Curve->nVertices : i;\n\t\tint ii = in_Curve->closed ? i : i + 1;\n\t\tint iip = in_Curve->closed ? (i + 1) % in_Curve->nVertices : i + 2;\n\n\t\tdouble restL_m = in_Curve->restLengths(iim);\n\t\tdouble restL = in_Curve->restLengths(ii);\n\n\t\tconst Eigen::Vector2d xim = in_Position.col(iim);\n\t\tconst Eigen::Vector2d xi = in_Position.col(ii);\n\t\tconst Eigen::Vector2d xip = in_Position.col(iip);\n\n\t\tconst Eigen::Vector2d xim_dx = xim + dx; const Eigen::Vector2d xim_dy = xim + dy;\n\t\tconst Eigen::Vector2d xi_dx = xi + dx; const Eigen::Vector2d xi_dy = xi + dy;\n\t\tconst Eigen::Vector2d xip_dx = xip + dx; const Eigen::Vector2d xip_dy = xip + dy;\n\n\t\tconst Eigen::Vector2d e_prev = xi - xim;\n\t\tconst Eigen::Vector2d e_next = xip - xi;\n\n\t\tconst Eigen::Vector2d e_prev_im_dx = xi - xim_dx; const Eigen::Vector2d e_prev_im_dy = xi - xim_dy;\n\t\tconst Eigen::Vector2d e_prev_i_dx = xi_dx - xim; const Eigen::Vector2d e_prev_i_dy = xi_dy - xim;\n\n\t\tconst Eigen::Vector2d e_next_i_dx = xip - xi_dx; const Eigen::Vector2d e_next_i_dy = xip - xi_dy;\n\t\tconst Eigen::Vector2d e_next_ip_dx = xip_dx - xi; const Eigen::Vector2d e_next_ip_dy = xip_dy - xi;\n\n\t\t/*\n\t\tconst double omega = 2.0 * fabs(e_prev(0)*e_next(1)-e_prev(1)*e_next(0)) / (e_prev.norm()*e_next.norm() + e_prev.dot(e_next));\n\n\t\tconst double omega_im_dx = 2.0 * fabs(e_prev_im_dx(0)*e_next(1)-e_prev_im_dx(1)*e_next(0)) / (e_prev_im_dx.norm()*e_next.norm() + e_prev_im_dx.dot(e_next));\n\t\tconst double omega_im_dy = 2.0 * fabs(e_prev_im_dy(0)*e_next(1)-e_prev_im_dy(1)*e_next(0)) / (e_prev_im_dy.norm()*e_next.norm() + e_prev_im_dy.dot(e_next));\n\t\tconst double omega_i_dx = 2.0 * fabs(e_prev_i_dx(0)*e_next_i_dx(1)-e_prev_i_dx(1)*e_next_i_dx(0)) / (e_prev_i_dx.norm()*e_next_i_dx.norm() + e_prev_i_dx.dot(e_next_i_dx));\n\t\tconst double omega_i_dy = 2.0 * fabs(e_prev_i_dy(0)*e_next_i_dy(1)-e_prev_i_dy(1)*e_next_i_dy(0)) / (e_prev_i_dy.norm()*e_next_i_dy.norm() + e_prev_i_dy.dot(e_next_i_dy));\n\t\tconst double omega_ip_dx = 2.0 * fabs(e_prev(0)*e_next_ip_dx(1)-e_prev(1)*e_next_ip_dx(0)) / (e_prev.norm()*e_next_ip_dx.norm() + e_prev.dot(e_next_ip_dx));\n\t\tconst double omega_ip_dy = 2.0 * fabs(e_prev(0)*e_next_ip_dy(1)-e_prev(1)*e_next_ip_dy(0)) / (e_prev.norm()*e_next_ip_dy.norm() + e_prev.dot(e_next_ip_dy));\n\t\t//*/\n\n\t\tconst double omega = computeOmega(e_prev, e_next);\n\n\t\tconst double omega_im_dx = computeOmega(e_prev_im_dx, e_next);\n\t\tconst double omega_im_dy = computeOmega(e_prev_im_dy, e_next);\n\t\tconst double omega_i_dx = computeOmega(e_prev_i_dx, e_next_i_dx);\n\t\tconst double omega_i_dy = computeOmega(e_prev_i_dy, e_next_i_dy);\n\t\tconst double omega_ip_dx = computeOmega(e_prev, e_next_ip_dx);\n\t\tconst double omega_ip_dy = computeOmega(e_prev, e_next_ip_dy);\t\t\n\n\t\tconst double fi = sqrt(in_Params->alpha/(restL_m + restL)) * omega; //omega_bar will be cancelled out, so omit it\n\t\tconst double fi_im_dx = sqrt(in_Params->alpha/(restL_m + restL)) * omega_im_dx;\n\t\tconst double fi_im_dy = sqrt(in_Params->alpha/(restL_m + restL)) * omega_im_dy;\n\t\tconst double fi_i_dx = sqrt(in_Params->alpha/(restL_m + restL)) * omega_i_dx;\n\t\tconst double fi_i_dy = sqrt(in_Params->alpha/(restL_m + restL)) * omega_i_dy;\n\t\tconst double fi_ip_dx = sqrt(in_Params->alpha/(restL_m + restL)) * omega_ip_dx;\n\t\tconst double fi_ip_dy = sqrt(in_Params->alpha/(restL_m + restL)) * omega_ip_dy;\n\t\t\n\t\tio_Jacobian(i+offset_row, iim) = (fi_im_dx - fi) / epsilon;\n\t\tio_Jacobian(i+offset_row, iim+in_Curve->nVertices) = (fi_im_dy - fi) / epsilon;\n\n\t\tio_Jacobian(i+offset_row, ii) = (fi_i_dx - fi) / epsilon;\n\t\tio_Jacobian(i+offset_row, ii+in_Curve->nVertices) = (fi_i_dy - fi) / epsilon;\n\n\t\tio_Jacobian(i+offset_row, iip) = (fi_ip_dx - fi) / epsilon;\n\t\tio_Jacobian(i+offset_row, iip+in_Curve->nVertices) = (fi_ip_dy - fi) / epsilon;\n\t}\n}\n\nvoid computeNumericalDerivative_fit(const SParameters* in_Params, const SCurve* in_Curve, const Eigen::Matrix2Xd& in_Position, double epsilon, Eigen::MatrixXd& io_Jacobian, int offset_row)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\n\tassert(io_Jacobian.rows() >= nSegs + offset_row);\n\tassert(io_Jacobian.cols() == in_Curve->nVertices * 2);\n\n\tconst Eigen::Vector2d dx(epsilon, 0.0); \n\tconst Eigen::Vector2d dy(0.0, epsilon);\n\n\t//dfit/dxi, dfit/dyi\n\tfor(int i=0; inVertices;\n\n\t\tconst Eigen::Vector2d xi = in_Position.col(i);\n\t\tconst Eigen::Vector2d xip = in_Position.col(ip);\n\t\tconst double restL = in_Curve->restLengths(i);\n\n\t\tconst double fi = sqrt(in_Params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_Params, xi, xip, restL));\n\n\t\t//dfit/dxi_i\n\t\tconst Eigen::Vector2d xi_dx = xi + dx;\n\t\tconst double fi_i_dx = sqrt(in_Params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_Params, xi_dx, xip, restL));\n\t\tio_Jacobian(i+offset_row, i) = (fi_i_dx - fi) / epsilon;\n\n\t\t//dfit/dyi_i\n\t\tconst Eigen::Vector2d xi_dy = xi + dy;\n\t\tconst double fi_i_dy = sqrt(in_Params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_Params, xi_dy, xip, restL));\n\t\tio_Jacobian(i+offset_row, i+in_Curve->nVertices) = (fi_i_dy - fi) / epsilon;\n\n\t\t//dfit/dxi_ip\n\t\tconst Eigen::Vector2d xip_dx = xip + dx;\n\t\tconst double fi_ip_dx = sqrt(in_Params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_Params, xi, xip_dx, restL));\n\t\tio_Jacobian(i+offset_row, ip) = (fi_ip_dx - fi) / epsilon;\n\t\t\n\t\t//dfit/dyi_i\n\t\tconst Eigen::Vector2d xip_dy = xip + dy;\n\t\tconst double fi_ip_dy = sqrt(in_Params->fit * 0.5) * sqrt(integrateDF2OverSegment(in_Params, xi, xip_dy, restL));\n\t\tio_Jacobian(i+offset_row, ip+in_Curve->nVertices) = (fi_ip_dy - fi) / epsilon;\n\t}\n}\n\nvoid computeNumericalDerivative(const SParameters* in_Params, const SCurve* in_Curve, const SVar& in_Vars, double epsilon, Eigen::MatrixXd& io_Jacobian)\n{\n\tint nSegs = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 1;\n\tint nAngles = in_Curve->closed ? in_Curve->nVertices : in_Curve->nVertices - 2; \n\n\t//assert(io_Jacobian.rows() == nSegs + nAngles + nSegs);\n\t//assert(io_Jacobian.cols() == in_Curve->nVertices * 2);\n\t//assert(in_Vars.pos.cols() == in_Curve->nVertices);\n\t//assert(in_Vars.conf.cols() == in_Curve->nVertices);\n\n\tio_Jacobian.setZero();\n\n\tcomputeNumericalDerivative_elastic(in_Params, in_Curve, in_Vars.pos, epsilon, io_Jacobian, 0);\n\tcomputeNumericalDerivative_bending(in_Params, in_Curve, in_Vars.pos, epsilon, io_Jacobian, nSegs);\n\tcomputeNumericalDerivative_fit(in_Params, in_Curve, in_Vars.pos, epsilon, io_Jacobian, nSegs+nAngles);\n\n\t/*\n\tprintf(\"B: [\\n\");\n\tfor(int j=0; jclosed ? io_Curve->nVertices : io_Curve->nVertices - 1;\n\tassert(io_Curve->nVertices == in_Position.cols());\n\n\tfor(int i=0; inVertices;\n\t\tconst Eigen::Vector2d diff = in_Position.col(ip) - in_Position.col(i);\n\t\tio_Curve->restLengths(i) = diff.norm();\n\t}\n}\n\nvoid updateCurveSubdivision(const SParameters* in_Params, SVar& io_InitialVars, SVar& io_Vars, SCurve* io_Curve, SSolverVars& io_SolverVars)\n{\n\tint nSegs = io_Curve->closed ? io_Curve->nVertices : io_Curve->nVertices - 1;\n\t//assert(io_Curve->nVertices == in_Position.cols());\n\n\tstd::vector pos;\n\tstd::vector angles;\n\tstd::vector vids;\n\n\tbool subdivided = false;\n\n\tfor(int i=0; ivertexIDs(i));\n\n\t\tif(i!=0 || io_Curve->closed) angles.push_back(io_Curve->restAngles(i));\n\n\t\tint ip = (i+1) % io_Curve->nVertices;\n\t\tconst Eigen::Vector2d diff = io_Vars.pos.col(ip) - io_Vars.pos.col(i);\n\t\tif(diff.norm() > in_Params->refLength)\n\t\t{\n\t\t\tSPoint2D p;\n\t\t\tp.x[0] = (io_Vars.pos.col(ip)(0) + io_Vars.pos.col(i)(0)) * 0.5;\n\t\t\tp.x[1] = (io_Vars.pos.col(ip)(1) + io_Vars.pos.col(i)(1)) * 0.5;\n\t\t\tpos.push_back(p);\n\t\t\t//angles.push_back((io_Curve->restAngles(i) + io_Curve->restAngles(ip)) * 0.5);\n\t\t\tangles.push_back(PI);\n\t\t\tvids.push_back(-1);\n\t\t\tsubdivided = true;\n\t\t}\n\t}\n\n\tif(!io_Curve->closed)\n\t{\n\t\tint ilast = io_Curve->nVertices-1;\n\t\tSPoint2D p; p.x[0] = io_Vars.pos.col(ilast)(0); p.x[1] = io_Vars.pos.col(ilast)(1);\n\t\tpos.push_back(p);\n\t\tvids.push_back(io_Curve->vertexIDs(ilast));\n\t}\n\n\tio_Curve->nVertices = pos.size();\n\tnSegs = io_Curve->closed ? io_Curve->nVertices : io_Curve->nVertices - 1;\n\tio_Curve->restLengths.resize(nSegs);\n\tint nAngles = io_Curve->closed ? io_Curve->nVertices : io_Curve->nVertices - 2; \n\tio_Curve->restAngles.resize(nAngles);\n\tio_Curve->vertexIDs.resize(io_Curve->nVertices);\n\n\tresize(io_Vars, io_Curve->nVertices);\n\tresize(io_InitialVars, io_Curve->nVertices);\n\n\tfor(int i=0; inVertices; i++)\n\t{\n\t\tio_Vars.pos.col(i)(0) = pos[i].x[0];\n\t\tio_Vars.pos.col(i)(1) = pos[i].x[1];\n\t\tio_Vars.conf(i) = 0.0;\n\t\tio_Curve->vertexIDs(i) = vids[i];\n\t}\n\n\tnSegs = io_Curve->closed ? io_Curve->nVertices : io_Curve->nVertices - 1;\n\tfor(int i=0; inVertices;\n\t\tconst Eigen::Vector2d diff = io_Vars.pos.col(ip) - io_Vars.pos.col(i);\n\t\tio_Curve->restLengths(i) = diff.norm();\n\t}\n\n\tfor(int i=0; irestAngles(i) = angles[i];\n\n\tio_InitialVars = io_Vars;\n\n\tinitSolverVars(in_Params, io_Curve, io_InitialVars, io_SolverVars, true);\n}\n\nbool secantLMMethodSingleUpdate(const SParameters* in_Params, const SCurve* in_Curve, const SVar& in_InitialVars, SSolverVars& io_SolverVars, SVar& solution)\n{\n\tif(io_SolverVars.found || io_SolverVars.k > in_Params->kmax)\n\t\treturn true;\n\n\tio_SolverVars.k++;\n\tio_SolverVars.A_muI = io_SolverVars.B.transpose() * io_SolverVars.B + io_SolverVars.mu * io_SolverVars.I;\n\tio_SolverVars.h = io_SolverVars.A_muI.ldlt().solve(-io_SolverVars.g);\n\n\tif(io_SolverVars.h.norm() <= in_Params->epsilon_2 * (io_SolverVars.x.pos.norm() + in_Params->epsilon_2))\n\t\tio_SolverVars.found = true;\n\telse\n\t{\n\t\tfor(int q=0; q 0)\n\t{\n\t\tio_SolverVars.x = io_SolverVars.xnew;\n\t\tcompute_f(in_Params, in_Curve, io_SolverVars.x, io_SolverVars.f);\n\t\tcomputeNumericalDerivative(in_Params, in_Curve, io_SolverVars.x, io_SolverVars.epsilon, io_SolverVars.B);\n\t\tio_SolverVars.g = io_SolverVars.B.transpose() * io_SolverVars.f;\n\t\tio_SolverVars.found = (io_SolverVars.g.lpNorm() <= in_Params->epsilon_1);\n\t\tprintf(\"k: %d, gain: %f, |g|_inf: %f\\n\", io_SolverVars.k, gain, io_SolverVars.g.lpNorm());\n\t\tio_SolverVars.mu = io_SolverVars.mu * std::max(1.0/3.0, 1.0 - (2.0 * gain - 1.0) * (2.0 * gain - 1.0) * (2.0 * gain - 1.0));\n\t\tio_SolverVars.nu = 2.0;\n\t}\n\telse\n\t{\n\t\tio_SolverVars.mu = io_SolverVars.mu * io_SolverVars.nu;\n\t\tio_SolverVars.nu = io_SolverVars.nu * 2.0;\n\t}\n\n\tif(io_SolverVars.found)\n\t\tprintf(\"found in %d steps\\n\", io_SolverVars.k);\n\n\tsolution = io_SolverVars.x;\n\n\treturn io_SolverVars.found || io_SolverVars.k > in_Params->kmax;\n}\n\nvoid showFeaturePoints(const SCurve* in_Curve, const SVar& solution)\n{\n\tprintf(\"Feature points:\\n\");\n\tfor(int i=0; inVertices; i++)\n\t{\n\t\tif(in_Curve->vertexIDs(i) >= 0)\n\t\t{\n\t\t\tprintf(\"%d: %f, %f\\n\", in_Curve->vertexIDs(i), solution.pos.col(i).x(), solution.pos.col(i).y());\n\t\t}\n\t}\n}\n\nvoid secantLMMethod(const SParameters* in_Params, SCurve* in_Curve, SVar& in_InitialVars, SSolverVars& io_SolverVars, SVar& solution)\n{\n\tinitSolverVars(in_Params, in_Curve, in_InitialVars, io_SolverVars);\n\n\twhile(1)\n\t{\n\t\tif(secantLMMethodSingleUpdate(in_Params, in_Curve, in_InitialVars, io_SolverVars, solution))\n\t\t\tbreak;\n\t\tupdateCurveSubdivision(in_Params, in_InitialVars, solution, in_Curve, io_SolverVars);\n\t}\n\n\tprintf(\"found in %d steps\\n\", io_SolverVars.k);\n\tsolution = io_SolverVars.x;\n\tshowFeaturePoints(in_Curve, solution);\n}\n", "meta": {"hexsha": "a4011b2e3fcc4c5e681f2ba32315a65527c09f94", "size": 24705, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "catkin_ws/src/folding_planner_cmake/project/2dregistration_v2/registration.cpp", "max_stars_repo_name": "roop-pal/robotic-folding", "max_stars_repo_head_hexsha": "a0e062ac6d23cd07fe10e3f45abc4ba50e533141", "max_stars_repo_licenses": ["RSA-MD"], "max_stars_count": 17.0, "max_stars_repo_stars_event_min_datetime": "2015-10-21T16:09:18.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-23T03:15:55.000Z", "max_issues_repo_path": "catkin_ws/src/folding_planner_cmake/project/2dregistration_v2/registration.cpp", "max_issues_repo_name": "roop-pal/robotic-folding", "max_issues_repo_head_hexsha": "a0e062ac6d23cd07fe10e3f45abc4ba50e533141", "max_issues_repo_licenses": ["RSA-MD"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2017-12-17T04:39:38.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-17T04:39:38.000Z", "max_forks_repo_path": "catkin_ws/src/folding_planner_cmake/project/2dregistration_v2/registration.cpp", "max_forks_repo_name": "roop-pal/robotic-folding", "max_forks_repo_head_hexsha": "a0e062ac6d23cd07fe10e3f45abc4ba50e533141", "max_forks_repo_licenses": ["RSA-MD"], "max_forks_count": 8.0, "max_forks_repo_forks_event_min_datetime": "2016-03-18T14:13:58.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-15T15:03:51.000Z", "avg_line_length": 38.3618012422, "max_line_length": 192, "alphanum_fraction": 0.6960534305, "num_tokens": 8425, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361652391386, "lm_q2_score": 0.7090191214879992, "lm_q1q2_score": 0.646934688291733}} {"text": "#include \n#include \n#include \n#include \n\n#include \n\nusing namespace rmagine;\n\nvoid print(Matrix3x3 M)\n{\n for(size_t i=0; i<3; i++)\n {\n for(size_t j=0; j<3; j++)\n {\n std::cout << M(i,j) << \" \";\n }\n std::cout << std::endl;\n }\n}\n\nvoid print(Matrix4x4 M)\n{\n for(size_t i=0; i<4; i++)\n {\n for(size_t j=0; j<4; j++)\n {\n std::cout << M(i,j) << \" \";\n }\n std::cout << std::endl;\n }\n}\n\nvoid print(Eigen::Matrix4f M)\n{\n for(size_t i=0; i<4; i++)\n {\n for(size_t j=0; j<4; j++)\n {\n std::cout << M(i,j) << \" \";\n }\n std::cout << std::endl;\n }\n}\n\nvoid print(Vector v)\n{\n std::cout << v.x << \" \" << v.y << \" \" << v.z << std::endl;\n}\n\nvoid print(Quaternion q)\n{\n std::cout << q.x << \" \" << q.y << \" \" << q.z << \" \" << q.w << std::endl;\n}\n\nvoid print(Transform T)\n{\n print(T.R);\n print(T.t);\n}\n\nbool rotationConversionTest()\n{\n std::cout << std::endl;\n std::cout << \"--------------------------------\" << std::endl;\n std::cout << \"---- rotationConversionTest ----\" << std::endl;\n std::cout << \"--------------------------------\" << std::endl;\n std::cout << std::endl;\n\n EulerAngles e0;\n e0.roll = -0.1;\n e0.pitch = 0.1;\n e0.yaw = M_PI / 2.0;\n\n EulerAngles e;\n Quaternion q;\n Matrix3x3 R;\n\n Vector x1{1.0, 0.0, 0.0};\n Vector x2{0.0, 1.0, 0.0};\n Vector x3{0.0, 0.0, 1.0};\n\n std::cout << \"Euler -> Quat\" << std::endl;\n q = e0;\n print(q * x1);\n print(q * x2);\n print(q * x3);\n std::cout << std::endl;\n\n std::cout << \"Quat -> Euler\" << std::endl;\n e = q;\n std::cout << e.roll << \" \" << e.pitch << \" \" << e.yaw << std::endl;\n std::cout << std::endl;\n\n if( fabs(e.roll - e0.roll) > 0.0001 \n || fabs(e.pitch - e0.pitch) > 0.0001 \n || fabs(e.yaw - e0.yaw) > 0.0001)\n {\n std::cout << \"Euler -> Quat -> Euler error.\" << std::endl;\n return false;\n }\n\n std::cout << \"Euler -> Matrix\" << std::endl;\n R = e0;\n print(R * x1);\n print(R * x2);\n print(R * x3);\n std::cout << std::endl;\n\n std::cout << \"Matrix -> Euler\" << std::endl;\n e = R;\n std::cout << e.roll << \" \" << e.pitch << \" \" << e.yaw << std::endl;\n std::cout << std::endl;\n\n std::cout << \"Quat -> Matrix\" << std::endl;\n R = q;\n print(R * x1);\n print(R * x2);\n print(R * x3);\n std::cout << std::endl;\n\n std::cout << \"Matrix -> Quat\" << std::endl;\n q = R;\n print(q * x1);\n print(q * x2);\n print(q * x3);\n std::cout << std::endl;\n\n return true;\n}\n\nEigen::Vector3f& eigenView(Vector3& v)\n{\n return *reinterpret_cast( &v );\n}\n\nEigen::Matrix3f& eigenView(Matrix3x3& M)\n{\n return *reinterpret_cast( &M );\n}\n\nEigen::Matrix4f& eigenView(Matrix4x4& M)\n{\n return *reinterpret_cast( &M );\n}\n\nbool checkMatrix3x3()\n{\n std::cout << \"---------- checkMatrix3x3\" << std::endl;\n EulerAngles e{-0.1, 0.1, M_PI / 2.0};\n\n Matrix3x3 M;\n M = e;\n M(0,1) = 10.0;\n\n // shallow copy. \n Eigen::Matrix3f& Meig_shallow = eigenView(M);\n std::cout << Meig_shallow << std::endl;\n\n // deep copy\n Eigen::Matrix3f Meig(&M(0,0));\n\n\n // Eigen::Matrix3f Meig_inv = Meig.inverse();\n Matrix3x3 M_inv = ~M;\n Eigen::Matrix3f Meig_inv = Meig.inverse();\n\n // std::cout << Meig_inv << std::endl;\n // print(M_inv);\n Matrix3x3 I = M_inv * M;\n Eigen::Matrix3f Ieig = Meig_inv * Meig;\n\n std::cout << \"M = \" << std::endl;\n print(M);\n\n std::cout << \"M_inv = \" << std::endl;\n print(M_inv);\n\n std::cout << \"M_inv * M = \" << std::endl;\n print(I);\n\n std::cout << \"Meig = \" << std::endl;\n std::cout << Meig << std::endl;\n\n std::cout << \"Meig_inv = \" << std::endl;\n std::cout << Meig_inv << std::endl;\n\n std::cout << \"Meig_inv * Meig =\" << std::endl;\n std::cout << Meig_inv * Meig << std::endl;\n \n\n std::cout << \"Eigen::Matrix3f stats: \" << std::endl;\n std::cout << \"- det: \" << Meig.determinant() << std::endl;\n std::cout << \"- trace: \" << Meig.trace() << std::endl;\n \n\n std::cout << \"Matrix3x3 stats:\" << std::endl;\n std::cout << \"- det: \" << M.det() << std::endl;\n std::cout << \"- trace: \" << M.trace() << std::endl;\n\n return true;\n}\n\nbool checkMatrix4x4()\n{\n std::cout << \"------- checkMatrix4x4\" << std::endl;\n EulerAngles e{-0.1, 0.1, M_PI / 2.0};\n\n Matrix4x4 M;\n M.setIdentity();\n M.setRotation(e);\n\n Eigen::Matrix4f& Meig_shallow = eigenView(M);\n \n \n // M(0,1) = 10.0;\n\n Vector trans{0.0, 0.0, 1.0};\n M.setTranslation(trans);\n\n std::cout << Meig_shallow << std::endl;\n\n Matrix4x4 M_inv = M.inv();\n Matrix4x4 I = M_inv * M;\n\n\n std::cout << \"M = \" << std::endl;\n print(M);\n std::cout << \"M_inv = \" << std::endl;\n print(M_inv);\n std::cout << \"(invRigid)=\" << std::endl;\n print(M.invRigid());\n \n std::cout << \"M_inv * M = \" << std::endl;\n print(I);\n\n Eigen::Matrix4f Meig(&M(0,0));\n Eigen::Matrix4f Meig_inv = Meig.inverse();\n\n std::cout << \"Meig = \" << std::endl;\n std::cout << Meig << std::endl;\n\n std::cout << \"Meig_inv = \" << std::endl;\n std::cout << Meig_inv << std::endl;\n\n std::cout << \"Meig_inv * Meig =\" << std::endl;\n std::cout << Meig_inv * Meig << std::endl;\n\n\n std::cout << \"Eigen::Matrix4f stats: \" << std::endl;\n std::cout << \"- det: \" << Meig.determinant() << std::endl;\n std::cout << \"- trace: \" << Meig.trace() << std::endl;\n \n std::cout << \"Matrix4x4 stats:\" << std::endl;\n std::cout << \"- det: \" << M.det() << std::endl;\n std::cout << \"- trace: \" << M.trace() << std::endl;\n\n return true;\n}\n\n\nint main(int argc, char** argv)\n{\n std::cout << \"Rmagine Test: Basic Math\" << std::endl;\n // rotationConversionTest();\n\n\n // checkMatrix3x3();\n // checkMatrix4x4();\n\n Vector ab{1.0, 2.0, 3.0};\n Vector ac{4.0, 5.0, 6.0};\n Vector n{7.0, 8.0, 9.0};\n\n\n Eigen::Matrix3f R;\n R.col(0) = Eigen::Vector3f(ab.x, ab.y, ab.z);\n R.col(1) = Eigen::Vector3f(ac.x, ac.y, ac.z);\n R.col(2) = Eigen::Vector3f(n.x, n.y, n.z);\n\n std::cout << R << std::endl;\n\n R(0,0) = ab.x;\n R(1,0) = ab.y;\n R(2,0) = ab.z;\n\n R(0,1) = ac.x;\n R(1,1) = ac.y;\n R(2,1) = ac.z;\n\n R(0,2) = n.x;\n R(1,2) = n.y;\n R(2,2) = n.z;\n\n std::cout << R << std::endl;\n\n\n return 0;\n}", "meta": {"hexsha": "16d5f1b93dd9517863d2f52cc1b0ce5305e0d50a", "size": 6506, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/rmagine_tests/basic_math/Main.cpp", "max_stars_repo_name": "uos/rmagine", "max_stars_repo_head_hexsha": "b2228d77ea685af050e43c697d3a76535a9d8940", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-30T07:31:03.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T07:31:03.000Z", "max_issues_repo_path": "src/rmagine_tests/basic_math/Main.cpp", "max_issues_repo_name": "uos/rmagine", "max_issues_repo_head_hexsha": "b2228d77ea685af050e43c697d3a76535a9d8940", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/rmagine_tests/basic_math/Main.cpp", "max_forks_repo_name": "uos/rmagine", "max_forks_repo_head_hexsha": "b2228d77ea685af050e43c697d3a76535a9d8940", "max_forks_repo_licenses": ["BSD-3-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.7591973244, "max_line_length": 76, "alphanum_fraction": 0.4875499539, "num_tokens": 2275, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.929440403812707, "lm_q2_score": 0.6959583376458152, "lm_q1q2_score": 0.6468517983783467}} {"text": "/*\n MIT License\n\n Copyright (c) 2021 Zhepei Wang (wangzhepei@live.com)\n\n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n*/\n\n#ifndef GEO_UTILS_HPP\n#define GEO_UTILS_HPP\n\n#include \"quickhull.hpp\"\n#include \"sdlp.hpp\"\n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace geo_utils\n{\n\n // Each row of hPoly is defined by h0, h1, h2, h3 as\n // h0*x + h1*y + h2*z + h3 <= 0\n inline bool findInterior(const Eigen::MatrixX4d &hPoly,\n Eigen::Vector3d &interior)\n {\n const int m = hPoly.rows();\n\n Eigen::MatrixX4d A(m, 4);\n Eigen::VectorXd b(m);\n Eigen::Vector4d c, x;\n const Eigen::ArrayXd hNorm = hPoly.leftCols<3>().rowwise().norm();\n A.leftCols<3>() = hPoly.leftCols<3>().array().colwise() / hNorm;\n A.rightCols<1>().setConstant(1.0);\n b = -hPoly.rightCols<1>().array() / hNorm;\n c.setZero();\n c(3) = -1.0;\n\n const double minmaxsd = sdlp::linprog<4>(c, A, b, x);\n interior = x.head<3>();\n\n return minmaxsd < 0.0 && !std::isinf(minmaxsd);\n }\n\n inline bool overlap(const Eigen::MatrixX4d &hPoly0,\n const Eigen::MatrixX4d &hPoly1,\n const double eps = 1.0e-6)\n\n {\n const int m = hPoly0.rows();\n const int n = hPoly1.rows();\n Eigen::MatrixX4d A(m + n, 4);\n Eigen::Vector4d c, x;\n Eigen::VectorXd b(m + n);\n A.leftCols<3>().topRows(m) = hPoly0.leftCols<3>();\n A.leftCols<3>().bottomRows(n) = hPoly1.leftCols<3>();\n A.rightCols<1>().setConstant(1.0);\n b.topRows(m) = -hPoly0.rightCols<1>();\n b.bottomRows(n) = -hPoly1.rightCols<1>();\n c.setZero();\n c(3) = -1.0;\n\n const double minmaxsd = sdlp::linprog<4>(c, A, b, x);\n\n return minmaxsd < -eps && !std::isinf(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::Matrix3Xd &rV,\n const double &epsilon,\n Eigen::Matrix3Xd &fV)\n {\n const double mag = std::max(fabs(rV.maxCoeff()), fabs(rV.minCoeff()));\n const 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 row of hPoly is defined by h0, h1, h2, h3 as\n // h0*x + h1*y + h2*z + h3 <= 0\n // proposed epsilon is 1.0e-6\n inline void enumerateVs(const Eigen::MatrixX4d &hPoly,\n const Eigen::Vector3d &inner,\n Eigen::Matrix3Xd &vPoly,\n const double epsilon = 1.0e-6)\n {\n const Eigen::VectorXd b = -hPoly.rightCols<1>() - hPoly.leftCols<3>() * inner;\n const Eigen::Matrix A =\n (hPoly.leftCols<3>().array().colwise() / b.array()).transpose();\n\n quickhull::QuickHull qh;\n const 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 const int hNum = idBuffer.size() / 3;\n Eigen::Matrix3Xd 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 row of hPoly is defined by h0, h1, h2, h3 as\n // h0*x + h1*y + h2*z + h3 <= 0\n // proposed epsilon is 1.0e-6\n inline bool enumerateVs(const Eigen::MatrixX4d &hPoly,\n Eigen::Matrix3Xd &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 geo_utils\n\n#endif\n", "meta": {"hexsha": "4d36966f8ce91ab01653da5dcd4a12c6ffcfba80", "size": 6222, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gcopter/include/gcopter/geo_utils.hpp", "max_stars_repo_name": "RENyunfan/GCOPTER", "max_stars_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2022-03-28T11:17:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T11:17:51.000Z", "max_issues_repo_path": "gcopter/include/gcopter/geo_utils.hpp", "max_issues_repo_name": "RENyunfan/GCOPTER", "max_issues_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gcopter/include/gcopter/geo_utils.hpp", "max_forks_repo_name": "RENyunfan/GCOPTER", "max_forks_repo_head_hexsha": "3b49c46b7467fd0b6b1abb2141912a1357e8da39", "max_forks_repo_licenses": ["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.7597765363, "max_line_length": 89, "alphanum_fraction": 0.5515911283, "num_tokens": 1702, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767810736692, "lm_q2_score": 0.7371581510799252, "lm_q1q2_score": 0.6468391615518303}} {"text": "// Boost.Geometry (aka GGL, Generic Geometry Library)\n\n// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.\n// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.\n// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.\n\n// This file was modified by Oracle on 2016-2020.\n// Modifications copyright (c) 2016-2020, Oracle and/or its affiliates.\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_ARITHMETIC_CROSS_PRODUCT_HPP\n#define BOOST_GEOMETRY_ARITHMETIC_CROSS_PRODUCT_HPP\n\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n\nnamespace boost { namespace geometry\n{\n\n#ifndef DOXYGEN_NO_DETAIL\nnamespace detail\n{\n\ntemplate \nstruct cross_product\n{\n // We define cross product only for 2d (see Wolfram) and 3d.\n // In Math, it is also well-defined for 7-dimension.\n // Generalisation of cross product to n-dimension is defined as\n // wedge product but it is not direct analogue to binary cross product.\n BOOST_GEOMETRY_STATIC_ASSERT_FALSE(\n \"Not implemented for this Dimension.\",\n std::integral_constant);\n};\n\ntemplate <>\nstruct cross_product<2>\n{\n template \n static void apply(P1 const& p1, P2 const& p2, ResultP& result)\n {\n assert_dimension();\n assert_dimension();\n assert_dimension();\n\n // For 2-dimensions, analog of the cross product U(x,y) and V(x,y) is\n // Ux * Vy - Uy * Vx\n // which is returned as 0-component (or X) of 2d vector, 1-component is undefined.\n set<0>(result, get<0>(p1) * get<1>(p2) - get<1>(p1) * get<0>(p2));\n }\n};\n\ntemplate <>\nstruct cross_product<3>\n{\n template \n static void apply(P1 const& p1, P2 const& p2, ResultP& result)\n {\n assert_dimension();\n assert_dimension();\n assert_dimension();\n\n set<0>(result, get<1>(p1) * get<2>(p2) - get<2>(p1) * get<1>(p2));\n set<1>(result, get<2>(p1) * get<0>(p2) - get<0>(p1) * get<2>(p2));\n set<2>(result, get<0>(p1) * get<1>(p2) - get<1>(p1) * get<0>(p2));\n }\n\n template \n static constexpr ResultP apply(P1 const& p1, P2 const& p2)\n {\n assert_dimension();\n assert_dimension();\n assert_dimension();\n\n return traits::make::apply(\n get<1>(p1) * get<2>(p2) - get<2>(p1) * get<1>(p2),\n get<2>(p1) * get<0>(p2) - get<0>(p1) * get<2>(p2),\n get<0>(p1) * get<1>(p2) - get<1>(p1) * get<0>(p2));\n }\n};\n\n} // namespace detail\n#endif // DOXYGEN_NO_DETAIL\n\n\n/*!\n\\brief Computes the cross product of two vectors.\n\\details All vectors should have the same dimension, 3 or 2.\n\\ingroup arithmetic\n\\param p1 first vector\n\\param p2 second vector\n\\return the cross product vector\n\n*/\n\ntemplate\n<\n typename ResultP, typename P1, typename P2,\n std::enable_if_t\n <\n dimension::value != 3\n || ! traits::make::is_specialized,\n int\n > = 0\n>\ninline ResultP cross_product(P1 const& p1, P2 const& p2)\n{\n BOOST_CONCEPT_ASSERT( (concepts::Point) );\n BOOST_CONCEPT_ASSERT( (concepts::ConstPoint) );\n BOOST_CONCEPT_ASSERT( (concepts::ConstPoint) );\n\n ResultP result;\n detail::cross_product::value>::apply(p1, p2, result);\n return result;\n}\n\ntemplate\n<\n typename ResultP, typename P1, typename P2,\n std::enable_if_t\n <\n dimension::value == 3\n && traits::make::is_specialized,\n int\n > = 0\n>\n// workaround for VS2015\n#if !defined(_MSC_VER) || (_MSC_VER >= 1910)\nconstexpr\n#endif\ninline ResultP cross_product(P1 const& p1, P2 const& p2)\n{\n BOOST_CONCEPT_ASSERT((concepts::Point));\n BOOST_CONCEPT_ASSERT((concepts::ConstPoint));\n BOOST_CONCEPT_ASSERT((concepts::ConstPoint));\n\n return detail::cross_product<3>::apply(p1, p2);\n}\n\n/*!\n\\brief Computes the cross product of two vectors.\n\\details All vectors should have the same dimension, 3 or 2.\n\\ingroup arithmetic\n\\param p1 first vector\n\\param p2 second vector\n\\return the cross product vector\n\n\\qbk{[heading Examples]}\n\\qbk{[cross_product] [cross_product_output]}\n*/\ntemplate\n<\n typename P,\n std::enable_if_t\n <\n dimension

::value != 3\n || ! traits::make

::is_specialized,\n int\n > = 0\n>\ninline P cross_product(P const& p1, P const& p2)\n{\n BOOST_CONCEPT_ASSERT((concepts::Point

));\n BOOST_CONCEPT_ASSERT((concepts::ConstPoint

));\n\n P result;\n detail::cross_product::value>::apply(p1, p2, result);\n return result;\n}\n\n\ntemplate\n<\n typename P,\n std::enable_if_t\n <\n dimension

::value == 3\n && traits::make

::is_specialized,\n int\n > = 0\n>\n// workaround for VS2015\n#if !defined(_MSC_VER) || (_MSC_VER >= 1910)\nconstexpr\n#endif\ninline P cross_product(P const& p1, P const& p2)\n{\n BOOST_CONCEPT_ASSERT((concepts::Point

));\n BOOST_CONCEPT_ASSERT((concepts::ConstPoint

));\n\n return detail::cross_product<3>::apply

(p1, p2);\n}\n\n\n}} // namespace boost::geometry\n\n#endif // BOOST_GEOMETRY_ARITHMETIC_CROSS_PRODUCT_HPP\n", "meta": {"hexsha": "9172a7e5778ec18196d079f34432d73e1370fb95", "size": 5858, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/arithmetic/cross_product.hpp", "max_stars_repo_name": "Harshitha91/Tmdb-react-native-node", "max_stars_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 326.0, "max_stars_repo_stars_event_min_datetime": "2015-02-08T13:47:49.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-16T02:13:59.000Z", "max_issues_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/arithmetic/cross_product.hpp", "max_issues_repo_name": "Harshitha91/Tmdb-react-native-node", "max_issues_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 623.0, "max_issues_repo_issues_event_min_datetime": "2015-01-02T23:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-09T11:15:23.000Z", "max_forks_repo_path": "ReactNativeFrontend/ios/Pods/boost/boost/geometry/arithmetic/cross_product.hpp", "max_forks_repo_name": "Harshitha91/Tmdb-react-native-node", "max_forks_repo_head_hexsha": "e06e3f25a7ee6946ef07a1f524fdf62e48424293", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 215.0, "max_forks_repo_forks_event_min_datetime": "2015-01-14T15:50:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-23T03:58:36.000Z", "avg_line_length": 27.7630331754, "max_line_length": 90, "alphanum_fraction": 0.6555138272, "num_tokens": 1673, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7490872187162397, "lm_q1q2_score": 0.6467556092457871}} {"text": "// Statistical Computing //\r\n// Load typical packages\r\n\r\n#include\r\n#include\r\n#include\r\n\r\n// Typiccal C libraries\r\n#include\r\n#include\r\n\r\n// C++ Data Structures\r\n#include\r\n#include\r\n#include\r\n\r\n// Include Eigen Package for Matrices\r\n#include \r\n\r\n// Load Matrix615 header file to read in from file\r\n#include \"Matrix615.h\"\r\n\r\nusing namespace std;\r\n// we avoid using namespace Eigen to be able to clearly see where we are calling the Eigen Package\r\n\r\n// Driver Code\r\nint main(int argc, char* argv[]) {\r\n\r\n\t// Steps corresponding to the commented code is associated with the following documents:\r\n\t\r\n\t// Tentative Read Matrix using Matrix615.h\r\n\t\r\n\tMatrix615 read_Design; // throw-away Matrices to read in data\r\n\tMatrix615 read_Y;\r\n\tMatrix615 read_ID;\r\n\r\n\t// Read the data in\r\n\tread_Design.readFromFile(argv[3]); // t\r\n\tread_Y.readFromFile(argv[2]);\r\n\tread_ID.readFromFile(argv[1]);\r\n\r\n\t// Step (1): Store the design matrix, response, and Id into an Eigen Matrix\r\n\tEigen::MatrixXd\tdesign_X;\r\n\tEigen::MatrixXd outcome_Y;\r\n\r\n\tread_Design.cloneToEigen(design_X);\r\n\tread_Y.cloneToEigen(outcome_Y);\r\n\r\n\t\r\n\r\n\t// cout << Weights.rows() << endl << endl;\r\n\t// cout << Weights << endl;\r\n\tEigen::MatrixXd Weights(outcome_Y.rows(), 1);\r\n\tWeights.setOnes();\r\n\r\n\tif (int (argc) == 5) {\r\n\t\tMatrix615 read_Weights;\r\n\t\tread_Weights.readFromFile(argv[4]);\r\n\r\n\t\tEigen::MatrixXd Weights;\r\n\t\tread_Weights.cloneToEigen(Weights);\r\n\t}\r\n\r\n\t// else {\r\n\t// \tEigen::MatrixXd Weights(outcome_Y.rows(), 1);\r\n\t// \tWeights.setOnes();\r\n\t// }\r\n\r\n\t// cout << design_X.rows() << \" \" << design_X.cols() << endl << endl;\r\n\t// cout << design_X << endl << endl << endl;\r\n\t// cout << outcome_Y.rows() << \" \" << outcome_Y.cols() << endl << endl;\r\n\t// cout << outcome_Y << endl << endl << endl;\r\n\r\n\t// Step (2): Count number of unique ID's, patients\r\n\tEigen::MatrixXd ID_Mat;\r\n\tread_ID.cloneToEigen(ID_Mat);\r\n\r\n\tstd::set unique_ID; // to dynamically count n\r\n\tstd::map id_map; // to dynamically count m\r\n\tstd::map weight_map;\r\n\r\n\tfor (int i = 0; i < int(ID_Mat.rows()); ++i) {\r\n\t\tunique_ID.insert( ID_Mat(i,0) );\r\n\t\tid_map[ID_Mat(i, 0)] += 1;\r\n\t\tweight_map[ID_Mat(i, 0)] = Weights(i, 0); \r\n\t}\r\n\r\n\tint n = int( unique_ID.size() );\r\n\t// int m = int( id_map[ID_Mat(1,0)] );\r\n\r\n\t// q = (p + 1) : # number of paramters to be estimated using GEE\r\n\tint q = int ( design_X.cols() );\r\n\r\n\t// Correlation Structure\r\n\r\n\t// Step : Weights\r\n\r\n\t// Step (3): Initialize betas *********** Should we incorporate the beta's that come from a fast linear regression or no?\r\n\r\n\tEigen::MatrixXd Betas_new(q , 1); // dimensions (p+1) x 1\r\n\tBetas_new.setZero();\r\n\r\n\t// cout << \"Betas ***********************\" << endl;\r\n\t// cout << Betas_new << endl << endl;\r\n\r\n\t// Step (4): Initialize rho and phi (rho: off diagonals of correlation structure & phi: )\r\n\tdouble rho = 0.0;\r\n\t// double phi = 0.0;\r\n\r\n\t// Step (5): Set up variables for iteration convergence check\r\n\r\n\t// Should we make this dynamic? \r\n\r\n\tdouble diff_beta = 1; // updated difference in beta estimation {beta (new) - beta (old)}\r\n\t\r\n\tdouble diff_threshold = 0.00000010; // threshold for the update difference in betas\r\n\t\r\n\tint iteration_threshold = 1000; // threshold on how many iterations there will be\r\n\r\n\t// Step (6): Initialize the iteration\r\n\tint iteration_count = 0;\r\n\r\n\t// Step (7): Assign appropriate value to n*\r\n\t// double n_star = (0.5) * double(n) * double(m) * double(m - 1);\r\n\r\n\t// double n_star = (0.5) * double(n) * double(5) * double(5 - 1);\r\n\r\n\t// cout << \" n* is \" << n_star << endl;\r\n\r\n\tdouble n_star_sum = 0.0;\r\n\r\n\t// Step (8): Start the GEE Estimation\r\n\r\n\tEigen::MatrixXd Betas_updated = Betas_new;\r\n\r\n\tEigen::MatrixXd sandwhich_Mat;\r\n\r\n\t// cout << Betas_updated << endl << endl;\r\n\r\n\twhile ( (diff_beta > diff_threshold) && (iteration_count < iteration_threshold) ) {\r\n\t\t// (1)\r\n\t\tBetas_updated = Betas_new;\r\n\r\n\t\t// (2) Vector EE ((p+1) x 1)\r\n\t\tEigen::MatrixXd EE(q , 1);\r\n\t\tEE.setZero();\r\n\r\n\t\t// (3) Matrix GI ( (p+1) x (p+1) )\r\n\t\t// First derivative of EE; Model-based Variance\r\n\t\tEigen::MatrixXd GI(q , q);\r\n\t\tGI.setZero();\r\n\r\n\t\t// (4) Matrix G ( (p+1) x (p+1) )\r\n\t\t// Meat of the Sandwhich Estimator\r\n\t\tEigen::MatrixXd G(q , q);\r\n\t\tG.setZero();\t\t\r\n\r\n\t\t// (5) Initialize phi(sum) and tau(sum)\r\n\t\tdouble phi_sum = 0.0;\r\n\t\tdouble tau_sum = 0.0;\r\n\r\n\t\t// (6) Initialize start and end\r\n\t\tint start = 0;\r\n\t\tint end = -1;\r\n\r\n\t\t// inner loop in while loop Time-Complexity: O(n^2)??\r\n\r\n\t\tfor (int i = 0; i < n; ++i) {\r\n\r\n\t\t\tint m = id_map[i + 1];\r\n\t\t\tstart = end + 1;\r\n\t\t\tend = start + m - 1;\r\n\r\n\t\t\t//update n*\r\n\t\t\tn_star_sum = n_star_sum + (0.5) * double(m) * double(double(m) - 1.0);\r\n\r\n\t\t\t// assign mu_i ( m x (p+1) ) for ith person\r\n\t\t\t// Eigen.block(starting_row = , starting_col = , dim_row = , dim_col = )\r\n\t\t\tEigen::MatrixXd mu_i = design_X.block(start, 0, m, q) * Betas_updated;\r\n\r\n\t\t\t// assign r_i (m x 1)\r\n\t\t\tEigen::MatrixXd r_i = outcome_Y.block(start, 0, m, 1) - mu_i;\r\n\r\n\t\t\t// Loop to update phi-sum\r\n\t\t\tfor (int j = 0; j < int(m); ++j) phi_sum = phi_sum + (r_i(j,0) * r_i(j,0));\r\n\r\n\t\t\t// Loop to update tau-sum\r\n\t\t\tfor (int j = 0; j < int(m - 1); ++j) {\r\n\t\t\t\tfor (int k = (j + 1); k < m; ++k) tau_sum = tau_sum + r_i(j,0) * r_i(k, 0);\r\n\t\t\t}\r\n\r\n\t\t\t// create R matrix (m x m) for each observation/patient\r\n\t\t\tEigen::MatrixXd R(m, m);\r\n\t\t\tR.setConstant(rho); // off-diagonals will be rho\r\n\t\t\tfor (int d = 0; d < int(m); ++d) R(d, d) = 1; //diagonals will be 1\r\n\r\n\t\t\t// update EE ((p+1) x 1)\r\n\t\t\tEE = EE + ((design_X.block(start, 0, m, q).transpose()) * (R.inverse() * (weight_map[i+1] * r_i) )); // weight_map\r\n\r\n\t\t\t// update GI ((p+1) x (p+1)) or (q x q)\r\n\t\t\tGI = GI + ((design_X.block(start, 0, m, q).transpose()) * R.inverse() * design_X.block(start, 0, m, q));\r\n\r\n\t\t\t// update G ((p+1) x (p+1)) or (q x q)\r\n\t\t\tG = G + ((design_X.block(start, 0, m, q).transpose()) *\r\n\t\t\t\t( ((R.inverse()) * r_i) * (r_i.transpose()*(R.inverse())) ) * design_X.block(start, 0, m, q));\r\n\t\t}\r\n\r\n\t\t// Update beta using either Newton Raphson or Gradient Boosting *** we can add an if statement\r\n\t\tBetas_new = Betas_updated + ( GI.inverse() * EE);\r\n\r\n\t\t// calculate the difference in the betas\r\n\t\tdiff_beta = (Betas_new - Betas_updated).norm();\r\n\r\n\t\t// update rho\r\n\t\trho = ( (( double(n) - double(q) ) * tau_sum) / ( (double(n_star_sum) - double(q) ) * phi_sum) );\r\n\r\n\r\n\t\tsandwhich_Mat = GI.inverse() * G * GI.inverse();\r\n\t\t// increment iteration count\r\n\t\titeration_count += 1;\r\n\t}\r\n\r\n\tcout << endl << \"Estimated Betas are: \" << endl;\r\n\tcout << Betas_new.transpose() << endl << endl << endl;\r\n\r\n\t// cout << \"The sandwhich matrix is: \" << endl << endl;\r\n\t// cout << sandwhich_Mat << endl << endl;\r\n\r\n\tcout << \"The beta Robust S.E.'s are: \" << endl << endl;\r\n\tcout << sandwhich_Mat.diagonal().array().sqrt() << endl << endl;\r\n\t\r\n\treturn 0;\r\n\r\n}", "meta": {"hexsha": "29cd6bd27c6dd60ac1407795c9794b54f6c7412c", "size": 6874, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "gee/geec_oneloop.cpp", "max_stars_repo_name": "hengshiyu/geeCpp", "max_stars_repo_head_hexsha": "bdcc54dd7fc0c28e4d27326c52670f2c4b2e0ede", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gee/geec_oneloop.cpp", "max_issues_repo_name": "hengshiyu/geeCpp", "max_issues_repo_head_hexsha": "bdcc54dd7fc0c28e4d27326c52670f2c4b2e0ede", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gee/geec_oneloop.cpp", "max_forks_repo_name": "hengshiyu/geeCpp", "max_forks_repo_head_hexsha": "bdcc54dd7fc0c28e4d27326c52670f2c4b2e0ede", "max_forks_repo_licenses": ["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.3760683761, "max_line_length": 123, "alphanum_fraction": 0.6012510911, "num_tokens": 2110, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.863391595913457, "lm_q2_score": 0.7490872131147276, "lm_q1q2_score": 0.6467556044094885}} {"text": "#pragma once\r\n\r\n\r\n#include \r\n\r\nclass CubicKernel\r\n{\r\npublic:\r\n\t double getRadius() { return m_radius; }\r\n\t void setRadius(double val)\r\n\t{\r\n\t\tm_radius = val;\r\n\t\tconst double pi = static_cast(M_PI);\r\n\r\n\t\tconst double 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(Eigen::Vector3d::Zero());\r\n\t}\r\n\r\npublic:\r\n\tdouble W(Eigen::Vector3d const& r)\r\n\t{\r\n\t\tdouble res = 0.0;\r\n\t\tconst double rl = r.norm();\r\n\t\tconst double 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 double q2 = q*q;\r\n\t\t\t\tconst double 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\tEigen::Vector3d gradW(const Eigen::Vector3d &r)\r\n\t{\r\n\t\tusing namespace Eigen;\r\n\t\tVector3d res;\r\n\t\tconst double rl = r.norm();\r\n\t\tconst double 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 Vector3d gradq = r * ((double) 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*((double) 3.0*q - (double) 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 double 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\tdouble W_zero()\r\n\t{\r\n\t\treturn m_W_zero;\r\n\t}\r\n\r\nprivate:\r\n\tdouble m_radius;\r\n\tdouble m_k;\r\n\tdouble m_l;\r\n\tdouble m_W_zero;\r\n};\r\n", "meta": {"hexsha": "9f22fc2c0d980d3d65f005da3de15e608ac2535e", "size": 1417, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "cmd/generate_density_map/sph_kernel.hpp", "max_stars_repo_name": "digitalillusions/Discregrid", "max_stars_repo_head_hexsha": "af5880ecfa62c736a25e23a607bd8bd51d833fe2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 214.0, "max_stars_repo_stars_event_min_datetime": "2017-11-10T11:53:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T16:24:01.000Z", "max_issues_repo_path": "cmd/generate_density_map/sph_kernel.hpp", "max_issues_repo_name": "digitalillusions/Discregrid", "max_issues_repo_head_hexsha": "af5880ecfa62c736a25e23a607bd8bd51d833fe2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 16.0, "max_issues_repo_issues_event_min_datetime": "2018-02-20T07:53:03.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T14:03:11.000Z", "max_forks_repo_path": "cmd/generate_density_map/sph_kernel.hpp", "max_forks_repo_name": "digitalillusions/Discregrid", "max_forks_repo_head_hexsha": "af5880ecfa62c736a25e23a607bd8bd51d833fe2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47.0, "max_forks_repo_forks_event_min_datetime": "2017-11-19T05:42:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T11:55:09.000Z", "avg_line_length": 17.0722891566, "max_line_length": 63, "alphanum_fraction": 0.5299929428, "num_tokens": 507, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7341195269001831, "lm_q1q2_score": 0.646610338774384}} {"text": "#include \n#include \n\nnamespace vpp\n{\n\n // http://www.cse.psu.edu/~rcollins/CSE486/lecture19_6pp.pdf\n // Page 5.\n inline vfloat2 epipole_left(const Eigen::Matrix3f& F)\n {\n // F e_l = 0.\n Eigen::EigenSolver es(F.cast().transpose() * F.cast());\n\n auto values = es.eigenvalues();\n auto vectors = es.eigenvectors();\n vdouble2 epipole;\n double min_ev = FLT_MAX;\n for (int i = 0; i < values.size(); i++)\n if (values[i].real() < min_ev)\n {\n min_ev = values[i].real();\n auto vc = vectors.col(i);\n epipole[0] = vc[0].real();\n epipole[1] = vc[1].real();\n epipole /= double(vc[2].real());\n }\n\n return epipole.cast();\n }\n\n // http://www.cse.psu.edu/~rcollins/CSE486/lecture19_6pp.pdf\n // Page 5.\n inline vfloat2 epipole_right(const Eigen::Matrix3f& F)\n {\n // e_r F = 0.\n Eigen::EigenSolver es(F.cast() * F.cast().transpose());\n\n\n auto values = es.eigenvalues();\n auto vectors = es.eigenvectors();\n vdouble2 epipole;\n double min_ev = FLT_MAX;\n for (int i = 0; i < values.size(); i++)\n if (values[i].real() < min_ev)\n {\n min_ev = values[i].real();\n auto vc = vectors.col(i);\n epipole[0] = vc[0].real();\n epipole[1] = vc[1].real();\n epipole /= double(vc[2].real());\n }\n\n return epipole.cast();\n }\n}\n", "meta": {"hexsha": "e55cd4459142e9a97c4cf8da0383c8a36d059776", "size": 1454, "ext": "hh", "lang": "C++", "max_stars_repo_path": "vpp/algorithms/epipolar_geometry.hh", "max_stars_repo_name": "jjzhang166/videopp", "max_stars_repo_head_hexsha": "f1421b16b8ffcefb3d1697460940d868e31ba79d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 624.0, "max_stars_repo_stars_event_min_datetime": "2015-01-05T16:40:41.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-01T03:09:43.000Z", "max_issues_repo_path": "vpp/algorithms/epipolar_geometry.hh", "max_issues_repo_name": "jjzhang166/videopp", "max_issues_repo_head_hexsha": "f1421b16b8ffcefb3d1697460940d868e31ba79d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 10.0, "max_issues_repo_issues_event_min_datetime": "2015-01-22T20:50:13.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-15T10:41:34.000Z", "max_forks_repo_path": "vpp/algorithms/epipolar_geometry.hh", "max_forks_repo_name": "jjzhang166/videopp", "max_forks_repo_head_hexsha": "f1421b16b8ffcefb3d1697460940d868e31ba79d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 113.0, "max_forks_repo_forks_event_min_datetime": "2015-01-19T11:58:35.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T05:15:20.000Z", "avg_line_length": 25.9642857143, "max_line_length": 92, "alphanum_fraction": 0.5715268226, "num_tokens": 456, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6466103285270899}} {"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 // TO DO (13-1.e): solve the cross-product ODE with the implicit RK method\n // defined in solve_imp_mid. Tabulate the norms of the results at all steps.\n double T = 10.;\n int N = 128;\n // set data\n double c = 1.;\n Eigen::Vector3d y0(1., 1., 1.);\n Eigen::Vector3d a(1., 0., 0.);\n\n // define rhs\n auto f = [a, c](Eigen::Vector3d y) -> Eigen::Vector3d {\n return a.cross(y) + c * y.cross(a.cross(y));\n };\n // define Jacobian of rhs\n auto Jf = [a, c](Eigen::Vector3d y) -> Eigen::Matrix3d {\n Eigen::Matrix3d temp;\n temp << -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 temp;\n };\n\n std::vector res_imp = solve_imp_mid(f, Jf, T, y0, N);\n\n std::cout << \"1. Implicit midpoint method\" << std::endl;\n std::cout << std::setw(10) << \"t\" << std::setw(15) << \"norm(y(t))\"\n << std::endl;\n\n for (int i = 0; i < N + 1; ++i) {\n std::cout << std::setw(10) << T * i / N << std::setw(15)\n << res_imp[i].norm() << std::endl;\n }\n /* SAM_LISTING_END_0 */\n\n /* SAM_LISTING_BEGIN_1 */\n // TO DO (13-1.g): solve the cross-product ODE with the implicit RK method\n // defined in solve_lin_mid. Tabulate the norms of the results at all steps.\n std::vector res_lin = solve_lin_mid(f, Jf, T, y0, N);\n\n std::cout << \"\\n2. Linear implicit midpoint method\" << std::endl;\n std::cout << std::setw(10) << \"t\" << std::setw(15) << \"norm(y(t))\"\n << std::endl;\n for (int i = 0; i < N + 1; ++i) {\n std::cout << std::setw(10) << T * i / N << std::setw(15)\n << res_lin[i].norm() << std::endl;\n }\n /* SAM_LISTING_END_1 */\n}\n\n} // namespace CrossProd\n", "meta": {"hexsha": "dc247a895e73c2ad9b41bdf29b35081f1ddd1344", "size": 2371, "ext": "cc", "lang": "C++", "max_stars_repo_path": "homeworks/CrossProd/mastersolution/crossprod.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "homeworks/CrossProd/mastersolution/crossprod.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "homeworks/CrossProd/mastersolution/crossprod.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.1973684211, "max_line_length": 78, "alphanum_fraction": 0.5229860818, "num_tokens": 892, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8289388040954683, "lm_q2_score": 0.7799929002541068, "lm_q1q2_score": 0.6465663819395951}} {"text": "#include \"problemes.h\"\n#include \"arithmetique.h\"\n#include \"graphe.h\"\n\n#include \n#include \n#include \n\ntypedef unsigned long long nombre;\ntypedef std::vector vecteur;\n\ntypedef std::pair paire;\n\nENREGISTRER_PROBLEME(107, \"Minimal network\") {\n // The following undirected network consists of seven vertices and twelve edges with a total weight of 243.\n //\n //\n // The same network can be represented by the matrix below.\n //\n // \tA\tB\tC\tD\tE\tF\tG\n // A\t-\t16\t12\t21\t-\t-\t-\n // B\t16\t-\t-\t17\t20\t-\t-\n // C\t12\t-\t-\t28\t-\t31\t-\n // D\t21\t17\t28\t-\t18\t19\t23\n // E\t-\t20\t-\t18\t-\t-\t11\n // F\t-\t-\t31\t19\t-\t-\t27\n // G\t-\t-\t-\t23\t11\t27\t-\n //\n // However, it is possible to optimise the network by removing some edges and still ensure that all points on the\n // network remain connected. The network which achieves the maximum saving is shown below. It has a weight of 93,\n // representing a saving of 243 − 93 = 150 from the original network.\n //\n // Using network.txt (right click and 'Save Link/Target As...'), a 6K text file containing a network with forty\n // vertices, and given in matrix form, find the maximum saving which can be achieved by removing redundant edges\n // whilst ensuring that the network remains connected.\n std::ifstream ifs(\"data/p107_network.txt\");\n\n graphe::Kruskal::aretes A;\n nombre i = 0;\n std::string ligne;\n while (ifs >> ligne) {\n std::vector strings;\n boost::split(strings, ligne, boost::is_any_of(\",\"));\n\n nombre j = 0;\n for (auto &s: strings) {\n if (s != \"-\" && i < j)\n A.emplace_back(i, j, std::stoull(s));\n ++j;\n }\n ++i;\n }\n\n graphe::Kruskal kruskal(A);\n auto arbre_mini = kruskal.algorithme();\n\n auto somme_poids = [](const nombre &r, const graphe::Kruskal::arete &a) { return r + std::get<2>(a); };\n\n nombre resultat = std::accumulate(A.begin(), A.end(), 0ull, somme_poids) -\n std::accumulate(arbre_mini.begin(), arbre_mini.end(), 0ull, somme_poids);\n return std::to_string(resultat);\n}\n", "meta": {"hexsha": "193d824af71b223a9a0f1c788bd3ca97560070a0", "size": 2212, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "problemes/probleme1xx/probleme107.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/probleme107.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/probleme107.cpp", "max_forks_repo_name": "ZongoForSpeed/ProjectEuler", "max_forks_repo_head_hexsha": "2e2d45f984d48a1da8275886c976f909a0de94ce", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1111111111, "max_line_length": 117, "alphanum_fraction": 0.6021699819, "num_tokens": 641, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711794579723, "lm_q2_score": 0.7606506472514406, "lm_q1q2_score": 0.646531127799777}} {"text": "// Created by dinies on 03/07/2018.\n\n//Collection of static functions and useful types to perform geometric computations\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace MultiRobot{\n class MyMath{\n\n public:\n // static Eigen::Isometry2d v2t(const std::vector &t_vec);\n // static std::vector t2v(const Eigen::Isometry2d& t_transf);\n\n static Eigen::Isometry2d v2t(const Eigen::Vector3d &t_vec);\n static Eigen::Vector3d t2v(const Eigen::Isometry2d& t_transf);\n\n static void rotate2D( Eigen::Vector2d &t_point, const double t_angle_rad );\n\n static std::vector vecSum(const std::vector &t_first,const std::vector &t_second);\n\n static std::vector vecMultEleWise(const std::vector &t_first,const std::vector &t_second);\n\n static double boxMinusAngleRad(const double t_ref,const double t_actual);\n static double boxPlusAngleRad(const double t_ref,const double t_actual);\n static double computeAvg(const double t_prevAvg,const int t_numEntries,const double t_newValue);\n };\n}\n", "meta": {"hexsha": "acf23643c5fea0b71ec5768b522fd835aaa5caa4", "size": 1145, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "code/src/utils/MyMath.hpp", "max_stars_repo_name": "dinies/MultiRobot", "max_stars_repo_head_hexsha": "eaf3cb34ce7baf5653bf54b31bffe02426885060", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/src/utils/MyMath.hpp", "max_issues_repo_name": "dinies/MultiRobot", "max_issues_repo_head_hexsha": "eaf3cb34ce7baf5653bf54b31bffe02426885060", "max_issues_repo_licenses": ["MIT"], "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/utils/MyMath.hpp", "max_forks_repo_name": "dinies/MultiRobot", "max_forks_repo_head_hexsha": "eaf3cb34ce7baf5653bf54b31bffe02426885060", "max_forks_repo_licenses": ["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.696969697, "max_line_length": 118, "alphanum_fraction": 0.7493449782, "num_tokens": 291, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.849971175657575, "lm_q2_score": 0.7606506418255927, "lm_q1q2_score": 0.646531120297188}} {"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\nPlotView *createPlotView(const std::string& title, const std::string& xLabel, const std::string yLabel, const PRectF& viewRange);\n\ntypedef std::vector Data;\ntypedef std::vector XList;\ntypedef std::vector YList;\n\nData readData(const std::string& file);\nHist1D binData(const Data& data);\nTable tableData(const Data& data);\n\nconst std::string dataFileName = \"../data01.dat\";\nconst std::string coarseResultFile = \"coarse-result.dat\";\nconst double nBin = 400;\nconst bool verbose = false;\nconst int SUCCESS = 3;\nconst size_t nTrial = 100;\nconst double wScale = 0.05;\nconst double nEffTrial = 1 * nTrial;\nconst double Precision = 32;\n\n// Coarse Search\nconst double fMin = 0.01;\nconst double fMax = 0.99;\nconst double mu1Min = 80;\nconst double mu1Max = 120;\nconst double mu2Min = mu1Min;\nconst double mu2Max = mu1Max;\nconst double gamma1Min = 0.01;\nconst double gamma1Max = 1;\nconst double gamma2Min = gamma1Min;\nconst double gamma2Max = gamma1Max;\nconst double pNBins = 200;\nconst std::string searchType = \"Coarse\";\nconst std::string fileExt = searchType + \".png\";\n\n\nint main(int argc, char **argv)\n{\n QApplication app(argc, argv);\n MultipleViewWindow window;\n\n Genfun::Square qPow2;\n Genfun::Sqrt qSqrt;\n Genfun::Exp qExp;\n\n const Data data = readData(dataFileName);\n Hist1D dataHist = binData(data);\n Table dataTable = tableData(data);\n TableLikelihoodFunctional objFunc(dataTable);\n Genfun::Variable X = dataTable.symbol(\"E\");\n\n// Prepare View\n const double viewXMin = dataHist.binLowerEdge(0) - 10;\n const double viewXMax = dataHist.binUpperEdge(nBin-1) + 10;\n const double viewYMin = 1e-2;\n const double viewYMax = dataHist.maxContents() * 3;\n PRectF viewRange(viewXMin, viewXMax, viewYMin, viewYMax);\n PlotView *view = createPlotView(\"Spectrum\", \"Energy / eV\", \"\", viewRange);\n view->setLogY(true);\n window.add(view, \"Fit\");\n\n PlotKey legend(viewXMin, viewYMax);\n legend.setFont(QFont(\"Times\", 25, QFont::Bold));\n view->add(&legend);\n\n// Plot Data\n PlotHist1D dataHistPlot(dataHist);\n {\n PlotHist1D::Properties prop;\n prop.plotStyle = PlotHist1D::Properties::SYMBOLS;\n prop.symbolSize = 10;\n prop.pen.setWidth(1.9);\n dataHistPlot.setProperties(prop);\n }\n view->add(&dataHistPlot);\n legend.add(&dataHistPlot, \"Data\");\n\n\n// Lorentz Fit\n Genfun::Parameter pMu1(\"Mu1\", 80, dataHist.min(), dataHist.max());\n Genfun::Parameter pMu2(\"Mu2\", 120, dataHist.min(), dataHist.max());\n Genfun::Parameter pGamma1(\"Gamma1\", 0.5, 0, 10*std::sqrt(dataHist.variance()));\n Genfun::Parameter pGamma2(\"Gamma2\", 0.5, 0, 10*std::sqrt(dataHist.variance()));\n Genfun::Parameter pF(\"fraction\", 0.5, 0, 1);\n\n Genfun::GENFUNCTION LorentzPDF1 = 1 / (M_PI * pGamma1 * (1 + qPow2((X - pMu1)/pGamma1)));\n Genfun::GENFUNCTION LorentzPDF2 = 1 / (M_PI * pGamma2 * (1 + qPow2((X - pMu2)/pGamma2)));\n Genfun::GENFUNCTION Lorentz = dataHist.sum() * (pF * LorentzPDF1 + (1-pF) * LorentzPDF2);\n\n std::cout << searchType + \" Search\" << std::endl;\n\n std::random_device rndDev;\n std::mt19937_64 rndEng(rndDev());\n std::uniform_real_distribution mu1Dist(mu1Min, mu1Max);\n std::uniform_real_distribution mu2Dist(mu2Min, mu2Max);\n std::uniform_real_distribution gamma1Dist(gamma1Min, gamma1Max);\n std::uniform_real_distribution gamma2Dist(gamma2Min, gamma2Max);\n std::uniform_real_distribution fDist(fMin, fMax);\n Hist1D mu1Hist(\"Mu1\", pNBins, mu1Min, mu1Max);\n Hist1D mu2Hist(\"Mu2\", pNBins, mu2Min, mu2Max);\n Hist1D gamma1Hist(\"Gamma1\", pNBins, gamma1Min, gamma1Max);\n Hist1D gamma2Hist(\"Gamma2\", pNBins, gamma2Min, gamma2Max);\n Hist1D fHist(\"Fraction\", pNBins, fMin, fMax);\n double count = nTrial;\n while (count > 0)\n {\n double mu10 = mu1Dist(rndEng);\n double mu20 = mu2Dist(rndEng);\n double gamma10 = gamma1Dist(rndEng);\n double gamma20 = gamma2Dist(rndEng);\n double f0 = fDist(rndEng);\n\n pMu1.setValue(mu10);\n pMu2.setValue(mu20);\n pGamma1.setValue(gamma10);\n pGamma2.setValue(gamma20);\n pF.setValue(f0);\n\n MinuitMinimizer lorentzMinimizer(verbose);\n lorentzMinimizer.addParameter(&pMu1);\n lorentzMinimizer.addParameter(&pMu2);\n lorentzMinimizer.addParameter(&pGamma1);\n lorentzMinimizer.addParameter(&pGamma2);\n lorentzMinimizer.addParameter(&pF);\n lorentzMinimizer.addStatistic(&objFunc, &Lorentz);\n lorentzMinimizer.minimize();\n \n if (lorentzMinimizer.getStatus() == SUCCESS)\n {\n --count;\n\n Eigen::MatrixXd errMat = lorentzMinimizer.getErrorMatrix();\n double weight = wScale / std::sqrt(errMat.trace());\n \n if (pMu1.getValue() <= pMu2.getValue())\n {\n mu1Hist.accumulate(pMu1.getValue(), weight);\n mu2Hist.accumulate(pMu2.getValue(), weight);\n gamma1Hist.accumulate(pGamma1.getValue(), weight);\n gamma2Hist.accumulate(pGamma2.getValue(), weight);\n fHist.accumulate(pF.getValue(), weight);\n }else\n {\n mu1Hist.accumulate(pMu2.getValue(),weight);\n mu2Hist.accumulate(pMu1.getValue(), weight);\n gamma1Hist.accumulate(pGamma2.getValue(), weight);\n gamma2Hist.accumulate(pGamma1.getValue(), weight);\n fHist.accumulate(1 - pF.getValue(), weight);\n }\n }\n }\n \n std::cout << \"Mu1 :\" << mu1Hist.mean() << \" +/- \" << std::sqrt(mu1Hist.variance()) << std::endl;\n std::cout << \"Mu2 :\" << mu2Hist.mean() << \" +/- \" << std::sqrt(mu2Hist.variance()) << std::endl;\n std::cout << \"Gamma1 :\" << gamma1Hist.mean() << \" +/- \" << std::sqrt(gamma1Hist.variance()) << std::endl;\n std::cout << \"Gamma2 :\" << gamma2Hist.mean() << \" +/- \" << std::sqrt(gamma2Hist.variance()) << std::endl;\n std::cout << \"Fraction :\" << fHist.mean() << \" +/- \" << std::sqrt(fHist.variance()) << std::endl;\n\n std::ofstream oFile(coarseResultFile);\n oFile << std::setprecision(Precision) << mu1Hist.mean() << \"\\t\";\n oFile << std::setprecision(Precision) << std::sqrt(mu1Hist.variance()) << std::endl;\n oFile << std::setprecision(Precision) << mu2Hist.mean() << \"\\t\";\n oFile << std::setprecision(Precision) << std::sqrt(mu2Hist.variance()) << std::endl;\n oFile << std::setprecision(Precision) << gamma1Hist.mean() << \"\\t\";\n oFile << std::setprecision(Precision) << std::sqrt(gamma1Hist.variance()) << std::endl;\n oFile << std::setprecision(Precision) << gamma2Hist.mean() << \"\\t\";\n oFile << std::setprecision(Precision) << std::sqrt(gamma2Hist.variance()) << std::endl;\n oFile << std::setprecision(Precision) << fHist.mean() << \"\\t\";\n oFile << std::setprecision(Precision) << std::sqrt(fHist.variance()) << std::endl;\n oFile.close();\n\n pMu1.setValue(mu1Hist.mean());\n pMu2.setValue(mu2Hist.mean());\n pGamma1.setValue(gamma1Hist.mean());\n pGamma2.setValue(gamma2Hist.mean());\n pF.setValue(fHist.mean());\n\n \n PlotFunction1D LorentzPlot(Lorentz);\n {\n PlotFunction1D::Properties prop;\n prop.pen.setWidth(2);\n prop.pen.setColor(Qt::red);\n LorentzPlot.setProperties(prop);\n }\n view->add(&LorentzPlot);\n legend.add(&LorentzPlot, \"Lorentz\");\n view->save(\"Lorentz\" + fileExt);\n\n PlotView *mu1View = createPlotView(\"Mu1\", \"\", \"\", PRectF(mu1Min, mu2Max, 0, nEffTrial));\n PlotHist1D mu1Plot(mu1Hist);\n mu1View->add(&mu1Plot);\n window.add(mu1View, \"Mu1\");\n mu1View->save(\"Mu1\" + fileExt);\n\n PlotView *mu2View = createPlotView(\"Mu2\", \"\", \"\", PRectF(mu2Min, mu2Max, 0, nEffTrial));\n PlotHist1D mu2Plot(mu2Hist);\n mu2View->add(&mu2Plot);\n window.add(mu2View, \"Mu2\");\n mu2View->save(\"Mu2\" + fileExt);\n\n PlotView *gamma1View = createPlotView(\"Gamma1\", \"\", \"\", PRectF(gamma1Min, gamma2Max, 0, nEffTrial));\n PlotHist1D gamma1Plot(gamma1Hist);\n gamma1View->add(&gamma1Plot);\n window.add(gamma1View, \"Gamma1\");\n gamma1View->save(\"Gamma1\" + fileExt);\n \n PlotView *gamma2View = createPlotView(\"Gamma2\", \"\", \"\", PRectF(gamma2Min, gamma2Max, 0, nEffTrial));\n PlotHist1D gamma2Plot(gamma2Hist);\n gamma2View->add(&gamma2Plot);\n window.add(gamma2View, \"Gamma2\");\n gamma2View->save(\"Gamma2\" + fileExt);\n\n PlotView *fView = createPlotView(\"Fraction\", \"\", \"\", PRectF(fMin, fMax, 0, nEffTrial));\n PlotHist1D fPlot(fHist);\n fView->add(&fPlot);\n window.add(fView, \"Fraction\");\n fView->save(\"Fraction\" + fileExt);\n\n/*\n\tQToolBar *toolBar = window.addToolBar(\"Tools\");\n\t\n QAction *quitAction = toolBar->addAction(\"Quit (q)\");\n quitAction->setShortcut(QKeySequence(\"q\"));\n\tQObject::connect(quitAction, SIGNAL(triggered()), &app, SLOT(quit()));\n \n QAction *saveAction = toolBar->addAction(\"Save as (s)\");\n saveAction->setShortcut(QKeySequence(\"s\"));\n QObject::connect(saveAction, SIGNAL(triggered()), view, SLOT(save()));\n*/\n\twindow.show();\n\tapp.exec();\n\n return 0;\n}\n\n\n//////////////////////////////////////////////////////////////////////////////\n\nData readData(const std::string& file)\n{\n std::ifstream dataFile(file);\n double dataIn;\n Data data;\n\n while (dataFile >> dataIn)\n {\n data.push_back(dataIn);\n }\n \n return data;\n}\n\nHist1D binData(const Data& data)\n{\n std::pair MIN_MAX_Iter = std::minmax_element(data.begin(), data.end());\n double dataMin = *(MIN_MAX_Iter.first);\n double dataMax = *(MIN_MAX_Iter.second);\n\n std::cout << \"Data Num: \" << data.size() << std::endl;\n std::cout << \"Data Min: \" << dataMin << std::endl;\n std::cout << \"Data Max: \" << dataMax << std::endl;\n \n Hist1D dataHist(nBin, std::floor(dataMin-1), std::ceil(dataMax+1));\n for (size_t i = 0; i < data.size(); i++)\n {\n dataHist.accumulate(data[i]);\n }\n \n std::cout << \"Data Mean: \" << dataHist.mean() << std::endl;\n std::cout << \"Data Variance: \" << dataHist.variance() << std::endl;\n std::cout << \"Data Sigma: \" << std::sqrt(dataHist.variance()) << std::endl;\n std::cout << std::endl;\n\n return dataHist;\n}\n\nTable tableData(const Data& data)\n{\n Table dataTable(\"Data Table\");\n\n for (size_t i = 0; i < data.size(); i++)\n {\n dataTable.add(\"E\", data[i]);\n dataTable.capture();\n }\n \n return dataTable;\n}\n\n\n////////////////////////////////////////////////////////////////////////////////\n\nPlotView *createPlotView(const std::string& title, const std::string& xLabel, const std::string yLabel, const PRectF& viewRange)\n{\n PlotView *view_ptr = new PlotView(viewRange);\n view_ptr->setFixedWidth(1200);\n view_ptr->setFixedHeight(800);\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": "487bc7c1caea72ff96997cc9b852058aeecf0278", "size": 12614, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Assignments/Assignments_12/EX3/b/coarse/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/EX3/b/coarse/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/EX3/b/coarse/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": 35.5323943662, "max_line_length": 129, "alphanum_fraction": 0.6308863168, "num_tokens": 3548, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8918110511888303, "lm_q2_score": 0.7248702642896702, "lm_q1q2_score": 0.646447312371696}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nvoid main() {\n\n\t{\n\t\tMatrix2f m;\n\t\tm << 1, 2, 3, 4;\n\t\tcout << m << endl;\n\n\t\tRowVectorXd vec1(3);\n\t\tvec1 << 1, 2, 3;\n\t\tcout << \"vec1 : \" << vec1 << endl;\n\n\t\tRowVectorXd vec2(4);\n\t\tvec2 << 1, 4, 9, 16;\n\t\tcout << \"vec2 : \" << vec2 << endl;\n\n\t\tRowVectorXd joined(7);\n\t\tjoined << vec1, vec2;\n\t\tcout << \"joined = \" << joined << endl;\n\n\t\tMatrixXf matA(2, 2); matA << 1, 2, 3, 4;\n\t\tMatrixXf matB(4, 4);\n\t\tmatB << matA, matA / 10, matA / 10, matA;\n\t\tcout << \"matA: \\n\" << matA << endl;\n\t\tcout << \"matB: \\n\" << matB << endl;\n\t}\n\t{\n\t\tMatrix3f m;\n\t\tm.row(0) << 1, 2, 3;\n\t\tm.block(1, 0, 2, 2) << 4, 5, 7, 8;\n\t\tm.col(2).tail(2) << 6, 9;\n\t\tcout << m << endl;\n\t}\n\t{\n\t\tcout << \"A fixed-size array:\\n\";\n\t\tArray33f a1 = Array33f::Zero();\n\t\tcout << a1 << endl;\n\n\t\tcout << \"A one-dimensional dynamic-size array: \\n\";\n\t\tArrayXf a2 = ArrayXf::Zero(3);\n\t\tcout << a2 << endl;\n\n\t\tcout << \"A two-dimensional dynamic-size array:\\n\";\n\t\tArrayXXf a3 = ArrayXXf::Zero(3, 4);\n\t\tcout << a3 << endl;\n\t}\n\t{\n\t\tfloat M_PI = 3.14;\n\t\tArrayXXf table(10, 4);\n\t\ttable.col(0) = ArrayXf::LinSpaced(10, 0, 90);\n\t\ttable.col(1) = M_PI / 180 * table.col(0);\n\t\ttable.col(2) = table.col(1).sin();\n\t\ttable.col(3) = table.col(1).cos();\n\t\tstd::cout << \" Degrees Radians Sine Cosine\\n\";\n\t\tstd::cout << table << std::endl;\n\t}\n\n\tsystem(\"pause\");\n}", "meta": {"hexsha": "958731d62bad763cbbe0fdea7beb26b7eef5414e", "size": 1389, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/eigen/eigen/advanced_initialization/advanced_initialization.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/advanced_initialization/advanced_initialization.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/advanced_initialization/advanced_initialization.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": 21.703125, "max_line_length": 59, "alphanum_fraction": 0.5421166307, "num_tokens": 571, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8175744761936437, "lm_q2_score": 0.7905303236047049, "lm_q1q2_score": 0.6463174152363081}} {"text": "// Copyright Paul A. Bristow 2017, 2018\n// Copyright John Z. Maddock 2017\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 Graph showing differences of Lambert W function double from nearest representable values.\n\n\\details\n\n*/\n\n#include \nusing boost::math::lambert_w0;\nusing boost::math::lambert_wm1;\n#include \nusing boost::math::isfinite;\n#include \nusing namespace boost::svg;\n\n// For higher precision computation of Lambert W.\n#include \n#include // For float_distance.\nusing boost::math::float_distance;\n\n#include \n// using std::cout;\n// using std::endl;\n#include \n#include \n#include \n#include \n#include \n#include \nusing std::pair;\n#include \nusing std::map;\n#include \nusing std::multiset;\n#include \nusing std::numeric_limits;\n#include // exp\n\n/*!\n*/\n\n\nint main()\n{\n try\n {\n std::cout << \"Lambert W errors graph.\" << std::endl;\n using boost::multiprecision::cpp_bin_float_50; \n using boost::multiprecision::cpp_bin_float_quad; \n\n typedef cpp_bin_float_quad HPT; // High precision type.\n\n using boost::math::float_distance;\n using boost::math::policies::precision;\n using boost::math::policies::digits10;\n using boost::math::policies::digits2;\n using boost::math::policies::policy;\n\n std::cout.precision(std::numeric_limits::max_digits10);\n\n //[lambert_w_graph_1\n\n //] [/lambert_w_graph_1]\n {\n std::map w0s; // Lambert W0 branch values, default double precision, digits2 = 53.\n std::map w0s_50; // Lambert W0 branch values digits2 = 50.\n\n int max_distance = 0;\n int total_distance = 0;\n int count = 0;\n const int bits = 7;\n double min_z = -0.367879; // Close to singularity at -0.3678794411714423215955237701614608727 -exp(-1)\n //double min_z = 0.06; // Above 0.05 switch point.\n double max_z = 99.99;\n double step_z = 0.05;\n\n for (HPT z = min_z; z < max_z; z += step_z)\n {\n double zd = static_cast(z);\n double w0d = lambert_w0(zd); // double result from same default.\n HPT w0_best = lambert_w0(z);\n double w0_best_d = static_cast(w0_best); // reference result.\n // w0s[zd] = (w0d - w0_best_d); // absolute difference.\n // w0s[z] = 100 * (w0 - w0_best) / w0_best; // difference relative % .\n w0s[zd] = float_distance(w0d, w0_best_d); // difference in bits.\n double fd = float_distance(w0d, w0_best_d);\n int distance = static_cast(fd);\n int abs_distance = abs(distance);\n\n // std::cout << count << \" \" << zd << \" \" << w0d << \" \" << w0_best_d\n // << \", Difference = \" << w0d - w0_best_d << \", % = \" << (w0d - w0_best_d) / w0d << \", Distance = \" << distance << std::endl;\n\n total_distance += abs_distance;\n if (abs_distance > max_distance)\n {\n max_distance = abs_distance;\n }\n count++;\n } // for z\n std::cout << \"points \" << count << std::endl;\n std::cout.precision(3);\n std::cout << \"max distance \" << max_distance << \", total distances = \" << total_distance\n << \", mean distance \" << (float)total_distance / count << std::endl;\n\n typedef std::map::const_iterator Map_Iterator;\n\n /* for (std::map::const_iterator it = w0s.begin(); it != w0s.end(); ++it)\n {\n std::cout << \" \" << *(it) << \"\\n\";\n }\n */\n svg_2d_plot data_plot_0; // <-0.368, -46> <-0.358, -4> <-0.348, 1>...\n\n data_plot_0.title(\"Lambert W0 function differences from 'best' for double.\")\n .title_font_size(11)\n .x_size(400)\n .y_size(200)\n .legend_on(false)\n //.legend_font_weight(1)\n .x_label(\"z\")\n .y_label(\"W0 difference (bits)\")\n //.x_label_on(true)\n //.y_label_on(true)\n //.xy_values_on(false)\n .x_range(-1, 100.)\n .y_range(-4., +4.)\n .x_major_interval(10.)\n .y_major_interval(2.)\n .x_major_grid_on(true)\n .y_major_grid_on(true)\n .x_label_font_size(9)\n .y_label_font_size(9)\n //.x_values_on(true)\n //.y_values_on(true)\n .y_values_rotation(horizontal)\n //.plot_window_on(true)\n .x_values_precision(3)\n .y_values_precision(3)\n .coord_precision(3) // Needed to avoid stepping on curves.\n //.coord_precision(4) // Needed to avoid stepping on curves.\n .copyright_holder(\"Paul A. Bristow\")\n .copyright_date(\"2018\")\n //.background_border_color(black);\n ;\n\n\n data_plot_0.plot(w0s, \"W0 branch\").line_color(red).shape(none).line_on(true).bezier_on(false).line_width(0.2);\n //data_plot.plot(wm1s, \"W-1 branch\").line_color(blue).shape(none).line_on(true).bezier_on(false).line_width(1);\n data_plot_0.write(\"./lambert_w0_errors_graph\");\n\n } // end W0 branch plot.\n { // Repeat for Lambert W-1 branch.\n\n std::map wm1s; // Lambert W-1 branch values.\n std::map wm1s_50; // Lambert Wm1 branch values digits2 = 50.\n\n int max_distance = 0;\n int total_distance = 0;\n int count = 0;\n const int bits = 7;\n double min_z = -0.367879; // Close to singularity at -0.3678794411714423215955237701614608727 -exp(-1)\n //double min_z = 0.06; // Above 0.05 switch point.\n double max_z = -0.0001;\n double step_z = 0.001;\n\n for (HPT z = min_z; z < max_z; z += step_z)\n {\n if (z > max_z)\n {\n break;\n }\n double zd = static_cast(z);\n double wm1d = lambert_wm1(zd); // double result from same default.\n HPT wm1_best = lambert_wm1(z);\n double wm1_best_d = static_cast(wm1_best); // reference result.\n // wm1s[zd] = (wm1d - wm1_best_d); // absolute difference.\n // wm1s[z] = 100 * (wm1 - wm1_best) / wm1_best; // difference relative % .\n wm1s[zd] = float_distance(wm1d, wm1_best_d); // difference in bits.\n double fd = float_distance(wm1d, wm1_best_d);\n int distance = static_cast(fd);\n int abs_distance = abs(distance);\n\n //std::cout << count << \" \" << zd << \" \" << wm1d << \" \" << wm1_best_d\n // << \", Difference = \" << wm1d - wm1_best_d << \", % = \" << (wm1d - wm1_best_d) / wm1d << \", Distance = \" << distance << std::endl;\n\n total_distance += abs_distance;\n if (abs_distance > max_distance)\n {\n max_distance = abs_distance;\n }\n count++;\n\n } // for z\n std::cout << \"points \" << count << std::endl;\n std::cout.precision(3);\n std::cout << \"max distance \" << max_distance << \", total distances = \" << total_distance\n << \", mean distance \" << (float)total_distance / count << std::endl;\n\n typedef std::map::const_iterator Map_Iterator;\n\n /* for (std::map::const_iterator it = wm1s.begin(); it != wm1s.end(); ++it)\n {\n std::cout << \" \" << *(it) << \"\\n\";\n }\n */\n svg_2d_plot data_plot_m1; // <-0.368, -46> <-0.358, -4> <-0.348, 1>...\n\n data_plot_m1.title(\"Lambert W-1 function differences from 'best' for double.\")\n .title_font_size(11)\n .x_size(400)\n .y_size(200)\n .legend_on(false)\n //.legend_font_weight(1)\n .x_label(\"z\")\n .y_label(\"W-1 difference (bits)\")\n .x_range(-0.39, +0.0001)\n .y_range(-4., +4.)\n .x_major_interval(0.1)\n .y_major_interval(2.)\n .x_major_grid_on(true)\n .y_major_grid_on(true)\n .x_label_font_size(9)\n .y_label_font_size(9)\n //.x_values_on(true)\n //.y_values_on(true)\n .y_values_rotation(horizontal)\n //.plot_window_on(true)\n .x_values_precision(3)\n .y_values_precision(3)\n .coord_precision(3) // Needed to avoid stepping on curves.\n //.coord_precision(4) // Needed to avoid stepping on curves.\n .copyright_holder(\"Paul A. Bristow\")\n .copyright_date(\"2018\")\n //.background_border_color(black);\n ;\n data_plot_m1.plot(wm1s, \"W-1 branch\").line_color(darkblue).shape(none).line_on(true).bezier_on(false).line_width(0.2);\n data_plot_m1.write(\"./lambert_wm1_errors_graph\");\n }\n }\n catch (std::exception& ex)\n {\n std::cout << ex.what() << std::endl;\n }\n} // int main()\n\n /*\n //[lambert_w_errors_graph_1_output\n Lambert W errors graph.\n points 2008\n max distance 46, total distances = 717, mean distance 0.357\n\n points 368\n max distance 23, total distances = 329, mean distance 0.894\n\n //] [/lambert_w_errors_graph_1_output]\n */\n", "meta": {"hexsha": "45baa200ce90bf62c8af303d78ac1c5eb1144888", "size": 9234, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/math/tools/lambert_w_errors_graph.cpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "libs/math/tools/lambert_w_errors_graph.cpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "libs/math/tools/lambert_w_errors_graph.cpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 35.1102661597, "max_line_length": 141, "alphanum_fraction": 0.5965995235, "num_tokens": 2587, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7905303186696747, "lm_q2_score": 0.8175744806385542, "lm_q1q2_score": 0.6463174147153901}} {"text": "#ifndef STAN_MATH_PRIM_FUN_CONSTANTS_HPP\n#define STAN_MATH_PRIM_FUN_CONSTANTS_HPP\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n// TODO(anyone) Use constexpr when moving to C++17\n\n/**\n * Return the base of the natural logarithm.\n *\n * @return Base of natural logarithm.\n */\nstatic constexpr double e() { return boost::math::constants::e(); }\n\n/**\n * Return the Euler's gamma constant.\n *\n * @return Euler's Gamma.\n */\nstatic constexpr double egamma() {\n return boost::math::constants::euler();\n}\n\n/**\n * Return the value of pi.\n *\n * @return Pi.\n */\nstatic constexpr double pi() { return boost::math::constants::pi(); }\n\n/**\n * Smallest positive value.\n */\nstatic constexpr double EPSILON = std::numeric_limits::epsilon();\n\n/**\n * Positive infinity.\n */\nstatic constexpr double INFTY = std::numeric_limits::infinity();\n\n/**\n * Negative infinity.\n */\nstatic constexpr double NEGATIVE_INFTY = -INFTY;\n\n/**\n * (Quiet) not-a-number value.\n */\nstatic constexpr double NOT_A_NUMBER = std::numeric_limits::quiet_NaN();\n\n/**\n * Twice the value of \\f$ \\pi \\f$,\n * \\f$ 2\\pi \\f$.\n */\nstatic constexpr double TWO_PI = boost::math::constants::two_pi();\n\n/**\n * The natural logarithm of 0,\n * \\f$ \\log 0 \\f$.\n */\nstatic constexpr double LOG_ZERO = -INFTY;\n\n/**\n * The natural logarithm of machine precision \\f$ \\epsilon \\f$,\n * \\f$ \\log \\epsilon \\f$.\n */\nconst double LOG_EPSILON = std::log(EPSILON);\n\n/**\n * The natural logarithm of \\f$ \\pi \\f$,\n * \\f$ \\log \\pi \\f$.\n */\nconst double LOG_PI = std::log(pi());\n\n/**\n * The natural logarithm of 2,\n * \\f$ \\log 2 \\f$.\n */\nstatic constexpr double LOG_TWO = boost::math::constants::ln_two();\n\n/**\n * The natural logarithm of 0.5,\n * \\f$ \\log 0.5 = \\log 1 - \\log 2 \\f$.\n */\nstatic constexpr double LOG_HALF = -LOG_TWO;\n\n/**\n * The natural logarithm of 2 plus the natural logarithm of \\f$ \\pi \\f$,\n * \\f$ \\log(2\\pi) \\f$.\n */\nconst double LOG_TWO_PI = LOG_TWO + LOG_PI;\n\n/**\n * The value of one quarter the natural logarithm of \\f$ \\pi \\f$,\n * \\f$ \\log(\\pi) / 4 \\f$.\n */\nconst double LOG_PI_OVER_FOUR = 0.25 * LOG_PI;\n\n/**\n * The natural logarithm of the square root of \\f$ \\pi \\f$,\n * \\f$ \\log(sqrt{\\pi}) \\f$.\n */\nconst double LOG_SQRT_PI = std::log(boost::math::constants::root_pi());\n\n/**\n * The natural logarithm of 10,\n * \\f$ \\log 10 \\f$.\n */\nstatic constexpr double LOG_TEN = boost::math::constants::ln_ten();\n\n/**\n * The value of the square root of 2,\n * \\f$ \\sqrt{2} \\f$.\n */\nstatic constexpr double SQRT_TWO = boost::math::constants::root_two();\n\n/**\n * The value of the square root of \\f$ \\pi \\f$,\n * \\f$ \\sqrt{\\pi} \\f$.\n */\nstatic constexpr double SQRT_PI = boost::math::constants::root_pi();\n\n/**\n * The value of the square root of \\f$ 2\\pi \\f$,\n * \\f$ \\sqrt{2\\pi} \\f$.\n */\nstatic constexpr double SQRT_TWO_PI\n = boost::math::constants::root_two_pi();\n\n/**\n * The square root of 2 divided by the square root of \\f$ \\pi \\f$,\n * \\f$ \\sqrt{2} / \\sqrt{\\pi} \\f$.\n */\nstatic constexpr double SQRT_TWO_OVER_SQRT_PI = SQRT_TWO / SQRT_PI;\n\n/**\n * The value of 1 over the square root of 2,\n * \\f$ 1 / \\sqrt{2} \\f$.\n */\nstatic constexpr double INV_SQRT_TWO\n = boost::math::constants::one_div_root_two();\n\n/**\n * The value of 1 over the square root of \\f$ \\pi \\f$,\n * \\f$ 1 / \\sqrt{\\pi} \\f$.\n */\nstatic constexpr double INV_SQRT_PI\n = boost::math::constants::one_div_root_pi();\n\n/**\n * The value of 1 over the square root of \\f$ 2\\pi \\f$,\n * \\f$ 1 / \\sqrt{2\\pi} \\f$.\n */\nstatic constexpr double INV_SQRT_TWO_PI\n = boost::math::constants::one_div_root_two_pi();\n\n/**\n * The value of 2 over the square root of \\f$ \\pi \\f$,\n * \\f$ 2 / \\sqrt{\\pi} \\f$.\n */\nstatic constexpr double TWO_OVER_SQRT_PI\n = boost::math::constants::two_div_root_pi();\n\n/**\n * The value of half the natural logarithm 2,\n * \\f$ \\log(2) / 2 \\f$.\n */\nstatic constexpr double HALF_LOG_TWO = 0.5 * LOG_TWO;\n\n/**\n * The value of half the natural logarithm \\f$ 2\\pi \\f$,\n * \\f$ \\log(2\\pi) / 2 \\f$.\n */\nconst double HALF_LOG_TWO_PI = 0.5 * LOG_TWO_PI;\n\n/**\n * The value of minus the natural logarithm of the square root of \\f$ 2\\pi \\f$,\n * \\f$ -\\log(\\sqrt{2\\pi}) \\f$.\n */\nconst double NEG_LOG_SQRT_TWO_PI = -std::log(SQRT_TWO_PI);\n\n/**\n * Largest rate parameter allowed in Poisson RNG\n */\nconst double POISSON_MAX_RATE = std::pow(2.0, 30);\n\n/**\n * Return positive infinity.\n *\n * @return Positive infinity.\n */\nstatic constexpr inline double positive_infinity() { return INFTY; }\n\n/**\n * Return negative infinity.\n *\n * @return Negative infinity.\n */\nstatic constexpr inline double negative_infinity() { return NEGATIVE_INFTY; }\n\n/**\n * Return (quiet) not-a-number.\n *\n * @return Quiet not-a-number.\n */\nstatic constexpr inline double not_a_number() { return NOT_A_NUMBER; }\n\n/**\n * Returns the difference between 1.0 and the next value\n * representable.\n *\n * @return Minimum positive number.\n */\nstatic constexpr inline double machine_precision() { return EPSILON; }\n\n/**\n * Returns the natural logarithm of ten.\n *\n * @return Natural logarithm of ten.\n */\nstatic constexpr inline double log10() { return LOG_TEN; }\n\n/**\n * Returns the square root of two.\n *\n * @return Square root of two.\n */\nstatic constexpr inline double sqrt2() { return SQRT_TWO; }\n\n} // namespace math\n} // namespace stan\n\n#endif\n", "meta": {"hexsha": "e7f483ce7f7daafade3bfd2375afddec04f4a227", "size": 5494, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "stan/math/prim/fun/constants.hpp", "max_stars_repo_name": "LaudateCorpus1/math", "max_stars_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stan/math/prim/fun/constants.hpp", "max_issues_repo_name": "LaudateCorpus1/math", "max_issues_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stan/math/prim/fun/constants.hpp", "max_forks_repo_name": "LaudateCorpus1/math", "max_forks_repo_head_hexsha": "990a66b3cccd27a5fd48626360bb91093a48278b", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 22.7966804979, "max_line_length": 80, "alphanum_fraction": 0.6543502002, "num_tokens": 1600, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942119105695, "lm_q2_score": 0.7154240079185319, "lm_q1q2_score": 0.6462383654146713}} {"text": "// Boost.Geometry\n\n// Copyright (c) 2016 Oracle and/or its affiliates.\n\n// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle\n\n// Use, modification and distribution is subject to the Boost Software License,\n// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_GEOMETRY_FORMULAS_GNOMONIC_INTERSECTION_HPP\n#define BOOST_GEOMETRY_FORMULAS_GNOMONIC_INTERSECTION_HPP\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\nnamespace boost { namespace geometry { namespace formula\n{\n\n/*!\n\\brief The intersection of two geodesics using spheroidal gnomonic projection\n as proposed by Karney.\n\\author See\n - Charles F.F Karney, Algorithms for geodesics, 2011\n https://arxiv.org/pdf/1109.4448.pdf\n - GeographicLib forum thread: Intersection between two geodesic lines\n https://sourceforge.net/p/geographiclib/discussion/1026621/thread/21aaff9f/\n*/\ntemplate\n<\n typename CT,\n template class Inverse,\n template class Direct\n>\nclass gnomonic_intersection\n{\npublic:\n template \n static inline bool apply(T1 const& lona1, T1 const& lata1,\n T1 const& lona2, T1 const& lata2,\n T2 const& lonb1, T2 const& latb1,\n T2 const& lonb2, T2 const& latb2,\n CT & lon, CT & lat,\n Spheroid const& spheroid)\n {\n CT const lon_a1 = lona1;\n CT const lat_a1 = lata1;\n CT const lon_a2 = lona2;\n CT const lat_a2 = lata2;\n CT const lon_b1 = lonb1;\n CT const lat_b1 = latb1;\n CT const lon_b2 = lonb2;\n CT const lat_b2 = latb2;\n\n return apply(lon_a1, lat_a1, lon_a2, lat_a2, lon_b1, lat_b1, lon_b2, lat_b2, lon, lat, spheroid);\n }\n\n template \n static inline bool apply(CT const& lona1, CT const& lata1,\n CT const& lona2, CT const& lata2,\n CT const& lonb1, CT const& latb1,\n CT const& lonb2, CT const& latb2,\n CT & lon, CT & lat,\n Spheroid const& spheroid)\n {\n typedef gnomonic_spheroid gnom_t;\n\n lon = (lona1 + lona2 + lonb1 + lonb2) / 4;\n lat = (lata1 + lata2 + latb1 + latb2) / 4;\n // TODO: consider normalizing lon\n\n for (int i = 0; i < 10; ++i)\n {\n CT xa1, ya1, xa2, ya2;\n CT xb1, yb1, xb2, yb2;\n CT x, y;\n double lat1, lon1;\n\n bool ok = gnom_t::forward(lon, lat, lona1, lata1, xa1, ya1, spheroid)\n && gnom_t::forward(lon, lat, lona2, lata2, xa2, ya2, spheroid)\n && gnom_t::forward(lon, lat, lonb1, latb1, xb1, yb1, spheroid)\n && gnom_t::forward(lon, lat, lonb2, latb2, xb2, yb2, spheroid)\n && intersect(xa1, ya1, xa2, ya2, xb1, yb1, xb2, yb2, x, y)\n && gnom_t::inverse(lon, lat, x, y, lon1, lat1, spheroid);\n\n if (! ok)\n {\n return false;\n }\n\n if (math::equals(lat1, lat) && math::equals(lon1, lon))\n {\n break;\n }\n\n lat = lat1;\n lon = lon1;\n }\n\n // NOTE: true is also returned if the number of iterations is too great\n // which means that the accuracy of the result is low\n return true;\n }\n\nprivate:\n static inline bool intersect(CT const& xa1, CT const& ya1, CT const& xa2, CT const& ya2,\n CT const& xb1, CT const& yb1, CT const& xb2, CT const& yb2,\n CT & x, CT & y)\n {\n typedef model::point v3d_t;\n\n CT const c0 = 0;\n CT const c1 = 1;\n\n v3d_t const va1(xa1, ya1, c1);\n v3d_t const va2(xa2, ya2, c1);\n v3d_t const vb1(xb1, yb1, c1);\n v3d_t const vb2(xb2, yb2, c1);\n\n v3d_t const la = cross_product(va1, va2);\n v3d_t const lb = cross_product(vb1, vb2);\n v3d_t const p = cross_product(la, lb);\n\n CT const z = get<2>(p);\n\n if (math::equals(z, c0))\n {\n // degenerated or collinear segments\n return false;\n }\n\n x = get<0>(p) / z;\n y = get<1>(p) / z;\n\n return true;\n }\n};\n\n}}} // namespace boost::geometry::formula\n\n\n#endif // BOOST_GEOMETRY_FORMULAS_GNOMONIC_INTERSECTION_HPP\n", "meta": {"hexsha": "33c2fe62b610f78a0af2d5f8c63e511adda558e9", "size": 4881, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "deps/src/boost_1_65_1/boost/geometry/formulas/gnomonic_intersection.hpp", "max_stars_repo_name": "shreyasvj25/turicreate", "max_stars_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 11356.0, "max_stars_repo_stars_event_min_datetime": "2017-12-08T19:42:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:55:25.000Z", "max_issues_repo_path": "deps/src/boost_1_65_1/boost/geometry/formulas/gnomonic_intersection.hpp", "max_issues_repo_name": "shreyasvj25/turicreate", "max_issues_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 2402.0, "max_issues_repo_issues_event_min_datetime": "2017-12-08T22:31:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:25:52.000Z", "max_forks_repo_path": "deps/src/boost_1_65_1/boost/geometry/formulas/gnomonic_intersection.hpp", "max_forks_repo_name": "shreyasvj25/turicreate", "max_forks_repo_head_hexsha": "32e84ca16aef8d04aff3d49ae9984bd49326bffd", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1343.0, "max_forks_repo_forks_event_min_datetime": "2017-12-08T19:47:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-26T11:31:36.000Z", "avg_line_length": 32.7583892617, "max_line_length": 105, "alphanum_fraction": 0.5666871543, "num_tokens": 1419, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.903294214513915, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.646238356315639}} {"text": "/*\n * StokesM2L.cpp\n *\n * Created on: Oct 12, 2016\n * Author: wyan\n */\n\n#include \"SVD_pvfmm.hpp\"\n\n#include \n\n#include \n#include \n\n#define DIRECTLAYER 2\n#define PI314 (3.1415926535897932384626433)\n\nnamespace Stokes2D3D {\n\ninline double ERFC(double x) { return std::erfc(x); }\ninline double ERF(double x) { return std::erf(x); }\n\n/*\n * def AEW(xi,rvec):\n r=np.sqrt(rvec.dot(rvec))\n A = 2*(xi*np.exp(-(xi**2)*(r**2))/(np.sqrt(np.pi)*r**2)+ss.erfc(xi*r)/(2*r**3))\n *(r*r*np.identity(3)+np.outer(rvec,rvec)) -\n 4*xi/np.sqrt(np.pi)*np.exp(-(xi**2)*(r**2))*np.identity(3)\n return A\n *\n * */\ninline Eigen::Matrix3d AEW(const double xi, const Eigen::Vector3d &rvec) {\n const double r = rvec.norm();\n Eigen::Matrix3d A =\n 2 *\n (xi * exp(-(xi * xi) * (r * r)) / (sqrt(PI314) * r * r) +\n erfc(xi * r) / (2 * r * r * r)) *\n (r * r * Eigen::Matrix3d::Identity() + (rvec * rvec.transpose())) -\n 4 * xi / sqrt(PI314) * exp(-(xi * xi) * (r * r)) *\n Eigen::Matrix3d::Identity();\n return A;\n}\n\ninline double lbda(double k, double xi, double z) {\n return exp(-k * k / (4 * xi * xi) - (xi * xi) * (z * z));\n}\n\ninline double thetaplus(double k, double xi, double z) {\n return exp(k * z) * ERFC(k / (2 * xi) + xi * z);\n}\n\ninline double thetaminus(double k, double xi, double z) {\n return exp(-k * z) * ERFC(k / (2 * xi) - xi * z);\n}\n\ninline double J00(double k, double xi, double z) {\n return sqrt(PI314) * lbda(k, xi, z) * xi;\n}\n\ninline double J10(double k, double xi, double z) {\n return PI314 * (thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (4 * k);\n}\n\ninline double J20(double k, double xi, double z) {\n return sqrt(PI314) * lbda(k, xi, z) / (4 * k * k * xi) +\n PI314 *\n ((thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (8 * k * k * k) +\n (thetaminus(k, xi, z) - thetaplus(k, xi, z)) * z / (8 * k * k) -\n (thetaplus(k, xi, z) + thetaminus(k, xi, z)) /\n (16 * k * (xi * xi)));\n}\n\ninline double J12(double k, double xi, double z) {\n return PI314 * (-thetaplus(k, xi, z) - thetaminus(k, xi, z)) * k / 4 +\n sqrt(PI314) * lbda(k, xi, z) * xi;\n}\n\ninline double J22(double k, double xi, double z) {\n return PI314 * ((thetaplus(k, xi, z) + thetaminus(k, xi, z)) * k /\n (16 * xi * xi) +\n (thetaplus(k, xi, z) + thetaminus(k, xi, z)) / (8 * k) +\n (thetaplus(k, xi, z) - thetaminus(k, xi, z)) * z / 8) -\n sqrt(PI314) * lbda(k, xi, z) / (4 * xi);\n}\n\ninline double K11(double k, double xi, double z) {\n return PI314 * ((thetaminus(k, xi, z) - thetaplus(k, xi, z))) / 4;\n}\n\ninline double K12(double k, double xi, double z) {\n return PI314 *\n ((thetaplus(k, xi, z) - thetaminus(k, xi, z)) / (16 * xi * xi) +\n (thetaminus(k, xi, z) + thetaplus(k, xi, z)) * z / (8 * k));\n}\n\ninline void QI(const Eigen::Vector3d &kvec, double xi, double z,\n Eigen::Matrix3d &QI) {\n // 3*3 tensor\n // kvec: np.array([k1,k2,0])\n double knorm = sqrt(kvec[0] * kvec[0] + kvec[1] * kvec[1]);\n QI = 2 * (J00(knorm, xi, z) / (4 * xi * xi) + J10(knorm, xi, z)) *\n Eigen::Matrix3d::Identity();\n}\n\ninline void Qkk(const Eigen::Vector3d &kvec, double xi, double z,\n Eigen::Matrix3d &Qreal, Eigen::Matrix3d &Qimg) {\n double k1 = kvec[0];\n double k2 = kvec[1];\n double knorm = sqrt(k1 * k1 + k2 * k2);\n auto j10 = J10(knorm, xi, z);\n auto j20 = J20(knorm, xi, z);\n auto j12 = J12(knorm, xi, z);\n auto j22 = J22(knorm, xi, z);\n\n auto k11 = K11(knorm, xi, z);\n auto k12 = K12(knorm, xi, z);\n Qreal.setZero();\n Qreal(0, 0) = k1 * k1;\n Qreal(1, 1) = k2 * k2;\n Qreal(0, 1) = k1 * k2;\n Qreal(1, 0) = k1 * k2;\n\n Qreal *= (j10 / (4 * (xi * xi)) + j20);\n Qreal(2, 2) = (j12 / (4 * xi * xi) + j22);\n Qreal *= -2;\n\n Qimg.setZero();\n Qimg(0, 2) = k1;\n Qimg(1, 2) = k2;\n Qimg(2, 0) = k1;\n Qimg(2, 1) = k2;\n // Qimg=np.array([[0,0,k1],[0,0,k2],[k1,k2,0]])*( k11/(4*xi**2) + k12 )\n Qimg *= (k11 / (4 * xi * xi) + k12);\n Qimg *= -2;\n}\n\n// inline Eigen::Matrix3d uFk0(double xi, double zmn) {\n//\tEigen::Matrix3d wavek0;\n//\twavek0 = -(4.0 / 1) * (PI314 * (zmn) * ERF(zmn * xi) + sqrt(PI314) / (2\n//* xi) * exp(-zmn * zmn * xi * xi));\n//\treturn wavek0;\n//\n//}\n\ninline void GkernelEwald(const Eigen::Vector3d &rvecIn, Eigen::Matrix3d &Gsum) {\n const double xi = 2;\n Eigen::Vector3d rvec = rvecIn;\n rvec[0] = rvec[0] - floor(rvec[0]);\n rvec[1] = rvec[1] - floor(rvec[1]); // reset to a periodic cell\n\n const double r = rvec.norm();\n Eigen::Matrix3d real = Eigen::Matrix3d::Zero();\n const int N = 5;\n if (r < 1e-14) {\n auto Gself = -4 * xi / sqrt(PI314) *\n Eigen::Matrix3d::Identity(); // the self term\n for (int i = -N; i < N + 1; i++) {\n for (int j = -N; j < N + 1; j++) {\n if (i == 0 && j == 0) {\n continue;\n }\n real = real + AEW(xi, rvec + Eigen::Vector3d(i, j, 0));\n }\n }\n real += Gself;\n } else {\n for (int i = -N; i < N + 1; i++) {\n for (int j = -N; j < N + 1; j++) {\n real = real + AEW(xi, rvec + Eigen::Vector3d(i, j, 0));\n }\n }\n }\n\n // k\n Eigen::Matrix3d wave = Eigen::Matrix3d::Zero();\n\n double zmn = rvec[2];\n Eigen::Vector3d rhomn = rvec;\n rhomn[2] = 0;\n Eigen::Matrix3d Qreal;\n Eigen::Matrix3d Qimg;\n Eigen::Matrix3d QImat;\n for (int i = -N; i < N + 1; i++) {\n for (int j = -N; j < N + 1; j++) {\n Eigen::Vector3d kvec(2 * PI314 * i, 2 * PI314 * j, 0);\n if (i == 0 and j == 0) {\n continue;\n }\n Qkk(kvec, xi, zmn, Qreal, Qimg);\n QI(kvec, xi, zmn, QImat);\n wave = wave + (QImat + Qreal) * cos(kvec.dot(rhomn)) -\n (Qimg)*sin(kvec.dot(rhomn));\n }\n }\n wave *= 4;\n\n // k=0\n Eigen::Matrix3d waveK0;\n waveK0.setZero();\n /*\n * I2fn=force\n I2fn[2]=0\n wavek0=-(4/1)*(np.pi*(zmn)*ss.erf(zmn*xi)+np.sqrt(np.pi)/(2*xi)*np.exp(-zmn**2*xi**2))*I2fn\n *\n * */\n waveK0 = -(4 / 1.0) *\n (PI314 * (zmn)*ERF(zmn * xi) +\n sqrt(PI314) / (2 * xi) * exp(-zmn * zmn * xi * xi)) *\n Eigen::Matrix3d::Identity();\n waveK0(2, 2) = 0;\n\n Gsum = real + wave + waveK0;\n}\n\ninline void Gkernel(const Eigen::Vector3d &target,\n const Eigen::Vector3d &source, Eigen::Matrix3d &answer) {\n auto rst = target - source;\n double rnorm = rst.norm();\n if (rnorm < 1e-14) {\n answer = Eigen::Matrix3d::Zero();\n return;\n }\n auto part2 = rst * rst.transpose() / (rnorm * rnorm * rnorm);\n auto part1 = Eigen::Matrix3d::Identity() / rnorm;\n answer = part1 + part2;\n}\n\n// Out of Layer 1\ninline void GkernelEwaldO1(const Eigen::Vector3d &rvec,\n Eigen::Matrix3d &GsumO1) {\n Eigen::Matrix3d Gfree = Eigen::Matrix3d::Zero();\n GkernelEwald(rvec, GsumO1);\n const int N = DIRECTLAYER;\n for (int i = -N; i < N + 1; i++) {\n for (int j = -N; j < N + 1; j++) {\n Gkernel(rvec, Eigen::Vector3d(i, j, 0), Gfree);\n GsumO1 -= Gfree;\n }\n }\n}\n\n/**\n * \\brief Returns the coordinates of points on the surface of a cube.\n * \\param[in] p Number of points on an edge of the cube is (n+1)\n * \\param[in] c Coordinates to the centre of the cube (3D array).\n * \\param[in] alpha Scaling factor for the size of the cube.\n * \\param[in] depth Depth of the cube in the octree.\n * \\return Vector with coordinates of points on the surface of the cube in the\n * format [x0 y0 z0 x1 y1 z1 .... ].\n */\n\ntemplate \nstd::vector surface(int p, Real_t *c, Real_t alpha, int depth) {\n size_t n_ = (6 * (p - 1) * (p - 1) + 2); // Total number of points.\n\n std::vector coord(n_ * 3);\n coord[0] = coord[1] = coord[2] = -1.0;\n size_t cnt = 1;\n for (int i = 0; i < p - 1; i++)\n for (int j = 0; j < p - 1; j++) {\n coord[cnt * 3] = -1.0;\n coord[cnt * 3 + 1] = (2.0 * (i + 1) - p + 1) / (p - 1);\n coord[cnt * 3 + 2] = (2.0 * j - p + 1) / (p - 1);\n cnt++;\n }\n for (int i = 0; i < p - 1; i++)\n for (int j = 0; j < p - 1; j++) {\n coord[cnt * 3] = (2.0 * i - p + 1) / (p - 1);\n coord[cnt * 3 + 1] = -1.0;\n coord[cnt * 3 + 2] = (2.0 * (j + 1) - p + 1) / (p - 1);\n cnt++;\n }\n for (int i = 0; i < p - 1; i++)\n for (int j = 0; j < p - 1; j++) {\n coord[cnt * 3] = (2.0 * (i + 1) - p + 1) / (p - 1);\n coord[cnt * 3 + 1] = (2.0 * j - p + 1) / (p - 1);\n coord[cnt * 3 + 2] = -1.0;\n cnt++;\n }\n for (size_t i = 0; i < (n_ / 2) * 3; i++)\n coord[cnt * 3 + i] = -coord[i];\n\n Real_t r = 0.5 * pow(0.5, depth);\n Real_t b = alpha * r;\n for (size_t i = 0; i < n_; i++) {\n coord[i * 3 + 0] = (coord[i * 3 + 0] + 1.0) * b + c[0];\n coord[i * 3 + 1] = (coord[i * 3 + 1] + 1.0) * b + c[1];\n coord[i * 3 + 2] = (coord[i * 3 + 2] + 1.0) * b + c[2];\n }\n return coord;\n}\n\nint main(int argc, char **argv) {\n Eigen::initParallel();\n Eigen::setNbThreads(1);\n const int pEquiv = atoi(argv[1]); // (8-1)^2*6 + 2 points\n const int pCheck = atoi(argv[1]);\n const double scaleEquiv = 1.05;\n const double scaleCheck = 2.95;\n const double pCenterEquiv[3] = {\n -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2, -(scaleEquiv - 1) / 2};\n const double pCenterCheck[3] = {\n -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2, -(scaleCheck - 1) / 2};\n\n const double scaleLEquiv = 1.05;\n const double scaleLCheck = 2.95;\n const double pCenterLEquiv[3] = {\n -(scaleLEquiv - 1) / 2, -(scaleLEquiv - 1) / 2, -(scaleLEquiv - 1) / 2};\n const double pCenterLCheck[3] = {\n -(scaleLCheck - 1) / 2, -(scaleLCheck - 1) / 2, -(scaleLCheck - 1) / 2};\n\n auto pointMEquiv = surface(\n pEquiv, (double *)&(pCenterEquiv[0]), scaleEquiv,\n 0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n auto pointMCheck = surface(\n pCheck, (double *)&(pCenterCheck[0]), scaleCheck,\n 0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n auto pointLEquiv = surface(\n pEquiv, (double *)&(pCenterLCheck[0]), scaleLCheck,\n 0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n auto pointLCheck = surface(\n pCheck, (double *)&(pCenterLEquiv[0]), scaleLEquiv,\n 0); // center at 0.5,0.5,0.5, periodic box 1,1,1, scale 1.05, depth = 0\n\n //\tfor (int i = 0; i < pointLEquiv.size() / 3; i++) {\n //\t\tstd::cout << pointLEquiv[3 * i] << \" \" << pointLEquiv[3 * i + 1]\n //<< \" \" << pointLEquiv[3 * i + 2] << \" \"\n //\t\t\t\t<< std::endl;\n //\t}\n //\n //\tfor (int i = 0; i < pointLCheck.size() / 3; i++) {\n //\t\tstd::cout << pointLCheck[3 * i] << \" \" << pointLCheck[3 * i + 1]\n //<< \" \" << pointLCheck[3 * i + 2] << \" \"\n //\t\t\t\t<< std::endl;\n //\t}\n\n // const int imageN = 100; // images to sum\n // calculate the operator M2L with least square\n const int equivN = pointMEquiv.size() / 3;\n const int checkN = pointLCheck.size() / 3;\n Eigen::MatrixXd M2L(3 * equivN, 3 * equivN);\n Eigen::MatrixXd A(3 * checkN, 3 * equivN);\n#pragma omp parallel for\n for (int k = 0; k < checkN; k++) {\n Eigen::Matrix3d G = Eigen::Matrix3d::Zero();\n Eigen::Vector3d Cpoint(pointLCheck[3 * k], pointLCheck[3 * k + 1],\n pointLCheck[3 * k + 2]);\n for (int l = 0; l < equivN; l++) {\n const Eigen::Vector3d Lpoint(pointLEquiv[3 * l],\n pointLEquiv[3 * l + 1],\n pointLEquiv[3 * l + 2]);\n Gkernel(Cpoint, Lpoint, G);\n A.block<3, 3>(3 * k, 3 * l) = G;\n }\n }\n Eigen::MatrixXd ApinvU(A.cols(), A.rows());\n Eigen::MatrixXd ApinvVT(A.cols(), A.rows());\n pinv(A, ApinvU, ApinvVT);\n\n#pragma omp parallel for\n for (int i = 0; i < equivN; i++) {\n const Eigen::Vector3d Mpoint(pointMEquiv[3 * i], pointMEquiv[3 * i + 1],\n pointMEquiv[3 * i + 2]);\n //\t\tstd::cout<<\"debug:\"<(3 * k, 0) = temp;\n }\n\n M2L.block(0, 3 * i, 3 * equivN, 3) =\n (ApinvU.transpose() * (ApinvVT.transpose() * f));\n }\n\n // dump M2L\n for (int i = 0; i < 3 * equivN; i++) {\n for (int j = 0; j < 3 * equivN; j++) {\n std::cout << i << \" \" << j << \" \" << std::scientific\n << std::setprecision(18) << M2L(i, j) << std::endl;\n }\n }\n\n /*\n * pointForce=[(np.array([1.0,0,0]),np.array([0.1,0.55,0.2]))\n ,(np.array([-1.0,1.0,1.0]),np.array([0.5,0.1,0.3]))\n ,(np.array([0.0,0.0,-1.0]),np.array([0.8,0.5,0.7]))]\n * */\n std::vector>\n forcePoint(3);\n std::vector>\n forceValue(3);\n forcePoint[0] = Eigen::Vector3d(0.1, 0.5, 0.5);\n forceValue[0] = Eigen::Vector3d(1, 0, 0);\n forcePoint[1] = Eigen::Vector3d(0.9, 0.5, 0.5);\n forceValue[1] = Eigen::Vector3d(-1, 0, 0);\n forcePoint[2] = Eigen::Vector3d(0.0, 0.0, 0.0);\n forceValue[2] = Eigen::Vector3d(0, 0, 0);\n\n // solve M\n A.resize(3 * checkN, 3 * equivN);\n ApinvU.resize(A.cols(), A.rows());\n ApinvVT.resize(A.cols(), A.rows());\n Eigen::VectorXd f(3 * checkN);\n for (int k = 0; k < checkN; k++) {\n Eigen::Vector3d temp = Eigen::Vector3d::Zero();\n Eigen::Matrix3d G = Eigen::Matrix3d::Zero();\n Eigen::Vector3d Cpoint(pointMCheck[3 * k], pointMCheck[3 * k + 1],\n pointMCheck[3 * k + 2]);\n for (size_t p = 0; p < forcePoint.size(); p++) {\n Gkernel(Cpoint, forcePoint[p], G);\n temp = temp + G * (forceValue[p]);\n }\n f.block<3, 1>(3 * k, 0) = temp;\n for (int l = 0; l < equivN; l++) {\n Eigen::Vector3d Mpoint(pointMEquiv[3 * l], pointMEquiv[3 * l + 1],\n pointMEquiv[3 * l + 2]);\n Gkernel(Cpoint, Mpoint, G);\n A.block<3, 3>(3 * k, 3 * l) = G;\n }\n }\n pinv(A, ApinvU, ApinvVT);\n Eigen::VectorXd Msource = (ApinvU.transpose() * (ApinvVT.transpose() * f));\n // impose net charge equal\n double fx = 0, fy = 0, fz = 0;\n for (int i = 0; i < equivN; i++) {\n fx += Msource[3 * i];\n fy += Msource[3 * i + 1];\n fz += Msource[3 * i + 2];\n }\n std::cout << \"fx svd before correction: \" << fx << std::endl;\n std::cout << \"fy svd before correction: \" << fy << std::endl;\n std::cout << \"fz svd before correction: \" << fz << std::endl;\n double fnetx = 0;\n double fnety = 0;\n double fnetz = 0;\n for (size_t p = 0; p < forcePoint.size(); p++) {\n fnetx += (forceValue[p][0]);\n fnety += (forceValue[p][1]);\n fnetz += (forceValue[p][2]);\n }\n\n std::cout << \"Msource: \" << Msource << std::endl;\n\n std::vector>\n forcePointExt(0);\n std::vector>\n forceValueExt(0);\n for (size_t p = 0; p < forcePoint.size(); p++) {\n for (int i = -DIRECTLAYER; i < DIRECTLAYER + 1; i++) {\n for (int j = -DIRECTLAYER; j < DIRECTLAYER + 1; j++) {\n forcePointExt.push_back(Eigen::Vector3d(i, j, 0) +\n forcePoint[p]);\n forceValueExt.push_back(forceValue[p]);\n }\n }\n }\n\n Eigen::VectorXd M2Lsource = M2L * (Msource);\n\n Eigen::Vector3d samplePoint(0.4, 0.5, 0.5);\n Eigen::Vector3d Usample(0, 0, 0);\n Eigen::Vector3d UsampleSP(0, 0, 0);\n Eigen::Matrix3d G;\n for (size_t p = 0; p < forcePointExt.size(); p++) {\n Gkernel(samplePoint, forcePointExt[p], G);\n Usample = Usample + G * (forceValueExt[p]);\n }\n std::cout << \"Usample Direct:\" << Usample << std::endl;\n for (int p = 0; p < equivN; p++) {\n Eigen::Vector3d Lpoint(pointLEquiv[3 * p], pointLEquiv[3 * p + 1],\n pointLEquiv[3 * p + 2]);\n Eigen::Vector3d Fpoint(M2Lsource[3 * p], M2Lsource[3 * p + 1],\n M2Lsource[3 * p + 2]);\n Gkernel(samplePoint, Lpoint, G);\n UsampleSP = UsampleSP + G * (Fpoint);\n }\n\n std::cout << \"Usample M2L:\" << UsampleSP << std::endl;\n std::cout << \"Usample M2L total:\" << UsampleSP + Usample << std::endl;\n\n Eigen::Vector3d UsampleDirect = 0 * Usample;\n for (size_t p = 0; p < forcePoint.size(); p++) {\n GkernelEwald(samplePoint - forcePoint[p], G);\n UsampleDirect += G * (forceValue[p]);\n }\n std::cout << \"Usample Ewald:\" << UsampleDirect << std::endl;\n\n std::cout << \"error\" << UsampleSP + Usample - UsampleDirect << std::endl;\n\n return 0;\n}\n\n} // namespace Stokes2D3D\n\n#undef DIRECTLAYER\n#undef PI314\n", "meta": {"hexsha": "28e34ea7b98878317102b00496f96192349ea4ef", "size": 17858, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "M2LStokes/src/Stokes2D3D.cpp", "max_stars_repo_name": "blackwer/PeriodicFMM", "max_stars_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2018-06-14T02:07:52.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-18T04:41:34.000Z", "max_issues_repo_path": "M2LStokes/src/Stokes2D3D.cpp", "max_issues_repo_name": "blackwer/PeriodicFMM", "max_issues_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "M2LStokes/src/Stokes2D3D.cpp", "max_forks_repo_name": "blackwer/PeriodicFMM", "max_forks_repo_head_hexsha": "343130eef6bbba5d7d4101bdec961858ea084b4a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2018-04-06T16:30:44.000Z", "max_forks_repo_forks_event_max_datetime": "2019-10-14T20:26:36.000Z", "avg_line_length": 35.3623762376, "max_line_length": 96, "alphanum_fraction": 0.4967521559, "num_tokens": 6415, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7122321903471563, "lm_q1q2_score": 0.6462169743185256}} {"text": "#include \"../include/Jabc.hpp\"\n#include \n#include \n#include \n\n\nusing namespace std;\nusing namespace arma;\n\n\nvoid transform_xlogx_mat(cx_mat &X)\n{\n cx_mat U, V;\n vec s, sp;\n\n svd_econ(U, s, V, X);\n\n sp = s;\n\n for (int i=0; i0)\n {\n n/=2;\n k++;\n }\n return k;\n}\n\n// |\\psi\\rangle \\to K_X|\\psi\\rangle, where X is the first k qubits.\n// (Note that this is equal to K_{\\bar{X}})|\\psi\\rangle).\n// n: Number of qubits\n// Input format: psi should be a column vector.\nvoid apply_modular_op(int k, int n, cx_mat &psi)\n{\n psi.reshape(1<_{ABCD}, return \\log \\rho_{AB} |\\psi>_{ABCD}\n// a, b, c: Number of bits in A, B, C.\n// Format: First a bits are A. Next b bits are B. The next c bits are C.\nvoid transform_ab(int a, int b, int c, cx_mat &psi)\n{\n int dim = psi.size();\n int n = log2_int(dim);\n apply_modular_op(a+b, n, psi);\n}\n\n// Given |\\psi>_{ABCD}, return \\log \\rho_{BC} |\\psi>_{ABCD}\n// a, b, c: Number of bits in A, B, C.\n// Format: First a bits are A. Next b bits are B. The next c bits are C.\nvoid transform_bc(int a, int b, int c, cx_mat &psi)\n{\n int dim = psi.size();\n int n = log2_int(dim);\n psi.reshape(1<\n#include \n#include \n\nusing namespace boost::numeric::ublas;\n\n#define RBF_KERNEL RBF_multiquadric\n//#define RBF_KERNEL RBF_inv_quadric\n//#define RBF_KERNEL RBF_inv_multiquadric\n\n /* Matrix inversion routine.\n Uses lu_factorize and lu_substitute in uBLAS to invert a matrix */\ntemplate\nbool InvertMatrix(const matrix& input, matrix& inverse)\n{\n\ttypedef permutation_matrix pmatrix;\n\n\t// create a working copy of the input\n\tmatrix A(input);\n\n\t// create a permutation matrix for the LU-factorization\n\tpmatrix pm(A.size1());\n\n\t// perform LU-factorization\n\tint res = lu_factorize(A, pm);\n\tif (res != 0)\n\t\treturn false;\n\n\t// create identity matrix of \"inverse\"\n\tinverse.assign(identity_matrix (A.size1()));\n\n\t// backsubstitute to get the inverse\n\tlu_substitute(A, pm, inverse);\n\n\treturn true;\n}\n\n\nMeshMorph::MeshMorph() : Wx(0),Wy(0),Wz(0)\n{\n}\n\n\nMeshMorph::~MeshMorph(void)\n{\n}\n\nvoid MeshMorph::init(float* vertexData_, unsigned short vertexNum_, unsigned short* featureIndices_, unsigned short featureNum_)\n{\n\tvertexNum = vertexNum_;\n\tvertexData = new float[3 * vertexNum];\n\tmemcpy(vertexData, vertexData_, vertexNum * 3 * sizeof(float));\n\tfeatureNum = featureNum_;\n\tfeatureIndices = new unsigned short[featureNum];\n\tmemcpy(featureIndices, featureIndices_, featureNum * sizeof(unsigned short));\n\n\t//std::cout << RBFmInv << std::endl<< std::endl;\n\n\t//unsigned short* indices = new unsigned short[featureNum_];\n\t//for(unsigned short i = 0; i < featureNum_; ++i)\n\t//{\n\t//\tindices[i] = i;\n\t//}\n\t//solveRBF(indices, featureNum_, newFeaturePos_);\t\n\t//delete indices;\n}\n\nfloat MeshMorph::dist2(float* p1, float* p2)\n{\n\treturn (p1[0]-p2[0]) * (p1[0]-p2[0]) + (p1[1]-p2[1]) * (p1[1]-p2[1]) + (p1[2]-p2[2]) * (p1[2]-p2[2]);\n}\n\nvoid MeshMorph::getMorphedData(float* out, float* newFeaturePos_)\n{\n\tunsigned short* indices = new unsigned short[featureNum];\n\tfor(unsigned short i = 0; i < featureNum; ++i)\n\t{\n\t\tindices[i] = i;\n\t}\n\tsolveRBF(indices, featureNum, newFeaturePos_);\t\n\tdelete indices;\n\tfor(int i = 0; i < vertexNum; ++i)\n\t{\n\t\tout[i*3 + 0] = 0;\n\t\tout[i*3 + 1] = 0;\n\t\tout[i*3 + 2] = 0;\n\t\tfor(int j = 0; j < featureNum; ++j)\n\t\t{\n\t\t\tfloat d2 = dist2(&vertexData[i*3], &vertexData[featureIndices[j]*3]);\n\t\t\tout[i*3 + 0] += RBF_KERNEL(d2, minDist2[j]) * Wx[j];\n\t\t\tout[i*3 + 1] += RBF_KERNEL(d2, minDist2[j]) * Wy[j];\n\t\t\tout[i*3 + 2] += RBF_KERNEL(d2, minDist2[j]) * Wz[j];\n\t\t}\n\t}\n}\n\nvoid MeshMorph::getMorphedData(float* out, unsigned short* vertexIndices, unsigned short vertexNum_, unsigned short* featureIndices_, unsigned short featureNum_, float* newFeaturePos_, bool morphAllVertices)\n{\n\tsolveRBF(featureIndices_, featureNum_, newFeaturePos_);\n\tif(morphAllVertices)\n\t{\n\t\t//Copy all vertex positions\n\t\tmemcpy(out, vertexData, vertexNum * 3 * sizeof(float));\n\t\tfor(int i = 0; i < vertexNum_; ++i)\n\t\t{\n\t\t\tout[vertexIndices[i]*3 + 0] = 0;\n\t\t\tout[vertexIndices[i]*3 + 1] = 0;\n\t\t\tout[vertexIndices[i]*3 + 2] = 0;\n\t\t\tfor(int j = 0; j < featureNum_; ++j)\n\t\t\t{\n\t\t\t\tfloat d2 = dist2(&vertexData[vertexIndices[i]*3], &vertexData[featureIndices[featureIndices_[j]]*3]);\n\t\t\t\tout[vertexIndices[i]*3 + 0] += RBF_KERNEL(d2, minDist2[j]) * Wx[j];\n\t\t\t\tout[vertexIndices[i]*3 + 1] += RBF_KERNEL(d2, minDist2[j]) * Wy[j];\n\t\t\t\tout[vertexIndices[i]*3 + 2] += RBF_KERNEL(d2, minDist2[j]) * Wz[j];\n\t\t\t}\n\t\t}\n\t}\n\telse\n\t{\n\t\t//only output the morphed vertices\n\t\tfor(int i = 0; i < vertexNum_; ++i)\n\t\t{\n\t\t\tout[i*3 + 0] = 0;\n\t\t\tout[i*3 + 1] = 0;\n\t\t\tout[i*3 + 2] = 0;\n\t\t\tfor(int j = 0; j < featureNum_; ++j)\n\t\t\t{\n\t\t\t\tfloat d2 = dist2(&vertexData[vertexIndices[i]*3], &vertexData[featureIndices[featureIndices_[j]]*3]);\n\t\t\t\tout[i*3 + 0] += RBF_KERNEL(d2, minDist2[j]) * Wx[j];\n\t\t\t\tout[i*3 + 1] += RBF_KERNEL(d2, minDist2[j]) * Wy[j];\n\t\t\t\tout[i*3 + 2] += RBF_KERNEL(d2, minDist2[j]) * Wz[j];\n\t\t\t}\n\t\t}\n\t}\n}\n\n\nvoid MeshMorph::solveRBF(unsigned short* featureIndices_, unsigned short featureNum_, float* newFeaturePos_)\n{\n\tmatrix RBFm(featureNum_, featureNum_);\n\tminDist2 = new float[featureNum_];\t\n\tfor(int i = 0; i < featureNum_; ++i)\n\t{\n\t\tminDist2[i] = FLT_MAX;\n\t\tfor(int j = 0; j < featureNum_; ++j)\n\t\t{\n\t\t\tfloat d2 = dist2(&vertexData[featureIndices[featureIndices_[i]] * 3], &vertexData[featureIndices[featureIndices_[j]] * 3]);\n\t\t\tRBFm(i, j) = d2;\n\t\t\tif(i != j && d2 < minDist2[i])\n\t\t\t\tminDist2[i] = d2;\n\t\t}\n\t}\n\t//std::cout << RBFm << std::endl << std::endl;\n\tfor(int i = 0; i < featureNum_; ++i)\n\t{\n\t\tfor(int j = 0; j < featureNum_; ++j)\n\t\t{\n\t\t\tRBFm(i, j) = RBF_KERNEL(RBFm(i, j), minDist2[i]);\n\t\t}\n\t}\n\n\t//std::cout << RBFm << std::endl<< std::endl;\n\n\tRBFmInv.resize(featureNum_, featureNum_);\n\t\n\tInvertMatrix(RBFm, RBFmInv);\n\n\tif(Wx != 0) delete Wx;\n\tif(Wy != 0) delete Wy;\n\tif(Wz != 0) delete Wz;\n\tWx = new float[featureNum_];\n\tWy = new float[featureNum_];\n\tWz = new float[featureNum_];\n\n\tfor(int i = 0; i < featureNum_; ++i)\n\t{\n\t\tWx[i] = 0;\n\t\tWy[i] = 0;\n\t\tWz[i] = 0;\n\t\tfor(int j = 0; j < featureNum_; ++j)\n\t\t{\n\t\t\tWx[i] += RBFmInv(j,i) * newFeaturePos_[featureIndices_[j]*3];\n\t\t\tWy[i] += RBFmInv(j,i) * newFeaturePos_[featureIndices_[j]*3+1];\n\t\t\tWz[i] += RBFmInv(j,i) * newFeaturePos_[featureIndices_[j]*3+2];\n\t\t}\n\t}\n}\n\ninline float MeshMorph::RBF_multiquadric(float dist2, float eps)\n{\n\treturn sqrt(eps + dist2);\n}\ninline float MeshMorph::RBF_inv_quadric(float dist2, float eps)\n{\n\treturn 1.0 / (eps + dist2);//sqrt(eps + dist2 > (100*eps) ? 100 * eps : dist2);\n}\ninline float MeshMorph::RBF_inv_multiquadric(float dist2, float eps)\n{\n\treturn 1.0 / sqrt(eps * 10 + dist2);\n}\n", "meta": {"hexsha": "8e605519878209a038f567275a1adb5f3ed8ed75", "size": 5580, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Qt-GL-Simple-Scene-master/MeshMorph.cpp", "max_stars_repo_name": "nacsa/Retopology", "max_stars_repo_head_hexsha": "03c009462db3d73dbb73ea543952d421ecc1416e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Qt-GL-Simple-Scene-master/MeshMorph.cpp", "max_issues_repo_name": "nacsa/Retopology", "max_issues_repo_head_hexsha": "03c009462db3d73dbb73ea543952d421ecc1416e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Qt-GL-Simple-Scene-master/MeshMorph.cpp", "max_forks_repo_name": "nacsa/Retopology", "max_forks_repo_head_hexsha": "03c009462db3d73dbb73ea543952d421ecc1416e", "max_forks_repo_licenses": ["Apache-2.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.6237623762, "max_line_length": 207, "alphanum_fraction": 0.6501792115, "num_tokens": 1946, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9196425223682085, "lm_q2_score": 0.7025300449389326, "lm_q1q2_score": 0.6460765025670908}} {"text": "/* boost histogram.cpp graphical verification of distribution functions\n *\n * Copyright Jens Maurer 2000\n * Distributed under the Boost Software License, Version 1.0. (See\n * accompanying file LICENSE_1_0.txt or copy at\n * http://www.boost.org/LICENSE_1_0.txt)\n *\n * $Id: histogram.cpp 60755 2010-03-22 00:45:06Z steven_watanabe $\n *\n * This test program allows to visibly examine the results of the\n * distribution functions.\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nvoid plot_histogram(const std::vector& slots, int samples,\n double from, double to)\n{\n int m = *std::max_element(slots.begin(), slots.end());\n const int nRows = 20;\n std::cout.setf(std::ios::fixed|std::ios::left);\n std::cout.precision(5);\n for(int r = 0; r < nRows; r++) {\n double y = ((nRows - r) * double(m))/(nRows * samples);\n std::cout << std::setw(10) << y << \" \";\n for(unsigned int col = 0; col < slots.size(); col++) {\n char out = ' ';\n if(slots[col]/double(samples) >= y)\n out = 'x';\n std::cout << out;\n }\n std::cout << std::endl;\n }\n std::cout << std::setw(12) << \" \"\n << std::setw(10) << from;\n std::cout.setf(std::ios::right, std::ios::adjustfield);\n std::cout << std::setw(slots.size()-10) << to << std::endl;\n}\n\n// I am not sure whether these two should be in the library as well\n\n// maintain sum of NumberGenerator results\ntemplate\nclass sum_result\n{\npublic:\n typedef NumberGenerator base_type;\n typedef typename base_type::result_type result_type;\n explicit sum_result(const base_type & g) : gen(g), _sum(0) { }\n result_type operator()() { result_type r = gen(); _sum += r; return r; }\n base_type & base() { return gen; }\n Sum sum() const { return _sum; }\n void reset() { _sum = 0; }\nprivate:\n base_type gen;\n Sum _sum;\n};\n\n\n// maintain square sum of NumberGenerator results\ntemplate\nclass squaresum_result\n{\npublic:\n typedef NumberGenerator base_type;\n typedef typename base_type::result_type result_type;\n explicit squaresum_result(const base_type & g) : gen(g), _sum(0) { }\n result_type operator()() { result_type r = gen(); _sum += r*r; return r; }\n base_type & base() { return gen; }\n Sum squaresum() const { return _sum; }\n void reset() { _sum = 0; }\nprivate:\n base_type gen;\n Sum _sum;\n};\n\n\ntemplate\nvoid histogram(RNG base, int samples, double from, double to, \n const std::string & name)\n{\n typedef squaresum_result, double > SRNG;\n SRNG gen((sum_result(base)));\n const int nSlots = 60;\n std::vector slots(nSlots,0);\n for(int i = 0; i < samples; i++) {\n double val = gen();\n if(val < from || val >= to) // early check avoids overflow\n continue;\n int slot = int((val-from)/(to-from) * nSlots);\n if(slot < 0 || slot > (int)slots.size())\n continue;\n slots[slot]++;\n }\n std::cout << name << std::endl;\n plot_histogram(slots, samples, from, to);\n double mean = gen.base().sum() / samples;\n std::cout << \"mean: \" << mean\n << \" sigma: \" << std::sqrt(gen.squaresum()/samples-mean*mean)\n << \"\\n\" << std::endl;\n}\n\ntemplate\ninline boost::variate_generator make_gen(PRNG & rng, Dist d)\n{\n return boost::variate_generator(rng, d);\n}\n\ntemplate\nvoid histograms()\n{\n PRNG rng;\n using namespace boost;\n histogram(make_gen(rng, uniform_smallint<>(0, 5)), 100000, -1, 6,\n \"uniform_smallint(0,5)\");\n histogram(make_gen(rng, uniform_int<>(0, 5)), 100000, -1, 6,\n \"uniform_int(0,5)\");\n histogram(make_gen(rng, uniform_real<>(0,1)), 100000, -0.5, 1.5,\n \"uniform_real(0,1)\");\n histogram(make_gen(rng, bernoulli_distribution<>(0.2)), 100000, -0.5, 1.5,\n \"bernoulli(0.2)\");\n histogram(make_gen(rng, binomial_distribution<>(4, 0.2)), 100000, -1, 5,\n \"binomial(4, 0.2)\");\n histogram(make_gen(rng, triangle_distribution<>(1, 2, 8)), 100000, 0, 10,\n \"triangle(1,2,8)\");\n histogram(make_gen(rng, geometric_distribution<>(5.0/6.0)), 100000, 0, 10,\n \"geometric(5/6)\");\n histogram(make_gen(rng, exponential_distribution<>(0.3)), 100000, 0, 10,\n \"exponential(0.3)\");\n histogram(make_gen(rng, cauchy_distribution<>()), 100000, -5, 5,\n \"cauchy\");\n histogram(make_gen(rng, lognormal_distribution<>(3, 2)), 100000, 0, 10,\n \"lognormal\");\n histogram(make_gen(rng, normal_distribution<>()), 100000, -3, 3,\n \"normal\");\n histogram(make_gen(rng, normal_distribution<>(0.5, 0.5)), 100000, -3, 3,\n \"normal(0.5, 0.5)\");\n histogram(make_gen(rng, poisson_distribution<>(1.5)), 100000, 0, 5,\n \"poisson(1.5)\");\n histogram(make_gen(rng, poisson_distribution<>(10)), 100000, 0, 20,\n \"poisson(10)\");\n histogram(make_gen(rng, gamma_distribution<>(0.5)), 100000, 0, 0.5,\n \"gamma(0.5)\");\n histogram(make_gen(rng, gamma_distribution<>(1)), 100000, 0, 3,\n \"gamma(1)\");\n histogram(make_gen(rng, gamma_distribution<>(2)), 100000, 0, 6,\n \"gamma(2)\");\n}\n\n\nint main()\n{\n histograms();\n // histograms();\n}\n\n", "meta": {"hexsha": "11ad00c3f32bf367fe8701b4e4b1039cefaa2a5c", "size": 5437, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/random/test/histogram.cpp", "max_stars_repo_name": "ai-nikolaev/repo-cppboost", "max_stars_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 11.0, "max_stars_repo_stars_event_min_datetime": "2016-04-12T16:29:29.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-28T11:01:57.000Z", "max_issues_repo_path": "libs/random/test/histogram.cpp", "max_issues_repo_name": "ai-nikolaev/repo-cppboost", "max_issues_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 3.0, "max_issues_repo_issues_event_min_datetime": "2018-10-31T19:35:14.000Z", "max_issues_repo_issues_event_max_datetime": "2019-06-04T17:11:27.000Z", "max_forks_repo_path": "libs/random/test/histogram.cpp", "max_forks_repo_name": "ai-nikolaev/repo-cppboost", "max_forks_repo_head_hexsha": "218c4a977c6d8cd6f2864cdcea1b6ab53160d203", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 9.0, "max_forks_repo_forks_event_min_datetime": "2015-09-09T02:38:32.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-30T00:24:24.000Z", "avg_line_length": 32.7530120482, "max_line_length": 76, "alphanum_fraction": 0.6288394335, "num_tokens": 1589, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8311430394931456, "lm_q2_score": 0.7772998714925403, "lm_q1q2_score": 0.6460473777899415}} {"text": "#pragma once\n#include \"coordinate_transform.hpp\"\n#include \"integrate.hpp\"\n#include \"shape.hpp\"\n#include \n#include \n#include \n\n//! Computes the H^1 differences between\n//! u1 (considered as coefficients for the shape functions)\n//! and u2grad.\ndouble computeH1Difference(const Eigen::MatrixXd &vertices,\n const Eigen::MatrixXi &triangles,\n const Eigen::VectorXd &u1,\n const std::function &u2grad) {\n\tconst int numberOfElements = triangles.rows();\n\n\tdouble error = 0;\n\tfor (int i = 0; i < numberOfElements; ++i) {\n\t\tauto &indexSet = triangles.row(i);\n\n\t\tconst int i0 = indexSet(0);\n\t\tconst int i1 = indexSet(1);\n\t\tconst int i2 = indexSet(2);\n\n\t\tconst auto &a = vertices.row(i0);\n\t\tconst auto &b = vertices.row(i1);\n\t\tconst auto &c = vertices.row(i2);\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\terror += integrate([&](double x, double y) {\n\t\t\tEigen::Vector2d z = coordinateTransform * Eigen::Vector2d(x, y) + Eigen::Vector2d(a(0), a(1));\n\n\t\t\tEigen::Vector2d approximate_grad = u1(i0) * elementMap * gradientLambda(0, x, y) + u1(i1) * elementMap * gradientLambda(1, x, y) + u1(i2) * elementMap * gradientLambda(2, x, y);\n\t\t\tEigen::Vector2d difference_grad = u2grad(z(0), z(1)) - approximate_grad;\n\t\t\treturn difference_grad.dot(difference_grad) * volumeFactor;\n\t\t});\n\t}\n\n\treturn std::sqrt(error);\n}\n", "meta": {"hexsha": "90bce007fef43de337b32ebf9f62566f9e204ade", "size": 1651, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "series2/2d-linFEM/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": "series2/2d-linFEM/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": "series2/2d-linFEM/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": 36.6888888889, "max_line_length": 180, "alphanum_fraction": 0.6535433071, "num_tokens": 438, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111796979521252, "lm_q2_score": 0.7090191337850933, "lm_q1q2_score": 0.6460438401645787}} {"text": "//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n//% Code implementing the paper \"Accelerated Quadratic Proxy for Geometric Optimization\", SIGGRAPH 2016.\n//% Disclaimer: The code is provided as-is for academic use only and without any guarantees. \n//% Please contact the author to report any bugs.\n//% Written by Shahar Kovalsky (http://www.wisdom.weizmann.ac.il/~shaharko/)\n//% Meirav Galun (http://www.wisdom.weizmann.ac.il/~/meirav/)\n//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n#include \"mex.h\"\n#include \n#include \n#include \"mexHelpers.cpp\"\n\nusing namespace Eigen;\n\nvoid computeMeshTranformationCoeffsFullDim(const MatrixXd& F, const MatrixXd& V, SparseMatrix &T, VectorXd& areas)\n{\n\t// init\n\tint n_tri = F.rows();\n\tint d_simplex = F.cols();\n\tint n_vert = V.rows();\n\tint dim = V.cols();\n\tint T_rows = n_tri*dim*dim;\n\tint T_cols = n_vert*dim;\n\tint T_nnz = n_tri*dim*dim*d_simplex;\n\n\n\t// prepare centering matrix\n\tMatrixXd B = MatrixXd::Identity(d_simplex, d_simplex);\n\tB = B.array() - (1.0 / d_simplex);\n\n\t// prepare output matrix\n\tT.resize(T_cols, T_rows);\n\tT.reserve(VectorXi::Constant(T_rows, d_simplex));\n\tareas.resize(n_tri);\n\n\t// calculate differential coefficients for each element\n\tMatrixXd currV(d_simplex, dim);\n\tMatrixXd currT(dim, d_simplex);\n\tint curr_row = 0;\n\tfor (int ii = 0; ii < n_tri; ii++)\n\t{\n\t\t// calculate current element\n\t\tfor (int jj = 0; jj < d_simplex; jj++)\n\t\t{\n\t\t\tcurrV.row(jj) = V.row(F(ii, jj));\n\t\t}\n\t\tcurrV = B*currV; // center\n\t\tcurrT = currV.fullPivLu().solve(B); // solver\n\n\t\t// fill into the correct places of T\n\t\tfor (int cd = 0; cd < dim; cd++)\n\t\tfor (int cr = 0; cr < dim; cr++)\n\t\t{\n\t\t\tfor (int cc = 0; cc < d_simplex; cc++)\n\t\t\t\tT.insert(F(ii, cc) + (cd*n_vert), curr_row) = currT(cr, cc);\n\t\t\tcurr_row += 1;\n\t\t}\n\n\t\t// calculate area\n\t\tareas(ii) = (currV.bottomRows(dim).rowwise() - currV.row(0)).determinant() / 2;\n\t}\n\n\t// compress\n\tT.makeCompressed();\n\tT = T.transpose();\n}\n\n\nvoid orth(const MatrixXd &A, MatrixXd &Q)\n{\n\n\t//perform svd on A = U*S*V' (V is not computed and only the thin U is computed)\n\tEigen::JacobiSVD svd(A, Eigen::ComputeThinU);\n\tEigen::MatrixXd U = svd.matrixU();\n\tconst Eigen::VectorXd S = svd.singularValues();\n\n\t//get rank of A\n\tint m = A.rows();\n\tint n = A.cols();\n\tdouble tol = std::max(m, n) * S.maxCoeff() * 2.2204e-16;\n\tint r = 0;\n\tfor (int i = 0; i < S.rows(); ++r, ++i)\n\t{\n\t\tif (S[i] < tol)\n\t\t\tbreak;\n\t}\n\n\t//keep r first columns of U\n\tQ = U.block(0, 0, U.rows(), r);\n}\n\nvoid compute2dEmbedding(const MatrixXd& V, MatrixXd& A)\n{\n\t// given a nXn matrix whose columns are the vertices of a (n-1)-D simplex,\n\t// returns the transformation A, s.t A*V gives embedding in (n-1)-D\n\n\tMatrixXd ctrV(V.rows() - 1, V.cols());\n\tctrV = -V.bottomRows(V.rows() - 1);\n\tctrV.rowwise() += V.row(0);\n\tctrV.transpose();\n\torth(ctrV, A);\n\t//if (((ctrV*A).determinant()) < 0)\n\t//\tA.col(0).swap(A.col(1));\n\tA.transpose();\n}\n\nvoid embedTriangle(const MatrixXd& V, MatrixXd& flatV, double& area)\n{\n\tVectorXd v1 = V.row(1) - V.row(0);\n\tVectorXd v2 = V.row(2) - V.row(0);\n\n\tdouble norm_v1 = v1.norm();\n\tdouble norm_v2 = v2.norm();\n\tdouble cos_theta = v1.dot(v2) / (norm_v1*norm_v2);\n\tdouble sin_theta = sqrt(1 - cos_theta*cos_theta);\n\n\tflatV << 0, 0,\n\t\tnorm_v1, 0,\n\t\tnorm_v2*cos_theta, norm_v2*sin_theta;\n\n\tarea = norm_v1*norm_v2*sin_theta / 2;\n}\n\nvoid computeMeshTranformationCoeffsFlatenning(const MatrixXd& F, const MatrixXd& V, SparseMatrix &T, VectorXd& areas)\n{\n\t// init\n\tint n_tri = F.rows();\n\tint d_simplex = F.cols();\n\tint n_vert = V.rows();\n\tint dim = V.cols();\n\tint d_diff = dim - 1;\n\tint T_rows = n_tri*d_diff*d_diff;\n\tint T_cols = n_vert*d_diff;\n\tint T_nnz = n_tri*d_diff*d_diff*d_simplex;\n\n\tassert(d_simplex == 3 && dim == 3);\n\n\t// prepare centering matrix\n\tMatrixXd B = MatrixXd::Identity(d_simplex, d_simplex);\n\tB = B.array() - (1.0 / d_simplex);\n\n\t// prepare output matrix\n\tT.resize(T_cols, T_rows);\n\tT.reserve(VectorXi::Constant(T_rows, d_simplex));\n\tareas.resize(n_tri);\n\n\t// calculate differential coefficients for each element\n\tMatrixXd currV(d_simplex, dim);\n\tMatrixXd currT(dim, d_simplex);\n\tMatrixXd RFlat(dim, d_diff);\n\tMatrixXd currVFlat(d_simplex, d_diff);\n\tint curr_row = 0;\n\tfor (int ii = 0; ii < n_tri; ii++)\n\t{\n\t\t// calculate current element\n\t\tfor (int jj = 0; jj < d_simplex; jj++)\n\t\t{\n\t\t\tcurrV.row(jj) = V.row(F(ii, jj));\n\t\t}\n\t\t// transform to plane\n\t\tembedTriangle(currV, currVFlat, areas(ii)); // this only works for triangles\n\t\t// compute\n\t\tcurrVFlat = B*currVFlat; // center\n\t\tcurrT = currVFlat.fullPivLu().solve(B); // solver\n\n\t\t// fill into the correct places of T\n\t\tfor (int cd = 0; cd < d_diff; cd++)\n\t\tfor (int cr = 0; cr < d_diff; cr++)\n\t\t{\n\t\t\tfor (int cc = 0; cc < d_simplex; cc++)\n\t\t\t\tT.insert(F(ii, cc) + (cd*n_vert), curr_row) = currT(cr, cc);\n\t\t\tcurr_row += 1;\n\t\t}\n\t}\n\n\t// compress\n\tT.makeCompressed();\n\tT = T.transpose();\n}\n\nvoid mexFunction(int nlhs, mxArray *plhs[],\n\tint nrhs, const mxArray*prhs[])\n{\n\t// assign input\n\tint n_tri = mxGetM(prhs[0]); // # rows of F\n\tint d_simplex = mxGetN(prhs[0]); // # cols of F\n\tint n_vert = mxGetM(prhs[1]); // # rows of V\n\tint dim = mxGetN(prhs[1]); // # cols of V\n\tconst Map Fmatlab(mxGetPr(prhs[0]), n_tri, d_simplex);\n\tconst Map V(mxGetPr(prhs[1]), n_vert, dim);\n\t\n\t// update index numbers to 0-base\n\tMatrixXd F (Fmatlab);\n\tF = F.array() - 1;\t\n\n\t// compute\n\tSparseMatrix T;\n\tVectorXd areas;\n\tif (d_simplex == 3 && dim == 2)\n\t{\n\t\t// Planar triangulation\n\t\tcomputeMeshTranformationCoeffsFullDim(F, V, T, areas);\n\t}\n\telse if (d_simplex == 4 && dim == 3)\n\t{\n\t\t// Tet mesh\n\t\tcomputeMeshTranformationCoeffsFullDim(F, V, T, areas);\n\t}\n\telse if (d_simplex == 3 && dim == 3)\n\t{\n\t\t// 3D surface\n\t\tcomputeMeshTranformationCoeffsFlatenning(F, V, T, areas);\n\t}\n\telse\n\t\tmexErrMsgIdAndTxt(\"MATLAB:invalidInputs\", \"Invalid input dimensions or mesh type not supported\");\n\n\n\t// assign outputs\n\tmapSparseMatrixToMex(T, &(plhs[0]));\n\tmapDenseMatrixToMex(areas, &(plhs[1]));\n}", "meta": {"hexsha": "21aa529445004efdf7f96c5856ff0ca070a0037e", "size": 6087, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/2D/lib/mex/computeMeshTranformationCoeffsMex.cpp", "max_stars_repo_name": "ErisZhang/BCQN", "max_stars_repo_head_hexsha": "6c103e0e173bb825e4207b282a0cba2ce5d10e24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2016-06-08T11:12:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-29T06:45:26.000Z", "max_issues_repo_path": "code/2D/lib/mex/computeMeshTranformationCoeffsMex.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/computeMeshTranformationCoeffsMex.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": 27.4189189189, "max_line_length": 125, "alphanum_fraction": 0.6369311648, "num_tokens": 1975, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9372107878954105, "lm_q2_score": 0.6893056295505783, "lm_q1q2_score": 0.6460246721718393}} {"text": "#include \n#include \n#include \n#include \n\n\nusing namespace Eigen;\nusing namespace std;\n\n\ndouble amips_param;\ndouble energy_min;\ndouble energy_max = 10;\ndouble c1_param;\ndouble c2_param;\ndouble d1_param;\n\n\nVector3d color_map(double v)\n{\n\tVector3d c;\n \n c[0] = c[1] = c[2] = 1;\n\n\tdouble dv;\n\n\tif (v < energy_min)\n\t\tv = energy_min;\n\tif (v > energy_max)\n\t\tv = energy_max;\n\tdv = energy_max - energy_min;\n\n\tif (v < (energy_min + 0.25 * dv)) {\n\t\tc[0] = 0;\n\t\tc[1] = 4 * (v - energy_min) / dv;\n\t}\n\telse if (v < (energy_min + 0.5 * dv)) {\n\t\tc[0] = 0;\n\t\tc[2] = 1 + 4 * (energy_min + 0.25 * dv - v) / dv;\n\t}\n\telse if (v < (energy_min + 0.75 * dv)) {\n\t\tc[0] = 4 * (v - energy_min - 0.5 * dv) / dv;\n\t\tc[2] = 0;\n\t}\n\telse {\n\t\tc[1] = 1 + 4 * (energy_min + 0.75 * dv - v) / dv;\n\t\tc[2] = 0;\n\t}\n\n\treturn c;\n}\n\n\nvoid set_energy_min(int type)\n{\n\n switch(type)\n {\n case 0: //arap\n energy_min = 0;\n break;\n \n case 1: // mips\n energy_min = 2;\n break;\n \n case 2: // iso\n energy_min = 4;\n break;\n \n case 3: // amips\n energy_min = exp(amips_param * 2);\n break;\n \n case 4: // conf\n energy_min = 1;\n break;\n \n case 5: \n energy_min = -c1_param - 2 * c2_param;\n break;\n }\n \n}\n\n\ndouble energy_value(int type, Vector2d S)\n{\n \n double value = 0;\n double J;\n double l1;\n double l2;\n \n switch(type)\n {\n case 0: //arap\n value = (S[0] - 1) * (S[0] - 1) + (S[1] - 1) * (S[1] - 1);\n break;\n \n case 1: // mips\n value = S[0] / S[1] + S[1] / S[0];\n break;\n \n case 2: // iso\n value = S[0] * S[0] + 1.0 / (S[0] * S[0]) + S[1] * S[1] + 1.0 / (S[1] * S[1]);\n break;\n \n case 3: // amips\n value = exp(amips_param * (S[0] / S[1] + S[1] / S[0]));\n break;\n \n case 4: // conf\n value = S[0] / S[1];\n value *= value;\n break;\n \n case 5: // gmr\n J = S[0] * S[1];\n l1 = S[0] * S[0] + S[1] * S[1];\n l2 = S[0] * S[0] * S[1] * S[1];\n \n value = c1_param * (pow(J, -2.0 / 3.0) * l1 - 3) + c2_param * (pow(J, -4.0 / 3.0) * l2 - 3) + d1_param * (J - 1) * (J - 1);\n break;\n \n case 6: // olg\n \n value = max(S[0], 1.0 / S[1]);\n break;\n }\n \n return value;\n\n}\n\n\nvoid mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])\n{\n \n mxArray *output_mex;\n const int *dims;\n double *tri_num, *X_g_inv, *tri_areas, *obj_tri, *q_target, *type, *amips_s, *c1, *c2, *d1;\n double *output;\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 c1 = mxGetPr(prhs[7]);\n c2 = mxGetPr(prhs[8]);\n d1 = mxGetPr(prhs[9]); \n \n int tri_n = tri_num[0];\n int energy_type = type[0];\n amips_param = amips_s[0];\n c1_param = c1[0];\n c2_param = c2[0];\n d1_param = d1[0];\n \n output_mex = plhs[0] = mxCreateDoubleMatrix(tri_n, 1, mxREAL);\n \n output = mxGetPr(output_mex);\n \n \n int tri[3];\n double tri_area;\n \n \n Matrix2d B, X_f, A;\n Vector2d S;\n Matrix2d U, V;\n \n for(int i = 0; i < tri_n; i++)\n {\n //mexPrintf(\"%d %d %d\\n\", (int)obj_tri[i], (int)obj_tri[i + tri_n], (int)obj_tri[i + 2 * tri_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 if(A.determinant() <= 0)\n {\n //mexPrintf(\"element inverted\");\n }\n \n JacobiSVD svd(A, ComputeFullU | ComputeFullV);\n \n S = svd.singularValues();\n U = svd.matrixU();\n V = svd.matrixV();\n \n output[i] = energy_value(energy_type, S);\n \n }\n \n return;\n \n}", "meta": {"hexsha": "118ca0b244d8eee8e97aa468a96861e7fc6a8325", "size": 4747, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "code/2D/lib/mex/energy_color_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/energy_color_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/energy_color_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": 22.2863849765, "max_line_length": 135, "alphanum_fraction": 0.4415420265, "num_tokens": 1698, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9416541659378681, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.6459271679767884}} {"text": "#include \"maxwellJuttner.h\"\n\n#include \n#include \n#include \n\n\ndouble f_norm(double g, double norm_temp)\n{\n\tdouble beta = sqrt(1.0-1.0/P2(g));\n\t\n\treturn P2(g)*beta*exp(-g/norm_temp); \n\t\n}\n\ndouble maxwellRel(double gamma, double norm_temp, double norm)\n{\n\t\t\n\tdouble beta = sqrt(1.0-1.0/(gamma*gamma));\n\t\n\tdouble K2 = boost::math::cyl_bessel_k(2, 1.0/norm_temp); //bessk(2, 1.0/norm_temp);\n\t\n\tdouble dist_g = gamma*gamma*beta*exp(-gamma/norm_temp) / (K2*norm_temp);\n\n\treturn dist_g*norm;\n\n}", "meta": {"hexsha": "cd8a03018e3eb918f88ea57924c454b7125152b4", "size": 569, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/adaf/maxwellJuttner.cpp", "max_stars_repo_name": "eduardomgutierrez/RIAF_radproc", "max_stars_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-08-30T06:56:03.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T06:56:03.000Z", "max_issues_repo_path": "src/adaf/maxwellJuttner.cpp", "max_issues_repo_name": "eduardomgutierrez/RIAF_radproc", "max_issues_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/adaf/maxwellJuttner.cpp", "max_forks_repo_name": "eduardomgutierrez/RIAF_radproc", "max_forks_repo_head_hexsha": "0e4166f04cce27fed2cbd2c7078023c10e0e8d12", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 21.0740740741, "max_line_length": 85, "alphanum_fraction": 0.7012302285, "num_tokens": 188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.9416541610257063, "lm_q2_score": 0.6859494485880928, "lm_q1q2_score": 0.6459271525162664}} {"text": "/**\n @file Project_1.cpp\n\n @author Terence Henriod\n\n Project 1: Bayesion Minimum Error Classification\n\n @brief The driver program for use of a Bayesian Minimum Error Classifier.\n\n @version Original Code 1.00 (3/8/2014) - T. Henriod\n\n UNOFFICIALLY:\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n\n\n\nCompilation notes:\ng++ -I /home/thenriod/Desktop/cpp_libs/Eigen_lib/ Project_1.cpp\n\n*/\n\n/*==============================================================================\n======= HEADER FILES ===================================================\n==============================================================================*/\n#include \n#include \n\n#include \"bayes_classifier.cpp\"\n#include // -I /home/thenriod/Desktop/cpp_libs/Eigen_lib\n\nusing namespace std;\n\n/*==============================================================================\n======= USER DEFINED TYPES =============================================\n==============================================================================*/\n\n\n\n/*==============================================================================\n======= CONSTANTS / MACROS =============================================\n==============================================================================*/\n\n\n/*==============================================================================\n======= GLOBAL VARIABLES ===============================================\n==============================================================================*/\n // none\n\n/*==============================================================================\n======= FUNCTION PROTOTYPES ============================================\n==============================================================================*/\n \n\n\n\n/*==============================================================================\n======= MAIN FUNCTION ==================================================\n==============================================================================*/\n\n/**\nmain\n\nThe main driver\n\n@param\n\n@return\n\n@pre\n-#\n\n@post\n-#\n\n@code\n@endcode\n*/\n\nint main( int argc, char** argv )\n{\n // variables\n BayesClassifier problem_solver;\n double part_A_prior_probability = 0.5;\n double part_B_prior_probability = 0.3;\n Eigen::Vector2d part_one_mean_one;\n part_one_mean_one << 1.502, 1.484;\n Eigen::Vector2d part_one_mean_two;\n part_one_mean_two << 2.499, 2.497;\n Eigen::Vector2d part_two_mean_one;\n part_two_mean_one << 1, 2;\n Eigen::Vector2d part_two_mean_two;\n part_two_mean_two << 1, 4;\n Eigen::Matrix2d part_one_covariance_one;\n part_one_covariance_one << 1.099, 0,\n 0, 1.099;\n Eigen::Matrix2d part_one_covariance_two;\n part_one_covariance_two << 1.813, 0,\n 0, 1.813;\n Eigen::Matrix2d part_two_covariance_one;\n part_two_covariance_one << 1, 0,\n 0, 1;\n Eigen::Matrix2d part_two_covariance_two;\n part_two_covariance_two << 3, 0,\n 0, 2;\n\n // setup for problem 1\n problem_solver.setMean( part_one_mean_one, CLASS_ONE );\n problem_solver.setMean( part_one_mean_two, CLASS_TWO );\n problem_solver.setCovariance( part_one_covariance_one, CLASS_ONE );\n problem_solver.setCovariance( part_one_covariance_two, CLASS_TWO );\n problem_solver.setPriorProbabilities( part_A_prior_probability );\n problem_solver.setAssumptionCase( CASE_ONE );\n\n // solve 1.a\n// problem_solver.performAnalysis( \"P1_data.txt\", \"test_1A_output.txt\" );\nproblem_solver.performAnalysis( \"Bebis11.txt\", \"Bebis1A.txt\" );\n\n // solve 1.b\n problem_solver.setPriorProbabilities( part_B_prior_probability );\n// problem_solver.performAnalysis( \"P1_data.txt\", \"test_1B_output.txt\" );\nproblem_solver.performAnalysis( \"Bebis11.txt\", \"Bebis1B.txt\" );\n\n // setup for problem 2\n problem_solver.setMean( part_two_mean_one, CLASS_ONE );\n problem_solver.setMean( part_two_mean_two, CLASS_TWO );\n problem_solver.setCovariance( part_two_covariance_one, CLASS_ONE );\n problem_solver.setCovariance( part_two_covariance_two, CLASS_TWO );\n problem_solver.setPriorProbabilities( part_A_prior_probability );\n problem_solver.setAssumptionCase( CASE_THREE );\n\n // solve 2.a\n// problem_solver.performAnalysis( \"P2_data.txt\", \"test_2A_output.txt\" );\nproblem_solver.performAnalysis( \"Bebis21.txt\", \"Bebis2A.txt\" );\n\n // solve 2.b\n problem_solver.setPriorProbabilities( part_B_prior_probability );\n// problem_solver.performAnalysis( \"P2_data.txt\", \"test_2B_output.txt\" );\nproblem_solver.performAnalysis( \"Bebis21.txt\", \"Bebis2B.txt\" );\n\n // end program\n return 0;\n}\n\n/*==============================================================================\n======= FUNCTION IMPLEMENTATIONS =======================================\n==============================================================================*/\n\n\n", "meta": {"hexsha": "7842dad357eb849a9f1441641e5519a916aadd87", "size": 5507, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CS479/Project_1/code_files/Project_1.cpp", "max_stars_repo_name": "T-R0D/Past-Courses", "max_stars_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2017-03-13T17:32:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-27T16:51:22.000Z", "max_issues_repo_path": "CS479/Project_1/code_files/Project_1.cpp", "max_issues_repo_name": "T-R0D/Past-Courses", "max_issues_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-29T19:54:02.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-29T19:54:52.000Z", "max_forks_repo_path": "CS479/Project_1/code_files/Project_1.cpp", "max_forks_repo_name": "T-R0D/Past-Courses", "max_forks_repo_head_hexsha": "0edc83a7bf09515f0d01d23a26df2ff90c0f458a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 25.0, "max_forks_repo_forks_event_min_datetime": "2016-10-18T03:31:44.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-29T13:23:10.000Z", "avg_line_length": 34.41875, "max_line_length": 80, "alphanum_fraction": 0.5184310877, "num_tokens": 1114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424373085145, "lm_q2_score": 0.7634837689358857, "lm_q1q2_score": 0.6458633203391138}} {"text": "/*****************************************************************************\n*\n* Rokko: Integrated Interface for libraries of eigenvalue decomposition\n*\n* Copyright (C) 2015 Rokko Developers https://github.com/t-sakashita/rokko\n*\n* Distributed under the Boost Software License, Version 1.0. (See accompanying\n* file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n*\n*****************************************************************************/\n\n#include \n#include \n#include \n\ntypedef rokko::localized_vector vector_t;\ntypedef rokko::localized_matrix, rokko::matrix_col_major> matrix_t;\n\nint main(int argc, char *argv[]) {\n int info;\n int m = 6;\n int n = 4;\n if (argc > 2) {\n m = boost::lexical_cast(argv[1]);\n n = boost::lexical_cast(argv[2]);\n }\n std::cout << \"m = \" << m << \"\\nn = \" << n << std::endl;\n int k = std::min(m, n);\n\n // generate random martix\n matrix_t mat = matrix_t::Random(m, n);\n std::cout << \"Input random matrix A:\\n\" << mat << std::endl;\n\n // singular value decomposition\n matrix_t a = mat; // 'a' will be destroyed by dgesvd\n vector_t s(k), superb(k);\n matrix_t u(m, k), vt(k, n);\n info = LAPACKE_zgesvd(LAPACK_COL_MAJOR, 'S', 'S', m, n, &a(0, 0), m, &s(0),\n &u(0, 0), m, &vt(0, 0), k, &superb(0));\n std::cout << \"U:\\n\" << u << std::endl;\n std::cout << \"S:\\n\" << s << std::endl;\n std::cout << \"Vt:\\n\" << vt << std::endl;\n\n // check correctness of SVD\n matrix_t smat = matrix_t::Zero(k, k);\n for (int i = 0; i < k; ++i) smat(i, i) = s(i);\n matrix_t check = u * smat * vt;\n std::cout << \"U * S * Vt:\\n\" << check << std::endl;\n std::cout << \"| A - U * S * Vt | = \" << (mat - check).norm() << std::endl;\n}\n", "meta": {"hexsha": "54c685f7719a224d4767b9304043a1abed5e9ed8", "size": 1794, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "example/cxx/lapack/svd_c.cpp", "max_stars_repo_name": "wistaria/rokko", "max_stars_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "example/cxx/lapack/svd_c.cpp", "max_issues_repo_name": "wistaria/rokko", "max_issues_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example/cxx/lapack/svd_c.cpp", "max_forks_repo_name": "wistaria/rokko", "max_forks_repo_head_hexsha": "7cd9d5155e82f038039a46c1dc8f382b3fe7e2b7", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.1764705882, "max_line_length": 88, "alphanum_fraction": 0.5451505017, "num_tokens": 565, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8397339797047029, "lm_q2_score": 0.7690802476562641, "lm_q1q2_score": 0.6458228170766732}} {"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_UNITY_ROOT_HPP\n#define CRYPTO3_MATH_UNITY_ROOT_HPP\n\n#include \n#include \n\n#include \n#include \n\nnamespace nil {\n namespace crypto3 {\n namespace math {\n\n template\n constexpr typename std::enable_if>::value,\n typename FieldType::value_type>::type\n unity_root(const std::size_t n) {\n const double PI = boost::math::constants::pi();\n\n return typename FieldType::value_type(cos(2 * PI / n), sin(2 * PI / n));\n }\n\n template\n constexpr\n typename std::enable_if>::value,\n typename FieldType::value_type>::type\n unity_root(const std::size_t n) {\n\n typedef typename FieldType::value_type value_type;\n\n const std::size_t logn = std::ceil(std::log2(n));\n\n if (n != (1u << logn)) {\n throw std::invalid_argument(\"expected n == (1u << logn)\");\n }\n if (logn > algebra::fields::arithmetic_params::s) {\n throw std::invalid_argument(\"expected logn <= arithmetic_params::s\");\n }\n\n value_type omega = value_type(algebra::fields::arithmetic_params::root_of_unity);\n for (std::size_t i = algebra::fields::arithmetic_params::s; i > logn; --i) {\n omega *= omega;\n }\n\n return omega;\n }\n } // namespace math\n } // namespace crypto3\n} // namespace nil\n\n#endif // CRYPTO3_MATH_UNITY_ROOT_HPP\n", "meta": {"hexsha": "86fa55fae1a5f3f7047c4aac50fbc797f46da3c3", "size": 3357, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/nil/crypto3/math/algorithms/unity_root.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/algorithms/unity_root.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/algorithms/unity_root.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": 43.5974025974, "max_line_length": 120, "alphanum_fraction": 0.6064938934, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8947894632969136, "lm_q2_score": 0.7217432062975979, "lm_q1q2_score": 0.6458082162012212}} {"text": "/** @file main.cpp Demonstrates arbitrary-precision factorial and Fibonacci\n * functions using Boost.Multiprecision.\n *\n * @note This implementation uses output parameters to allow reuse of\n * previously allocated memory. The technique also supports the potential\n * future use of custom allocators, since the caller of each function\n * allocates and configures the result object. Moreover, the use of in-place\n * operators for assignments avoids the creation of unnecessary temporary\n * objects.\n *\n * @todo Memoize functions. They currently require O(n) time per call.\n */\n\n#include \n#include \n\nusing big_int = boost::multiprecision::cpp_int;\n\nusing std::swap;\n\nvoid factorial(big_int* r, int n)\n{\n for (*r = 1; n > 1; --n) {\n *r *= n;\n }\n}\n\nvoid fibonacci(big_int* r, int n)\n{\n *r = 1;\n for (big_int s = 1; n > 0; --n) {\n swap(*r, s);\n s += *r;\n }\n}\n\nint main()\n{\n big_int r;\n for (int i = 0; i < 100; ++i) {\n factorial(&r, i);\n std::cout << i << ' ' << r << ' ';\n fibonacci(&r, i);\n std::cout << r << '\\n';\n }\n}\n", "meta": {"hexsha": "cdddf9cb00b81bc34da7009378127db91af6b200", "size": 1147, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/control.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/control.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/control.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": 24.4042553191, "max_line_length": 78, "alphanum_fraction": 0.6129032258, "num_tokens": 317, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7401743735019595, "lm_q1q2_score": 0.6456891666156742}} {"text": "// (C) Copyright Nick Thompson 2018.\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0. (See accompanying file\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_TOOLS_BIVARIATE_STATISTICS_HPP\n#define BOOST_MATH_TOOLS_BIVARIATE_STATISTICS_HPP\n\n#include \n#include \n#include \n#include \n\nBOOST_MATH_HEADER_DEPRECATED(\"\");\n\nnamespace boost{ namespace math{ namespace tools {\n\ntemplate\nauto means_and_covariance(Container const & u, Container const & v)\n{\n using Real = typename Container::value_type;\n using std::size;\n BOOST_MATH_ASSERT_MSG(size(u) == size(v), \"The size of each vector must be the same to compute covariance.\");\n BOOST_MATH_ASSERT_MSG(size(u) > 0, \"Computing covariance requires at least one sample.\");\n\n // See Equation III.9 of \"Numerically Stable, Single-Pass, Parallel Statistics Algorithms\", Bennet et al.\n Real cov = 0;\n Real mu_u = u[0];\n Real mu_v = v[0];\n\n for(size_t i = 1; i < size(u); ++i)\n {\n Real u_tmp = (u[i] - mu_u)/(i+1);\n Real v_tmp = v[i] - mu_v;\n cov += i*u_tmp*v_tmp;\n mu_u = mu_u + u_tmp;\n mu_v = mu_v + v_tmp/(i+1);\n }\n\n return std::make_tuple(mu_u, mu_v, cov/size(u));\n}\n\ntemplate\nauto covariance(Container const & u, Container const & v)\n{\n auto [mu_u, mu_v, cov] = boost::math::tools::means_and_covariance(u, v);\n return cov;\n}\n\ntemplate\nauto correlation_coefficient(Container const & u, Container const & v)\n{\n using Real = typename Container::value_type;\n using std::size;\n BOOST_MATH_ASSERT_MSG(size(u) == size(v), \"The size of each vector must be the same to compute covariance.\");\n BOOST_MATH_ASSERT_MSG(size(u) > 0, \"Computing covariance requires at least two samples.\");\n\n Real cov = 0;\n Real mu_u = u[0];\n Real mu_v = v[0];\n Real Qu = 0;\n Real Qv = 0;\n\n for(size_t i = 1; i < size(u); ++i)\n {\n Real u_tmp = u[i] - mu_u;\n Real v_tmp = v[i] - mu_v;\n Qu = Qu + (i*u_tmp*u_tmp)/(i+1);\n Qv = Qv + (i*v_tmp*v_tmp)/(i+1);\n cov += i*u_tmp*v_tmp/(i+1);\n mu_u = mu_u + u_tmp/(i+1);\n mu_v = mu_v + v_tmp/(i+1);\n }\n\n // If both datasets are constant, then they are perfectly correlated.\n if (Qu == 0 && Qv == 0)\n {\n return Real(1);\n }\n // If one dataset is constant and the other isn't, then they have no correlation:\n if (Qu == 0 || Qv == 0)\n {\n return Real(0);\n }\n\n // Make sure rho in [-1, 1], even in the presence of numerical noise.\n Real rho = cov/sqrt(Qu*Qv);\n if (rho > 1) {\n rho = 1;\n }\n if (rho < -1) {\n rho = -1;\n }\n return rho;\n}\n\n}}}\n#endif\n", "meta": {"hexsha": "40f51dcc383770a5b7a0b323a6896036bffff017", "size": 2898, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/tools/bivariate_statistics.hpp", "max_stars_repo_name": "mscastanho/math", "max_stars_repo_head_hexsha": "e149c340089e937949ea9566f88df30428d119b8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 106.0, "max_stars_repo_stars_event_min_datetime": "2015-08-07T04:23:50.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-27T18:25:15.000Z", "max_issues_repo_path": "include/boost/math/tools/bivariate_statistics.hpp", "max_issues_repo_name": "mscastanho/math", "max_issues_repo_head_hexsha": "e149c340089e937949ea9566f88df30428d119b8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 130.0, "max_issues_repo_issues_event_min_datetime": "2016-06-22T22:11:25.000Z", "max_issues_repo_issues_event_max_datetime": "2020-11-29T20:24:09.000Z", "max_forks_repo_path": "include/boost/math/tools/bivariate_statistics.hpp", "max_forks_repo_name": "mscastanho/math", "max_forks_repo_head_hexsha": "e149c340089e937949ea9566f88df30428d119b8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 41.0, "max_forks_repo_forks_event_min_datetime": "2015-07-08T19:18:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-14T16:39:56.000Z", "avg_line_length": 29.2727272727, "max_line_length": 113, "alphanum_fraction": 0.626984127, "num_tokens": 823, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473746782093, "lm_q2_score": 0.7401743563075447, "lm_q1q2_score": 0.6456891565290201}} {"text": "#include \n#include \n\nnamespace dr {\n\n/// Interpolate linearly between two vectors.\n/**\n * At factor 0, the first vector is returned, at factor 1 the second.\n */\ntemplate\nauto interpolateVector(\n\tEigen::MatrixBase const & a, ///< The first vector.\n\tEigen::MatrixBase const & b, ///< The second vector.\n\tdouble factor ///< The interpolation factor.\n) -> decltype(a + factor * (b - a)) {\n\treturn a + factor * (b - a);\n}\n\n/// Interpolate spherical linearly between two rotations.\n/**\n * At factor 0, the first rotation is returned, at factor 1 the second.\n */\ntemplate\nEigen::AngleAxis interpolateRotation(\n\tEigen::AngleAxis const & a, ///< The first rotation.\n\tEigen::AngleAxis const & b, ///< The second rotation.\n\tdouble factor ///< The interpolation factor.\n) {\n\tEigen::AngleAxis difference = b * a.inverse();\n\tdifference.angle() *= factor;\n\treturn difference * a;\n}\n\n/// Interpolate spherical linearly between two rotations.\n/**\n * At factor 0, the first rotation is returned, at factor 1 the second.\n */\ntemplate\nEigen::Quaternion interpolateRotation(\n\tEigen::Quaternion const & a, ///< The first rotation.\n\tEigen::Quaternion const & b, ///< The second rotation.\n\tdouble factor ///< The interpolation factor.\n) {\n\treturn a.slerp(factor, b);\n}\n\n/// Interpolate spherical linearly between two rotations.\n/**\n * At factor 0, the first rotation is returned, at factor 1 the second.\n */\ntemplate\nEigen::Quaternion::Scalar> interpolateRotation(\n\tEigen::MatrixBase const & a, ///< The first rotation.\n\tEigen::MatrixBase const & b, ///< The second rotation.\n\tdouble factor ///< The interpolation factor.\n) {\n\tusing Scalar1 = typename Eigen::MatrixBase::Scalar;\n\tusing Scalar2 = typename Eigen::MatrixBase::Scalar;\n\treturn interpolateRotation(Eigen::Quaternion(a), Eigen::Quaternion(b), factor);\n}\n\n/// Interpolate spherical linearly between two isometries.\n/**\n * At factor 0, the first isometry is returned, at factor 1 the second.\n * The translation will be interpolated linearly and the rotation spherial linearly.\n */\nEigen::Isometry3d interpolateIsometry(\n\tEigen::Isometry3d const & a, ///< The first isometry.\n\tEigen::Isometry3d const & b, ///< The second isometry.\n\tdouble factor ///< The interpolation factor.\n) {\n\treturn Eigen::Translation3d{interpolateVector(a.translation(), b.translation(), factor)}\n\t\t* interpolateRotation(Eigen::Quaterniond{a.rotation()}, Eigen::Quaterniond{b.rotation()}, factor);\n}\n\n}\n", "meta": {"hexsha": "e9105d39137de51a7332150088ed7a62a70b0fa7", "size": 2786, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/dr_eigen/interpolate.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/interpolate.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/interpolate.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": 36.1818181818, "max_line_length": 107, "alphanum_fraction": 0.6966977746, "num_tokens": 638, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8723473680407889, "lm_q2_score": 0.7401743563075446, "lm_q1q2_score": 0.6456891516161717}} {"text": "#include \"Constraint.h\"\n#include \"AttachmentConstraint.h\"\n#include \n#include \nusing namespace FEM;\nAttachmentConstraint::\nAttachmentConstraint(const double& stiffness,int i0,const Eigen::Vector2d& p)\n\t:Constraint(stiffness),mi0(i0),mp(p)\n{\n\n}\n\ndouble\nAttachmentConstraint::\nEvalPotentialEnergy(const Eigen::VectorXd& x)\n{\n\tEigen::Vector2d x_p0 = x.block<2,1>(mi0*2,0) - mp;\n\n return 0.5*mStiffness*x_p0.squaredNorm();\n}\nvoid\nAttachmentConstraint::\nEvalGradient(const Eigen::VectorXd& x, Eigen::VectorXd& gradient)\n{\n\tEigen::Vector2d x_p0 = x.block<2,1>(mi0*2,0) - mp;\n\tgradient.block<2,1>(mi0*2,0) += mStiffness*x_p0;\n}\n\nvoid\nAttachmentConstraint::\nEvalHessian(const Eigen::VectorXd& x, const Eigen::VectorXd& dx, Eigen::VectorXd& dg)\n{\n\t//Compute H*x\n\tdg.block<2,1>(mi0*2,0) += mStiffness*dx.block<2,1>(mi0*2,0);\n}\n\nvoid\nAttachmentConstraint::\nEvaluateDVector(int index, const Eigen::VectorXd& x,Eigen::VectorXd& d)\n{\n\td.block<2,1>(2*index,0) = mp;\n}\nvoid\nAttachmentConstraint::\nEvaluateJMatrix(int index, std::vector>& J_triplets)\n{\n\tJ_triplets.push_back(Eigen::Triplet(2*mi0, 2*index, mStiffness));\n\tJ_triplets.push_back(Eigen::Triplet(2*mi0+1, 2*index+1, mStiffness));\n}\nvoid\nAttachmentConstraint::\nEvaluateLMatrix(std::vector>& L_triplets)\n{\n\tL_triplets.push_back(Eigen::Triplet(2*mi0+0, 2*mi0+0, mStiffness));\n\tL_triplets.push_back(Eigen::Triplet(2*mi0+1, 2*mi0+1, mStiffness));\n}\n\nint\nAttachmentConstraint::\nGetDof()\n{\n\treturn 1;\n}\nint\nAttachmentConstraint::\nGetNumHessianTriplets()\n{\n\treturn 2;\n}\n\n\nConstraintType \nAttachmentConstraint::\nGetType()\t \n{\n\treturn ConstraintType::ATTACHMENT; \n}\nvoid \nAttachmentConstraint::\nAddOffset(const int& offset) \n{\n\tmi0+=offset;\n}\n\nEigen::Vector2d& \nAttachmentConstraint::\nGetP() \n{\n\treturn mp;\n}\nint&\t\t\t \nAttachmentConstraint::\nGetI0()\t \n{\n\treturn mi0;\n}", "meta": {"hexsha": "40ebafef6942e74530d0035b4d059f0d942148d3", "size": 1908, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "fem2D/Constraint/AttachmentConstraint.cpp", "max_stars_repo_name": "snumrl/volcon2D", "max_stars_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "fem2D/Constraint/AttachmentConstraint.cpp", "max_issues_repo_name": "snumrl/volcon2D", "max_issues_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "fem2D/Constraint/AttachmentConstraint.cpp", "max_forks_repo_name": "snumrl/volcon2D", "max_forks_repo_head_hexsha": "4b4277cef2caa0f62429781acedc71d9f8b6bd0d", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.875, "max_line_length": 85, "alphanum_fraction": 0.7316561845, "num_tokens": 593, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8688267626522814, "lm_q2_score": 0.7431680143008301, "lm_q1q2_score": 0.6456842599717146}} {"text": "// =========================================================================\n// @author Leonardo Florez-Valencia (florez-l@javeriana.edu.co)\n// =========================================================================\n\n#include \n\n#include \n\n#include \n#include \n#include \n\n// -- Types\nusing TScalar = double;\nusing TModel = PUJ_ML::Model::Linear< TScalar >;\nusing TMatrix = TModel::TMatrix;\nnamespace po = boost::program_options;\n\n// -- Main --\nint main( int argc, char** argv )\n{\n std::string csv = \"[NO INPUT FILE]\";\n TScalar alpha = 1e-2;\n TScalar lambda = 0;\n TScalar epsilon = std::numeric_limits< TScalar >::epsilon( );\n unsigned long long epochs = 10000;\n unsigned long long debug_step = 100;\n bool use_LASSO = false;\n\n po::options_description desc( \"Allowed parameters\" );\n desc.add_options( )\n ( \"help,h\", \"Help message\" )\n ( \"alpha,a\", po::value( &alpha )->default_value( alpha ), \"Learning rate\" )\n ( \"lambda,l\", po::value( &lambda )->default_value( lambda ), \"Regularization\" )\n ( \"LASSO\", po::bool_switch( &use_LASSO )->default_value( use_LASSO ), \"Use LASSO?\" )\n ( \"epsilon,e\", po::value( &epsilon )->default_value( epsilon ), \"Epsilon\" )\n ( \"epochs\", po::value( &epochs )->default_value( epochs ), \"Epochs\" )\n ( \"debug_step\", po::value( &debug_step )->default_value( debug_step ), \"Debug step\" )\n ( \"csv\", po::value( &csv )->default_value( csv ), \"Input file\" )\n ;\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\" ) )\n { \n std::cerr << desc << std::endl;\n return( EXIT_FAILURE );\n } // end if\n\n auto D = PUJ_ML::Helpers::CSV::Read< TMatrix >( csv, true, \",\" );\n unsigned long long p = 1;\n unsigned long long m = D.rows( );\n unsigned long long n = D.cols( ) - p;\n TMatrix X = D.block( 0, 0, m, n );\n TMatrix Y = D.block( 0, n, m, p );\n\n TModel model;\n model.SetParameters( TModel::TCol::Zero( n + 1 ) );\n TModel::Cost cost( &model, X, Y );\n\n PUJ_ML::Optimizer::GradientDescent< TModel > opt;\n opt.SetCost( cost );\n opt.SetLearningRate( alpha );\n opt.SetRegularizationCoefficient( lambda );\n if( use_LASSO ) opt.SetRegularizationToLASSO( );\n else opt.SetRegularizationToRidge( );\n opt.SetEpsilon( epsilon );\n opt.SetNumberOfEpochs( epochs );\n opt.SetDebugStep( debug_step );\n\n TScalar final_cost;\n unsigned long long final_epochs;\n opt.SetDebug(\n [&]( unsigned long long i, TScalar J, bool show ) -> bool\n {\n if( show )\n std::cout << i << \" \" << J << std::endl;\n final_cost = J;\n final_epochs = i;\n return( false );\n }\n );\n opt.Fit( );\n\n std::cout << \"---------------------\" << std::endl;\n std::cout << \"Fitted model : \" << model << std::endl;\n std::cout << \"Final cost : \" << final_cost << std::endl;\n std::cout << \"Final epochs : \" << final_epochs << std::endl;\n std::cout << \"---------------------\" << std::endl;\n\n /* TODO\n std::cout << X.colwise( ).minCoeff( ) << std::endl;\n std::cout << X.colwise( ).maxCoeff( ) << std::endl;\n TModel::TCol L = TModel::TCol::LinSpaced( 100, -10, 10 );\n */\n\n return( EXIT_SUCCESS );\n}\n\n// eof - $RCSfile$\n", "meta": {"hexsha": "134bbd9836996bed9f18067c9ac6f88450121a97", "size": 3294, "ext": "cxx", "lang": "C++", "max_stars_repo_path": "examples/LinearModel_FitGradientDescent_00.cxx", "max_stars_repo_name": "florez-l/PUJ_ML", "max_stars_repo_head_hexsha": "ee634d798fcf26e0b56ee804012a4eca9a997c7f", "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/LinearModel_FitGradientDescent_00.cxx", "max_issues_repo_name": "florez-l/PUJ_ML", "max_issues_repo_head_hexsha": "ee634d798fcf26e0b56ee804012a4eca9a997c7f", "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/LinearModel_FitGradientDescent_00.cxx", "max_forks_repo_name": "florez-l/PUJ_ML", "max_forks_repo_head_hexsha": "ee634d798fcf26e0b56ee804012a4eca9a997c7f", "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": 32.2941176471, "max_line_length": 89, "alphanum_fraction": 0.5783242259, "num_tokens": 965, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891305219504, "lm_q2_score": 0.7853085859124002, "lm_q1q2_score": 0.6456721834427387}} {"text": "/**\n * @file radauthreetimestepping.cc\n * @brief NPDE homework RadauThreeTimestepping\n * @author Erick Schulz, edited by Oliver Rietmann\n * @date 08/04/2019\n * @copyright Developed at ETH Zurich\n */\n\n#include \"radauthreetimestepping.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace RadauThreeTimestepping {\n\n/**\n * @brief Implementation of the right hand side (time dependent) source vector\n * for the parabolic heat equation\n * @param dofh A reference to the DOFHandler\n * @param time The time at which to evaluate the source vector\n * @returns The source vector at time `time`\n */\n/* SAM_LISTING_BEGIN_1 */\nEigen::VectorXd rhsVectorheatSource(const lf::assemble::DofHandler &dofh,\n double time) {\n // Dimension of finite element space\n const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n // Right-hand side vector has to be set to zero initially\n Eigen::VectorXd phi(N_dofs);\n#if SOLUTION\n // Functor for computing the source function at 2d coordinates\n auto f = [time](Eigen::Vector2d x) -> double {\n const double PI = 3.14159265358979323846;\n Eigen::Vector2d v(std::cos(time * PI), std::sin(time * PI));\n return ((x - 0.5 * v).norm() < 0.5) ? 1.0 : 0.0;\n };\n auto mesh_p = dofh.Mesh(); // pointer to current mesh\n phi.setZero();\n\n /* Assembling right-hand side source vector */\n // Initialize object taking care of local computations on all cells.\n TrapRuleLinFEElemVecProvider elvec_builder(f);\n // Computing right hand side vector\n // Invoke assembly on cells (codim == 0 as first agrument)\n lf::assemble::AssembleVectorLocally(0, dofh, elvec_builder, phi);\n\n /* Enforce the zero Dirichlet boundary conditions */\n // Obtain an array of boolean flags for the vertices of the mesh: 'true'\n // indicates that the vertex lies on the boundary. This predicate will\n // guarantee that the computations are carried only on the boundary vertices\n auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 2)};\n // Creating predicate that will guarantee that the computations are carried\n // only on the vertices of the mesh using the boundary flags\n auto vertices_predicate =\n [&bd_flags](const lf::mesh::Entity &vertex) -> bool {\n return bd_flags(vertex);\n };\n // Assigning zero to the boundary values of phi\n for (const lf::mesh::Entity *vertex : mesh_p->Entities(2)) {\n if (bd_flags(*vertex)) {\n auto dof_idx = dofh.GlobalDofIndices(*vertex);\n LF_ASSERT_MSG(\n dofh.NumLocalDofs(*vertex) == 1,\n \"Too many global indices were returned for a vertex entity!\");\n phi(dof_idx[0]) = 0.0;\n }\n }\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return phi;\n}\n/* SAM_LISTING_END_1 */\n\n/**\n * @brief Heat evolution solver: the solver obtains the\n * discrete evolution operator from the Radau3MOLTimestepper class and\n * repeatedly iterates its applicaiton starting from the initial condition\n * @param dofh The DOFHandler object\n * @param m is total number of steps until final time final_time (double)\n * @param final_time The duration for which to solve the PDE\n * @returns The solution at the final timestep\n */\n/* SAM_LISTING_BEGIN_6 */\nEigen::VectorXd solveHeatEvolution(const lf::assemble::DofHandler &dofh,\n unsigned int m, double final_time) {\n Eigen::VectorXd discrete_heat_sol(dofh.NumDofs());\n#if SOLUTION\n double tau = final_time / m; // step size\n const lf::uscalfe::size_type N_dofs(dofh.NumDofs()); // dim. of FE space\n\n std::cout << \"*********************************************************\"\n << std::endl;\n std::cout << \"\\n>>> SolveHeatEvolution: m = \" << m << \", N = \" << N_dofs\n << std::endl;\n /* Setting up the problem information */\n // Precomputing the required data for the Runge-Kutta method\n // Assemble the Runge-Kutta Radau IIA 2-stages method solver (order 3)\n Radau3MOLTimestepper radau_solver(dofh);\n // Starting with the zero initial condition vector\n Eigen::VectorXd discrete_solution_cur =\n radau_solver.discreteEvolutionOperator(0.0, tau,\n Eigen::VectorXd::Zero(N_dofs));\n\n std::cout << \"\\n>> Iterating the action of discreteEvolutionOperator\"\n << std::endl;\n /* Evolving the parabolic heat system */\n // While less elegant, we use a current and next step solution vector in the\n // iteration to stay away from potential harming aliasing effects of putting\n // an Eigen::Vector on both sides of an assignment statement.\n Eigen::VectorXd discrete_solution_next;\n for (int i = 1; i < m; i++) {\n discrete_solution_next = radau_solver.discreteEvolutionOperator(\n i * tau, tau, discrete_solution_cur);\n discrete_solution_cur = discrete_solution_next;\n }\n discrete_heat_sol = discrete_solution_cur;\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return discrete_heat_sol;\n}\n/* SAM_LISTING_END_6 */\n\n/* Implementing member function Eval of class LinFEMassMatrixProvider*/\nEigen::Matrix LinFEMassMatrixProvider::Eval(\n const lf::mesh::Entity &tria) {\n Eigen::Matrix elMat;\n#if SOLUTION\n // Throw error in case no triangular cell\n LF_VERIFY_MSG(tria.RefEl() == lf::base::RefEl::kTria(),\n \"Unsupported cell type \" << tria.RefEl());\n // Compute the area of the triangle cell\n const double area = lf::geometry::Volume(*(tria.Geometry()));\n // Assemble the mass element matrix over the cell\n // clang-format off\n elMat << 2.0, 1.0, 1.0,\n 1.0, 2.0, 1.0,\n 1.0, 1.0, 2.0;\n // clang-format on\n elMat *= area / 12.0;\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return elMat; // return the local mass element matrix\n}\n\n/* Implementing constructor of class Radau3MOLTimestepper */\n/* SAM_LISTING_BEGIN_4 */\nRadau3MOLTimestepper::Radau3MOLTimestepper(const lf::assemble::DofHandler &dofh)\n : dofh_(dofh) {\n#if SOLUTION\n std::cout << \"\\n>> Constructing SRadau3MOLTimestepper \" << std::endl;\n auto mesh_p = dofh.Mesh(); // pointer to current mesh\n\n // Instantiating Galerkin matrices to be pre-computed\n // Dimension of finite element space\n const lf::uscalfe::size_type N_dofs(dofh.NumDofs());\n // Matrices in triplet format holding Galerkin matrices, zero initially.\n lf::assemble::COOMatrix A_COO(N_dofs,\n N_dofs); // element matrix Laplace\n lf::assemble::COOMatrix M_COO(N_dofs,\n N_dofs); // element mass matrix\n\n std::cout << \"> Initializing the Galerking local matrices builders\"\n << std::endl;\n // Initialize classes containing the information required for the\n // local computations of the Galerkin matrices. Simple implementations of\n // LinFEMassMatrixProvider and TrapRuleLinFEElemVecProvider adapted to this\n // particular problem was written to spare some of the overhead calculations\n // involved in the use of the more general LehrFEM++ matrices providers.\n lf::uscalfe::LinearFELaplaceElementMatrix elLapMat_builder;\n LinFEMassMatrixProvider elMassMat_builder;\n\n std::cout << \"> Assembling Galerking matrices in COO format\" << std::endl;\n // Compute the Galerkin matrices\n // Invoke assembly on cells (co-dimension = 0 as first argument)\n // Information about the mesh and the local-to-global map is passed through\n // a Dofhandler object, argument 'dofh'. This function call adds triplets to\n // the internal COO-format representation of the sparse matrices A and M.\n lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elLapMat_builder, A_COO);\n lf::assemble::AssembleMatrixLocally(0, dofh, dofh, elMassMat_builder, M_COO);\n\n // Enforcing zero Dirichlet boundary conditions\n // Obtain an array of boolean flags for the vertices of the mesh: 'true'\n // indicates that the vertex lies on the boundary.\n auto bd_flags{lf::mesh::utils::flagEntitiesOnBoundary(mesh_p, 2)};\n // Index predicate for the selectvals FUNCTOR of dropMatrixRowsColumns\n auto bdy_vertices_selector = [&bd_flags, &dofh](unsigned int idx) -> bool {\n return bd_flags(dofh.Entity(idx));\n };\n dropMatrixRowsColumns(bdy_vertices_selector, A_COO);\n dropMatrixRowsColumns(bdy_vertices_selector, M_COO);\n\n std::cout << \"> Converting triplets to sparse matrices\" << std::endl;\n // Creating the private Galerkin stiffness and mass matrices\n A_ = A_COO.makeSparse();\n Eigen::SparseMatrix M = M_COO.makeSparse();\n\n // Runge-Kutta matrices defining the 2-stage Radau timestepping. In the\n // Butcher tableau, this corresponds to c = (1/3 1)^T (top-left column\n // vector), b^T = (3/4 1/4) (bottom-right row vector), U_11 = 5/12, U_12 =\n // -1/12, U_21 = 3/4, U_22 = 1/4 (top-right block); values are fixed in\n // time\n // clang-format off\n U_ << 5.0/12.0, -1.0/12.0,\n 0.75, 0.25;\n c_ << 1.0/3.0, 1.0;\n b_ << 0.75, 0.25;\n // clang-format on\n // Precomputing the kronecker products involved in the implicit linear system\n // for the increments of the RADAU-2 method\n M_Kp_ = Eigen::kroneckerProduct(Eigen::Matrix::Identity(), M);\n A_Kp_ = Eigen::kroneckerProduct(U_, A_);\n#else\n //====================\n // Your code goes here\n // Add any additional members you need in the header file\n //====================\n#endif\n}\n/* SAM_LISTING_END_4 */\n\n/* Implementation of Radau3MOLTimestepper member functions */\n// The function discreteEvolutionOperator() returns the discretized evolution\n// operator as obtained from the Runge-Kutta Radau IIA 2-stages method using the\n// Butcher table as stored in the Radau3MOLTimestepper class\n/* SAM_LISTING_BEGIN_5 */\nEigen::VectorXd Radau3MOLTimestepper::discreteEvolutionOperator(\n double time, double tau, const Eigen::VectorXd &mu) const {\n Eigen::VectorXd discrete_evolution_operator(dofh_.NumDofs());\n#if SOLUTION\n // Dimension of finite element space\n const lf::uscalfe::size_type N_dofs(dofh_.NumDofs());\n LF_VERIFY_MSG(N_dofs == mu.size(),\n \"Dimension mismatch between the number of degrees of freedom \"\n \"and the dimension of the argument vector.\");\n\n // Building the linear system for the implicitely defined increments\n // Assembling the right hand side using block initialization\n Eigen::VectorXd linSys_rhs(2 * N_dofs);\n Eigen::VectorXd rhs_subtraction_term = A_ * mu; // precomputation\n linSys_rhs << rhsVectorheatSource(dofh_, time + c_[0] * tau) -\n rhs_subtraction_term,\n rhsVectorheatSource(dofh_, time + tau) - rhs_subtraction_term;\n\n // Implicit Runge-Kutta methods lead to systems of equations that must be\n // solved in order to obtained the increments.\n Eigen::SparseMatrix linSys_mat;\n // Assembling the system right hand side matrix using the (unfortunately\n // officially not supported) Eigen Kronecker product\n linSys_mat = M_Kp_ + tau * A_Kp_;\n LF_VERIFY_MSG(linSys_mat.rows() == linSys_mat.cols(),\n \"The linSys_mat Eigen matrix is not squared.\");\n Eigen::SparseLU> solver;\n solver.compute(linSys_mat);\n LF_VERIFY_MSG(solver.info() == Eigen::Success, \"LU decomposition failed\");\n\n // Solve linear system using Eigen's sparse direct elimination\n Eigen::VectorXd k_vec = solver.solve(linSys_rhs);\n LF_VERIFY_MSG(solver.info() == Eigen::Success, \"Solving LSE failed\");\n\n // Compute action of the discrete evolution operator on argument vec\n discrete_evolution_operator = mu + tau * (b_[0] * k_vec.topRows(N_dofs) +\n b_[1] * k_vec.bottomRows(N_dofs));\n#else\n //====================\n // Your code goes here\n //====================\n#endif\n return discrete_evolution_operator;\n}\n/* SAM_LISTING_END_5 */\n\n} // namespace RadauThreeTimestepping\n", "meta": {"hexsha": "fd910f0aefbc945f42058906b30088db746a761b", "size": 12141, "ext": "cc", "lang": "C++", "max_stars_repo_path": "developers/RadauThreeTimestepping/mastersolution/radauthreetimestepping.cc", "max_stars_repo_name": "kryo4096/NPDECODES", "max_stars_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 15.0, "max_stars_repo_stars_event_min_datetime": "2019-04-29T11:28:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-22T05:10:58.000Z", "max_issues_repo_path": "developers/RadauThreeTimestepping/mastersolution/radauthreetimestepping.cc", "max_issues_repo_name": "kryo4096/NPDECODES", "max_issues_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 12.0, "max_issues_repo_issues_event_min_datetime": "2020-02-29T15:05:58.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:51:07.000Z", "max_forks_repo_path": "developers/RadauThreeTimestepping/mastersolution/radauthreetimestepping.cc", "max_forks_repo_name": "kryo4096/NPDECODES", "max_forks_repo_head_hexsha": "3498c0e4abec6ba21447849ba2ddc9286c068ea1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 26.0, "max_forks_repo_forks_event_min_datetime": "2020-01-09T15:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T16:27:33.000Z", "avg_line_length": 41.7216494845, "max_line_length": 80, "alphanum_fraction": 0.6837986986, "num_tokens": 3212, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.822189121808099, "lm_q2_score": 0.785308580887758, "lm_q1q2_score": 0.6456721724684702}} {"text": "#include \n#include \n#include \n#include \n#include \n#include \"g2o/EXTERNAL/ceres/autodiff.h\"\n#include \n\n#include \n#include \n\n#include \"common.h\"\n#include \n#include \n#include \n#include \n\nusing namespace Sophus;\nusing namespace Eigen;\nusing namespace std;\n\n\n\nclass VertexCamera: public g2o::BaseVertex<9, Eigen::Matrix> // here the camera is parameterized as a 9-vector (angle axis, t, f, k1, k2) \n{\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n virtual void setToOriginImpl() override {\n _estimate = Eigen::Matrix::Zero();\n }\n\n virtual void oplusImpl(const double *update) override {\n _estimate += Eigen::Map>(update);\n }\n\n virtual bool read(std::istream&) override {}\n virtual bool write(std::ostream&) const override {}\n};\n\nclass VertexLandmark: public g2o::BaseVertex<3, Eigen::Vector3d>\n{\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n virtual void setToOriginImpl() override {\n _estimate = Eigen::Vector3d::Zero(); \n }\n\n virtual void oplusImpl(const double *update) override {\n _estimate += Eigen::Map(update);\n }\n\n virtual bool read(std::istream&) override {}\n virtual bool write(std::ostream&) const override {}\n};\n\n\nclass EdgeReprojection: public g2o::BaseBinaryEdge<2, Eigen::Vector2d, VertexCamera, VertexLandmark>\n{\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW;\n\n EdgeReprojection() { }\n\n template \n bool operator() (const T* camera, const T* landmark, T* residuals) const \n {\n T Xc[3];\n ceres::AngleAxisRotatePoint(camera, landmark, Xc);\n Xc[0] += camera[3];\n Xc[1] += camera[4];\n Xc[2] += camera[5];\n\n T Xp[2];\n Xp[0] = Xc[0] / Xc[2];\n Xp[1] = Xc[1] / Xc[2];\n\n T n2 = Xp[0] * Xp[0] + Xp[1] * Xp[1];\n T r = T(1.0) + n2 * (camera[7] + n2 * camera[8]);\n\n T uv[2];\n uv[0] = -Xp[0] * camera[6] * r;\n uv[1] = -Xp[1] * camera[6] * r;\n\n residuals[0] = T(_measurement[0]) - uv[0];\n residuals[1] = T(_measurement[1]) - uv[1];\n return true;\n }\n\n virtual bool read(std::istream&) override {}\n virtual bool write(std::ostream&) const override {}\n \n G2O_MAKE_AUTO_AD_FUNCTIONS // use autodiff\n\n};\n\n\nint main(int argc, char **argv) {\n\n if (argc != 2) {\n cout << \"usage: bundle_adjustment_g2o bal_data.txt\" << endl;\n return 1;\n }\n\n BALProblem dataset(argv[1]);\n dataset.Normalize();\n dataset.Perturb(0.1, 0.5, 0.5);\n dataset.WriteToPLYFile(\"initial_pc.ply\");\n\n std::cout << \"\\n\";\n std::cout << \"nb cameras: \" << dataset.num_cameras() << std::endl;\n std::cout << \"nb landmarks: \" << dataset.num_points() << std::endl;\n std::cout << \"nb observations: \" << dataset.num_observations() << std::endl;\n std::cout << \"nb parameters: \" << dataset.num_parameters() << std::endl;\n std::cout << \"check: \" << dataset.num_cameras() * 9 + dataset.num_points()*3 << std::endl;\n\n\n // pose dimension 9, landmark is 3\n typedef g2o::BlockSolver> BlockSolverType;\n typedef g2o::LinearSolverCSparse LinearSolverType;\n\n auto solver = new g2o::OptimizationAlgorithmLevenberg(\n g2o::make_unique(g2o::make_unique())\n );\n g2o::SparseOptimizer optimizer;\n optimizer.setAlgorithm(solver);\n optimizer.setVerbose(true);\n\n\n auto* cameras = dataset.mutable_cameras();\n std::vector camera_vertices;\n for (int i = 0; i < dataset.num_cameras(); ++i)\n {\n auto *c = new VertexCamera();\n c->setId(i);\n c->setEstimate(Eigen::Map>(cameras + (i*dataset.camera_block_size())));\n optimizer.addVertex(c);\n camera_vertices.push_back(c);\n }\n \n auto* landmarks = dataset.mutable_points();\n std::vector landmark_vertices;\n for (int i = 0; i < dataset.num_points(); ++i)\n {\n auto* l = new VertexLandmark();\n l->setId(dataset.num_cameras() + i);\n l->setEstimate(Eigen::Map(landmarks + i*dataset.point_block_size()));\n l->setMarginalized(true);\n optimizer.addVertex(l);\n landmark_vertices.push_back(l);\n }\n\n auto* observations = dataset.observations();\n auto* cam_indices = dataset.camera_index();\n auto* landmark_indices = dataset.point_index();\n for (int i = 0; i < dataset.num_observations(); ++i)\n {\n auto* e = new EdgeReprojection();\n e->setVertex(0, camera_vertices[cam_indices[i]]);\n e->setVertex(1, landmark_vertices[landmark_indices[i]]);\n e->setMeasurement(Eigen::Map(observations + i*2));\n e->setInformation(Eigen::Matrix2d::Identity());\n optimizer.addEdge(e);\n }\n\n optimizer.initializeOptimization();\n optimizer.optimize(40);\n\n\n for (int i = 0; i < dataset.num_cameras(); ++i)\n {\n Eigen::Matrix in = camera_vertices[i]->estimate();\n double *out = cameras + i * dataset.camera_block_size();\n for (int i = 0; i < 9; ++i)\n {\n out[i] = in[i];\n }\n }\n for (int i = 0; i < dataset.num_points(); ++i)\n {\n Eigen::Vector3d X = landmark_vertices[i]->estimate();\n landmarks[i*3] = X.x();\n landmarks[i*3+1] = X.y();\n landmarks[i*3+2] = X.z();\n }\n\n dataset.WriteToPLYFile(\"after_ba_g2o.ply\");\n\n return 0;\n}\n", "meta": {"hexsha": "c9ac4f46ff1385777e5025b885add8bfe9a9e934", "size": 5838, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "ch9/bundle_adjustment_g2o_custom_autodiff.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": "ch9/bundle_adjustment_g2o_custom_autodiff.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": "ch9/bundle_adjustment_g2o_custom_autodiff.cpp", "max_forks_repo_name": "zinsmatt/slambook2", "max_forks_repo_head_hexsha": "3648caff838241553d9f3de332068eb0d501a7dc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.40625, "max_line_length": 158, "alphanum_fraction": 0.6216169921, "num_tokens": 1651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8757869981319863, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6455935394541912}} {"text": "#include \n#include \n\nusing namespace Eigen;\nusing namespace std;\n\nint main(int, char**)\n{\n cout.precision(3);\n MatrixXcd X = MatrixXcd::Random(4,4);\nMatrixXcd A = X + X.adjoint();\ncout << \"Here is a random self-adjoint 4x4 matrix:\" << endl << A << endl << endl;\n\nTridiagonalization triOfA(A);\nMatrixXd T = triOfA.matrixT();\ncout << \"The tridiagonal matrix T is:\" << endl << T << endl << endl;\n\ncout << \"We can also extract the diagonals of T directly ...\" << endl;\nVectorXd diag = triOfA.diagonal();\ncout << \"The diagonal is:\" << endl << diag << endl; \nVectorXd subdiag = triOfA.subDiagonal();\ncout << \"The subdiagonal is:\" << endl << subdiag << endl;\n\n return 0;\n}\n", "meta": {"hexsha": "4fe9efcc361dded2afc77daf03d21cef06b85186", "size": 703, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_diagonal.cpp", "max_stars_repo_name": "TANHAIYU/Self-calibration-using-Homography-Constraints", "max_stars_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-03-17T16:34:31.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-17T18:30:13.000Z", "max_issues_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_diagonal.cpp", "max_issues_repo_name": "TANHAIYU/planecalib", "max_issues_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cmake-build-debug/3rdparty/Eigen/Debug/src/Eigen-build/doc/snippets/compile_Tridiagonalization_diagonal.cpp", "max_forks_repo_name": "TANHAIYU/planecalib", "max_forks_repo_head_hexsha": "a3e7efa8cc3de1be1489891d81c0fb00b5b98777", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.0384615385, "max_line_length": 81, "alphanum_fraction": 0.6600284495, "num_tokens": 203, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240825770432, "lm_q2_score": 0.7461389986757757, "lm_q1q2_score": 0.6455774306042017}} {"text": "/**\n * @date Tue Jan 18 17:07:26 2011 +0100\n * @author André Anjos \n * @author Laurent El Shafey \n *\n * @brief Principal Component Analysis implemented with Singular Value\n * Decomposition or using the Covariance Method. Both are implemented using\n * LAPACK. Implementation.\n *\n * Copyright (C) Idiap Research Institute, Martigny, Switzerland\n */\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nnamespace bob { namespace learn { namespace linear {\n\n PCATrainer::PCATrainer(bool use_svd)\n : m_use_svd(use_svd), m_safe_svd(false)\n {\n }\n\n PCATrainer::PCATrainer(const PCATrainer& other)\n : m_use_svd(other.m_use_svd), m_safe_svd(other.m_safe_svd)\n {\n }\n\n PCATrainer::~PCATrainer() {}\n\n PCATrainer& PCATrainer::operator= (const PCATrainer& other) {\n if (this != &other) {\n m_use_svd = other.m_use_svd;\n m_safe_svd = other.m_safe_svd;\n }\n return *this;\n }\n\n bool PCATrainer::operator== (const PCATrainer& other) const {\n\n return m_use_svd == other.m_use_svd &&\n m_safe_svd == other.m_safe_svd;\n\n }\n\n bool PCATrainer::operator!= (const PCATrainer& other) const {\n\n return !(this->operator==(other));\n\n }\n\n /**\n * Sets up the machine calculating the PC's via the Covariance Matrix\n */\n static void pca_via_covmat(Machine& machine,\n blitz::Array& eigen_values, const blitz::Array& X,\n int rank) {\n\n /**\n * computes the covariance matrix (X-mu)(X-mu)^T / (len(X)-1) and then solves\n * the generalized eigen-value problem taking into consideration the\n * covariance matrix is symmetric (and, by extension, hermitian).\n */\n blitz::Array mean(X.extent(1));\n blitz::Array Sigma(X.extent(1), X.extent(1));\n bob::math::scatter_(X, Sigma, mean);\n Sigma /= (X.extent(0)-1); //unbiased variance estimator\n\n blitz::Array U(X.extent(1), X.extent(1));\n blitz::Array e(X.extent(1));\n bob::math::eigSym_(Sigma, U, e);\n e.reverseSelf(0);\n U.reverseSelf(1);\n\n /**\n * sets the linear machine with the results:\n */\n machine.setInputSubtraction(mean);\n machine.setInputDivision(1.0);\n machine.setBiases(0.0);\n if (e.size() == eigen_values.size()) {\n eigen_values = e;\n machine.setWeights(U);\n }\n else {\n eigen_values = e(blitz::Range(0,rank-1));\n machine.setWeights(U(blitz::Range::all(), blitz::Range(0,rank-1)));\n }\n\n }\n\n /**\n * Sets up the machine calculating the PC's via SVD\n */\n static void pca_via_svd(Machine& machine, blitz::Array& eigen_values,\n const blitz::Array& X, int rank, bool safe_svd) {\n\n // removes the empirical mean from the training data\n blitz::Array data(X.extent(1), X.extent(0));\n blitz::Range a = blitz::Range::all();\n for (int i=0; i mean(X.extent(1));\n mean = blitz::mean(data, j);\n\n // applies the training data mean\n for (int i=0; i U(X.extent(1), rank_1);\n blitz::Array sigma(rank_1);\n bob::math::svd_(data, U, sigma, safe_svd);\n\n /**\n * sets the linear machine with the results:\n *\n * note: eigen values are sigma^2/X.extent(0) diagonal\n * eigen vectors are the rows of U\n */\n machine.setInputSubtraction(mean);\n machine.setInputDivision(1.0);\n machine.setBiases(0.0);\n blitz::Range up_to_rank(0, rank-1);\n machine.setWeights(U(a,up_to_rank));\n\n //weight normalization (if necessary):\n //norm_factor = blitz::sum(blitz::pow2(V(all,i)))\n\n // finally, we set also the eigen values in this version\n eigen_values = (blitz::pow2(sigma)/(X.extent(0)-1))(up_to_rank);\n }\n\n void PCATrainer::train(Machine& machine, blitz::Array& eigen_values,\n const blitz::Array& X) const {\n\n // data is checked now and conforms, just proceed w/o any further checks.\n const int rank = output_size(X);\n\n // Checks that the dimensions are matching\n if (machine.inputSize() != (size_t)X.extent(1)) {\n boost::format m(\"Number of features at input data set (%d columns) does not match machine input size (%d)\");\n m % X.extent(1) % machine.inputSize();\n throw std::runtime_error(m.str());\n }\n if (machine.outputSize() != (size_t)rank) {\n boost::format m(\"Number of outputs of the given machine (%d) does not match the maximum covariance rank, i.e., min(#samples-1,#features) = min(%d, %d) = %d\");\n m % machine.outputSize() % (X.extent(0)-1) % X.extent(1) % rank;\n throw std::runtime_error(m.str());\n }\n if (eigen_values.extent(0) != rank) {\n boost::format m(\"Number of eigenvalues on the given 1D array (%d) does not match the maximum covariance rank, i.e., min(#samples-1,#features) = min(%d,%d) = %d\");\n m % eigen_values.extent(0) % (X.extent(0)-1) % X.extent(1) % rank;\n throw std::runtime_error(m.str());\n }\n\n if (m_use_svd) pca_via_svd(machine, eigen_values, X, rank, m_safe_svd);\n else pca_via_covmat(machine, eigen_values, X, rank);\n }\n\n void PCATrainer::train(Machine& machine, const blitz::Array& X) const {\n blitz::Array throw_away_eigen_values(output_size(X));\n train(machine, throw_away_eigen_values, X);\n }\n\n size_t PCATrainer::output_size (const blitz::Array& X) const {\n return (size_t)std::min(X.extent(0)-1,X.extent(1));\n }\n\n}}}\n", "meta": {"hexsha": "fa21bc447ee09c57f5ec6ccb1fef797670f825f5", "size": 6090, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "bob/learn/linear/cpp/pca.cpp", "max_stars_repo_name": "bioidiap/bob.learn.linear", "max_stars_repo_head_hexsha": "111323c3d0a7d1f0f2249ef95c18a3c0dd52be89", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 4.0, "max_stars_repo_stars_event_min_datetime": "2015-10-14T08:06:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T08:02:13.000Z", "max_issues_repo_path": "bob/learn/linear/cpp/pca.cpp", "max_issues_repo_name": "bioidiap/bob.learn.linear", "max_issues_repo_head_hexsha": "111323c3d0a7d1f0f2249ef95c18a3c0dd52be89", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 4.0, "max_issues_repo_issues_event_min_datetime": "2015-03-18T05:27:50.000Z", "max_issues_repo_issues_event_max_datetime": "2015-11-25T15:30:27.000Z", "max_forks_repo_path": "bob/learn/linear/cpp/pca.cpp", "max_forks_repo_name": "bioidiap/bob.learn.linear", "max_forks_repo_head_hexsha": "111323c3d0a7d1f0f2249ef95c18a3c0dd52be89", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 6.0, "max_forks_repo_forks_event_min_datetime": "2015-07-17T12:58:53.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-09T14:30:27.000Z", "avg_line_length": 33.097826087, "max_line_length": 168, "alphanum_fraction": 0.6489326765, "num_tokens": 1742, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8652240860523328, "lm_q2_score": 0.7461389817407016, "lm_q1q2_score": 0.6455774185446168}} {"text": "#pragma once\n\n#include \n#include \n#include \n\n#include \"number_representation.hpp\"\n\nnamespace abo::error_metrics {\n\n/**\n * @brief Computes the maximum relative difference between f and f_hat for any input\n * It is defined as the maximum of |f(x) - f_hat(x)| / max(1, |f(x)|) over all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * The computation is performed with ADDs and might be quite slow\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param num_rep The number representation for f and f_hat\n * @return the maximum relative difference of the inputs\n */\ndouble wcre_add(const Cudd& mgr, const std::vector& f,\n const std::vector& f_hat,\n const abo::util::NumberRepresentation num_rep\n = abo::util::NumberRepresentation::BaseTwo);\n\n/**\n * @brief Computes bounds on the maximum relative value of f in relation to g\n * It is defined as the maximum of |f(x)| / max(1, |g(x)|) over all inputs x\n * This function returns a range in which the actual relative value is guaranteed to lie\n * The computed bounds are always within a factor of 2, meaning that the maximum bound\n * returned by this function is at most twice the minimum bound\n * @param mgr The BDD object manager\n * @param f The function to compute the maximum relative value of (must be an unsigned integer)\n * @param g The function to use as a relation. Must have the same number of bits as f (must be an\n * unsigned integer)\n * @return {min, max}, the lower and upper bound on the maximum relative value\n */\nstd::pair\nmaximum_relative_value_bounds(const Cudd& mgr, const std::vector& f,\n const std::vector& g);\n\n/**\n * @brief Computes bounds on the maximum relative difference between f and f_hat\n * It is defined as the maximum of |f(x) - f_hat(x)| / max(1, |f(x)|) over all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * This function returns a range in which the actual maximum relative error is guaranteed to lie\n * The computed bounds are always within a factor of 2, meaning that the maximum error\n * returned by this function is at most twice the minimum error\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param num_rep The number representation for f and f_hat\n * @return {min, max}, the lower and upper bound on the maximum relative error\n */\nstd::pair\n wcre_bounds(\n const Cudd& mgr,\n const std::vector& f,\n const std::vector& f_hat,\n const abo::util::NumberRepresentation num_rep\n = abo::util::NumberRepresentation::BaseTwo);\n\n/**\n * @brief Computes the maximum relative difference between f and f_hat for any input\n * It is defined as the maximum of |f(x) - f_hat(x)| / max(1, |f(x)|) over all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * The computation is performed with BDDs using a binary search to find the maximum value\n * If the correct value is found, the search is aborted. Otherwise, it is run until the desired\n * precision is reached\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param num_extra_bits The number of additional bits used during the search to represent values\n * smaller than one\n * @param precision The desired precision of the result if the correct value is not found during the\n * binary search Do not set it lower than 2^-num_extra_bits\n * @param num_rep The number representation for f and f_hat\n * @return the maximum relative difference of the inputs\n */\ndouble wcre_search(\n const Cudd& mgr, const std::vector& f,\n const std::vector& f_hat,\n unsigned int num_extra_bits = 16,\n double precision = 0.0001,\n const abo::util::NumberRepresentation num_rep\n = abo::util::NumberRepresentation::BaseTwo);\n\n/**\n * @brief Computes the maximum relative difference between f and f_hat for any input\n * It is defined as the maximum of |f(x) - f_hat(x)| / max(1, |f(x)|) over all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * The computation is performed with BDDs using a binary search to find the maximum value\n * If the correct value is found, the search is aborted. Otherwise, it is run until the desired\n * precision is reached\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param samples The number of random input samples drawn in each iteration\n * @param num_rep The number representation for f and f_hat\n * @return the maximum relative difference of the inputs as a fraction [numerator, denominator]\n */\nstd::pair wcre_randomized_search(\n const Cudd& mgr, const std::vector& f,\n const std::vector& f_hat,\n unsigned int samples = 1,\n const abo::util::NumberRepresentation num_rep\n = abo::util::NumberRepresentation::BaseTwo);\n/**\n * @brief Computes the maximum relative difference between f and f_hat for any input\n * It is defined as the maximum of |f(x) - f_hat(x)| / max(1, |f(x)|) over all inputs x\n * As it is not symmetric, it is not a metric in the mathematical sense\n * The computation is performed with BDDs using a symbolic division and might be quite slow\n * @param mgr The BDD object manager\n * @param f The original function\n * @param f_hat The approximated function. Must have the same number of bits as f\n * @param num_extra_bits The number of additional fixed precision bits to use during the division\n * As the result of each division is not an integer, the result is described as a fixed point number\n * with exactly num_extra_bits bits with a lower significance than one. Roughly correlates the the\n * precision of the result\n * @param num_rep The number representation for f and f_hat\n * @return the maximum relative difference of the inputs\n */\nboost::multiprecision::cpp_dec_float_100 wcre_symbolic_division(\n const Cudd& mgr, const std::vector& f,\n const std::vector& f_hat,\n unsigned int num_extra_bits = 16,\n const abo::util::NumberRepresentation num_rep\n = abo::util::NumberRepresentation::BaseTwo);\n\n} // namespace abo::error_metrics\n", "meta": {"hexsha": "88e6e0d7ac224e657d6fd5e79bcd4f7a1783c9ae", "size": 6825, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/error_metrics/worst_case_relative_error.hpp", "max_stars_repo_name": "keszocze/abo", "max_stars_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/error_metrics/worst_case_relative_error.hpp", "max_issues_repo_name": "keszocze/abo", "max_issues_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/error_metrics/worst_case_relative_error.hpp", "max_forks_repo_name": "keszocze/abo", "max_forks_repo_head_hexsha": "2d59ac20832b308ef5f90744fc98752797a4f4ba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-03-11T14:50:31.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-11T14:50:31.000Z", "avg_line_length": 50.9328358209, "max_line_length": 100, "alphanum_fraction": 0.7245421245, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.833324611869563, "lm_q2_score": 0.7745833945721304, "lm_q1q2_score": 0.6454794066424291}} {"text": "/*\n Copyright (C) 2016-2021 by Synge Todo \n Chihiro Kondo \n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF 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// Density of state of square lattice Ising model\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ising {\nnamespace dos {\nnamespace square {\n\ntypedef unsigned long uint_t;\n\nstd::vector count(uint_t Lx, uint_t Ly) {\n auto basis = lattice::basis::simple(2);\n auto unitcell = lattice::unitcell(2);\n unitcell.add_site(lattice::coordinate(0, 0), 0);\n unitcell.add_bond(0, 0, lattice::offset(1, 0), 0);\n unitcell.add_bond(0, 0, lattice::offset(0, 1), 0);\n auto graph = lattice::graph(basis, unitcell, lattice::extent(Lx, Ly));\n if (graph.num_bonds() >= std::numeric_limits::digits)\n throw std::range_error(\"Error: system size is too large\\n\");\n \n std::vector dos(graph.num_bonds() + 1, 0);\n uint_t num_states = 1 << graph.num_sites();\n for (uint_t c = 0; c < num_states; ++c) {\n uint_t energy = 0;\n for (uint_t b = 0; b < graph.num_bonds(); ++b) {\n uint_t ci = (c >> graph.source(b)) & 1;\n uint_t cj = (c >> graph.target(b)) & 1;\n energy += (ci ^ cj);\n }\n ++dos[energy];\n }\n return dos;\n}\n\n// Density of state of square lattice Ising model\n\n// Ref: P. Beale, Phys. Rev. Lett. 76, 78-81 (1996)\n\nnamespace {\n \ntemplate\nT zero(const T& x) { return 0 * x; }\n\ntemplate\nT one(const T& x) { return 1 + zero(x); }\n\ntemplate\nT power_n(const T& x, unsigned n) {\n auto res = one(x);\n for (unsigned i = 0; i < n; ++i) res *= x;\n return res;\n}\n\ntemplate\nT alpha(const T& x, const T& beta, unsigned n, unsigned k) {\n using std::cos;\n auto pi = boost::math::constants::pi();\n return power_n(1 + x * x, 2) - beta * cos(pi * k / n);\n}\n\n}\n\nusing namespace boost::math;\nusing namespace boost::math::differentiation;\nnamespace mp = boost::multiprecision;\ntypedef mp::cpp_int int_type;\n \ntemplate\nstd::vector finite(uint_t m, uint_t n) {\n typedef mp::number> real_type;\n std::cout << std::setprecision(std::numeric_limits::max_digits10);\n\n auto const x = make_fvar(0);\n auto const xpo = make_fvar(-1);\n auto const xmo = make_fvar(+1);\n\n auto beta = 2 * x * xpo * xmo;\n auto beta_m = power_n(beta, m);\n auto c0 = power_n(xmo, m) + power_n(x * xpo, m);\n auto s0 = power_n(xmo, m) - power_n(x * xpo, m);\n auto cn = power_n(xpo, m) + power_n(x * xmo, m);\n auto sn = power_n(xpo, m) - power_n(x * xmo, m);\n\n auto z1 = zero(x);\n auto z2 = zero(x);\n auto z3 = zero(x);\n auto z4 = zero(x);\n if ((n & 1) == 0) {\n z1 = one(x) / 2;\n z2 = one(x) / 2;\n z3 = c0 * cn / 2;\n z4 = s0 * sn / 2;\n } else {\n z1 = cn / 2;\n z2 = sn / 2;\n z3 = c0 / 2;\n z4 = s0 / 2;\n }\n for (unsigned k = 1; k < n; ++k) {\n auto ak = alpha(x, beta, n, k);\n auto v = zero(x);\n for (unsigned j = 0; j <= m; j += 2)\n v += binomial_coefficient(m, j)\n * power_n(ak * ak - beta * beta, j/2) * power_n(ak, m-j);\n if ((k & 1) == 1) {\n z1 *= (v + beta_m) / power_n(real_type(2), m - 1);\n z2 *= (v - beta_m) / power_n(real_type(2), m - 1);\n } else {\n z3 *= (v + beta_m) / power_n(real_type(2), m - 1);\n z4 *= (v - beta_m) / power_n(real_type(2), m - 1);\n }\n }\n auto zmn = z1 + z2 + z3 + z4;\n\n std::vector dos;\n for (unsigned i = 0; i <= 2 * m * n; ++i) dos.push_back(int_type(zmn.at(i) + 0.01));\n auto sum = std::accumulate(dos.begin(), dos.end(), int_type(0));\n if (sum != power_n(int_type(2), m * n)) {\n std::cerr << \"Error: result check failed\\n\";\n throw(0);\n }\n return dos;\n}\n\n}\n}\n}\n", "meta": {"hexsha": "6c3eea9d5fdff386a7e6a840db8a7334c2ceeff9", "size": 4745, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ising/dos/square.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/dos/square.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/dos/square.hpp", "max_forks_repo_name": "todo-group/exact", "max_forks_repo_head_hexsha": "ee76421fab9b2b1eaf77d6b01830a18e66f7180a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.4166666667, "max_line_length": 86, "alphanum_fraction": 0.6282402529, "num_tokens": 1528, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467548438124, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6453988099698644}} {"text": "// HelloWorld.cpp : main project file.\r\n//#define _CRTDBG_MAP_ALLOC\r\n//#include \r\n//#include \r\n#include \"stdafx.h\"\r\n#include \r\n#include \"Shamir.h\"\r\n#include \"string.h\"\r\n#include \"ShamirShare.h\"\r\n#include \"BenalohLeichter.h\"\r\n//#include \"AccessStructure.h\"\r\n//#include \"Trustee.h\"\r\n#include \"ISecretShare.h\"\r\n#include \"NonInteractiveChaumPedersen.h\"\r\n#include \"NTLHelper.h\"\r\n#include \"PrimeGenerator.h\"\r\n#include \r\n#include \"Schoenmakers.h\"\r\n#include \"PublicKeyEncryption.h\"\r\n#include \r\n//#include \"vld.h\"\r\nusing namespace System;\r\nusing namespace std;\r\nusing namespace NTL;\r\nusing namespace System::Collections::Generic;\r\nusing namespace SecretSharingCore::Algorithms;\r\nusing namespace SecretSharingCore::Algorithms::PVSS;\r\nusing namespace SecretSharingCore::Algorithms::PKE;\r\nusing namespace SecretSharingCore::Common;\r\nusing namespace SecretSharingCore::Algorithms::GeneralizedAccessStructure;\r\nusing namespace SecretSharing::OptimalThreshold::Models;\r\nusing namespace SecretSharing::OptimalThreshold;\r\nusing namespace SecretSharingCore::ZKProtocols;\r\nusing namespace SecretSharingCore;\r\n\r\nvoid MarshalString(String ^ s, string& os)\r\n{\r\n\tusing namespace Runtime::InteropServices;\r\n\tconst char* chars =\r\n\t\t(const char*)(Marshal::StringToHGlobalAnsi(s)).ToPointer();\r\n\tos = chars;\r\n\tMarshal::FreeHGlobal(IntPtr((void*)chars));\r\n}\r\n\r\n\r\nvoid runByteChunkShare(){\r\n\tint k = 3;\r\n\tint n = 10;\r\n\tByte chunkSize = 16;\r\n\tString^ secret = \"1234567812345678\";\r\n\tarray^ bytes = Encoding::UTF8->GetBytes(secret->ToCharArray());\r\n\tShamir^ secretshare = gcnew Shamir();\r\n#ifdef calcPrimeTime\r\n\tdouble a = 0;\r\n\tList^ shares = secretshare->DivideSecret(k, n, bytes,chunkSize,a);\r\n#else\r\n\tList^ shares = secretshare->DivideSecret(k, n, bytes, chunkSize);\r\n#endif\r\n\t//List^ sharesStr = secretshare->DivideSecret(k, n,secret);\r\n\tdelete bytes;\r\n\tfor (int i = 0; i < k; i++)\r\n\t{\r\n\t\tIShareCollection^ col = shares[i];\r\n\t\t//IShareCollection^ colstr = sharesStr[i];\r\n\r\n\t\tConsole::WriteLine(col->ToString());\r\n\t\t//Console::WriteLine(colstr->ToString()); \r\n\r\n\t/*\tfor (int j = 0; j < col->GetCount(); j++)\r\n\t\t{\r\n\t\t\tIShare^ share = col->GetShare(j);\r\n\t\t\tIShare^ shareStr = colstr->GetShare(j);\r\n\t\t\tConsole::WriteLine(share->ToString());\r\n\t\t\tConsole::WriteLine(shareStr->ToString());\r\n\t\t}*/\r\n\t}\r\n\r\n\tList^ recshares = shares->GetRange(0, k);\r\n\tarray^ recoveredSecret = secretshare->ReconstructSecret(recshares, chunkSize);\r\n\t//List^ recsharesstr = sharesStr->GetRange(0, k);\r\n\t//String^ recoveredSecretstr = secretshare->ReconstructSecret(recsharesstr);\r\n\r\n\tConsole::WriteLine(\"Secret:\"+Encoding::UTF8->GetString(recoveredSecret));\r\n\tfor (int i = 0; i < recshares->Count; i++)\r\n\t{\r\n\t\tdelete recshares[i];\r\n\t}\r\n\t//Console::WriteLine(\"SecretStr:\" + recoveredSecretstr);\r\n}\r\n\r\n\r\nvoid PrintIShares(List^ shares){\r\n\tfor (int j = 0; j < shares-> Count; j++)\r\n\t{\r\n\t\tConsole::WriteLine(shares[j]->ToString());\r\n\t}\r\n}\r\n\r\nint main(array ^args)\r\n{\r\n\t//PrimeGenerator^ pg = gcnew PrimeGenerator();\r\n\t//ZZ p = ZZ(263);\r\n\t//ZZ_p::init(p);\r\n\t//cout<< pg->IsGeneratorOfP(p, ZZ_p(5));\r\n\t//Console::Read();\r\n\r\n\tSchoenmakers^ sch = gcnew Schoenmakers();\r\n\tsch->SelectPrimeAndGenerators(1);\r\n\tZZ_p g = sch->Getg();\r\n\tZZ_p G = sch->GetG();\r\n\tZZ q = sch->Getq();\r\n\tcout <<\"g:\"< publickeys;\r\n\tvector> keypairs;\r\n\tPublicKeyEncryption^ pke = gcnew PublicKeyEncryption();\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\ttuple pair= pke->GenerateKeyPair(q, G);\r\n\t\tkeypairs.push_back(pair);\r\n\t\t//cout <<\"x:\"<< get<0>(pair)<<\" y:\"<(pair)<<'\\n';\r\n\t\tpublickeys.push_back(get<1>(pair));\r\n\t}\r\n\t\r\n\r\n\tint t = 3;\r\n\t\r\n\tvector encryptedShares;\r\n\tvector commitments;\r\n\tvector c,r;\r\n\tZZ_p secret;\r\n\t//provide public keys to schoenmakers\r\n\tsch->SetPublicKeys(publickeys);\r\n\r\n\tList^>^ commitsList = gcnew List^>();\r\n\tarray^ secretB;\r\n\tarray^ U;\r\n\tarray^ sigma = Encoding::UTF8->GetBytes(\"4\");\r\n\tList^ shares = sch->Distribute(t, n,sigma, commitsList, secretB,U);\r\n\tList^ poolesshares = gcnew List ();\r\n\tint i = 0;\r\n\tfor each (SchoenmakersShare^ share in shares)\r\n\t{\r\n\t\tSchoenmakersShare^ pooledshare = share;\r\n\t\tsch->PoolShare(gcnew Tuple^, array^>(NTLHelper::ZZpToByte(get<0>(keypairs.at(i))), NTLHelper::ZZpToByte(get<1>(keypairs.at(i)))), pooledshare);\r\n\t\tpoolesshares->Add(pooledshare);\r\n\t\ti++;\r\n\t}\r\n\tarray^ reconed = sch->Reconstruct(t, poolesshares, U);\r\n\t//Console::Read();\r\n\r\n\tsch->Distribute(t, n, encryptedShares, commitments, r, c,secret);\r\n\r\n\tfor (int i = 0; i < n; i++)\r\n\t{\r\n\t\tbool verified = sch->VerifyDistributedShare(i+1, r.at(i), c.at(i), encryptedShares.at(i), commitments, publickeys.at(i));\r\n\t\tcout << \"share i:\" << i+1 << \" verified status:\" << verified<<'\\n';\r\n\t\t//if (!verified) throw gcnew Exception(\"Failed to verify the share!\");\r\n\t}\r\n\tvector rshares;\r\n\tvector cshares;\r\n\tvector S;\r\n\tfor (int i = 0; i < encryptedShares.size(); i++)\r\n\t{\r\n\t\tZZ_p rshare, cshare;\r\n\t\t//each party pool his share and compute zero knowledge r and c\r\n\t\tZZ_p Si = sch->PoolShare(get<0>(keypairs.at(i)), get<1>(keypairs.at(i)), encryptedShares.at(i), rshare, cshare);\r\n\t\trshares.push_back(rshare);\r\n\t\tcshares.push_back(cshare);\r\n\t\tS.push_back(Si);\r\n\t}\r\n\t//dealer, at this point can verify decrypted shares\r\n\tbool verifyConstruction = sch->VerifyPooledShares(t, S, encryptedShares, rshares, cshares);\r\n\tcout << \"Construction verified:\" << verifyConstruction<<'\\n';\r\n\r\n\tif (verifyConstruction){\r\n\t\tZZ_p secret = sch->Reconstruct(t,S);\r\n\t\tcout <<\"secret:\" <^ Prime = NTLHelper::NumberToZZByte(17);\r\n\tNTLHelper::InitZZ_p(Prime);\r\n\r\n\tarray^ Base1 = NTLHelper::NumberToZZpByte(3);\r\n\tarray^ Base2 = NTLHelper::NumberToZZpByte(5); \r\n array^ Result1 = NTLHelper::NumberToZZpByte((long)pow(3,7));\r\n\tarray^ Result2 = NTLHelper::NumberToZZpByte((long)pow(5,7));\r\n\tarray^ Secret = NTLHelper::NumberToZZpByte(7);\r\n\tarray^ R;\r\n\tarray^ C;\r\n\r\n\t\r\n\t\r\n\tNonInteractiveChaumPedersen^ NICP = gcnew NonInteractiveChaumPedersen(Prime);\r\n\tNICP->ComputeProofs(Base1,Base2,Result1,Result2,Secret,R,C);\r\n\tbool Proved = NICP ->VerifyProofs(Base1,Base2,Result1,Result2,R,C);\r\n\tcout << \"Proved:\" << Proved<<'\\n';\r\n\tConsole::Read();\r\n\tgoto again;\r\n\r\n\t/*ZZ prime = ZZ(17);\r\n\tZZ_p::init(prime);\r\n\tNonInteractiveChaumPedersen^ nicp = gcnew NonInteractiveChaumPedersen(prime);\r\n\tZZ_p base1 = ZZ_p(3);\r\n\tZZ_p base2 = ZZ_p(5);\r\n\tZZ secret = ZZ(7);\r\n\tZZ_p result1 = power(base1, secret);\r\n\tZZ_p result2 = power(base2, secret);\r\n\tZZ_p c;\r\n\tZZ_p r;\r\n\tnicp->ComputeProofs(base1, base2, result1, result2, to_ZZ_p(secret), r, c);\r\n\r\n\tcout <<\"r: \"<< r<<'\\n';\r\n\tcout << \"c: \" << c << '\\n';\r\n\r\n\tbool proved = nicp->VerifyProofs(base1, base2, result1, result2, r, c);\r\n\tcout << \"proved:\" << proved<<'\\n';\r\n\tConsole::Read();\r\n\r\n\tgoto again;*/\r\n\r\n\t/*BenalohLeichter^ benaloh = gcnew BenalohLeichter();\r\n\tAccessStructure^ access = gcnew AccessStructure(\"p1^p2^p3,p2^p3^p4,p1^p3^p4,p1^p2^p4\");\r\n\taccess = ThresholdHelper::OptimiseAccessStructure(access, true);\r\n\tarray^ secretBytes = Encoding::UTF8->GetBytes(\"12345678\");\r\n\tList^ shares = benaloh->DivideSecret(secretBytes, access);\r\n\tarray^ reconSecretBytes = benaloh->ReconstructSecret(shares[0]);\r\n\tConsole::WriteLine(Encoding::UTF8->GetString(reconSecretBytes));\r\n*/\r\n\t//_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_DEBUG);\r\n\r\n\t/*Vec y = vec_ZZ_p();\r\n\tVec x = vec_ZZ_p();\r\n\r\n\tZZ_p::init(ZZ(199));\r\n\tZZ_p y1 = ZZ_p(68);\r\n\tZZ_p y2 = ZZ_p(2);\r\n\tZZ_p y3 = ZZ_p(92);\r\n\r\n\r\n\r\n\t\tx.append(ZZ_p(1));\r\n\t\tx.append(ZZ_p(2));\r\n\t\tx.append(ZZ_p(3));\r\n\r\n\r\n\t\ty.append(y1);\r\n\t\ty.append(y2);\r\n\t\ty.append(y3);\r\n\t\t\r\n\r\n\tZZ_pX interpolatedf = interpolate(x, y);\r\n\tcout << \"interpol g(x):\" << interpolatedf;*/\r\n\r\n\t//runByteChunkShare();\r\n\r\n\t//IShare^ sharezz = gcnew ShamirShare(1, &ZZ_p(2));\r\n\r\n\t/*\r\n\tint k = 4;\r\n\tint n = 10;\r\n\tString^ secret = \"1234\";\r\n\r\n\r\n\r\n\tShamir^ secretshare = gcnew Shamir();\r\n\tList^ shares = secretshare->DivideSecret(k, n, secret);\r\n\t\r\n\t\r\n\tfor (int i = 0; i < shares->Count; i++)\r\n\t{\r\n\t\tIShareCollection^ col = shares[i];\r\n\t\tConsole::WriteLine(col->ToString());\r\n\t\tfor (int j = 0; j < col->GetCount(); j++)\r\n\t\t{\r\n\t\t\tIShare^ share = col->GetShare(j);\r\n\t\t\tConsole::WriteLine(share->ToString());\r\n\t\t}\r\n\t}\r\n\r\n\r\n\tList^ frecshares = shares->GetRange(0, k - 1);\r\n\tString^ frecoveredSecret = secretshare ->ReconstructSecret(frecshares);\r\n\tConsole::WriteLine(\"recovered secret with k-1 shares:{0} secret:{1}\", frecshares->Count, frecoveredSecret);\r\n\r\n\r\n\tList^ recshares = shares->GetRange(0, k);\r\n\tString^ recoveredSecret = secretshare->ReconstructSecret(recshares);\r\n\tConsole::WriteLine(\"recovered secret with k shares:{0} secret:{1}\", recshares->Count, recoveredSecret);*/\r\n\r\n\t/*\r\n\tint a1 = 166;\r\n\tint a2 = 94;\r\n\r\n\tint p = 1613;\r\n\r\n\tZZ_p::init(ZZ(p));\r\n\r\n\tZZ_pX f;\r\n\tf.SetLength( k-1);\r\n\tSetCoeff(f, 0, ZZ_p(secret));\r\n\tSetCoeff(f, 1, ZZ_p(a1));\r\n\tSetCoeff(f, 2, ZZ_p(a2));\r\n\r\n\tcout << f;\r\n\r\n\tZZ_p d1 = eval(f, ZZ_p(1));\r\n\tZZ_p d2 = eval(f, ZZ_p(2));\r\n\tZZ_p d3 = eval(f, ZZ_p(3));\r\n\tZZ_p d4 = eval(f, ZZ_p(4));\r\n\tZZ_p d5 = eval(f, ZZ_p(5));\r\n\tZZ_p d6 = eval(f, ZZ_p(6));\r\n\r\n\tcout << '\\n' << d1 << '\\n' << d2 << '\\n' << d3 << '\\n' << d4 << '\\n' << d5 << '\\n' << d6;\r\n\r\n\tVec x = vec_ZZ_p();\r\n\tfor (int i = 1; i < 4; i++)\r\n\t{\r\n\t\tx.append(ZZ_p(i));\r\n\t}\r\n\t\r\n\tVec y = vec_ZZ_p();\r\n\ty.append(d1);\r\n\ty.append(d2);\r\n\ty.append(d3);\r\n\tZZ_pX interpolatedf = interpolate(x, y);\r\n\tcout << \"secret is:\" << eval(interpolatedf, ZZ_p(0));\r\n\r\n\t/*ZZ p;\r\n\tGenPrime(p, 10);\r\n\tlong val = RandomPrime_long(8);\r\n\tcout << p << \"/n\";\r\n\tcout << val;\r\n\tcin >> p;\r\n\tZZ_p::init(p);\r\n\r\n\t\r\n\r\n\tZZ_pX f;\r\n\tcin >> f;\r\n\r\n\tVec< Pair< ZZ_pX, long > > factors;\r\n\r\n\tCanZass(factors, f); // calls \"Cantor/Zassenhaus\" algorithm\r\n\r\n\tcout << factors << \"\\n\";\r\n\t*/\t//_CrtDumpMemoryLeaks(); \r\n}\r\n", "meta": {"hexsha": "76e50d07bfc77fb0a05495da28c95b60e23cc345", "size": 10310, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "SecretSharing.Core/Main.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": "SecretSharing.Core/Main.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": "SecretSharing.Core/Main.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": 28.9606741573, "max_line_length": 164, "alphanum_fraction": 0.6526673133, "num_tokens": 3211, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467706759583, "lm_q2_score": 0.734119521083126, "lm_q1q2_score": 0.6453988062504112}} {"text": "\n// solving A * X = B\n// using driver function gesv()\n\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 ublas::matrix m_t;\n\nint main() {\n\n cout << endl; \n\n size_t n = 5; \n m_t a (n, n); // system matrix \n\n size_t nrhs = 2; \n m_t x (n, nrhs), b (n, nrhs); // b -- right-hand side matrix\n\n init_symm (a); \n // [n n-1 n-2 ... 1]\n // [n-1 n n-1 ... 2]\n // a = [n-2 n-1 n ... 3]\n // [ ... ]\n // [1 2 ... n-1 n]\n\n m_t aa (a); // copy of a, because a is `lost' after gesv()\n\n ublas::matrix_column xc0 (x, 0), xc1 (x, 1); \n for (int i = 0; i < xc0.size(); ++i) {\n xc0 (i) = 1.;\n xc1 (i) = 2.; \n }\n b = prod (a, x); \n\n print_m (a, \"A\"); \n cout << endl; \n print_m (b, \"B\"); \n cout << endl; \n\n lapack::gesv (a, b); // solving the system, b contains x \n\n print_m (b, \"X\");\n cout << endl; \n\n x = prod (aa, b); \n print_m (x, \"B = A X\"); \n\n cout << endl; \n\n}\n\n", "meta": {"hexsha": "70dd07e02b181d394684d92c7a336deb8d72e4e1", "size": 1359, "ext": "cc", "lang": "C++", "max_stars_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gesv2.cc", "max_stars_repo_name": "diku-dk/PROX", "max_stars_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-01-14T19:18:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-01-14T19:18:21.000Z", "max_issues_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gesv2.cc", "max_issues_repo_name": "diku-dk/PROX", "max_issues_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PROX/3RDPARTY/BOOST_BINDINGS/boost_bindings/libs/numeric/bindings/lapack/test/ublas_gesv2.cc", "max_forks_repo_name": "diku-dk/PROX", "max_forks_repo_head_hexsha": "c6be72cc253ff75589a1cac28e4e91e788376900", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-11-23T09:56:06.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-23T09:56:06.000Z", "avg_line_length": 20.5909090909, "max_line_length": 63, "alphanum_fraction": 0.5540838852, "num_tokens": 498, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7341195210831258, "lm_q1q2_score": 0.6453987992767989}} {"text": "/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */\n\n/*\n Copyright (C) 2020 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 momentbasedgaussianpolynomial.hpp\n \\brief Gaussian quadrature defined by the moments of the distribution\n*/\n\n#ifndef quantlib_moment_based_gaussian_polynomial_hpp\n#define quantlib_moment_based_gaussian_polynomial_hpp\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace QuantLib {\n /*! References:\n Gauss quadratures and orthogonal polynomials\n\n G.H. Gloub and J.H. Welsch: Calculation of Gauss quadrature rule.\n Math. Comput. 23 (1986), 221-230,\n http://web.stanford.edu/class/cme335/spr11/S0025-5718-69-99647-1.pdf\n\n M. Morandi Cecchi and M. Redivo Zaglia, Computing the coefficients\n of a recurrence formula for numerical integration by moments and\n modified moments.\n http://ac.els-cdn.com/0377042793901522/1-s2.0-0377042793901522-main.pdf?_tid=643d5dca-a05d-11e6-9a56-00000aab0f27&acdnat=1478023545_cf7c87cba4cc9e37a136e68a2564d411\n */\n\n template \n class MomentBasedGaussianPolynomial\n : public GaussianOrthogonalPolynomial {\n public:\n MomentBasedGaussianPolynomial();\n\n Real mu_0() const;\n Real alpha(Size i) const;\n Real beta(Size i) const;\n\n virtual mp_real moment(Size i) const = 0;\n\n private:\n mp_real alpha_(Size i) const;\n mp_real beta_(Size i) const;\n\n mp_real z(Integer k, Integer i) const;\n\n mutable std::vector b_, c_;\n mutable std::vector > z_;\n };\n\n template inline\n MomentBasedGaussianPolynomial::MomentBasedGaussianPolynomial()\n : z_(1, std::vector()) {}\n\n template inline\n mp_real MomentBasedGaussianPolynomial::z(Integer k, Integer i) const {\n if (k == -1) return mp_real(0.0);\n\n const Integer rows = z_.size();\n const Integer cols = z_[0].size();\n\n if (cols <= i) {\n for (Integer l=0; l::quiet_NaN());\n }\n if (rows <= k) {\n z_.resize(k+1, std::vector(\n z_[0].size(), std::numeric_limits::quiet_NaN()));\n }\n\n if (boost::math::isnan(z_[k][i])) {\n if (k == 0)\n z_[k][i] = moment(i);\n else {\n const mp_real tmp = z(k-1, i+1)\n - alpha_(k-1)*z(k-1, i) - beta_(k-1)*z(k-2, i);\n z_[k][i] = tmp;\n }\n }\n\n return z_[k][i];\n };\n\n template inline\n mp_real MomentBasedGaussianPolynomial::alpha_(Size u) const {\n\n if (b_.size() <= u)\n b_.resize(u+1, std::numeric_limits::quiet_NaN());\n\n if (boost::math::isnan(b_[u])) {\n if (u == 0)\n b_[u] = moment(1);\n else {\n const Integer iu(u);\n const mp_real tmp =\n -z(iu-1, iu)/z(iu-1, iu-1) + z(iu, iu+1)/z(iu, iu);\n b_[u] = tmp;\n }\n }\n return b_[u];\n }\n\n template inline\n mp_real MomentBasedGaussianPolynomial::beta_(Size u) const {\n if (u == 0)\n return mp_real(1.0);\n\n if (c_.size() <= u)\n c_.resize(u+1, std::numeric_limits::quiet_NaN());\n\n if (boost::math::isnan(c_[u])) {\n const Integer iu(u);\n const mp_real tmp = z(iu, iu) / z(iu-1, iu-1);\n c_[u] = tmp;\n }\n return c_[u];\n }\n\n template <> inline\n Real MomentBasedGaussianPolynomial::alpha(Size u) const {\n return alpha_(u);\n }\n\n template inline\n Real MomentBasedGaussianPolynomial::alpha(Size u) const {\n return alpha_(u).template convert_to();\n }\n\n template <> inline\n Real MomentBasedGaussianPolynomial::beta(Size u) const {\n return beta_(u);\n }\n\n template inline\n Real MomentBasedGaussianPolynomial::beta(Size u) const {\n mp_real b = beta_(u);\n return b.template convert_to();\n }\n\n template <> inline\n Real MomentBasedGaussianPolynomial::mu_0() const {\n const Real m0 = moment(0);\n QL_REQUIRE(close_enough(m0, 1.0), \"zero moment must by one.\");\n\n return moment(0);\n }\n\n template inline\n Real MomentBasedGaussianPolynomial::mu_0() const {\n return moment(0).template convert_to();\n }\n}\n\n#endif\n", "meta": {"hexsha": "ba3a6eca41428cd9538cc412b704ff9a545d9391", "size": 5504, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ql/math/integrals/momentbasedgaussianpolynomial.hpp", "max_stars_repo_name": "urgu00/QuantLib", "max_stars_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2020-10-13T09:57:04.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-13T09:57:04.000Z", "max_issues_repo_path": "ql/math/integrals/momentbasedgaussianpolynomial.hpp", "max_issues_repo_name": "urgu00/QuantLib", "max_issues_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 19.0, "max_issues_repo_issues_event_min_datetime": "2020-11-23T08:36:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-28T10:06:53.000Z", "max_forks_repo_path": "ql/math/integrals/momentbasedgaussianpolynomial.hpp", "max_forks_repo_name": "urgu00/QuantLib", "max_forks_repo_head_hexsha": "fecce0abb0ff3d50da29c129f8f9e73176e20ab9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 5.0, "max_forks_repo_forks_event_min_datetime": "2020-06-04T15:19:22.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-18T08:24:37.000Z", "avg_line_length": 31.8150289017, "max_line_length": 172, "alphanum_fraction": 0.6157340116, "num_tokens": 1479, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.879146761176671, "lm_q2_score": 0.7341195152660688, "lm_q1q2_score": 0.645398794162752}} {"text": "#include \n#include // for assert\n#include // for min\n#include // for enable_if_c<>::type\n#include // for out_of_range\n\nusing namespace boost ;\n\n\n//https://stackoverflow.com/questions/35971827/c-boost-rational-class-floor-function\nnamespace boost {\n template \n constexpr IntType floor(rational const &num) {\n return static_cast(num.numerator() / num.denominator());\n }\n template \n constexpr IntType ceil(rational const &num) {\n auto inum = static_cast(num.numerator() / num.denominator());\n return (num == inum) ? inum : ((num.numerator() > 0) ? ++ inum : --inum) ;\n }\n}\n\n/*\nfor i in range(0,10):\n if floor(i*delta)==floor((i+1)*delta):\n print B[i-int(floor((i+1)*delta))],\n else:\n print A[int(floor(i*delta))],\n\ndeltaC = (deltaA*deltaB)/(deltaA+deltaB)\n*/\n\nrational deltaHash(const rational &arg1, const rational &arg2) {\n assert(arg1 + arg2 != 0);\n return (arg1 * arg2) / (arg1 + arg2);\n}\n\nbool Hash(const rational &deltaA, const rational &deltaB, const int i, int &retPos) {\n assert(deltaA > 0);\n assert(deltaB > 0);\n const rational delta = deltaB / (deltaA + deltaB) ;\n bool ret = floor(delta * i) == floor(delta * (i + 1));\n\n if (ret) {\n retPos = i - (floor((i + 1) * delta)); //B\n } else {\n retPos = floor(i * delta); //A\n }\n\n return ret ;\n}\n\n/*\n#hash - begin\ndelta=deltaB/(deltaA+deltaB)\n\nfor i in range(0,24):\n if int(i*delta)==int((i+1)*delta):\n C.append( B[i-int((i+1)*delta)] )\n else:\n C.append( A[int(i*delta)] )\n#hash - end\n\n#div - begin\ndeltaC=(deltaA*deltaB)/(deltaA+deltaB)\n\ndeltaA_ = deltaB*deltaC/(deltaB-deltaC)\nassert(deltaA_ == deltaA)\nfrom math import ceil\nfor i in range(0,5) :\n print C[i+int(ceil((i+1)*deltaA/deltaB))], <--- tu jest to div\n#Output: 1 2 3 4 5\n\n#div- end\n*/\n\nint Div(const boost::rational &deltaA, const boost::rational &deltaB, const int i) {\n return i + ceil((i + 1) * deltaA / deltaB);\n}\n\n/*\n#hash - begin\ndelta=deltaB/(deltaA+deltaB)\n\nfor i in range(0,24):\n if int(i*delta)==int((i+1)*delta):\n C.append( B[i-int((i+1)*delta)] )\n else:\n C.append( A[int(i*delta)] )\n\n#hash - end\n\n#mod - begin\ndeltaC=(deltaA*deltaB)/(deltaA+deltaB)\n\ndeltaB_ = deltaA*deltaC/(deltaA-deltaC)\nassert(deltaB_ == deltaB)\nfor i in range(0,10) :\n print C[i+int(i*deltaB/deltaA)], <--- tu jest mod\n#Output: a b c d e f g h i j#\n\n#mod - end\n*/\n\n\nint Mod(const boost::rational &deltaA, const boost::rational &deltaB, const int i) {\n return i + floor(i * deltaB / deltaA);\n}\n\n/* Ta funkcja jest taka sama dla obu operacji */\n\nrational deltaDivMod(const rational &arg1, const rational &arg2) {\n assert(arg1 != arg2);\n\n if (arg1 == arg2) {\n throw std::out_of_range(\"Delta are equal in DehashDiv - undefinied.\");\n }\n\n return (arg1 * arg2) / abs(arg1 - arg2);\n}\n\n/*\nfrom math import ceil\nfor i in range(0,10):\n if deltaA > deltaB :\n print C[int(ceil(i*deltaA/deltaB))][0],\n else:\n print C[i][0],\n*/\n\nrational deltaSubstract(const rational &arg1) {\n return arg1 ;\n}\n//todo\nint Substract(const rational &deltaA, const rational &deltaB, const int i) {\n return ceil(i * deltaA / deltaB);\n}\n\nrational deltaAdd(const rational &arg1, const rational &arg2) {\n return std::min(arg1, arg2) ;\n}\n\n/*\ndeltaC = min( deltaA,deltaB )\nfor i in range(0,10):\n if deltaC == deltaA:\n print str(A[i])+B[int(i*deltaA/deltaB)],\n else:\n print str(A[int(i*deltaB/deltaA)])+B[i],\n*/\n\n\nrational deltaTimemove(const rational &arg1, const rational &arg2) {\n return arg1 ;\n}\n\nint agse(int offset, int step) {\n return floor(boost::rational (offset) / boost::rational (step));\n}\n\nvoid SOperations_regtest() {\n boost::rational a(1, 2) ;\n boost::rational b(1, 3) ;\n boost::rational c(2, 3) ;\n boost::rational d(5, 4) ;\n boost::rational e(1) ;\n boost::rational f(0) ;\n boost::rational g(-2, 3);\n boost::rational h(-1);\n boost::rational j(-5, 4);\n assert(floor(a) == 0);\n assert(floor(b) == 0);\n assert(floor(c) == 0);\n assert(floor(d) == 1);\n assert(floor(e) == 1);\n assert(floor(f) == 0);\n assert(floor(g) == 0);\n assert(floor(h) == -1);\n assert(floor(j) == -1);\n assert(ceil(a) == 1);\n assert(ceil(b) == 1);\n assert(ceil(c) == 1);\n assert(ceil(d) == 2);\n assert(ceil(e) == 1);\n assert(ceil(f) == 0);\n assert(ceil(g) == -1);\n assert(ceil(h) == -1);\n assert(ceil(j) == -2);\n}", "meta": {"hexsha": "a61038d4ccea2fda96ab89a46178044870580818", "size": 4863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/share/SOperations.cpp", "max_stars_repo_name": "fossabot/retractordb", "max_stars_repo_head_hexsha": "b926c93fdb0fbe3897d85335d483e91573192bfd", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/share/SOperations.cpp", "max_issues_repo_name": "fossabot/retractordb", "max_issues_repo_head_hexsha": "b926c93fdb0fbe3897d85335d483e91573192bfd", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/share/SOperations.cpp", "max_forks_repo_name": "fossabot/retractordb", "max_forks_repo_head_hexsha": "b926c93fdb0fbe3897d85335d483e91573192bfd", "max_forks_repo_licenses": ["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.7301587302, "max_line_length": 95, "alphanum_fraction": 0.5924326547, "num_tokens": 1568, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8791467580102418, "lm_q2_score": 0.7341195152660687, "lm_q1q2_score": 0.6453987918382145}} {"text": "#ifndef USE_CUDA\n\n#include \n#include \n\n// C++ Version\nnamespace Kernel\n{\n // sets vf := v\n // vf is a vectorfield\n // v is a vector\n void fill(vectorfield & vf, const Vector3 & v)\n {\n for (unsigned int i=0; i\n#include \n#include \"matplotlibcpp.h\"\n#include \n\nusing namespace boost::numeric::odeint;\n\n// Define a abbreviation for state type\ntypedef std::vector< double > state_type;\n\nnamespace plt = matplotlibcpp;\n\nconst double sigma = 10.0;\nconst double R = 28.0;\nconst double b = 8.0 / 3.0;\n\n// the system function can be a classical functions\nvoid lorenz( state_type &x , state_type &dxdt , double t )\n{ \n dxdt[0] = sigma * ( x[1] - x[0] );\n dxdt[1] = R * x[0] - x[1] - x[0] * x[2];\n dxdt[2] = x[0]*x[1] - b * x[2];\n}\n\nint main(int argc, char const *argv[])\n{\n state_type x( 3 );\n x[0] = x[1] = x[2] = 10.0;\n const double dt = 0.01;\n integrate_const( runge_kutta4< state_type >() , lorenz , x , 0.0 , 10.0 , dt );\n \n return 0;\n}\n", "meta": {"hexsha": "2e0669d984d231048f1e412be9f89130ba8ff572", "size": 863, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Lectures/Lec5/main.cpp", "max_stars_repo_name": "amirnn/Engineering-Mathematics", "max_stars_repo_head_hexsha": "99dd270dba8ca3357259afb9195a9136b33510d8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Lectures/Lec5/main.cpp", "max_issues_repo_name": "amirnn/Engineering-Mathematics", "max_issues_repo_head_hexsha": "99dd270dba8ca3357259afb9195a9136b33510d8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lectures/Lec5/main.cpp", "max_forks_repo_name": "amirnn/Engineering-Mathematics", "max_forks_repo_head_hexsha": "99dd270dba8ca3357259afb9195a9136b33510d8", "max_forks_repo_licenses": ["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.3823529412, "max_line_length": 83, "alphanum_fraction": 0.5747392816, "num_tokens": 284, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9184802484881361, "lm_q2_score": 0.7025300636233416, "lm_q1q2_score": 0.6452599874071528}} {"text": "#include \n#include \n\nusing namespace std;\nusing namespace Eigen;\n\nint main()\n{\n\tMatrix3f A;\n\tA << 1, 2, 1,\n\t 2, 1, 0,\n\t -1, 1, 2;\n\tcout << A << endl;\n\tcout << A * A * A * A * A * A * A << endl;\n\tcout << A.inverse() << endl;\n\tcout << A.determinant() << endl;\n\n\tMatrixXf B = MatrixXf::Random(5, 3);\n\tcout << B << endl;\n\n\treturn 0;\n}\n", "meta": {"hexsha": "7497373cb4d64c11417fd0c975f3fa675feca761", "size": 360, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "snippets/eigen/test_eigen.cpp", "max_stars_repo_name": "qeedquan/misc_utilities", "max_stars_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2018-10-17T18:17:25.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T09:02:53.000Z", "max_issues_repo_path": "snippets/eigen/test_eigen.cpp", "max_issues_repo_name": "qeedquan/misc_utilities", "max_issues_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "snippets/eigen/test_eigen.cpp", "max_forks_repo_name": "qeedquan/misc_utilities", "max_forks_repo_head_hexsha": "94c6363388662ac8ebbf075b9c853ce6defbb5b3", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2020-07-01T13:52:42.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T09:10:59.000Z", "avg_line_length": 15.652173913, "max_line_length": 43, "alphanum_fraction": 0.5416666667, "num_tokens": 127, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.90192067652954, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.645255694282497}} {"text": "#include \n#include \n\nint main(int, char**)\n{\n typedef mtl::dense2D Matrix;\n typedef mtl::dense_vector Vector;\n \n Matrix A(4, 4), L(4, 4), U(4, 4), AA(4, 4);\n Vector\t \t\t v(4);\n double \t\t\t c=1.0; \n \n for (unsigned i= 0; i < 4; i++)\n\tfor(unsigned j= 0; j < 4; j++) {\n\t U[i][j]= i <= j ? c * (i+j+2) : (0);\n\t L[i][j]= i > j ? c * (i+j+1) : (i == j ? (1) : (0));\n\t}\n \n std::cout << \"L is:\\n\" << L << \"U is:\\n\" << U;\n A= L * U;\n std::cout << \"A is:\\n\" << A;\n AA= adjoint(A);\n \n for (unsigned i= 0; i < 4; i++)\n\tv[i]= double(i);\n\n Vector b( A*v ), b2( adjoint(A)*v );\n\n Matrix LU(A);\n lu(LU);\n std::cout << \"LU decomposition of A is:\\n\" << LU;\n\n Matrix B( lu_f(A) );\n std::cout << \"LU decomposition of A (as function result) is:\\n\" << B;\n \n Vector v1( lu_solve_straight(A, b) );\n std::cout << \"v1 is \" << v1 << \"\\n\";\n\n Vector v2( lu_solve(A, b) );\n std::cout << \"v2 is \" << v2 << \"\\n\";\n \n mtl::dense_vector P;\n lu(A, P);\n std::cout << \"LU with pivoting is \\n\" << with_format(A, 5, 2) << \"Permutation is \" << P << \"\\n\";\n Vector v3( lu_apply(A, P, b) );\n std::cout << \"v3 is \" << v3 << \"\\n\";\n \n Vector v4(lu_adjoint_apply(A, P, b2));\n std::cout << \"v4 is \" << v4 << \"\\n\";\n \n Vector v5(lu_adjoint_solve(AA, b));\n std::cout << \"v5 is \" << v5 << \"\\n\";\n \n return 0;\n}\n", "meta": {"hexsha": "f21a99202fa14f973ca01c9228c9f6afe38f78df", "size": 1498, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "libs/numeric/mtl/examples/lu_example.cpp", "max_stars_repo_name": "lit-uriy/mtl4-mirror", "max_stars_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_stars_repo_licenses": ["MTLL"], "max_stars_count": 24.0, "max_stars_repo_stars_event_min_datetime": "2019-03-26T15:25:45.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T10:00:45.000Z", "max_issues_repo_path": "libs/numeric/mtl/examples/lu_example.cpp", "max_issues_repo_name": "lit-uriy/mtl4-mirror", "max_issues_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_issues_repo_licenses": ["MTLL"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2020-04-17T12:35:32.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-03T15:46:25.000Z", "max_forks_repo_path": "libs/numeric/mtl/examples/lu_example.cpp", "max_forks_repo_name": "lit-uriy/mtl4-mirror", "max_forks_repo_head_hexsha": "37cf7c2847165d3537cbc3400cb5fde6f80e3d8b", "max_forks_repo_licenses": ["MTLL"], "max_forks_count": 10.0, "max_forks_repo_forks_event_min_datetime": "2019-12-01T13:40:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-14T08:39:54.000Z", "avg_line_length": 26.75, "max_line_length": 100, "alphanum_fraction": 0.4506008011, "num_tokens": 556, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9019206659843132, "lm_q2_score": 0.7154240018510026, "lm_q1q2_score": 0.6452556922106188}} {"text": "//\n// Created by senbaikang on 21.05.21.\n//\n\n#include \n#include \n\n#include \n\n#include \"probabilities.h\"\n\ndouble logBetaBinCountsTerm(\n double sup,\n double cov\n )\n{\n return std::lgamma(cov + 1.0) - std::lgamma(sup + 1.0) - std::lgamma(cov - sup + 1.0);\n}\n\ndouble logBetaBinMixedTerm(\n double sup,\n double cov,\n double mean,\n double overDis\n )\n{\n return std::lgamma(sup + mean * overDis) + std::lgamma(cov - sup + overDis * (1.0 - mean)) - std::lgamma(cov + overDis);\n}\n\ndouble logBetaBinParamsTerm(\n double mean,\n double overDis\n )\n{\n return std::lgamma(overDis) - std::lgamma(mean * overDis) - std::lgamma(overDis * (1.0 - mean));\n}\n\ndouble logBetaBinPDF(\n double sup,\n double cov,\n double mean,\n double overDis\n)\n{\n if (cov == 0)\n return 0;\n\n return logBetaBinCountsTerm(sup, cov) +\n logBetaBinMixedTerm(sup, cov, mean, overDis) +\n logBetaBinParamsTerm(mean, overDis);\n}\n\ndouble computeRawWildLogScore(\n Config const &config,\n double altCount,\n double coverage\n )\n{\n return logBetaBinPDF(\n altCount,\n coverage,\n config.getEffectiveSeqErrRate() / 3.0,\n config.getWildOverdispersion()\n );\n// return logBetaBinPDF(\n// altCount,\n// coverage,\n// config.getEffectiveSeqErrRate(),\n// config.getWildOverdispersion()\n// );\n}\n\ndouble computeRawHeteroMutLogScore(\n Config const &config,\n double altCount,\n double coverage\n )\n{\n return logBetaBinPDF(\n altCount,\n coverage,\n 0.5 - config.getEffectiveSeqErrRate() / 3.0,\n config.getMuOverdispersion()\n );\n// return logBetaBinPDF(\n// altCount,\n// coverage,\n// 0.5 - (2.0 / 3.0 * config.getEffectiveSeqErrRate()),\n// config.getMuOverdispersion()\n// );\n}\n\ndouble computeRawHomoMutLogScore(\n Config const &config,\n double covMinusSup,\n double coverage\n )\n{\n return logBetaBinPDF(\n covMinusSup,\n coverage,\n config.getEffectiveSeqErrRate(),\n config.getWildOverdispersion()\n );\n}\n\n// Add two values in real space by first exponentiating\ndouble addLogProb(double x, double y)\n{\n double maxScore;\n double minScore;\n\n if (x > y)\n {\n maxScore = x;\n minScore = y;\n }\n else\n {\n maxScore = y;\n minScore = x;\n }\n\n return std::log(1.0 + std::exp(minScore - maxScore)) + maxScore;\n}\n\ndouble logNChoose2(u_int32_t numMut)\n{\n return log(static_cast(numMut)) + log((static_cast(numMut) - 1.0) / 2.0);\n}\n\ndouble logNChooseK(u_int32_t n, u_int32_t k, double logNChoosekMinusOne)\n{\n if (k == 0)\n return 0;\n\n return logNChoosekMinusOne + log(static_cast(n + 1 - k) / static_cast(k));\n}\n\ndouble logNChooseK(u_int32_t n, u_int32_t k)\n{\n if (k == 0)\n return 0;\n\n return std::lgamma(n + 1) - std::lgamma(k + 1) - std::lgamma(n - k + 1);\n}\n\nOptimizeBetaBinMeanOverDis::OptimizeBetaBinMeanOverDis(\n const std::vector> &counts\n ):\n counts(counts)\n{}\n\ndouble OptimizeBetaBinMeanOverDis::operator()(const dlib::matrix &x) const\n{\n double result = 0;\n for (const auto & count : this->counts)\n result += logBetaBinPDF(count.first, count.second, x(0), x(1));\n\n return result;\n}\n\nOptimizeBetaBinMeanOverDisDerivates::OptimizeBetaBinMeanOverDisDerivates(\n const std::vector> &counts\n ):\n counts(counts)\n{}\n\ndlib::matrix OptimizeBetaBinMeanOverDisDerivates::operator()(const dlib::matrix &x) const\n{\n double mean = x(0);\n double overDis = x(1);\n dlib::matrix res = {0,0};\n\n double temp = 0;\n unsigned counter = 0;\n for (const auto & count : this->counts)\n {\n unsigned k = count.first;\n unsigned n = count.second;\n temp += overDis * boost::math::digamma(k + mean * overDis)\n - overDis * boost::math::digamma(n - k + overDis - overDis * mean);\n ++counter;\n }\n res(0) = counter * (-overDis * boost::math::digamma(mean * overDis) + overDis * boost::math::digamma(overDis - overDis * mean)) + temp;\n\n temp = 0;\n for (const auto & count : this->counts)\n {\n unsigned k = count.first;\n unsigned n = count.second;\n temp += mean * boost::math::digamma(k + mean * overDis) +\n (1.0 - mean) * boost::math::digamma(n - k + overDis - overDis * mean) -\n boost::math::digamma(n + overDis);\n }\n res(1) = counter * (boost::math::digamma(overDis) - mean * boost::math::digamma(mean * overDis) - (1.0 - mean) * boost::math::digamma(overDis - overDis * mean)) + temp;\n\n return res;\n}\n\nOptimizeBetaBinOverDis::OptimizeBetaBinOverDis(\n const std::vector> &counts,\n double meanFilter\n):\n counts(counts),\n meanFilter(meanFilter)\n{}\n\ndouble OptimizeBetaBinOverDis::operator()(const dlib::matrix &x) const\n{\n double result = 0;\n for (const auto & count : this->counts)\n result += logBetaBinPDF(count.first, count.second, meanFilter, x(0));\n\n return result;\n}\n\nOptimizeBetaBinOverDisDerivates::OptimizeBetaBinOverDisDerivates(\n const std::vector> &counts,\n double meanFilter\n ):\n counts(counts),\n meanFilter(meanFilter)\n{}\n\ndlib::matrix OptimizeBetaBinOverDisDerivates::operator()(const dlib::matrix &x) const\n{\n double mean = this->meanFilter;\n double overDis = x(0);\n dlib::matrix res = {0};\n\n double temp = 0;\n u_int32_t counter = 0;\n for (const auto & count : this->counts)\n {\n unsigned k = count.first;\n unsigned n = count.second;\n temp += mean * boost::math::digamma(k + mean * overDis) +\n (1.0 - mean) * boost::math::digamma(n - k + overDis - overDis * mean) -\n boost::math::digamma(n + overDis);\n ++counter;\n }\n res(0) = counter * (boost::math::digamma(overDis) - mean * boost::math::digamma(mean * overDis) - (1.0 - mean) * boost::math::digamma(overDis - overDis * mean)) + temp;\n\n return res;\n}\n", "meta": {"hexsha": "1b26b0b3f620ec0e9a386cc27dd11c6380cfe912", "size": 6020, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source/probabilities.cpp", "max_stars_repo_name": "senbaikang/DataFilter", "max_stars_repo_head_hexsha": "cd3c1e30edfff235a325de6c560941f4f31bc01f", "max_stars_repo_licenses": ["Apache-2.0"], "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/probabilities.cpp", "max_issues_repo_name": "senbaikang/DataFilter", "max_issues_repo_head_hexsha": "cd3c1e30edfff235a325de6c560941f4f31bc01f", "max_issues_repo_licenses": ["Apache-2.0"], "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/probabilities.cpp", "max_forks_repo_name": "senbaikang/DataFilter", "max_forks_repo_head_hexsha": "cd3c1e30edfff235a325de6c560941f4f31bc01f", "max_forks_repo_licenses": ["Apache-2.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.3724696356, "max_line_length": 170, "alphanum_fraction": 0.6428571429, "num_tokens": 1849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9314624993576758, "lm_q2_score": 0.6926419704455589, "lm_q1q2_score": 0.6451700209512456}} {"text": "/*\n * Copyright (C) 2016-2019 Istituto Italiano di Tecnologia (IIT)\n *\n * This software may be modified and distributed under the terms of the\n * BSD 3-Clause license. See the accompanying LICENSE file for details.\n */\n\n#include \n\n#include \n\nusing namespace bfl;\nusing namespace Eigen;\n\n\nLTIStateModel::LTIStateModel(const Ref& transition_matrix, const Ref& noise_covariance_matrix) :\n F_(transition_matrix), Q_(noise_covariance_matrix)\n{\n if ((F_.rows() == 0) || (F_.cols() == 0))\n throw std::runtime_error(\"ERROR::LTISTATEMODEL::CTOR\\nERROR:\\n\\tState transition matrix dimensions cannot be 0.\");\n else if ((Q_.rows() == 0) || (Q_.cols() == 0))\n throw std::runtime_error(\"ERROR::LTISTATEMODEL::CTOR\\nERROR:\\n\\tNoise covariance matrix dimensions cannot be 0.\");\n else if (F_.rows() != F_.cols())\n throw std::runtime_error(\"ERROR::LTISTATEMODEL::CTOR\\nERROR:\\n\\tState transition matrix must be a square matrix.\");\n else if (Q_.rows() != Q_.cols())\n throw std::runtime_error(\"ERROR::LTISTATEMODEL::CTOR\\nERROR:\\n\\tNoise covariance matrix must be a square matrix.\");\n else if (F_.rows() != Q_.rows())\n throw std::runtime_error(\"ERROR::LTISTATEMODEL::CTOR\\nERROR:\\n\\tNumber of rows of the state transition matrix must be the same as the size of the noise covariance matrix.\");\n}\n\n\nvoid LTIStateModel::propagate(const Eigen::Ref& cur_states, Eigen::Ref prop_states)\n{\n prop_states = F_ * cur_states;\n}\n\n\nEigen::MatrixXd LTIStateModel::getNoiseCovarianceMatrix()\n{\n return Q_;\n}\n\n\nEigen::MatrixXd LTIStateModel::getStateTransitionMatrix()\n{\n return F_;\n}\n\n\nbool LTIStateModel::setProperty(const std::string& property)\n{\n return false;\n}\n\n\nEigen::MatrixXd LTIStateModel::getJacobian()\n{\n return F_;\n}\n", "meta": {"hexsha": "d5f3ae9d3438636cf0f3d687574c8898da66971c", "size": 1877, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BayesFilters/src/LTIStateModel.cpp", "max_stars_repo_name": "vesor/bayes-filters-lib", "max_stars_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2021-05-27T02:52:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-10T07:06:39.000Z", "max_issues_repo_path": "src/BayesFilters/src/LTIStateModel.cpp", "max_issues_repo_name": "vesor/bayes-filters-lib", "max_issues_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_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/LTIStateModel.cpp", "max_forks_repo_name": "vesor/bayes-filters-lib", "max_forks_repo_head_hexsha": "24cfbed786a017f7aebb5bf3ace3694d4f7d5f66", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-04-14T08:20:28.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-14T08:20:28.000Z", "avg_line_length": 31.2833333333, "max_line_length": 181, "alphanum_fraction": 0.7112413426, "num_tokens": 485, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.882427872638409, "lm_q2_score": 0.7310585669110202, "lm_q1q2_score": 0.6451064559733756}} {"text": "/*\n * Refs:\n * https://eigen.tuxfamily.org/dox/index.html\n * https://dritchie.github.io/csci2240/assignments/eigen_tutorial.pdf\n * */\n\n#include \n#include \n\n#define PRINT(x) std::cout << #x << \": \" << std::endl << (x) << std::endl << std::endl\n#define PRINT_SIZE(x) std::cout << #x << \" is of size \" << x.rows() << \"x\" << x.cols() << std::endl << std::endl\n#define SECTION(x) std::cout << \"======================== \" << x << \" =======================\" << std::endl << std::endl\n\nint main() {\n\n using namespace Eigen;\n\n SECTION(\"Initialisations\");\n // Different ways to initialise matrix\n Matrix m0 = Matrix4d::Ones();\n // the last three are optional, so we don't have to worry about it most of the time.\n // isRowMajor=0: default is column major, MaxRowsAtCompileTime, MaxColsAtCompileTime\n PRINT(m0);\n MatrixXd m1(4, 4); // typedef Matrix MatrixXd;\n m1 = Matrix4d::Zero();\n PRINT(m1);\n // fix size matrix\n Matrix4d m2 = Matrix4d::Random(); // [-1, 1]\n PRINT(m2);\n Vector4d m3(1.0, 2.0, 3.0, 4.0); // typedef Matrix Vector3d;\n PRINT(m3);\n MatrixXd v = Vector4d::Ones(); // vectors just one dimensional matrices\n PRINT(v);\n VectorXd m4 = Vector4d::Constant(108.5); // column vector\n PRINT(m4);\n RowVectorXd m4r = Vector4d::Constant(108.5); // row vector\n PRINT(m4r);\n\n SECTION(\"Store orders\");\n // store orders\n // https://eigen.tuxfamily.org/dox/group__TopicStorageOrders.html\n Matrix m5;\n m5 << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16; // comma-initializer syntax\n PRINT(m5);\n std::cout << \"In memory (row-major):\" << std::endl;\n for (int i = 0; i < m5.size(); i++)\n std::cout << *(m5.data() + i) << \" \";\n std::cout << std::endl << std::endl;\n\n Matrix m6;\n m6 << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;\n PRINT(m6);\n std::cout << \"In memory (column-major):\" << std::endl;\n for (int i = 0; i < m6.size(); i++)\n std::cout << *(m6.data() + i) << \" \";\n std::cout << std::endl << std::endl;\n\n Matrix m7; // default is Column major\n m7 << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16;\n PRINT(m7);\n std::cout << \"In memory (column-major) is default:\" << std::endl;\n for (int i = 0; i < m7.size(); i++)\n std::cout << *(m7.data() + i) << \" \";\n std::cout << std::endl << std::endl;\n\n // ref: https://eigen.tuxfamily.org/dox/group__TutorialAdvancedInitialization.html\n MatrixXd m8(4, 8);\n m8 << m6, m7;\n PRINT(m8);\n\n MatrixXd m9(8, 4);\n m9 << m6, m7;\n PRINT(m9);\n\n SECTION(\"Block Operation\");\n // block operation https://eigen.tuxfamily.org/dox/group__TutorialBlockOperations.html\n MatrixXd m10(5, 9);\n m10.row(0) << RowVectorXd::Ones(9)*100;\n m10.block(1, 0, 4, 4) << m6;\n m10.block<4, 4>(1, 4) = m7*2;\n m10.col(8).tail(4) << VectorXd::Ones(4)*99; // col and row are special case of block\n PRINT(m10);\n // some other keywords:\n // topLeftCorner, bottomLeftCorner, topRightCorner, bottomRightCorner, topRows, bottomRows, leftCols, rightCols.\n PRINT(m5);\n PRINT(m5.leftCols(2));\n PRINT(m5.bottomRows<2>());\n m5.topLeftCorner(1,3) = m5.bottomRightCorner(3,1).transpose();\n PRINT(m5);\n VectorXd v0(6);\n v0 << 1, 2, 3, 4, 5, 6;\n PRINT(v0.head(3));\n PRINT(v0.tail<3>());\n v0.segment(1,4) *= 2;\n PRINT(v0);\n\n SECTION(\"Diagonal\");\n // Coefficient accessors\n m0(2, 2) = 100;\n PRINT(m0);\n PRINT(m0.diagonal());\n MatrixXd m0d1 = m0.diagonal().asDiagonal();\n // https://eigen.tuxfamily.org/dox/classEigen_1_1MatrixBase.html#a14235b62c90f93fe910070b4743782d0\n PRINT(m0d1);\n DiagonalMatrix m0d2;\n // http://eigen.tuxfamily.org/dox/classEigen_1_1DiagonalMatrix.html\n m0d2.diagonal() = m0.diagonal();\n PRINT(MatrixXd(m0d2));\n\n m1 = Matrix4d::Identity(); // overwrite matrix values\n PRINT(m1);\n\n SECTION(\"Vector operations\");\n // Vector operations\n Vector3f v1, v2;\n v1 = Vector3f::Random();\n v2 = Vector3f::Random();\n PRINT(v1);\n PRINT(v2);\n PRINT(v1 * v2.transpose());\n PRINT(v1.transpose() * v2);\n PRINT(v1.dot(v2));\n PRINT(v1.cross(Vector3f(3., 4., 6.).normalized()));\n PRINT(v1.cross(v2));\n\n Vector4f v3 = v1.homogeneous();\n PRINT(v3);\n PRINT(v3.hnormalized());\n // element-wise similar to matrix\n PRINT(v1.array().sin());\n\n SECTION(\"Matrix Operations\");\n // Matrix Operations\n PRINT(m0 + m1);\n PRINT(m0 * m1);\n PRINT(m1 += m1);\n PRINT(m1 *= 2);\n PRINT(m0 - m1 * 2.2);\n // Check if two matrices are the same\n PRINT(m0 * m1 == m0 - m1 * 2.2);\n PRINT(m1 == Matrix4d::Identity()*4);\n\n PRINT(m6.transpose()); // this doesn't modify m6\n // NEVER DO \"a = a.transpose()\" aliasing issue: https://eigen.tuxfamily.org/dox/group__TutorialMatrixArithmetic.html\n // but matrix operation is fine, no problem! a = a*a;\n // https://eigen.tuxfamily.org/dox/group__TopicAliasing.html\n m6.transposeInPlace(); // we can do this instead\n PRINT(m6);\n PRINT(m6.inverse()); // if not invertible then shows NaN\n\n SECTION(\"Element-Wise\");\n // element-wise\n PRINT(m6.array().square());\n PRINT(m6.array() * m6.transpose().array());\n PRINT(((m0 * m1).array() == (m0 - m1 * 2.2).array()));\n\n SECTION(\"Basic arithmetic reduction operations\");\n // Basic arithmetic reduction operations\n // https://eigen.tuxfamily.org/dox/group__TutorialMatrixArithmetic.html\n // https://eigen.tuxfamily.org/dox/group__TutorialReductionsVisitorsBroadcasting.html\n PRINT(m1);\n PRINT(m1.sum());\n PRINT(m1.prod());\n PRINT(m1.mean());\n PRINT(m1.minCoeff());\n PRINT(m1.maxCoeff());\n PRINT(m1.trace());\n // visitors\n MatrixXd::Index maxRow, maxCol;\n double maxOfm1 = m1.maxCoeff(&maxRow, &maxCol);\n std::cout << maxOfm1 << \" is at position: (\" << maxRow << \",\" << maxCol << \")\" << std::endl << std::endl;\n std::ptrdiff_t i, j;\n double minOfm1 = m1.minCoeff(&i, &j);\n std::cout << minOfm1 << \" is at position: (\" << i << \",\" << j << \")\" << std::endl << std::endl;\n // partial reductions\n PRINT(m1.colwise().maxCoeff());\n PRINT(m1.rowwise().maxCoeff());\n PRINT(m1.cwiseSqrt());\n PRINT(m1.cwiseSqrt().colwise().maxCoeff());\n\n SECTION(\"Norm\");\n PRINT(m1.squaredNorm());\n PRINT(m1.norm());\n // lp-norm\n PRINT(m1.lpNorm<2>());\n PRINT(m1.lpNorm<1>());\n PRINT(m1.lpNorm());\n // Operator norm: https://en.wikipedia.org/wiki/Operator_norm\n // 1-norm(m1)\n PRINT(m1.cwiseAbs().colwise().sum().maxCoeff());\n PRINT(m1.colwise().lpNorm<1>().maxCoeff());\n // Infinity-norm(m1)\n PRINT(m1.cwiseAbs().rowwise().sum().maxCoeff());\n PRINT(m1.rowwise().lpNorm<1>().maxCoeff());\n\n PRINT(m6);\n MatrixXd::Index maxIndex;\n double maxNorm = m6.colwise().sum().maxCoeff(&maxIndex);\n std::cout << \"Maximum sum at position \" << maxIndex << std::endl\n << \"The corresponding vector is: \" << std::endl\n << m6.col(maxIndex) << std::endl\n << \"And its sum is is: \" << maxNorm << std::endl << std::endl;\n\n SECTION(\"Broadcasting\");\n // https://eigen.tuxfamily.org/dox/group__TutorialReductionsVisitorsBroadcasting.html\n MatrixXd mb = MatrixXd::Zero(2, 4);\n VectorXd vb = Vector2d(0, 1);\n PRINT(mb);\n PRINT(vb);\n mb.colwise() += vb;\n PRINT(mb);\n mb.setZero();\n vb = Vector4d(0, 1, 2, 3);\n mb.rowwise() += vb.transpose();\n PRINT(mb);\n PRINT(vb);\n // find nearest neighbour\n mb.setRandom();\n vb.setRandom(2);\n PRINT(mb);\n PRINT(vb);\n MatrixXf::Index index;\n (mb.colwise() - vb).colwise().squaredNorm().minCoeff(&index);\n std::cout << \"Nearest neighbour is column \" << index << \":\" << std::endl;\n std::cout << mb.col(index) << std::endl;\n\n SECTION(\"Resizing\");\n // resizing\n // https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html\n VectorXd v4 = Vector4d::Ones()*100;\n PRINT(v4);\n v4.conservativeResize(6); // this leave the old value untouched\n PRINT(v4);\n v4.resize(8);\n PRINT(v4);\n\n PRINT_SIZE(m1);\n m1 = MatrixXd::Identity(6, 6); // copy and resize of matrix with dynamic size\n PRINT(m1);\n PRINT_SIZE(m1);\n\n // change type of matrix\n MatrixXf m11 = m1.cast();\n PRINT(m11);\n\n SECTION(\"Temporary objects\");\n // using comma-initializer as temporary objects\n // https://eigen.tuxfamily.org/dox/group__TutorialAdvancedInitialization.html\n MatrixXf mat = MatrixXf::Random(2, 3);\n PRINT(mat);\n mat = (MatrixXf(2,2) << 0, 1, 1, 0).finished() * mat;\n PRINT(mat);\n // https://eigen.tuxfamily.org/dox/structEigen_1_1CommaInitializer.html#a3cf9e2b8a227940f50103130b2d2859a\n\n}\n", "meta": {"hexsha": "b9c8bb308941ba6bcfb533e0108bd640ce9f3113", "size": 8450, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/102_Matrix/main.cpp", "max_stars_repo_name": "GeneKao/Eigen-Cpp-Notes", "max_stars_repo_head_hexsha": "fbc558af3926cb2f033a44403923af621fee1e92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/102_Matrix/main.cpp", "max_issues_repo_name": "GeneKao/Eigen-Cpp-Notes", "max_issues_repo_head_hexsha": "fbc558af3926cb2f033a44403923af621fee1e92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/102_Matrix/main.cpp", "max_forks_repo_name": "GeneKao/Eigen-Cpp-Notes", "max_forks_repo_head_hexsha": "fbc558af3926cb2f033a44403923af621fee1e92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.0078125, "max_line_length": 120, "alphanum_fraction": 0.6282840237, "num_tokens": 2872, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.766293653760418, "lm_q2_score": 0.8418256472515684, "lm_q1q2_score": 0.6450856510616332}} {"text": "/**\n * \\file boost/numeric/ublasx/operation/ql.hpp\n *\n * \\brief The QL matrix decomposition.\n *\n * Given an \\f$m\\f$-by-\\f$n\\f$ matrix \\f$A\\f$, its QL-decomposition is a matrix\n * decomposition of the form:\n * \\f[\n * A=QL\n * \\f]\n * where \\f$L\\f$ is an m-by-n lower trapezoidal (or, when \\f$m \\ge n\\f$,\n * triangular) matrix and \\f$Q\\f$ is an m-by-m orthogonal (or unitary) matrix,\n * that is one satisfying:\n * \\f[\n * Q^{T}Q=I\n * \\f]\n where \\f$Q^{T}\\f$ is the transpose of \\f$Q\\f$ and \\f$I\\f$ is the identity\n * matrix.\n *\n * For the special case of \\f$m \\ge n\\f$, the factorization can be rewritten as:\n * \\f[\n * A=\\begin{pmatrix}\n * Q_1 & Q_2\n * \\end{pmatrix}\n * \\begin{pmatrix}\n * L_1 \\\\\n * L_2 \\\\\n * \\end{pmatrix}\n * =\\begin{pmatrix}\n * Q_1 & Q_2\n * \\end{pmatrix}\n * \\begin{pmatrix}\n * 0 \\\\\n * L_2 \\\\\n * \\end{pmatrix}\n * = Q_2 L_2\n * \\f] \n * where \\f$Q_1\\f$ is an m-by-(m-n) matrix, \\f$Q_2\\f$ is an m-by-n matrix,\n * \\f$L_1\\f$ is an (m-n)-by-n zero matrix, and \\f$L_2\\f$ is an n-by-n lower\n * triangular matrix.\n *\n * The QL factorization is particular useful for computing minimum-phase\n * filters.\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 * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\n\n#ifndef BOOST_NUMERIC_UBLASX_OPERATION_QL_HPP\n#define BOOST_NUMERIC_UBLASX_OPERATION_QL_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\n\nnamespace boost { namespace numeric { namespace ublasx {\n\nusing namespace ::boost::numeric::ublas;\n\n\nnamespace detail { namespace /**/ {\n\nstruct ql_decomposition_impl_common;\n\n/**\n * \\brief Type-oriented operations for QL decomposition.\n *\n * \\tparam IsComplex Logical parameter telling if the we are doing either a real\n * or a complex QL decomposition.\n *\n * This class makes distinction between the real and the complex case.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate \nstruct ql_decomposition_impl;\n\n\n/**\n * \\brief Common operations for QL decomposition.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\nstruct ql_decomposition_impl_common\n{\n\t/// Performan QL decomposition of the given input matrix \\a A\n\t/// (row-major case).\n\ttemplate \n\t\tstatic void decompose(AMatrixT& A, TauVectorT& tau, row_major_tag)\n\t{\n\t\tmatrix::value_type, column_major> tmp_A(A);\n\n\t\tdecompose(tmp_A, tau, column_major_tag());\n\n\t\tA = tmp_A;\n\t}\n\n\n\t/// Performan QL decomposition of the given input matrix \\a A\n\t/// (column-major case).\n\ttemplate \n\t\tstatic void decompose(AMatrixT& A, TauVectorT& tau, column_major_tag)\n\t{\n\t\ttypedef typename matrix_traits::size_type size_type;\n\n\t\tsize_type m = num_rows(A);\n\t\tsize_type n = num_columns(A);\n\t\tsize_type k = ::std::min(m,n);\n\n\t\tif (size(tau) != k)\n\t\t{\n\t\t\ttau.resize(k, false);\n\t\t}\n\n\t\t::boost::numeric::bindings::lapack::geqlf(A, tau);\n\t}\n\n\n\t/// Extract the L matrix from a previously computing QL decomposition\n\t/// (row-major case).\n\ttemplate \n\t\tstatic void extract_L(QLMatrixT const& QL, LMatrixT& L, bool full, row_major_tag)\n\t{\n\t\tmatrix::value_type, column_major> tmp_QL(QL);\n\t\tmatrix::value_type, column_major> tmp_L(L);\n\n\t\textract_L(tmp_QL, tmp_L, full, column_major_tag());\n\n\t\tL = tmp_L;\n\t}\n\n\n\t/**\n\t * \\brief Extract the L matrix from a previously computing QL decomposition\n\t * (column-major case).\n\t *\n\t * Let QL be an m-by-n matrix, then the L matrix is built as:\n\t * - If m >= n, the lower triangle of the submatrix QL(m-n+1:m,1:n)\n\t * contains the n-by-n lower triangular matrix L;\n\t * - if m <= n, the elements on and below the (n-m)-th\n\t * superdiagonal contain the m-by-n lower trapezoidal matrix L.\n\t * .\n\t */\n\ttemplate \n\t\tstatic void extract_L(QLMatrixT const& QL, LMatrixT& L, bool full, column_major_tag)\n\t{\n\t\ttypedef typename matrix_traits::size_type size_type;\n\t\ttypedef typename matrix_traits::value_type value_type;\n\n\t\tsize_type m = num_rows(QL);\n\t\tsize_type n = num_columns(QL);\n\t\tsize_type nr = full ? m : ::std::min(m,n);\n\n\t\tif (num_rows(L) != nr && num_columns(L) != n)\n\t\t{\n\t\t\tL.resize(nr, n, false);\n\t\t}\n\n\t\t//::std::fill(L.data().begin(), L.data().end(), value_type/*zero*/());\n\t\tif (m >= n)\n\t\t{\n\t\t\tsize_type k = m-n;\n\t\t\tsize_type kr = k;\n\n\t\t\t// Set to zero the first m-n rows\n\t\t\tif (full)\n\t\t\t{\n\t\t\t\tsubrange(L, 0, k, 0, n) = scalar_matrix(k, n, value_type/*zero*/());\n//\t\t\t\tfor (size_type row = 0; row < k; ++row)\n//\t\t\t\t{\n//\t\t\t\t\tfor(size_type col = 0; col < n; ++col)\n//\t\t\t\t\t{\n//\t\t\t\t\t\tL(row,col) = value_type/*zero*/();\n//\t\t\t\t\t}\n//\t\t\t\t}\n\t\t\t\tkr = 0;\n\t\t\t}\n\t\t\t// the lower triangle of the submatrix QL(m-n+1:m,1:n) contains the\n\t\t\t// n-by-n lower triangular matrix L\n\t\t\tfor (size_type row = k; row < m; ++row)\n\t\t\t{\n\t\t\t\tfor (size_type col = 0; col < n; ++col)\n\t\t\t\t{\n\t\t\t\t\tif (col <= (row-k))\n\t\t\t\t\t{\n\t\t\t\t\t\tL(row-kr,col) = QL(row,col);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tL(row-kr,col) = value_type/*zero*/();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t // the elements on and below the (n-m)-th\n\t\t\t // superdiagonal contain the m-by-n lower trapezoidal matrix L.\n\t\t\tsize_type k = n-m;\n\t\t\tfor (size_type row = 0; row < m; ++row)\n\t\t\t{\n\t\t\t\tfor(size_type col = 0; col < n; ++col)\n\t\t\t\t{\n\t\t\t\t\tif (col <= (row+k))\n\t\t\t\t\t{\n\t\t\t\t\t\tL(row,col) = QL(row,col);\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tL(row,col) = value_type/*zero*/();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/**\n\t * \\brief Multiply the given \\a C matrix by the \\c Q matrix obtained from\n\t * the QL decomposition.\n\t *\n\t * \\tparam QLMatrixT The type of the \\a QL matrix.\n\t * \\tparam TAUMatrixT The type of the \\a tau vector.\n\t * \\tparam CMatrixT The type of the \\a C matrix.\n\t *\n\t * \\param QL The matrix obtained by the QL decomposition such that the i-th\n\t * column contains the vector which defines the elementary reflector\n\t * \\f$H(i)\\f$, for \\f$i = 1,2,\\ldots,k\\f$.\n\t * \\param tau The vector obtained by the QL decomposition containing the\n\t * scalar factors of the elementary reflectors \\f$H(i)\\f$, for\n\t * \\f$i=1,2,\\ldots,k\\f$.\n\t * \\param left_Q A boolean value indicating which side of the product the\n\t * matrix \\c Q will occupy. A \\c true value indicates that \\c Q is the left\n\t * operand, while a \\c false value indicates that \\c Q is the right\n\t * operand.\n\t * \\param trans_Q A boolean value indicating if the matrix \\c Q is to be\n\t * transposed. A \\c true value indicates that \\c Q is to be transposed,\n\t * while a \\c false value indicates that \\c Q is to be taken as-is.\n\t * \\param orientation The matrix orientation fixed to row-major.\n\t *\n\t * Let \\c Q be the matrix obtained from the QL decomposition represented\n\t * by the \\a QL matrix and the \\a tau vector parameters. \n\t * Then this function computes the following matrix product:\n\t * \\f{equation*}{\n\t * \\begin{cases}\n\t * Q C, & \\text{\\texttt{left\\_Q} = \\emph{true} and \\texttt{trans\\_Q} = \\emph{false}}, \\\\\n\t * Q^T C, & \\text{\\texttt{left\\_Q} = \\emph{true} and \\texttt{trans\\_Q} = \\emph{true}}, \\\\\n\t * C Q, & \\text{\\texttt{left\\_Q} = \\emph{false} and \\texttt{trans\\_Q} = \\emph{false}}, \\\\\n\t * C Q^T, & \\text{\\texttt{left\\_Q} = \\emph{false} and \\texttt{trans\\_Q} = \\emph{true}}.\n\t * \\end{cases}\n\t * \\f}\n\t */\n\ttemplate \n\t\tstatic void prod(QLMatrixT& QL, TAUVectorT const& tau, CMatrixT& C, bool left_Q, bool trans_Q, row_major_tag)\n\t{\n\t\t//NOTE: QL cannot be const since LAPACK::ORMQL modified it, restoring\n\t\t// it at the end of the function.\n\n\t\tmatrix::value_type, column_major> tmp_QL(QL);\n\t\tmatrix::value_type, column_major> tmp_C(C);\n\n\t\tprod(tmp_QL, tau, tmp_C, left_Q, trans_Q, column_major_tag());\n\n\t\tC = tmp_C;\n\t}\n\n\n\t/**\n\t * \\brief Multiply the given \\a C matrix by the \\c Q matrix obtained from\n\t * the QL decomposition.\n\t *\n\t * \\tparam QLMatrixT The type of the \\a QL matrix.\n\t * \\tparam TAUMatrixT The type of the \\a tau vector.\n\t * \\tparam CMatrixT The type of the \\a C matrix.\n\t *\n\t * \\param QL The matrix obtained by the QL decomposition such that the i-th\n\t * column contains the vector which defines the elementary reflector\n\t * \\f$H(i)\\f$, for \\f$i = 1,2,\\ldots,k\\f$.\n\t * \\param tau The vector obtained by the QL decomposition containing the\n\t * scalar factors of the elementary reflectors \\f$H(i)\\f$, for\n\t * \\f$i=1,2,\\ldots,k\\f$.\n\t * \\param left_Q A boolean value indicating which side of the product the\n\t * matrix \\c Q will occupy. A \\c true value indicates that \\c Q is the left\n\t * operand, while a \\c false value indicates that \\c Q is the right\n\t * operand.\n\t * \\param trans_Q A boolean value indicating if the matrix \\c Q is to be\n\t * transposed. A \\c true value indicates that \\c Q is to be transposed,\n\t * while a \\c false value indicates that \\c Q is to be taken as-is.\n\t * \\param orientation The matrix orientation fixed to column-major.\n\t *\n\t * Let \\c Q be the matrix obtained from the QL decomposition represented\n\t * by the \\a QL matrix and the \\a tau vector parameters. \n\t * Then this function computes the following matrix product:\n\t * \\f{equation*}{\n\t * \\begin{cases}\n\t * Q C, & \\text{\\texttt{left\\_Q} = \\emph{true} and \\texttt{trans\\_Q} = \\emph{false}}, \\\\\n\t * Q^T C, & \\text{\\texttt{left\\_Q} = \\emph{true} and \\texttt{trans\\_Q} = \\emph{true}}, \\\\\n\t * C Q, & \\text{\\texttt{left\\_Q} = \\emph{false} and \\texttt{trans\\_Q} = \\emph{false}}, \\\\\n\t * C Q^T, & \\text{\\texttt{left\\_Q} = \\emph{false} and \\texttt{trans\\_Q} = \\emph{true}}.\n\t * \\end{cases}\n\t * \\f}\n\t */\n\ttemplate \n\t\tstatic void prod(QLMatrixT& QL, TAUVectorT const& tau, CMatrixT& C, bool left_Q, bool trans_Q, column_major_tag /*orientation*/)\n\t{\n\t\t//NOTE: QL cannot be const since LAPACK::ORMQL modified it, restoring\n\t\t// it at the end of the function.\n\n//\t\ttypedef typename matrix_traits::value_type value_type;\n//\t\ttypedef typename matrix_traits::size_type size_type;\n//\t\ttypedef typename type_traits::real_type real_type;\n//\n//\t\tconst ::fortran_int_t m = num_rows(C);\n//\t\tconst ::fortran_int_t n = num_columns(C);\n//\t\tconst ::fortran_int_t k = size(tau);\n//\t\tconst ::fortran_int_t lda = num_rows(QL);\n//\t\tconst ::fortran_int_t ldc = m;\n//\t\treal_type* work;\n//\t\treal_type opt_work_size;\n//\t\t::fortran_int_t lwork;\n//\t\t::std::ptrdiff_t info;\n\n\t\tif (left_Q)\n\t\t{\n\t\t\tif (trans_Q)\n\t\t\t{\n//\t\t\t\t//FIXME: actually (2010-08-13) bindinds::lapack::ormql has problems\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::left(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\t&opt_work_size,\n//\t\t\t\t\t-1\n//\t\t\t\t);\n//\t\t\t\tlwork = static_cast< ::fortran_int_t >(opt_work_size);\n//\t\t\t\twork = new real_type[lwork];\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::left(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\twork,\n//\t\t\t\t\tlwork\n//\t\t\t\t);\n//\t\t\t\tdelete[] work;\n\t\t\t\t::boost::numeric::bindings::lapack::ormql(\n\t\t\t\t\t::boost::numeric::bindings::tag::left(),\n\t\t\t\t\t::boost::numeric::bindings::trans(QL),\n\t\t\t\t\ttau,\n\t\t\t\t\tC\n\t\t\t\t);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n//\t\t\t\t//FIXME: actually (2010-08-13) bindinds::lapack::ormql has problems\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::left(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::no_transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\t&opt_work_size,\n//\t\t\t\t\t-1\n//\t\t\t\t);\n//\t\t\t\tlwork = static_cast< ::fortran_int_t >(opt_work_size);\n//\t\t\t\twork = new real_type[lwork];\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::left(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::no_transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\twork,\n//\t\t\t\t\tlwork\n//\t\t\t\t);\n//\t\t\t\tdelete[] work;\n\t\t\t\t::boost::numeric::bindings::lapack::ormql(\n\t\t\t\t\t::boost::numeric::bindings::tag::left(),\n\t\t\t\t\tQL,\n\t\t\t\t\ttau,\n\t\t\t\t\tC\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif (trans_Q)\n\t\t\t{\n//\t\t\t\t//FIXME: actually (2010-08-13) bindinds::lapack::ormql has problems\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::right(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\t&opt_work_size,\n//\t\t\t\t\t-1\n//\t\t\t\t);\n//\t\t\t\tlwork = static_cast< ::fortran_int_t >(opt_work_size);\n//\t\t\t\twork = new real_type[lwork];\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::right(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\twork,\n//\t\t\t\t\tlwork\n//\t\t\t\t);\n//\t\t\t\tdelete[] work;\n\t\t\t\t::boost::numeric::bindings::lapack::ormql(\n\t\t\t\t\t::boost::numeric::bindings::tag::right(),\n\t\t\t\t\t::boost::numeric::bindings::trans(QL),\n\t\t\t\t\ttau,\n\t\t\t\t\tC\n\t\t\t\t);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n//\t\t\t\t//FIXME: actually (2010-08-13) bindinds::lapack::ormql has problems\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::right(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::no_transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\t&opt_work_size,\n//\t\t\t\t\t-1\n//\t\t\t\t);\n//\t\t\t\tlwork = static_cast< ::fortran_int_t >(opt_work_size);\n//\t\t\t\twork = new real_type[lwork];\n//\t\t\t\tinfo = ::boost::numeric::bindings::lapack::detail::ormql(\n//\t\t\t\t\t::boost::numeric::bindings::tag::right(),\n//\t\t\t\t\t::boost::numeric::bindings::tag::no_transpose(),\n//\t\t\t\t\tm,\n//\t\t\t\t\tn,\n//\t\t\t\t\tk,\n//\t\t\t\t\tQL.data().begin(),\n//\t\t\t\t\tlda,\n//\t\t\t\t\ttau.data().begin(),\n//\t\t\t\t\tC.data().begin(),\n//\t\t\t\t\tldc,\n//\t\t\t\t\twork,\n//\t\t\t\t\tlwork\n//\t\t\t\t);\n//\t\t\t\tdelete[] work;\n\t\t\t\t::boost::numeric::bindings::lapack::ormql(\n\t\t\t\t\t::boost::numeric::bindings::tag::right(),\n\t\t\t\t\tQL,\n\t\t\t\t\ttau,\n\t\t\t\t\tC\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n};\n\n\n/**\n * \\brief QL decomposition operations for non-complex types.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <>\nstruct ql_decomposition_impl: public ql_decomposition_impl_common\n{\n\t/// Extract the Q matrix from a previously computing QL decomposition\n\t/// (row-major case).\n\ttemplate \n\t\tstatic void extract_Q(QLMatrixT const& QL, TauVectorT const& tau, QMatrixT& Q, bool full, row_major_tag)\n\t{\n\t\tmatrix::value_type, column_major> tmp_QL(QL);\n\t\tmatrix::value_type, column_major> tmp_Q(Q);\n\n\t\textract_Q(tmp_QL, tau, tmp_Q, full, column_major_tag());\n\n\t\tQ = tmp_Q;\n\t}\n\n\n\t/// Extract the Q matrix from a previously computing QL decomposition\n\t/// (column-major case).\n\ttemplate \n\t\tstatic void extract_Q(QLMatrixT const& QL, TauVectorT& tau, QMatrixT& Q, bool full, column_major_tag)\n\t{\n\t\ttypedef typename matrix_traits::size_type size_type;\n\t\ttypedef typename matrix_traits::value_type value_type;\n\n\t\tsize_type m = num_rows(QL);\n\t\tsize_type n = num_columns(QL);\n\t\tsize_type nc = full ? m : ::std::min(m,n);\n\n\t\tif (num_rows(Q) != m || num_columns(Q) != nc)\n\t\t{\n\t\t\tQ.resize(m, nc, false);\n\t\t}\n\n\t\tif (m > n)\n\t\t{\n\t\t\tif (full)\n\t\t\t{\n\t\t\t\tsubrange(Q, 0, m, 0, m-n) = scalar_matrix(m, m-n, value_type/*zero*/());\n\t\t\t\tsubrange(Q, 0, m, m-n, m) = QL;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tQ = QL;\n\t\t\t}\n\t\t}\n\t\telse if (m < n)\n\t\t{\n\t\t\tsubrange(Q, 0, m-1, 0, 1) = scalar_matrix(m-1, 1, value_type/*zero*/());\n\t\t\tsubrange(Q, m-1, m, 0, m) = scalar_matrix(1, m, value_type/*zero*/());\n\t\t\tsubrange(Q, 0, m-1, 1, m) = subrange(QL, 0, m-1, n-m+1, n);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQ = QL;\n\t\t}\n\n\t\t::boost::numeric::bindings::lapack::orgql(Q, tau);\n/*\n\t\t// Compute Q without LAPACK\n\t\t//\n\t\t// The matrix Q is represented as a product of elementary reflectors\n\t\t// Q = H(k) . . . H(2) H(1), where k = min(m,n).\n\t\t// Each H(i) has the form\n\t\t// H(i) = I - tau * v * v'\n\t\t// where tau is a real scalar, and v is a real vector with\n\t\t// v(m-k+i+1:m) = 0 and v(m-k+i) = 1; v(1:m-k+i-1) is stored on exit in\n\t\t// A(1:m-k+i-1,n-k+i), and tau in TAU(i).\n\n\t\tsize_type k = std::min(m, n);\n\n\t\tif (num_rows(Q) != m || num_columns(Q) != m)\n\t\t{\n\t\t\tQ.resize(m, m, false);\n\t\t}\n\n\t\tidentity_matrix I(m);\n\n\t\tQ = I;\n\t\tfor (size_type i = k-1; (i+1) > 0; --i)\n\t\t{\n\t\t\t// Build v = [ A(1:m-k+i-1,n-k+i) 1 0 ... 0 ]\n\n\t\t\tvector v(m, value_type());\n\t\t\tfor (size_type j = 0; j < m-k+i; ++j)\n\t\t\t{\n\t\t\t\tv(j) = QL(j,i);\n\t\t\t}\n\t\t\tv(m-k+i) = value_type(1);\n\n\t\t\tmatrix H = I - tau(i)*outer_prod(v, v);\n\t\t\tQ = prod(Q, H);\n\t\t}\n*/\n\t}\n};\n\n\n/**\n * \\brief QL decomposition operations for complex types.\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate <>\nstruct ql_decomposition_impl: public ql_decomposition_impl_common\n{\n\t/// Extract the Q matrix from a previously computing QL decomposition\n\t/// (row-major case).\n\ttemplate \n\t\tstatic void extract_Q(QLMatrixT const& QL, TauVectorT const& tau, QMatrixT& Q, bool full, row_major_tag)\n\t{\n\t\tmatrix::value_type, column_major> tmp_QL(QL);\n\t\tmatrix::value_type, column_major> tmp_Q(Q);\n\n\t\textract_Q(tmp_QL, tau, tmp_Q, full, column_major_tag());\n\n\t\tQ = tmp_Q;\n\t}\n\n\n\t/// Extract the Q matrix from a previously computing QL decomposition\n\t/// (column-major case).\n\ttemplate \n\t\tstatic void extract_Q(QLMatrixT const& QL, TauVectorT& tau, QMatrixT& Q, bool full, column_major_tag)\n\t{\n\t\ttypedef typename matrix_traits::size_type size_type;\n\t\ttypedef typename matrix_traits::value_type value_type;\n\n\t\tsize_type m = num_rows(QL);\n\t\tsize_type n = num_columns(QL);\n\t\tsize_type nc = full ? m : std::min(m,n);\n\n\t\tif (num_rows(Q) != m || num_columns(Q) != nc)\n\t\t{\n\t\t\tQ.resize(m, nc, false);\n\t\t}\n\n\t\tif (m > n)\n\t\t{\n\t\t\tif (full)\n\t\t\t{\n\t\t\t\tsubrange(Q, 0, m, 0, m-n) = scalar_matrix(m, m-n, 0);\n\t\t\t\tsubrange(Q, 0, m, m-n, m) = QL;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tQ = QL;\n\t\t\t}\n\t\t}\n\t\telse if (m < n)\n\t\t{\n\t\t\tsubrange(Q, 0, m-1, 0, 1) = scalar_matrix(m-1, 1, 0);\n\t\t\tsubrange(Q, m-1, m, 0, m) = scalar_matrix(1, m, 0);\n\t\t\tsubrange(Q, 0, m-1, 1, m) = subrange(QL, 0, m-1, n-m+1, n);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tQ = QL;\n\t\t}\n\n\t\t::boost::numeric::bindings::lapack::ungql(Q, tau);\n/*\n\t\t// Compute Q without LAPACK\n\t\t//\n\t\t// The matrix Q is represented as a product of elementary reflectors\n\t\t// Q = H(k) . . . H(2) H(1), where k = min(m,n).\n\t\t// Each H(i) has the form\n\t\t// H(i) = I - tau * v * v'\n\t\t// where tau is a real scalar, and v is a real vector with\n\t\t// v(m-k+i+1:m) = 0 and v(m-k+i) = 1; v(1:m-k+i-1) is stored on exit in\n\t\t// A(1:m-k+i-1,n-k+i), and tau in TAU(i).\n\n\t\tsize_type k = std::min(m, n);\n\n\t\tif (num_rows(Q) != m || num_columns(Q) != m)\n\t\t{\n\t\t\tQ.resize(m, m, false);\n\t\t}\n\n\t\tidentity_matrix I(m);\n\n\t\tQ = I;\n\t\tfor (size_type i = k-1; (i+1) > 0; --i)\n\t\t{\n\t\t\t// Build v = [ A(1:m-k+i-1,n-k+i) 1 0 ... 0 ]\n\n\t\t\tvector v(m, value_type());\n\t\t\tfor (size_type j = 0; j < m-k+i; ++j)\n\t\t\t{\n\t\t\t\tv(j) = QL(j,i);\n\t\t\t}\n\t\t\tv(m-k+i) = value_type(1);\n\n\t\t\tmatrix H = I - tau(i)*outer_prod(v, v);\n\t\t\tQ = prod(Q, H);\n\t\t}\n*/\n\t}\n};\n\n\n/// Free function performing the QL decomposition of the given matrix expression \\a A.\ntemplate\nvoid ql_decompose_impl(matrix_expression const& A, QMatrixT& Q, LMatrixT& L, bool full, OrientationT orientation)\n{\n\ttypedef typename matrix_traits::value_type value_type;\n\n\tmatrix::type> tmp_QL(A);\n\tvector tmp_tau;\n\n\tql_decomposition_impl<\n\t\t\t::boost::is_complex::value\n\t\t>::template decompose(tmp_QL, tmp_tau, orientation);\n\n\n\tql_decomposition_impl<\n\t\t\t::boost::is_complex::value\n\t\t>::template extract_Q(tmp_QL, tmp_tau, Q, full, orientation);\n\n\n\tql_decomposition_impl<\n\t\t\t::boost::is_complex::value\n\t\t>::template extract_L(tmp_QL, L, full, orientation);\n}\n\n}} // Namespace detail::\n\n\n/**\n * \\brief QL decomposition.\n *\n * \\tparam ValueT The type of the elements stored in the input matrices.\n *\n * \\todo Currently, the type of the L matrix is a dense matrix.\n * Can we use a better matrix structure?\n *\n * \\author Marco Guazzone, marco.guazzone@gmail.com\n */\ntemplate \nclass ql_decomposition\n{\n\tpublic: typedef ValueT value_type;\n\tprivate: typedef matrix work_matrix_type;\n\tprivate: typedef vector tau_vector_type;\n\tpublic: typedef work_matrix_type QL_matrix_type;\n\tpublic: typedef work_matrix_type Q_matrix_type;\n\tpublic: typedef work_matrix_type L_matrix_type;//TODO: Can I use a special matrix\n\n\n\t/// Default constructor.\n\tpublic: ql_decomposition()\n\t{\n\t\t// empty\n\t}\n\n\n\t/// Decompose the given matrix expression \\a A.\n\tpublic: template \n\t\tql_decomposition(matrix_expression const& A)\n\t\t: QL_(A)\n\t{\n\t\tdecompose();\n\t}\n\n\n\t/// Decompose the given matrix expression \\a A.\n\tpublic: template \n\t\tvoid decompose(matrix_expression const& A)\n\t{\n\t\tQL_ = A;\n\n\t\tdecompose();\n\t}\n\n\n\t/**\n\t * \\brief Extract the \\c Q matrix.\n\t * \\param full If \\c false enables the economy-size mode whereby a\n\t * reduced (rectangular) Q matrix is returned instead of full (square) one.\n\t * \\return The \\c Q matrix.\n\t *\n\t * The economy-size mode is useful when \\f$m > n\\f$ (where \\f$m\\f$\n\t * and \\f$n\\f$ are the number of rows and columns of the decomposed matrix\n\t * \\f$A\\f$).\n\t * As a matter of fact, in this case, the QL factorization can be viewed as:\n\t * \\f[\n\t * A = QL = \\begin{pmatrix} Q_1 & Q_2 \\end{pmatrix} \\begin{pmatrix} 0 \\\\ L \\end{pmatrix} = Q_2 L\n\t * \\f]\n\t * where \\f$Q_2\\f$ is an m-by-n matrix containing the n trailing columns of\n\t * \\f$Q\\f$.\n\t */\n\tpublic: Q_matrix_type Q(bool full = true) const\n\t{\n\t\tQ_matrix_type tmp_Q;\n\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex::value\n\t\t\t>::template extract_Q(QL_, tau_, tmp_Q, full, column_major_tag());\n\n\t\treturn tmp_Q;\n\t}\n\n\n\t/**\n\t * \\brief Extract the \\c L matrix.\n\t * \\param full If \\c false enables the economy-size mode whereby a\n\t * reduced \\f$\\min(m,n)\\f$-by\\f$n\\f$ \\c L matrix is returned instead of the\n\t * full \\f$m\\f$-by-\\f$n\\f$ one.\n\t * \\return The \\c L matrix.\n\t *\n\t * The economy-size mode is useful when \\f$m > n\\f$ (where \\f$m\\f$\n\t * and \\f$n\\f$ are the number of rows and columns of the decomposed matrix\n\t * \\f$A\\f$).\n\t * As a matter of fact, in this case, the QL factorization can be viewed as:\n\t * \\f[\n\t * A = QL = \\begin{pmatrix} Q_1 & Q_2 \\end{pmatrix} \\begin{pmatrix} 0 \\\\ L \\end{pmatrix} = Q_2 L\n\t * \\f]\n\t * where \\f$Q_2\\f$ is an m-by-n matrix containing the n trailing columns of\n\t * \\f$Q\\f$.\n\t */\n\tpublic: L_matrix_type L(bool full = true) const\n\t{\n\t\tL_matrix_type tmp_L;\n\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex::value\n\t\t\t>::template extract_L(QL_, tmp_L, full, column_major_tag());\n\n\t\treturn tmp_L;\n\t}\n\n\n\t/// Perform the product \\f$Q C\\f$ and store the result in \\a C.\n\tpublic: template \n\t\tvoid lprod_inplace(CMatrixT& C) const\n\t{\n\t\ttypedef typename matrix_traits::orientation_category orientation_category;\n\n\t\tlprod_inplace(C, orientation_category());\n\t}\n\n\n\t/// Perform the product \\f$C Q\\f$ and store the result in \\a C.\n\tpublic: template \n\t\tvoid rprod_inplace(CMatrixT& C) const\n\t{\n\t\ttypedef typename matrix_traits::orientation_category orientation_category;\n\n\t\trprod_inplace(C, orientation_category());\n\t}\n\n\n\t/// Perform the product \\f$Q^T C\\f$ and store the result in \\a C.\n\tpublic: template \n\t\tvoid tlprod_inplace(CMatrixT& C) const\n\t{\n\t\ttypedef typename matrix_traits::orientation_category orientation_category;\n\n\t\ttlprod_inplace(C, orientation_category());\n\t}\n\n\n\t/// Perform the product \\f$C Q^T\\f$ and store the result in \\a C.\n\tpublic: template \n\t\tvoid trprod_inplace(CMatrixT& C) const\n\t{\n\t\ttypedef typename matrix_traits::orientation_category orientation_category;\n\n\t\ttrprod_inplace(C, orientation_category());\n\t}\n\n\n\t/// Perform the product \\f$Q C\\f$ and return the result.\n\tpublic: template \n\t\ttypename matrix_temporary_traits::type lprod(matrix_expression const& C) const\n\t{\n\t\ttypename matrix_temporary_traits::type tmp_C(C);\n\n\t\tlprod_inplace(tmp_C);\n\n\t\treturn tmp_C;\n\t}\n\n\n\t/// Perform the product \\f$C Q\\f$ and return the result.\n\tpublic: template \n\t\ttypename matrix_temporary_traits::type rprod(matrix_expression const& C) const\n\t{\n\t\ttypename matrix_temporary_traits::type tmp_C(C);\n\n\t\trprod_inplace(tmp_C);\n\n\t\treturn tmp_C;\n\t}\n\n\n\t/// Perform the product \\f$Q^T C\\f$ and return the result.\n\tpublic: template \n\t\ttypename matrix_temporary_traits::type tlprod(matrix_expression const& C) const\n\t{\n\t\ttypename matrix_temporary_traits::type tmp_C(C);\n\n\t\ttlprod_inplace(tmp_C);\n\n\t\treturn tmp_C;\n\t}\n\n\n\t/// Perform the product \\f$C Q^T\\f$ and return the result.\n\tpublic: template \n\t\ttypename matrix_temporary_traits::type trprod(matrix_expression const& C) const\n\t{\n\t\ttypename matrix_temporary_traits::type tmp_C(C);\n\n\t\ttrprod_inplace(tmp_C);\n\n\t\treturn tmp_C;\n\t}\n\n\n\tprivate: void decompose()\n\t{\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex::value\n\t\t\t>::template decompose(QL_, tau_, column_major_tag());\n\t}\n\n\n\t/// Perform the product \\f$Q C\\f$ and store the result in \\a C (column-major\n\t/// case).\n\tprivate: template \n\t\tvoid lprod_inplace(CMatrixT& C, column_major_tag) const\n\t{\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex::value\n\t\t\t>::template prod(QL_, tau_, C, true, false, column_major_tag());\n\t}\n\n\n\t/// Perform the product \\f$Q C\\f$ and store the result in \\a C (row-major\n\t/// case).\n\tprivate: template \n\t\tvoid lprod_inplace(CMatrixT& C, row_major_tag) const\n\t{\n\t\twork_matrix_type tmp_C(C);\n\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex::value\n\t\t\t>::template prod(QL_, tau_, tmp_C, true, false, column_major_tag());\n\n\t\tC = tmp_C;\n\t}\n\n\n\t/// Perform the product \\f$C Q\\f$ and store the result in \\a C (column-major\n\t/// case).\n\tprivate: template \n\t\tvoid rprod_inplace(CMatrixT& C, column_major_tag) const\n\t{\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex::value\n\t\t\t>::template prod(QL_, tau_, C, false, false, column_major_tag());\n\t}\n\n\n\t/// Perform the product \\f$C Q\\f$ and store the result in \\a C (row-major\n\t/// case).\n\tprivate: template \n\t\tvoid rprod_inplace(CMatrixT& C, row_major_tag) const\n\t{\n\t\twork_matrix_type tmp_C(C);\n\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex::value\n\t\t\t>::template prod(QL_, tau_, tmp_C, false, false, column_major_tag());\n\n\t\tC = tmp_C;\n\t}\n\n\n\t/// Perform the product \\f$Q^T C\\f$ and store the result in \\a C\n\t/// (column-major case).\n\tprivate: template \n\t\tvoid tlprod_inplace(CMatrixT& C, column_major_tag) const\n\t{\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex::value\n\t\t\t>::template prod(QL_, tau_, C, true, true, column_major_tag());\n\t}\n\n\n\t/// Perform the product \\f$Q^T C\\f$ and store the result in \\a C\n\t/// (row-major case).\n\tprivate: template \n\t\tvoid tlprod_inplace(CMatrixT& C, row_major_tag) const\n\t{\n\t\twork_matrix_type tmp_C(C);\n\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex::value\n\t\t\t>::template prod(QL_, tau_, tmp_C, true, true, column_major_tag());\n\n\t\tC = tmp_C;\n\t}\n\n\n\t/// Perform the product \\f$C Q^T\\f$ and store the result in \\a C\n\t/// (column-major case).\n\tprivate: template \n\t\tvoid trprod_inplace(CMatrixT& C, column_major_tag) const\n\t{\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex::value\n\t\t\t>::template prod(QL_, tau_, C, false, true, column_major_tag());\n\t}\n\n\n\t/// Perform the product \\f$C Q^T\\f$ and store the result in \\a C\n\t/// (row-major case).\n\tprivate: template \n\t\tvoid trprod_inplace(CMatrixT& C, row_major_tag) const\n\t{\n\t\twork_matrix_type tmp_C(C);\n\n\t\tdetail::ql_decomposition_impl<\n\t\t\t\t::boost::is_complex::value\n\t\t\t>::template prod(QL_, tau_, tmp_C, false, true, column_major_tag());\n\n\t\tC = tmp_C;\n\t}\n\n\n\t// NOTE: the 'mutable' keyword is needed in order to make 'const' the\n\t// '?prod' methods ('lprod', 'tlprod', 'rprod', 'trprod').\n\t// Indeed, these methods call the respective '?prod_inplace' methods\n\t// which, in turns, call the LAPACK::ORMQL function which temporarily\n\t// changes the QL matrix (and restores it before returning).\n\tprivate: mutable QL_matrix_type QL_;\n\tprivate: tau_vector_type tau_;\n};\n\n\n/// Free function performing the QL decomposition of the given matrix expression \\a A.\ntemplate\nBOOST_UBLAS_INLINE\nvoid ql_decompose(matrix_expression const& A, OutMatrix1T& Q, OutMatrix2T& L, bool full = true)\n{\n\ttypedef typename matrix_traits::orientation_category orientation_category1;\n\ttypedef typename matrix_traits::orientation_category orientation_category2;\n\ttypedef typename matrix_traits::orientation_category orientation_category3;\n\n\t// precondition: same orientation category\n\tBOOST_MPL_ASSERT(\n\t\t(::boost::mpl::and_<\n\t\t\t::boost::is_same,\n\t\t\t::boost::is_same\n\t\t>)\n\t);\n\n\tdetail::ql_decompose_impl(A, Q, L, full, orientation_category1());\n}\n\n\n/// Free function performing the QL decomposition of the given matrix expression \\a A.\ntemplate\nBOOST_UBLAS_INLINE\nql_decomposition::value_type> ql_decompose(matrix_expression const& A)\n{\n\ttypedef typename matrix_traits::value_type value_type;\n\n\treturn ql_decomposition(A);\n}\n\n}}} // Namespace boost::numeric::ublasx\n\n\n#endif // BOOST_NUMERIC_UBLASX_OPERATION_QL_HPP\n", "meta": {"hexsha": "444417d952fe4a0453b2b692de9f372ba854ed6b", "size": 32591, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/numeric/ublasx/operation/ql.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/ql.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/ql.hpp", "max_forks_repo_name": "comcon1/boost-ublasx", "max_forks_repo_head_hexsha": "290b92b643a944825df99bece3468a4f81518056", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.3348334833, "max_line_length": 130, "alphanum_fraction": 0.65797306, "num_tokens": 10128, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8479677545357568, "lm_q2_score": 0.7606506526772883, "lm_q1q2_score": 0.645007225936918}} {"text": "#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"SAMSON.hpp\"\n#include \"ADNConstants.hpp\"\n\n\nnamespace ublas = boost::numeric::ublas;\n\nnamespace ADNVectorMath {\n using namespace ublas;\n\n ublas::vector CreateBoostVector(std::vector vec);\n std::vector CreateStdVector(ublas::vector vec);\n ublas::matrix CreateBoostMatrix(std::vector> vecovec);\n ublas::vector CalculateCM(ublas::matrix positions);\n ublas::vector CalculateCM(ublas::matrix weightedPositions, double totalMass);\n ublas::vector CrossProduct(ublas::vector v, ublas::vector w);\n ublas::vector DirectionVector(ublas::vector p, ublas::vector q);\n double DegToRad(double degree);\n ublas::matrix MakeRotationMatrix(ublas::vector dir, double angle);\n ublas::matrix SkewMatrix(ublas::vector v);\n ublas::vector InitializeVector(size_t size); // deprecated, use constructor\n ublas::matrix InitializeMatrix(size_t sz_r, size_t sz_c); // deprecated, use constructor\n ublas::matrix InitializeMatrix(size_t sz); // deprecated, use constructor\n ublas::matrix Translate(ublas::matrix input, ublas::vector t_vector);\n ublas::matrix Rotate(ublas::matrix input, ublas::matrix rot_matrix); // deprecated, use ApplyTransformation\n ublas::matrix CenterSystem(ublas::matrix input);\n void AddRowToMatrix(ublas::matrix &input, ublas::vector r);\n ublas::vector CalculatePlane(ublas::matrix mat);\n ublas::matrix FindOrthogonalSubspace(ublas::vector z);\n ublas::matrix InvertMatrix(const ublas::matrix& input);\n double Determinant(ublas::matrix mat);\n bool IsNearlyZero(double n, double tol = 0.000000001);\n double CalculateVectorNorm(ublas::vector v);\n /*!\n * Applies the transformation given by t_mat to a set of points\n * \\param the transformation matrix\n * \\param a matrix holding coordinates of points\n * \\return a matrix with the coordinates after the transformation\n */\n ublas::matrix ApplyTransformation(ublas::matrix t_mat, ublas::matrix points);\n\n ublas::vector Spherical2Cartesian(ublas::vector spher);\n\n // SAMSON types operations\n SBVector3 SBCrossProduct(SBVector3 v, SBVector3 w);\n double SBInnerProduct(SBVector3 v, SBVector3 w);\n\n //! Calculation of parameters of dna nanotubes\n SBQuantity::length CalculateNanotubeRadius(int numDs);\n int CalculateNanotubeDoubleStrands(SBQuantity::length radius);\n\n //! Bezier curves\n //! Calculates the length of a quadratic Bezier curve\n SBQuantity::length LengthQuadraticBezier(SBPosition3 P0, SBPosition3 P1, SBPosition3 P2);\n SBPosition3 QuadraticBezierPoint(SBPosition3 P0, SBPosition3 P1, SBPosition3 P2, double t);\n SBVector3 DerivativeQuadraticBezier(SBPosition3 P0, SBPosition3 P1, SBPosition3 P2, double t);\n};", "meta": {"hexsha": "7fa34617d8363cc5a683edd715e93fd43f15abd0", "size": 3218, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "AdenitaCoreSE/include/ADNVectorMath.hpp", "max_stars_repo_name": "edellano/Adenita-SAMSON-Edition-Win-", "max_stars_repo_head_hexsha": "6df8d21572ef40fe3fc49165dfaa1d4318352a69", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-09-07T20:48:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-03T05:49:59.000Z", "max_issues_repo_path": "AdenitaCoreSE/include/ADNVectorMath.hpp", "max_issues_repo_name": "edellano/Adenita-SAMSON-Edition-Linux", "max_issues_repo_head_hexsha": "a7e267e5dd37e0073f4d1e3e603c5fb1c69a350a", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6.0, "max_issues_repo_issues_event_min_datetime": "2020-04-05T18:39:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-11T14:28:55.000Z", "max_forks_repo_path": "AdenitaCoreSE/include/ADNVectorMath.hpp", "max_forks_repo_name": "edellano/Adenita-SAMSON-Edition-Linux", "max_forks_repo_head_hexsha": "a7e267e5dd37e0073f4d1e3e603c5fb1c69a350a", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2021-07-13T12:58:13.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T13:52:00.000Z", "avg_line_length": 50.28125, "max_line_length": 134, "alphanum_fraction": 0.766314481, "num_tokens": 858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9353465152482724, "lm_q2_score": 0.6893056104028797, "lm_q1q2_score": 0.6447396006314169}} {"text": "#include \"ssd_ros_tracking/ssd_ekf.h\"\n#include \n#include \n\n// association param\n#define PRE_SIZE 5\n\n// dynamic detector param\n#define MIN_VELOCITY 0.3\n#define MAX_VELOCITY 2\n\nusing namespace std;\nusing namespace Eigen;\n\nMatrixXf EKF::move(MatrixXf x, MatrixXf u, float dt)\n{\n\t/* 動作予測\n\t * x : 状態\n\t * u : 制御\n\t * dt: 前ステップとの時間差\n\t */\n\tMatrixXf A(3,1);\n\tMatrixXf I = MatrixXf::Identity(3,3);\n\tMatrixXf B(3,2);\n\n\tfloat theta = x.coeffRef(2,0) + u.coeffRef(1,0)*dt/2;\n\t\n\tB << dt*cos(theta), 0,\n\t\t dt*sin(theta), 0,\n\t\t 0, dt;\n\t\n\tA = I*x + B*u;\n\t\n\treturn A;\n}\n\nMatrixXf EKF::jacobF(MatrixXf x, MatrixXf u, float dt)\n{\n\t/* ヤコビ行列\n\t * x : 状態\n\t * u : 制御\n\t * dt: 前ステップとの時間差\n\t */\n\tMatrixXf F(3,3);\n\tfloat b = dt*u.coeffRef(0,0);\n\tfloat theta = x.coeffRef(2,0); \n\t\n\tF << 1, 0, -b*sin(theta),\n\t\t 0, 1, b*cos(theta),\n\t\t 0, 0, 1;\n\n\treturn F;\n}\n\nMatrixXf EKF::jacobG(MatrixXf x, MatrixXf u, float dt)\n{\n\t/* ヤコビ行列\n\t * x : 状態\n\t * u : 制御\n\t * dt: 前ステップとの時間差\n\t */\n\tMatrixXf G(3,3);\n\tfloat b = u.coeffRef(0,0)*dt;\n\tfloat theta = u.coeffRef(1,0)*dt/2 + x.coeffRef(2,0);\n\n\tG << 1, 0, -b*sin(theta),\n\t\t 0, 1, b*cos(theta),\n\t\t 0, 0, 1;\n\treturn G;\n}\n\nMatrixXf EKF::jacobV(MatrixXf x, MatrixXf u, float dt)\n{\n\t/* ヤコビ行列\n\t * x : 状態\n\t * u : 制御\n\t * dt: 前ステップとの時間差\n\t */\n\tMatrixXf V(3,2);\n\tfloat theta = u.coeffRef(1,0)*dt/2 + x.coeffRef(2,0);\n\tfloat v = u.coeffRef(0,0);\n\t\n\tV << dt*cos(theta), (-v*dt*dt)*sin(theta)/2,\n\t\t dt*sin(theta), (v*dt*dt)*cos(theta)/2,\n\t\t 0, dt;\n\t\t \n\treturn V;\n}\n\nMatrixXf EKF::jacobM(MatrixXf u, double s_input[])\n{\n\t/* ヤコビ行列\n\t * u : 制御\n\t * s_input: 制御系の計測誤差パラメータ\n\t */\n\tMatrixXf M(2,2);\n\tfloat v = u.coeffRef(0,0);\n\tfloat w = u.coeffRef(1,0);\n\tfloat a1 = (float)s_input[0];\n\tfloat a2 = (float)s_input[1];\n\tfloat a3 = (float)s_input[2];\n\tfloat a4 = (float)s_input[3];\n\t\n\tM << a1*v*v + a2*w*w, 0,\n\t\t 0, a3*v*v + a4*w*w;\n\t\t \n\treturn M;\n}\n\nMatrixXf EKF::jacobH(MatrixXf x)\n{\n\t/* ヤコビ行列\n\t * x : 状態\n\t */\n\tMatrixXf H(3,3);\n\n\tH<< 1, 0, 0,\n\t 0, 1, 0,\n\t 0, 0, 1;\n\t \n\t return H;\n}\n\nvoid initCluster( clusterInfo& cluster,\n\t\t\t\t PointI& init_pt)\n{\n\t// float init_r = 0.01; // 観測誤差\n\tfloat init_p = 0.001; //初期位置の分散値\n\tfloat init_theta = 0;\n\t// cluster.x << init_pt.x, init_pt.y, 0.0, 0.0;\n\tcluster.x << init_pt.x, init_pt.y, init_theta;\n\tcluster.P << init_p, 0.0, 0.0,\n\t\t \t\t 0.0, init_p, 0.0,\n\t\t \t\t 0.0, 0.0, init_p;\n\t// cluster.R << init_r, 0.0,\n\t// \t\t\t 0.0, init_r;\n\tcluster.pre_vel.x = 0;\n\tcluster.pre_vel.y = 0;\n\tcluster.u = Eigen::VectorXf::Zero(2);\n\tcluster.track_num = 1;\n\tcluster.confidence = 1;\n\tcluster.width = init_pt.normal_x;\n\tcluster.length = init_pt.normal_y;\n\tcluster.height = init_pt.normal_z;\n\tcluster.count = 0;\n\tcluster.pre_position.resize(PRE_SIZE);\n\tcluster.pre_position[0] = init_pt;\n\tcluster.label = 0; // static: 0 dynamic: 1\n\tcluster.update_comp_flag = true;\n\tcluster.init_flag = true;\n\n\tcluster.velocity = 0;\n}\n\nvoid Prediction( clusterInfo& cluster,\n\t\t\t\t double dt,\n\t\t\t\t double s_input[])\n{\n\tEKF ekf;\n\t/* u : (v, w)の転置行列 v:並進速度, w:角速度\n\t * x : (x, y, θ)の転置行列\n\t * dt\t : 前ステップからの経過時間\n\t * s_input : 動作モデルのノイズパラメータ\n\t */\n\n\n\tMatrixXf Gt = MatrixXf::Zero(3,3);\n\tMatrixXf Vt = MatrixXf::Zero(3,2);\n\tMatrixXf Mt = MatrixXf::Zero(2,2);\n\t\n\n\t// Gt = ekf.jacobG(cluster.x, cluster.u, dt, pitch);\n\tGt = ekf.jacobF(cluster.x, cluster.u, dt);\n\tVt = ekf.jacobV(cluster.x, cluster.u, dt);\n\tMt = ekf.jacobM(cluster.u, s_input);\n\n\n\tcluster.x = ekf.move(cluster.x, cluster.u, dt);\n\tcluster.P = Gt*cluster.P*Gt.transpose() + Vt*Mt*Vt.transpose();\n\n\t// cluster.label = 1;\n}\n\nvoid MeasurementUpdate(\tclusterInfo& cluster,\n\t\t\t\t\t\tPointI& obj_centroid,\n\t\t\t\t\t\tdouble dt,\n\t\t\t\t\t\tdouble s_measurement[])\n{\n\t/* x\t: 状態(x, y, yaw)の転置行列\n\t * u\t: 制御(v, w)の転置行列\n\t * s_measurement: 観測ノイズ\n\t * sigma: 推定誤差\n\t */\n\n\tEKF ekf;\n\n\n\tMatrixXf Z = MatrixXf::Zero(3,1);\t// 観測 (x,y,θ)\n\tMatrixXf Q = MatrixXf::Zero(3,3);\n\tMatrixXf H = MatrixXf::Zero(3,3);\n\tMatrixXf y = MatrixXf::Zero(3,1);\n\tMatrixXf S = MatrixXf::Zero(3,3);\n\tMatrixXf K = MatrixXf::Zero(3,3);\n\tMatrixXf I = MatrixXf::Identity(3,3);\n\n\tZ.coeffRef(0,0) = obj_centroid.x;\n\tZ.coeffRef(1,0) = obj_centroid.y;\n\tZ.coeffRef(2,0) = atan2((obj_centroid.y-cluster.x[1]), (obj_centroid.x-cluster.x[0]));\n\n\n\t// cluster.u[0] = sqrt(pow((obj_centroid.y-cluster.x[1]), 2) + pow((obj_centroid.x-cluster.x[0]), 2))/dt;\n\tcluster.u[0] = sqrt(pow((obj_centroid.y-cluster.x[1]), 2) + pow((obj_centroid.x-cluster.x[0]), 2))/dt;\n\n\tif(cluster.init_flag){\n\t// cluster.u[1] = atan2((obj_centroid.y-cluster.x[1]), (obj_centroid.x-cluster.x[0]))/dt;\n\tcluster.u[1] = 0;\n\tcluster.init_flag = false;\n\t}\n\n\t// else cluster.u[1] = (atan2((obj_centroid.y-cluster.x[1]), (obj_centroid.x-cluster.x[0])) - cluster.x[2])/dt;\n\telse cluster.u[1] = (Z.coeffRef(2,0) - cluster.x[2])/dt;\n\t\n\tQ.coeffRef(0,0) = (float)s_measurement[0];\n\tQ.coeffRef(1,1) = (float)s_measurement[1];\n\tQ.coeffRef(2,2) = (float)s_measurement[2];\n\n\tH = ekf.jacobH(cluster.x);\n\ty = Z - H*cluster.x;\n\tS = H*cluster.P*H.transpose() + Q;\n\tK = cluster.P*H.transpose()*S.inverse();\n\n\tcluster.x = cluster.x + K*y;\n\tcluster.P = (I - K*H)*cluster.P;\n\n\n\t// 今まで座標をPRE_SIZEの数だけ格納\n\tfor (int i=0; i<(PRE_SIZE-1); i++) cluster.pre_position[i+1] = cluster.pre_position[i];\n\tcluster.pre_position[0].x = cluster.x(0);\n\tcluster.pre_position[0].y = cluster.x(1);\n\tcluster.pre_position[0].z = cluster.x(2);\n\n\tif(cluster.pre_position[PRE_SIZE-1].x != 0.0){\n\t\tcluster.velocity = sqrt(pow((cluster.pre_position[0].x-cluster.pre_position[PRE_SIZE-1].x), 2.0) + pow((cluster.pre_position[0].y-cluster.pre_position[PRE_SIZE-1].y), 2.0));\n\t}\n\n\tif(cluster.velocity > 0.1 && cluster.velocity < 1) cluster.label = 1;\n\n\t// cout<<\"pre_position = \"< 0 && cluster.label == 1){ // label 0:static 1:dynamic\n\t\t// \t\tcout<<\" confidence = \"<\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\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, property < edge_weight_t, int > > 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 weight_pmap = get(edge_weight, g);\r\n int i = 0;\r\n for (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 (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(edge_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": "ddc450812bd70af2a8e29359bfec3aaf7b70782b", "size": 4873, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "sdk/boost_1_30_0/libs/graph/example/bellman-example.cpp", "max_stars_repo_name": "acidicMercury8/xray-1.0", "max_stars_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_stars_repo_licenses": ["Linux-OpenIB"], "max_stars_count": 2.0, "max_stars_repo_stars_event_min_datetime": "2020-01-30T12:51:49.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-31T08:36:49.000Z", "max_issues_repo_path": "sdk/boost_1_30_0/libs/graph/example/bellman-example.cpp", "max_issues_repo_name": "acidicMercury8/xray-1.0", "max_issues_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_issues_repo_licenses": ["Linux-OpenIB"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/boost_1_30_0/libs/graph/example/bellman-example.cpp", "max_forks_repo_name": "acidicMercury8/xray-1.0", "max_forks_repo_head_hexsha": "65e85c0e31e82d612c793d980dc4b73fa186c76c", "max_forks_repo_licenses": ["Linux-OpenIB"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.8071428571, "max_line_length": 78, "alphanum_fraction": 0.5836240509, "num_tokens": 1367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673087708699, "lm_q2_score": 0.7931059609645724, "lm_q1q2_score": 0.6446899080594065}} {"text": "\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\nNTL_START_IMPL\r\n\r\n\r\n\r\nstatic\r\nvoid IterPower(ZZ_pE& c, const ZZ_pE& a, long n)\r\n{\r\n ZZ_pE res;\r\n\r\n long i;\r\n\r\n res = a;\r\n\r\n for (i = 0; i < n; i++)\r\n power(res, res, ZZ_p::modulus());\r\n\r\n c = res;\r\n}\r\n \r\n\r\n\r\nvoid SquareFreeDecomp(vec_pair_ZZ_pEX_long& u, const ZZ_pEX& ff)\r\n{\r\n ZZ_pEX f = ff;\r\n\r\n if (!IsOne(LeadCoeff(f)))\r\n LogicError(\"SquareFreeDecomp: bad args\");\r\n\r\n ZZ_pEX r, t, v, tmp1;\r\n long m, j, finished, done;\r\n\r\n u.SetLength(0);\r\n\r\n if (deg(f) == 0)\r\n return;\r\n\r\n m = 1;\r\n finished = 0;\r\n\r\n do {\r\n j = 1;\r\n diff(tmp1, f);\r\n GCD(r, f, tmp1);\r\n div(t, f, r);\r\n\r\n if (deg(t) > 0) {\r\n done = 0;\r\n do {\r\n GCD(v, r, t);\r\n div(tmp1, t, v);\r\n if (deg(tmp1) > 0) append(u, cons(tmp1, j*m));\r\n if (deg(v) > 0) {\r\n div(r, r, v);\r\n t = v;\r\n j++;\r\n }\r\n else\r\n done = 1;\r\n } while (!done);\r\n if (deg(r) == 0) finished = 1;\r\n }\r\n\r\n if (!finished) {\r\n /* r is a p-th power */\r\n\r\n long k, d;\r\n long p = to_long(ZZ_p::modulus()); \r\n\r\n d = deg(r)/p;\r\n f.rep.SetLength(d+1);\r\n for (k = 0; k <= d; k++) \r\n IterPower(f.rep[k], r.rep[k*p], ZZ_pE::degree()-1);\r\n m = m*p;\r\n }\r\n } while (!finished);\r\n}\r\n \r\n\r\n\r\nstatic\r\nvoid AbsTraceMap(ZZ_pEX& h, const ZZ_pEX& a, const ZZ_pEXModulus& F)\r\n{\r\n ZZ_pEX res, tmp;\r\n\r\n long k = NumBits(ZZ_pE::cardinality())-1;\r\n\r\n res = a;\r\n tmp = a;\r\n\r\n long i;\r\n for (i = 0; i < k-1; i++) {\r\n SqrMod(tmp, tmp, F);\r\n add(res, res, tmp);\r\n }\r\n\r\n h = res;\r\n}\r\n\r\nvoid FrobeniusMap(ZZ_pEX& h, const ZZ_pEXModulus& F)\r\n{\r\n PowerXMod(h, ZZ_pE::cardinality(), F);\r\n}\r\n\r\n\r\nstatic\r\nvoid RecFindRoots(vec_ZZ_pE& x, const ZZ_pEX& f)\r\n{\r\n if (deg(f) == 0) return;\r\n\r\n if (deg(f) == 1) {\r\n long k = x.length();\r\n x.SetLength(k+1);\r\n negate(x[k], ConstTerm(f));\r\n return;\r\n }\r\n \r\n ZZ_pEX h;\r\n\r\n ZZ_pEX r;\r\n\r\n \r\n {\r\n ZZ_pEXModulus F;\r\n build(F, f);\r\n\r\n do {\r\n random(r, deg(F));\r\n if (IsOdd(ZZ_pE::cardinality())) {\r\n PowerMod(h, r, RightShift(ZZ_pE::cardinality(), 1), F);\r\n sub(h, h, 1);\r\n }\r\n else {\r\n AbsTraceMap(h, r, F);\r\n }\r\n GCD(h, h, f);\r\n } while (deg(h) <= 0 || deg(h) == deg(f));\r\n }\r\n\r\n RecFindRoots(x, h);\r\n div(h, f, h); \r\n RecFindRoots(x, h);\r\n}\r\n\r\nvoid FindRoots(vec_ZZ_pE& x, const ZZ_pEX& ff)\r\n{\r\n ZZ_pEX f = ff;\r\n\r\n if (!IsOne(LeadCoeff(f)))\r\n LogicError(\"FindRoots: bad args\");\r\n\r\n x.SetMaxLength(deg(f));\r\n x.SetLength(0);\r\n RecFindRoots(x, f);\r\n}\r\n\r\nvoid split(ZZ_pEX& f1, ZZ_pEX& g1, ZZ_pEX& f2, ZZ_pEX& g2,\r\n const ZZ_pEX& f, const ZZ_pEX& g, \r\n const vec_ZZ_pE& roots, long lo, long mid)\r\n{\r\n long r = mid-lo+1;\r\n\r\n ZZ_pEXModulus F;\r\n build(F, f);\r\n\r\n vec_ZZ_pE lroots(INIT_SIZE, r);\r\n long i;\r\n\r\n for (i = 0; i < r; i++)\r\n lroots[i] = roots[lo+i];\r\n\r\n\r\n ZZ_pEX h, a, d;\r\n BuildFromRoots(h, lroots);\r\n CompMod(a, h, g, F);\r\n\r\n\r\n GCD(f1, a, f);\r\n \r\n div(f2, f, f1);\r\n\r\n rem(g1, g, f1);\r\n rem(g2, g, f2);\r\n}\r\n\r\nvoid RecFindFactors(vec_ZZ_pEX& factors, const ZZ_pEX& f, const ZZ_pEX& g,\r\n const vec_ZZ_pE& roots, long lo, long hi)\r\n{\r\n long r = hi-lo+1;\r\n\r\n if (r == 0) return;\r\n\r\n if (r == 1) {\r\n append(factors, f);\r\n return;\r\n }\r\n\r\n ZZ_pEX f1, g1, f2, g2;\r\n\r\n long mid = (lo+hi)/2;\r\n\r\n split(f1, g1, f2, g2, f, g, roots, lo, mid);\r\n\r\n RecFindFactors(factors, f1, g1, roots, lo, mid);\r\n RecFindFactors(factors, f2, g2, roots, mid+1, hi);\r\n}\r\n\r\n\r\nvoid FindFactors(vec_ZZ_pEX& factors, const ZZ_pEX& f, const ZZ_pEX& g,\r\n const vec_ZZ_pE& roots)\r\n{\r\n long r = roots.length();\r\n\r\n factors.SetMaxLength(r);\r\n factors.SetLength(0);\r\n\r\n RecFindFactors(factors, f, g, roots, 0, r-1);\r\n}\r\n\r\nvoid IterFindFactors(vec_ZZ_pEX& factors, const ZZ_pEX& f,\r\n const ZZ_pEX& g, const vec_ZZ_pE& roots)\r\n{\r\n long r = roots.length();\r\n long i;\r\n ZZ_pEX h;\r\n\r\n factors.SetLength(r);\r\n\r\n for (i = 0; i < r; i++) {\r\n sub(h, g, roots[i]);\r\n GCD(factors[i], f, h);\r\n }\r\n}\r\n\r\n\r\nvoid TraceMap(ZZ_pEX& w, const ZZ_pEX& a, long d, const ZZ_pEXModulus& F, \r\n const ZZ_pEX& b)\r\n\r\n{\r\n if (d < 0) LogicError(\"TraceMap: bad args\");\r\n\r\n ZZ_pEX y, z, t;\r\n\r\n z = b;\r\n y = a;\r\n clear(w);\r\n\r\n while (d) {\r\n if (d == 1) {\r\n if (IsZero(w)) \r\n w = y;\r\n else {\r\n CompMod(w, w, z, F);\r\n add(w, w, y);\r\n }\r\n }\r\n else if ((d & 1) == 0) {\r\n Comp2Mod(z, t, z, y, z, F);\r\n add(y, t, y);\r\n }\r\n else if (IsZero(w)) {\r\n w = y;\r\n Comp2Mod(z, t, z, y, z, F);\r\n add(y, t, y);\r\n }\r\n else {\r\n Comp3Mod(z, t, w, z, y, w, z, F);\r\n add(w, w, y);\r\n add(y, t, y);\r\n }\r\n\r\n d = d >> 1;\r\n }\r\n}\r\n\r\n\r\nvoid PowerCompose(ZZ_pEX& y, const ZZ_pEX& h, long q, const ZZ_pEXModulus& F)\r\n{\r\n if (q < 0) LogicError(\"PowerCompose: bad args\");\r\n\r\n ZZ_pEX z(INIT_SIZE, F.n);\r\n long sw;\r\n\r\n z = h;\r\n SetX(y);\r\n\r\n while (q) {\r\n sw = 0;\r\n\r\n if (q > 1) sw = 2;\r\n if (q & 1) {\r\n if (IsX(y))\r\n y = z;\r\n else\r\n sw = sw | 1;\r\n }\r\n\r\n switch (sw) {\r\n case 0:\r\n break;\r\n\r\n case 1:\r\n CompMod(y, y, z, F);\r\n break;\r\n\r\n case 2:\r\n CompMod(z, z, z, F);\r\n break;\r\n\r\n case 3:\r\n Comp2Mod(y, z, y, z, z, F);\r\n break;\r\n }\r\n\r\n q = q >> 1;\r\n }\r\n}\r\n\r\n\r\nlong ProbIrredTest(const ZZ_pEX& f, long iter)\r\n{\r\n long n = deg(f);\r\n\r\n if (n <= 0) return 0;\r\n if (n == 1) return 1;\r\n\r\n ZZ_pEXModulus F;\r\n\r\n build(F, f);\r\n\r\n ZZ_pEX b, r, s;\r\n\r\n FrobeniusMap(b, F);\r\n\r\n long all_zero = 1;\r\n\r\n long i;\r\n\r\n for (i = 0; i < iter; i++) {\r\n random(r, n);\r\n TraceMap(s, r, n, F, b);\r\n\r\n all_zero = all_zero && IsZero(s);\r\n\r\n if (deg(s) > 0) return 0;\r\n }\r\n\r\n if (!all_zero || (n & 1)) return 1;\r\n\r\n PowerCompose(s, b, n/2, F);\r\n return !IsX(s);\r\n}\r\n\r\n\r\nNTL_THREAD_LOCAL long ZZ_pEX_BlockingFactor = 10;\r\n\r\n\r\n\r\n\r\nvoid RootEDF(vec_ZZ_pEX& factors, const ZZ_pEX& f, long verbose)\r\n{\r\n vec_ZZ_pE roots;\r\n double t;\r\n\r\n if (verbose) { cerr << \"finding roots...\"; t = GetTime(); }\r\n FindRoots(roots, f);\r\n if (verbose) { cerr << (GetTime()-t) << \"\\n\"; }\r\n\r\n long r = roots.length();\r\n factors.SetLength(r);\r\n for (long j = 0; j < r; j++) {\r\n SetX(factors[j]);\r\n sub(factors[j], factors[j], roots[j]);\r\n }\r\n}\r\n\r\nvoid EDFSplit(vec_ZZ_pEX& v, const ZZ_pEX& f, const ZZ_pEX& b, long d)\r\n{\r\n ZZ_pEX a, g, h;\r\n ZZ_pEXModulus F;\r\n vec_ZZ_pE roots;\r\n \r\n build(F, f);\r\n long n = F.n;\r\n long r = n/d;\r\n random(a, n);\r\n TraceMap(g, a, d, F, b);\r\n MinPolyMod(h, g, F, r);\r\n FindRoots(roots, h);\r\n FindFactors(v, f, g, roots);\r\n}\r\n\r\nvoid RecEDF(vec_ZZ_pEX& factors, const ZZ_pEX& f, const ZZ_pEX& b, long d,\r\n long verbose)\r\n{\r\n vec_ZZ_pEX v;\r\n long i;\r\n ZZ_pEX bb;\r\n\r\n if (verbose) cerr << \"+\";\r\n\r\n EDFSplit(v, f, b, d);\r\n for (i = 0; i < v.length(); i++) {\r\n if (deg(v[i]) == d) {\r\n append(factors, v[i]);\r\n }\r\n else {\r\n ZZ_pEX bb;\r\n rem(bb, b, v[i]);\r\n RecEDF(factors, v[i], bb, d, verbose);\r\n }\r\n }\r\n}\r\n \r\n\r\nvoid EDF(vec_ZZ_pEX& factors, const ZZ_pEX& ff, const ZZ_pEX& bb,\r\n long d, long verbose)\r\n\r\n{\r\n ZZ_pEX f = ff;\r\n ZZ_pEX b = bb;\r\n\r\n if (!IsOne(LeadCoeff(f)))\r\n LogicError(\"EDF: bad args\");\r\n\r\n long n = deg(f);\r\n long r = n/d;\r\n\r\n if (r == 0) {\r\n factors.SetLength(0);\r\n return;\r\n }\r\n\r\n if (r == 1) {\r\n factors.SetLength(1);\r\n factors[0] = f;\r\n return;\r\n }\r\n\r\n if (d == 1) {\r\n RootEDF(factors, f, verbose);\r\n return;\r\n }\r\n\r\n \r\n double t;\r\n if (verbose) { \r\n cerr << \"computing EDF(\" << d << \",\" << r << \")...\"; \r\n t = GetTime(); \r\n }\r\n\r\n factors.SetLength(0);\r\n\r\n RecEDF(factors, f, b, d, verbose);\r\n\r\n if (verbose) cerr << (GetTime()-t) << \"\\n\";\r\n}\r\n\r\n\r\nvoid SFCanZass(vec_ZZ_pEX& factors, const ZZ_pEX& ff, long verbose)\r\n{\r\n ZZ_pEX f = ff;\r\n\r\n if (!IsOne(LeadCoeff(f)))\r\n LogicError(\"SFCanZass: bad args\");\r\n\r\n if (deg(f) == 0) {\r\n factors.SetLength(0);\r\n return;\r\n }\r\n\r\n if (deg(f) == 1) {\r\n factors.SetLength(1);\r\n factors[0] = f;\r\n return;\r\n }\r\n\r\n factors.SetLength(0);\r\n\r\n double t;\r\n\r\n \r\n ZZ_pEXModulus F;\r\n build(F, f);\r\n\r\n ZZ_pEX h;\r\n\r\n if (verbose) { cerr << \"computing X^p...\"; t = GetTime(); }\r\n FrobeniusMap(h, F);\r\n if (verbose) { cerr << (GetTime()-t) << \"\\n\"; }\r\n\r\n vec_pair_ZZ_pEX_long u;\r\n if (verbose) { cerr << \"computing DDF...\"; t = GetTime(); }\r\n NewDDF(u, f, h, verbose);\r\n if (verbose) { \r\n t = GetTime()-t; \r\n cerr << \"DDF time: \" << t << \"\\n\";\r\n }\r\n\r\n ZZ_pEX hh;\r\n vec_ZZ_pEX v;\r\n\r\n long i;\r\n for (i = 0; i < u.length(); i++) {\r\n const ZZ_pEX& g = u[i].a;\r\n long d = u[i].b;\r\n long r = deg(g)/d;\r\n\r\n if (r == 1) {\r\n // g is already irreducible\r\n\r\n append(factors, g);\r\n }\r\n else {\r\n // must perform EDF\r\n\r\n if (d == 1) {\r\n // root finding\r\n RootEDF(v, g, verbose);\r\n append(factors, v);\r\n }\r\n else {\r\n // general case\r\n rem(hh, h, g);\r\n EDF(v, g, hh, d, verbose);\r\n append(factors, v);\r\n }\r\n }\r\n }\r\n}\r\n \r\nvoid CanZass(vec_pair_ZZ_pEX_long& factors, const ZZ_pEX& f, long verbose)\r\n{\r\n if (!IsOne(LeadCoeff(f)))\r\n LogicError(\"CanZass: bad args\");\r\n\r\n double t;\r\n vec_pair_ZZ_pEX_long sfd;\r\n vec_ZZ_pEX x;\r\n\r\n \r\n if (verbose) { cerr << \"square-free decomposition...\"; t = GetTime(); }\r\n SquareFreeDecomp(sfd, f);\r\n if (verbose) cerr << (GetTime()-t) << \"\\n\";\r\n\r\n factors.SetLength(0);\r\n\r\n long i, j;\r\n\r\n for (i = 0; i < sfd.length(); i++) {\r\n if (verbose) {\r\n cerr << \"factoring multiplicity \" << sfd[i].b \r\n << \", deg = \" << deg(sfd[i].a) << \"\\n\";\r\n }\r\n\r\n SFCanZass(x, sfd[i].a, verbose);\r\n\r\n for (j = 0; j < x.length(); j++)\r\n append(factors, cons(x[j], sfd[i].b));\r\n }\r\n}\r\n\r\nvoid mul(ZZ_pEX& f, const vec_pair_ZZ_pEX_long& v)\r\n{\r\n long i, j, n;\r\n\r\n n = 0;\r\n for (i = 0; i < v.length(); i++)\r\n n += v[i].b*deg(v[i].a);\r\n\r\n ZZ_pEX g(INIT_SIZE, n+1);\r\n\r\n set(g);\r\n for (i = 0; i < v.length(); i++)\r\n for (j = 0; j < v[i].b; j++) {\r\n mul(g, g, v[i].a);\r\n }\r\n\r\n f = g;\r\n}\r\n\r\n\r\nlong BaseCase(const ZZ_pEX& h, long q, long a, const ZZ_pEXModulus& F)\r\n{\r\n long b, e;\r\n ZZ_pEX lh(INIT_SIZE, F.n);\r\n\r\n lh = h;\r\n b = 1;\r\n e = 0;\r\n while (e < a-1 && !IsX(lh)) {\r\n e++;\r\n b *= q;\r\n PowerCompose(lh, lh, q, F);\r\n }\r\n\r\n if (!IsX(lh)) b *= q;\r\n\r\n return b;\r\n}\r\n\r\n\r\n\r\nvoid TandemPowerCompose(ZZ_pEX& y1, ZZ_pEX& y2, const ZZ_pEX& h, \r\n long q1, long q2, const ZZ_pEXModulus& F)\r\n{\r\n ZZ_pEX z(INIT_SIZE, F.n);\r\n long sw;\r\n\r\n z = h;\r\n SetX(y1);\r\n SetX(y2);\r\n\r\n while (q1 || q2) {\r\n sw = 0;\r\n\r\n if (q1 > 1 || q2 > 1) sw = 4;\r\n\r\n if (q1 & 1) {\r\n if (IsX(y1))\r\n y1 = z;\r\n else\r\n sw = sw | 2;\r\n }\r\n\r\n if (q2 & 1) {\r\n if (IsX(y2))\r\n y2 = z;\r\n else\r\n sw = sw | 1;\r\n }\r\n\r\n switch (sw) {\r\n case 0:\r\n break;\r\n\r\n case 1:\r\n CompMod(y2, y2, z, F);\r\n break;\r\n\r\n case 2:\r\n CompMod(y1, y1, z, F);\r\n break;\r\n\r\n case 3:\r\n Comp2Mod(y1, y2, y1, y2, z, F);\r\n break;\r\n\r\n case 4:\r\n CompMod(z, z, z, F);\r\n break;\r\n\r\n case 5:\r\n Comp2Mod(z, y2, z, y2, z, F);\r\n break;\r\n\r\n case 6:\r\n Comp2Mod(z, y1, z, y1, z, F);\r\n break;\r\n\r\n case 7:\r\n Comp3Mod(z, y1, y2, z, y1, y2, z, F);\r\n break;\r\n }\r\n\r\n q1 = q1 >> 1;\r\n q2 = q2 >> 1;\r\n }\r\n}\r\n\r\n\r\nlong RecComputeDegree(long u, const ZZ_pEX& h, const ZZ_pEXModulus& F,\r\n FacVec& fvec)\r\n{\r\n if (IsX(h)) return 1;\r\n\r\n if (fvec[u].link == -1) return BaseCase(h, fvec[u].q, fvec[u].a, F);\r\n\r\n ZZ_pEX h1, h2;\r\n long q1, q2, r1, r2;\r\n\r\n q1 = fvec[fvec[u].link].val; \r\n q2 = fvec[fvec[u].link+1].val;\r\n\r\n TandemPowerCompose(h1, h2, h, q1, q2, F);\r\n r1 = RecComputeDegree(fvec[u].link, h2, F, fvec);\r\n r2 = RecComputeDegree(fvec[u].link+1, h1, F, fvec);\r\n return r1*r2;\r\n}\r\n\r\n \r\n\r\n\r\nlong RecComputeDegree(const ZZ_pEX& h, const ZZ_pEXModulus& F)\r\n // f = F.f is assumed to be an \"equal degree\" polynomial\r\n // h = X^p mod f\r\n // the common degree of the irreducible factors of f is computed\r\n{\r\n if (F.n == 1 || IsX(h)) \r\n return 1;\r\n\r\n FacVec fvec;\r\n\r\n FactorInt(fvec, F.n);\r\n\r\n return RecComputeDegree(fvec.length()-1, h, F, fvec);\r\n}\r\n\r\n\r\nvoid FindRoot(ZZ_pE& root, const ZZ_pEX& ff)\r\n// finds a root of ff.\r\n// assumes that ff is monic and splits into distinct linear factors\r\n\r\n{\r\n ZZ_pEXModulus F;\r\n ZZ_pEX h, h1, f;\r\n ZZ_pEX r;\r\n\r\n f = ff;\r\n \r\n if (!IsOne(LeadCoeff(f)))\r\n LogicError(\"FindRoot: bad args\");\r\n\r\n if (deg(f) == 0)\r\n LogicError(\"FindRoot: bad args\");\r\n\r\n\r\n while (deg(f) > 1) {\r\n build(F, f);\r\n random(r, deg(F));\r\n if (IsOdd(ZZ_pE::cardinality())) {\r\n PowerMod(h, r, RightShift(ZZ_pE::cardinality(), 1), F);\r\n sub(h, h, 1);\r\n }\r\n else {\r\n AbsTraceMap(h, r, F);\r\n }\r\n GCD(h, h, f);\r\n if (deg(h) > 0 && deg(h) < deg(f)) {\r\n if (deg(h) > deg(f)/2)\r\n div(f, f, h);\r\n else\r\n f = h;\r\n }\r\n }\r\n \r\n negate(root, ConstTerm(f));\r\n}\r\n\r\n\r\nstatic\r\nlong power(long a, long e)\r\n{\r\n long i, res;\r\n\r\n res = 1;\r\n for (i = 1; i <= e; i++)\r\n res = res * a;\r\n\r\n return res;\r\n}\r\n\r\n\r\nstatic\r\nlong IrredBaseCase(const ZZ_pEX& h, long q, long a, const ZZ_pEXModulus& F)\r\n{\r\n long e;\r\n ZZ_pEX X, s, d;\r\n\r\n e = power(q, a-1);\r\n PowerCompose(s, h, e, F);\r\n SetX(X);\r\n sub(s, s, X);\r\n GCD(d, F.f, s);\r\n return IsOne(d);\r\n}\r\n\r\n\r\nstatic\r\nlong RecIrredTest(long u, const ZZ_pEX& h, const ZZ_pEXModulus& F,\r\n const FacVec& fvec)\r\n{\r\n long q1, q2;\r\n ZZ_pEX h1, h2;\r\n\r\n if (IsX(h)) return 0;\r\n\r\n if (fvec[u].link == -1) {\r\n return IrredBaseCase(h, fvec[u].q, fvec[u].a, F);\r\n }\r\n\r\n\r\n q1 = fvec[fvec[u].link].val; \r\n q2 = fvec[fvec[u].link+1].val;\r\n\r\n TandemPowerCompose(h1, h2, h, q1, q2, F);\r\n return RecIrredTest(fvec[u].link, h2, F, fvec) \r\n && RecIrredTest(fvec[u].link+1, h1, F, fvec);\r\n}\r\n\r\nlong DetIrredTest(const ZZ_pEX& f)\r\n{\r\n if (deg(f) <= 0) return 0;\r\n if (deg(f) == 1) return 1;\r\n\r\n ZZ_pEXModulus F;\r\n\r\n build(F, f);\r\n \r\n ZZ_pEX h;\r\n\r\n FrobeniusMap(h, F);\r\n\r\n ZZ_pEX s;\r\n PowerCompose(s, h, F.n, F);\r\n if (!IsX(s)) return 0;\r\n\r\n FacVec fvec;\r\n\r\n FactorInt(fvec, F.n);\r\n\r\n return RecIrredTest(fvec.length()-1, h, F, fvec);\r\n}\r\n\r\n\r\n\r\nlong IterIrredTest(const ZZ_pEX& f)\r\n{\r\n if (deg(f) <= 0) return 0;\r\n if (deg(f) == 1) return 1;\r\n\r\n ZZ_pEXModulus F;\r\n\r\n build(F, f);\r\n \r\n ZZ_pEX h;\r\n\r\n FrobeniusMap(h, F);\r\n\r\n long CompTableSize = 2*SqrRoot(deg(f));\r\n\r\n ZZ_pEXArgument H;\r\n\r\n build(H, h, F, CompTableSize);\r\n\r\n long i, d, limit, limit_sqr;\r\n ZZ_pEX g, X, t, prod;\r\n\r\n\r\n SetX(X);\r\n\r\n i = 0;\r\n g = h;\r\n d = 1;\r\n limit = 2;\r\n limit_sqr = limit*limit;\r\n\r\n set(prod);\r\n\r\n\r\n while (2*d <= deg(f)) {\r\n sub(t, g, X);\r\n MulMod(prod, prod, t, F);\r\n i++;\r\n if (i == limit_sqr) {\r\n GCD(t, f, prod);\r\n if (!IsOne(t)) return 0;\r\n\r\n set(prod);\r\n limit++;\r\n limit_sqr = limit*limit;\r\n i = 0;\r\n }\r\n\r\n d = d + 1;\r\n if (2*d <= deg(f)) {\r\n CompMod(g, g, H, F);\r\n }\r\n }\r\n\r\n if (i > 0) {\r\n GCD(t, f, prod);\r\n if (!IsOne(t)) return 0;\r\n }\r\n\r\n return 1;\r\n}\r\n\r\nstatic\r\nvoid MulByXPlusY(vec_ZZ_pEX& h, const ZZ_pEX& f, const ZZ_pEX& g)\r\n// h represents the bivariate polynomial h[0] + h[1]*Y + ... + h[n-1]*Y^k,\r\n// where the h[i]'s are polynomials in X, each of degree < deg(f),\r\n// and k < deg(g).\r\n// h is replaced by the bivariate polynomial h*(X+Y) (mod f(X), g(Y)).\r\n\r\n{\r\n long n = deg(g);\r\n long k = h.length()-1;\r\n\r\n if (k < 0) return;\r\n\r\n if (k < n-1) {\r\n h.SetLength(k+2);\r\n h[k+1] = h[k];\r\n for (long i = k; i >= 1; i--) {\r\n MulByXMod(h[i], h[i], f);\r\n add(h[i], h[i], h[i-1]);\r\n }\r\n MulByXMod(h[0], h[0], f);\r\n }\r\n else {\r\n ZZ_pEX b, t;\r\n\r\n b = h[n-1];\r\n for (long i = n-1; i >= 1; i--) {\r\n mul(t, b, g.rep[i]);\r\n MulByXMod(h[i], h[i], f);\r\n add(h[i], h[i], h[i-1]);\r\n sub(h[i], h[i], t);\r\n }\r\n mul(t, b, g.rep[0]);\r\n MulByXMod(h[0], h[0], f);\r\n sub(h[0], h[0], t);\r\n }\r\n\r\n // normalize\r\n\r\n k = h.length()-1;\r\n while (k >= 0 && IsZero(h[k])) k--;\r\n h.SetLength(k+1);\r\n}\r\n\r\n\r\nstatic\r\nvoid IrredCombine(ZZ_pEX& x, const ZZ_pEX& f, const ZZ_pEX& g)\r\n{\r\n if (deg(f) < deg(g)) {\r\n IrredCombine(x, g, f);\r\n return;\r\n }\r\n\r\n // deg(f) >= deg(g)...not necessary, but maybe a little more\r\n // time & space efficient\r\n\r\n long df = deg(f);\r\n long dg = deg(g);\r\n long m = df*dg;\r\n\r\n vec_ZZ_pEX h(INIT_SIZE, dg);\r\n\r\n long i;\r\n for (i = 0; i < dg; i++) h[i].SetMaxLength(df);\r\n\r\n h.SetLength(1);\r\n set(h[0]);\r\n\r\n vec_ZZ_pE a;\r\n\r\n a.SetLength(2*m);\r\n\r\n for (i = 0; i < 2*m; i++) {\r\n a[i] = ConstTerm(h[0]);\r\n if (i < 2*m-1)\r\n MulByXPlusY(h, f, g);\r\n }\r\n\r\n MinPolySeq(x, a, m);\r\n}\r\n\r\n\r\nstatic\r\nvoid BuildPrimePowerIrred(ZZ_pEX& f, long q, long e)\r\n{\r\n long n = power(q, e);\r\n\r\n do {\r\n random(f, n);\r\n SetCoeff(f, n);\r\n } while (!IterIrredTest(f));\r\n}\r\n\r\nstatic\r\nvoid RecBuildIrred(ZZ_pEX& f, long u, const FacVec& fvec)\r\n{\r\n if (fvec[u].link == -1)\r\n BuildPrimePowerIrred(f, fvec[u].q, fvec[u].a);\r\n else {\r\n ZZ_pEX g, h;\r\n RecBuildIrred(g, fvec[u].link, fvec);\r\n RecBuildIrred(h, fvec[u].link+1, fvec);\r\n IrredCombine(f, g, h);\r\n }\r\n}\r\n\r\n\r\nvoid BuildIrred(ZZ_pEX& f, long n)\r\n{\r\n if (n <= 0)\r\n LogicError(\"BuildIrred: n must be positive\");\r\n\r\n if (NTL_OVERFLOW(n, 1, 0)) ResourceError(\"overflow in BuildIrred\");\r\n\r\n if (n == 1) {\r\n SetX(f);\r\n return;\r\n }\r\n\r\n FacVec fvec;\r\n\r\n FactorInt(fvec, n);\r\n\r\n RecBuildIrred(f, fvec.length()-1, fvec);\r\n}\r\n\r\n\r\n\r\n#if 0\r\nvoid BuildIrred(ZZ_pEX& f, long n)\r\n{\r\n if (n <= 0)\r\n LogicError(\"BuildIrred: n must be positive\");\r\n\r\n if (n == 1) {\r\n SetX(f);\r\n return;\r\n }\r\n\r\n ZZ_pEX g;\r\n\r\n do {\r\n random(g, n);\r\n SetCoeff(g, n);\r\n } while (!IterIrredTest(g));\r\n\r\n f = g;\r\n\r\n}\r\n#endif\r\n\r\n\r\n\r\nvoid BuildRandomIrred(ZZ_pEX& f, const ZZ_pEX& g)\r\n{\r\n ZZ_pEXModulus G;\r\n ZZ_pEX h, ff;\r\n\r\n build(G, g);\r\n do {\r\n random(h, deg(g));\r\n IrredPolyMod(ff, h, G);\r\n } while (deg(ff) < deg(g));\r\n\r\n f = ff;\r\n}\r\n\r\n\r\n/************* NEW DDF ****************/\r\n\r\nNTL_THREAD_LOCAL long ZZ_pEX_GCDTableSize = 4;\r\nNTL_THREAD_LOCAL double ZZ_pEXFileThresh = NTL_FILE_THRESH;\r\nNTL_THREAD_LOCAL static vec_ZZ_pEX *BabyStepFile=0;\r\nNTL_THREAD_LOCAL static vec_ZZ_pEX *GiantStepFile=0;\r\nNTL_THREAD_LOCAL static long use_files;\r\n\r\n\r\nstatic\r\ndouble CalcTableSize(long n, long k)\r\n{\r\n double sz = ZZ_p::storage();\r\n sz = sz*ZZ_pE::degree();\r\n sz = sz + NTL_VECTOR_HEADER_SIZE + sizeof(vec_ZZ_p);\r\n sz = sz*n;\r\n sz = sz + NTL_VECTOR_HEADER_SIZE + sizeof(vec_ZZ_pE);\r\n sz = sz * k;\r\n sz = sz/1024;\r\n return sz;\r\n}\r\n\r\n\r\nstatic\r\nvoid GenerateBabySteps(ZZ_pEX& h1, const ZZ_pEX& f, const ZZ_pEX& h, long k,\r\n FileList& flist, long verbose)\r\n\r\n{\r\n double t;\r\n\r\n if (verbose) { cerr << \"generating baby steps...\"; t = GetTime(); }\r\n\r\n ZZ_pEXModulus F;\r\n build(F, f);\r\n\r\n ZZ_pEXArgument H;\r\n\r\n#if 0\r\n double n2 = sqrt(double(F.n));\r\n double n4 = sqrt(n2);\r\n double n34 = n2*n4;\r\n long sz = long(ceil(n34/sqrt(sqrt(2.0))));\r\n#else\r\n long sz = 2*SqrRoot(F.n);\r\n#endif\r\n\r\n build(H, h, F, sz);\r\n\r\n\r\n h1 = h;\r\n\r\n long i;\r\n\r\n if (!use_files) {\r\n (*BabyStepFile).SetLength(k-1);\r\n }\r\n\r\n for (i = 1; i <= k-1; i++) {\r\n if (use_files) {\r\n ofstream s;\r\n OpenWrite(s, FileName(\"baby\", i), flist);\r\n s << h1 << \"\\n\";\r\n CloseWrite(s);\r\n }\r\n else\r\n (*BabyStepFile)(i) = h1;\r\n\r\n CompMod(h1, h1, H, F);\r\n if (verbose) cerr << \"+\";\r\n }\r\n\r\n if (verbose)\r\n cerr << (GetTime()-t) << \"\\n\";\r\n\r\n}\r\n\r\n\r\nstatic\r\nvoid GenerateGiantSteps(const ZZ_pEX& f, const ZZ_pEX& h, long l, \r\n FileList& flist, long verbose)\r\n{\r\n\r\n double t;\r\n\r\n if (verbose) { cerr << \"generating giant steps...\"; t = GetTime(); }\r\n\r\n ZZ_pEXModulus F;\r\n build(F, f);\r\n\r\n ZZ_pEXArgument H;\r\n\r\n#if 0\r\n double n2 = sqrt(double(F.n));\r\n double n4 = sqrt(n2);\r\n double n34 = n2*n4;\r\n long sz = long(ceil(n34/sqrt(sqrt(2.0))));\r\n#else\r\n long sz = 2*SqrRoot(F.n);\r\n#endif\r\n\r\n build(H, h, F, sz);\r\n\r\n ZZ_pEX h1;\r\n\r\n h1 = h;\r\n\r\n long i;\r\n\r\n if (!use_files) {\r\n (*GiantStepFile).SetLength(l);\r\n }\r\n\r\n for (i = 1; i <= l-1; i++) {\r\n if (use_files) {\r\n ofstream s;\r\n OpenWrite(s, FileName(\"giant\", i), flist);\r\n s << h1 << \"\\n\";\r\n CloseWrite(s);\r\n }\r\n else\r\n (*GiantStepFile)(i) = h1;\r\n\r\n CompMod(h1, h1, H, F);\r\n if (verbose) cerr << \"+\";\r\n }\r\n\r\n if (use_files) {\r\n ofstream s;\r\n OpenWrite(s, FileName(\"giant\", i), flist);\r\n s << h1 << \"\\n\";\r\n CloseWrite(s);\r\n }\r\n else\r\n (*GiantStepFile)(i) = h1;\r\n\r\n if (verbose)\r\n cerr << (GetTime()-t) << \"\\n\";\r\n\r\n}\r\n\r\n\r\nstatic\r\nvoid NewAddFactor(vec_pair_ZZ_pEX_long& u, const ZZ_pEX& g, long m, long verbose)\r\n{\r\n long len = u.length();\r\n\r\n u.SetLength(len+1);\r\n u[len].a = g;\r\n u[len].b = m;\r\n\r\n if (verbose) {\r\n cerr << \"split \" << m << \" \" << deg(g) << \"\\n\";\r\n }\r\n}\r\n\r\n \r\n\r\n\r\nstatic\r\nvoid NewProcessTable(vec_pair_ZZ_pEX_long& u, ZZ_pEX& f, const ZZ_pEXModulus& F,\r\n vec_ZZ_pEX& buf, long size, long StartInterval,\r\n long IntervalLength, long verbose)\r\n\r\n{\r\n if (size == 0) return;\r\n\r\n ZZ_pEX& g = buf[size-1];\r\n\r\n long i;\r\n\r\n for (i = 0; i < size-1; i++)\r\n MulMod(g, g, buf[i], F);\r\n\r\n GCD(g, f, g);\r\n\r\n if (deg(g) == 0) return;\r\n\r\n div(f, f, g);\r\n\r\n long d = (StartInterval-1)*IntervalLength + 1;\r\n i = 0;\r\n long interval = StartInterval;\r\n\r\n while (i < size-1 && 2*d <= deg(g)) {\r\n GCD(buf[i], buf[i], g);\r\n if (deg(buf[i]) > 0) {\r\n NewAddFactor(u, buf[i], interval, verbose);\r\n div(g, g, buf[i]);\r\n }\r\n\r\n i++;\r\n interval++;\r\n d += IntervalLength;\r\n }\r\n\r\n if (deg(g) > 0) {\r\n if (i == size-1)\r\n NewAddFactor(u, g, interval, verbose);\r\n else\r\n NewAddFactor(u, g, (deg(g)+IntervalLength-1)/IntervalLength, verbose);\r\n }\r\n}\r\n\r\n\r\nstatic\r\nvoid FetchGiantStep(ZZ_pEX& g, long gs, const ZZ_pEXModulus& F)\r\n{\r\n if (use_files) {\r\n ifstream s;\r\n OpenRead(s, FileName(\"giant\", gs));\r\n NTL_INPUT_CHECK_ERR(s >> g);\r\n }\r\n else\r\n g = (*GiantStepFile)(gs);\r\n\r\n\r\n rem(g, g, F);\r\n}\r\n\r\n\r\nstatic\r\nvoid FetchBabySteps(vec_ZZ_pEX& v, long k)\r\n{\r\n v.SetLength(k);\r\n\r\n SetX(v[0]);\r\n\r\n long i;\r\n for (i = 1; i <= k-1; i++) {\r\n if (use_files) {\r\n ifstream s;\r\n OpenRead(s, FileName(\"baby\", i));\r\n NTL_INPUT_CHECK_ERR(s >> v[i]);\r\n }\r\n else\r\n v[i] = (*BabyStepFile)(i);\r\n }\r\n}\r\n \r\n\r\n\r\nstatic\r\nvoid GiantRefine(vec_pair_ZZ_pEX_long& u, const ZZ_pEX& ff, long k, long l,\r\n long verbose)\r\n\r\n{\r\n double t;\r\n\r\n if (verbose) {\r\n cerr << \"giant refine...\";\r\n t = GetTime();\r\n }\r\n\r\n u.SetLength(0);\r\n\r\n vec_ZZ_pEX BabyStep;\r\n\r\n FetchBabySteps(BabyStep, k);\r\n\r\n vec_ZZ_pEX buf(INIT_SIZE, ZZ_pEX_GCDTableSize);\r\n\r\n ZZ_pEX f;\r\n f = ff;\r\n\r\n ZZ_pEXModulus F;\r\n build(F, f);\r\n\r\n ZZ_pEX g;\r\n ZZ_pEX h;\r\n\r\n long size = 0;\r\n\r\n long first_gs;\r\n\r\n long d = 1;\r\n\r\n while (2*d <= deg(f)) {\r\n\r\n long old_n = deg(f);\r\n\r\n long gs = (d+k-1)/k;\r\n long bs = gs*k - d;\r\n\r\n if (bs == k-1) {\r\n size++;\r\n if (size == 1) first_gs = gs;\r\n FetchGiantStep(g, gs, F);\r\n sub(buf[size-1], g, BabyStep[bs]);\r\n }\r\n else {\r\n sub(h, g, BabyStep[bs]);\r\n MulMod(buf[size-1], buf[size-1], h, F);\r\n }\r\n\r\n if (verbose && bs == 0) cerr << \"+\";\r\n\r\n if (size == ZZ_pEX_GCDTableSize && bs == 0) {\r\n NewProcessTable(u, f, F, buf, size, first_gs, k, verbose);\r\n if (verbose) cerr << \"*\";\r\n size = 0;\r\n }\r\n\r\n d++;\r\n\r\n if (2*d <= deg(f) && deg(f) < old_n) {\r\n build(F, f);\r\n\r\n long i;\r\n for (i = 1; i <= k-1; i++) \r\n rem(BabyStep[i], BabyStep[i], F);\r\n }\r\n }\r\n\r\n if (size > 0) {\r\n NewProcessTable(u, f, F, buf, size, first_gs, k, verbose);\r\n if (verbose) cerr << \"*\";\r\n }\r\n\r\n if (deg(f) > 0) \r\n NewAddFactor(u, f, 0, verbose);\r\n\r\n if (verbose) {\r\n t = GetTime()-t;\r\n cerr << \"giant refine time: \" << t << \"\\n\";\r\n }\r\n}\r\n\r\n\r\nstatic\r\nvoid IntervalRefine(vec_pair_ZZ_pEX_long& factors, const ZZ_pEX& ff,\r\n long k, long gs, const vec_ZZ_pEX& BabyStep, long verbose)\r\n\r\n{\r\n vec_ZZ_pEX buf(INIT_SIZE, ZZ_pEX_GCDTableSize);\r\n\r\n ZZ_pEX f;\r\n f = ff;\r\n\r\n ZZ_pEXModulus F;\r\n build(F, f);\r\n\r\n ZZ_pEX g;\r\n\r\n FetchGiantStep(g, gs, F);\r\n\r\n long size = 0;\r\n\r\n long first_d;\r\n\r\n long d = (gs-1)*k + 1;\r\n long bs = k-1;\r\n\r\n while (bs >= 0 && 2*d <= deg(f)) {\r\n\r\n long old_n = deg(f);\r\n\r\n if (size == 0) first_d = d;\r\n rem(buf[size], BabyStep[bs], F);\r\n sub(buf[size], buf[size], g);\r\n size++;\r\n\r\n if (size == ZZ_pEX_GCDTableSize) {\r\n NewProcessTable(factors, f, F, buf, size, first_d, 1, verbose);\r\n size = 0;\r\n }\r\n\r\n d++;\r\n bs--;\r\n\r\n if (bs >= 0 && 2*d <= deg(f) && deg(f) < old_n) {\r\n build(F, f);\r\n rem(g, g, F);\r\n }\r\n }\r\n\r\n NewProcessTable(factors, f, F, buf, size, first_d, 1, verbose);\r\n\r\n if (deg(f) > 0) \r\n NewAddFactor(factors, f, deg(f), verbose);\r\n}\r\n \r\n\r\n\r\n\r\nstatic\r\nvoid BabyRefine(vec_pair_ZZ_pEX_long& factors, const vec_pair_ZZ_pEX_long& u,\r\n long k, long l, long verbose)\r\n\r\n{\r\n double t;\r\n\r\n if (verbose) {\r\n cerr << \"baby refine...\";\r\n t = GetTime();\r\n }\r\n\r\n factors.SetLength(0);\r\n\r\n vec_ZZ_pEX BabyStep;\r\n\r\n long i;\r\n for (i = 0; i < u.length(); i++) {\r\n const ZZ_pEX& g = u[i].a;\r\n long gs = u[i].b;\r\n\r\n if (gs == 0 || 2*((gs-1)*k+1) > deg(g))\r\n NewAddFactor(factors, g, deg(g), verbose);\r\n else {\r\n if (BabyStep.length() == 0)\r\n FetchBabySteps(BabyStep, k);\r\n IntervalRefine(factors, g, k, gs, BabyStep, verbose);\r\n }\r\n }\r\n\r\n if (verbose) {\r\n t = GetTime()-t;\r\n cerr << \"baby refine time: \" << t << \"\\n\";\r\n }\r\n}\r\n\r\n \r\n \r\n\r\n \r\n\r\nvoid NewDDF(vec_pair_ZZ_pEX_long& factors,\r\n const ZZ_pEX& f,\r\n const ZZ_pEX& h,\r\n long verbose)\r\n\r\n{\r\n if (!IsOne(LeadCoeff(f)))\r\n LogicError(\"NewDDF: bad args\");\r\n\r\n if (deg(f) == 0) {\r\n factors.SetLength(0);\r\n return;\r\n }\r\n\r\n if (deg(f) == 1) {\r\n factors.SetLength(0);\r\n append(factors, cons(f, 1L));\r\n return;\r\n }\r\n\r\n long B = deg(f)/2;\r\n long k = SqrRoot(B);\r\n long l = (B+k-1)/k;\r\n\r\n ZZ_pEX h1;\r\n\r\n if (CalcTableSize(deg(f), k + l - 1) > ZZ_pEXFileThresh)\r\n use_files = 1;\r\n else\r\n use_files = 0;\r\n\r\n\r\n FileList flist;\r\n\r\n vec_ZZ_pEX local_BabyStepFile;\r\n vec_ZZ_pEX local_GiantStepFile;\r\n\r\n BabyStepFile = &local_BabyStepFile;\r\n GiantStepFile = &local_GiantStepFile;\r\n\r\n\r\n GenerateBabySteps(h1, f, h, k, flist, verbose);\r\n\r\n GenerateGiantSteps(f, h1, l, flist, verbose);\r\n\r\n vec_pair_ZZ_pEX_long u;\r\n GiantRefine(u, f, k, l, verbose);\r\n BabyRefine(factors, u, k, l, verbose);\r\n}\r\n\r\nlong IterComputeDegree(const ZZ_pEX& h, const ZZ_pEXModulus& F)\r\n{\r\n long n = deg(F);\r\n\r\n if (n == 1 || IsX(h)) return 1;\r\n\r\n long B = n/2;\r\n long k = SqrRoot(B);\r\n long l = (B+k-1)/k;\r\n\r\n\r\n ZZ_pEXArgument H;\r\n\r\n#if 0\r\n double n2 = sqrt(double(n));\r\n double n4 = sqrt(n2);\r\n double n34 = n2*n4;\r\n long sz = long(ceil(n34/sqrt(sqrt(2.0))));\r\n#else\r\n long sz = 2*SqrRoot(F.n);\r\n#endif\r\n\r\n build(H, h, F, sz);\r\n\r\n ZZ_pEX h1;\r\n h1 = h;\r\n\r\n vec_ZZ_pEX baby;\r\n baby.SetLength(k);\r\n\r\n SetX(baby[0]);\r\n\r\n long i;\r\n\r\n for (i = 1; i <= k-1; i++) {\r\n baby[i] = h1;\r\n CompMod(h1, h1, H, F);\r\n if (IsX(h1)) return i+1;\r\n }\r\n\r\n build(H, h1, F, sz);\r\n\r\n long j;\r\n\r\n for (j = 2; j <= l; j++) {\r\n CompMod(h1, h1, H, F);\r\n\r\n for (i = k-1; i >= 0; i--) {\r\n if (h1 == baby[i])\r\n return j*k-i;\r\n }\r\n }\r\n\r\n return n;\r\n}\r\n\r\nNTL_END_IMPL\r\n", "meta": {"hexsha": "4f58b5ba6d376543d7e1923d1c153fa64be0fa67", "size": 29688, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "WinNTL-8_1_2/src/ZZ_pEXFactoring.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/ZZ_pEXFactoring.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/ZZ_pEXFactoring.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": 18.6131661442, "max_line_length": 82, "alphanum_fraction": 0.4672258151, "num_tokens": 9858, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8128673178375734, "lm_q2_score": 0.7931059511841119, "lm_q1q2_score": 0.6446899073000464}} {"text": "#pragma once\n#include \n#include \n\nnamespace filter_bay\n{\n/*!\nModel of a gaussian measurement.\nThe equation ist:\n\\f[\n y_k = H x_k + v_k\n\\f]\nWhere \\f$x_k\\f$ is the state and \\f$v_k\\f$ the measurement noise at step k.\nThe measurement noise is assumed to be a constant white noise.\n\nSee https://en.wikipedia.org/wiki/Kalman_filter#Update for further explanation.\n*/\ntemplate \nstruct GaussianObservationModel\n{\n /*! \\f$x_k\\f$ */\n using State = typename Eigen::Matrix;\n /*! \\f$P_k\\f$ */\n using StateCovariance = typename Eigen::Matrix;\n /*! \\f$y_k\\f$ */\n using Observation = typename Eigen::Matrix;\n /*! \\f$H\\f$ */\n using ObservationMatrix = typename Eigen::Matrix;\n /*! \\f$R\\f$ */\n using NoiseCovariance = typename Eigen::Matrix;\n /*! \\f$K\\f$ */\n using KalmanGain = typename Eigen::Matrix;\n\n /*! Observatin matrix of the state */\n ObservationMatrix H;\n /*! Measurement covariance matrix */\n NoiseCovariance R;\n\n GaussianObservationModel() {}\n\n GaussianObservationModel(ObservationMatrix h, NoiseCovariance r)\n : H(std::move(h)), R(std::move(r)) {}\n\n /*!\n Calculates the expected measurement for the given state.\n \\param x current state\n */\n Observation calculate_measurement(const State &x) const\n {\n return H * x;\n }\n\n /*!\n Calculates the kalman gain via the observation model.\n \\param P the current covariance of the state (serves as confidence)\n */\n KalmanGain calculate_gain(const StateCovariance &P) const\n {\n // Calculate P * H^T only once\n Eigen::Matrix PH_T = P * H.transpose();\n Eigen::Matrix S = R + H * PH_T;\n return PH_T * S.inverse();\n }\n\n /*!\n Calculates the update of the state with the given observation model.\n \\param x current (predicted) state\n \\param y current measurement\n \\param K kalman gain for the (predicted) state covariance\n */\n State update_state(const State &x, const Observation &y, KalmanGain &K) const\n {\n Observation residual = y - calculate_measurement(x);\n return x + K * residual;\n }\n\n StateCovariance update_covariance(const StateCovariance &P,\n const KalmanGain &K) const\n {\n // P = (I-KH)P(I-KH)^T + KRK^T\n // This is more numerically stable and works for non-optimal K vs the equation\n // P = (I - KH) P usually seen in the literature.\n // https://github.com/rlabbe/filterpy/blob/master/filterpy/kalman/kalman_filter.py\n StateCovariance I = StateCovariance::Identity();\n auto I_KH = I - K * H;\n return I_KH * P * I_KH.transpose() + K * R * K.transpose();\n }\n};\n} // namespace filter_bay", "meta": {"hexsha": "758e4d9f1d6d3680c6ae57acd5b4aefe1fd745db", "size": 2899, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/filter_bay/model/gaussian_observation_model.hpp", "max_stars_repo_name": "Tuebel/filter_bay", "max_stars_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/filter_bay/model/gaussian_observation_model.hpp", "max_issues_repo_name": "Tuebel/filter_bay", "max_issues_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-08-10T14:36:16.000Z", "max_issues_repo_issues_event_max_datetime": "2018-08-21T10:10:08.000Z", "max_forks_repo_path": "include/filter_bay/model/gaussian_observation_model.hpp", "max_forks_repo_name": "Tuebel/filter_bay", "max_forks_repo_head_hexsha": "43728be441c3db0f3001b0d31068ce3c3e01d579", "max_forks_repo_licenses": ["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.5730337079, "max_line_length": 93, "alphanum_fraction": 0.6905829596, "num_tokens": 756, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972751232809, "lm_q2_score": 0.7401743620390162, "lm_q1q2_score": 0.6443937827072803}} {"text": "#include \n#include \n\n#include \n#include \n#include \n\nnamespace fs = std::experimental::filesystem;\n\ntemplate \nbool read_row_help(std::index_sequence, T& row, R& r) {\n return r.read_row(std::get(row)...);\n}\n\ntemplate \nvoid fill_values(std::index_sequence,\n T& row,\n std::vector& data) {\n data.insert(data.end(), {std::get(row)...});\n}\n\nint main(int argc, char** argv) {\n if (argc > 1) {\n auto file_path = fs::path(argv[1]);\n if (fs::exists(file_path)) {\n const uint32_t columns_num = 5;\n io::CSVReader csv_reader(file_path);\n\n std::vector categorical_column;\n std::vector values;\n using RowType = std::tuple;\n RowType row;\n\n uint32_t rows_num = 0;\n try {\n bool done = false;\n while (!done) {\n done = !read_row_help(\n std::make_index_sequence::value>{}, row,\n csv_reader);\n if (!done) {\n categorical_column.push_back(std::get<4>(row));\n fill_values(std::make_index_sequence{}, row,\n values);\n ++rows_num;\n }\n }\n } catch (const io::error::no_digit& err) {\n // ignore bad formated samples\n std::cerr << err.what() << std::endl;\n }\n\n auto x_data = Eigen::Map>(\n values.data(), rows_num, columns_num - 1);\n\n std::cout << x_data << std::endl;\n\n // Feature-scaling(Normalization):\n // Standardization - zero mean + 1 std\n Eigen::Array std_dev =\n ((x_data.rowwise() - x_data.colwise().mean())\n .array()\n .square()\n .colwise()\n .sum() /\n (x_data.rows() - 1))\n .sqrt();\n\n Eigen::Matrix x_data_std =\n (x_data.rowwise() - x_data.colwise().mean()).array().rowwise() /\n std_dev;\n\n std::cout << x_data_std << std::endl;\n\n // Min-Max normalization\n Eigen::Matrix x_data_min_max =\n (x_data.rowwise() - x_data.colwise().minCoeff()).array().rowwise() /\n (x_data.colwise().maxCoeff() - x_data.colwise().minCoeff()).array();\n\n std::cout << x_data_min_max << std::endl;\n\n // Average normalization\n Eigen::Matrix x_data_avg =\n (x_data.rowwise() - x_data.colwise().mean()).array().rowwise() /\n (x_data.colwise().maxCoeff() - x_data.colwise().minCoeff()).array();\n\n std::cout << x_data_avg << std::endl;\n\n } else {\n std::cout << \"File path is incorrect \" << file_path << \"\\n\";\n }\n } else {\n std::cout << \"Please provide a path to a dataset file\\n\";\n }\n\n return 0;\n}\n", "meta": {"hexsha": "9b50be09c8093f5f7686cf043f14d4c5c6662dfe", "size": 3164, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Chapter02/csv/cpp/csv.cc", "max_stars_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_stars_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 201.0, "max_stars_repo_stars_event_min_datetime": "2020-05-13T12:50:50.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-27T20:56:11.000Z", "max_issues_repo_path": "Chapter02/csv/cpp/csv.cc", "max_issues_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_issues_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2021-05-12T10:01:40.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-14T19:35:05.000Z", "max_forks_repo_path": "Chapter02/csv/cpp/csv.cc", "max_forks_repo_name": "bdonkey/Hands-On-Machine-Learning-with-CPP", "max_forks_repo_head_hexsha": "d2b17abeb48db3d45369fdb1be806682ab9819ed", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 63.0, "max_forks_repo_forks_event_min_datetime": "2020-06-05T15:03:39.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-22T02:07:09.000Z", "avg_line_length": 31.9595959596, "max_line_length": 79, "alphanum_fraction": 0.5600505689, "num_tokens": 800, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8705972616934406, "lm_q2_score": 0.740174367770488, "lm_q1q2_score": 0.6443937777566605}} {"text": "#include \r\n#include \r\n#include \r\n#include \"LCPSolve.h\"\r\n\r\nusing namespace Eigen;\r\nusing namespace std;\r\n\r\n// Forward declarations.\r\nbool checkCompatability(const MatrixXd &M, const int &dim);\r\nbool checkTrivialSol(const VectorXd &q);\r\nMatrixXd constructTableau(const MatrixXd &M, const VectorXd &q);\r\nvoid pivot(MatrixXd &tableau, const int &row, const int &col);\r\nint initializeTableau(MatrixXd &tableau);\r\nVectorXd basicVars(const MatrixXd &tableau);\r\nbool checkSol(const MatrixXd &tableau);\r\nbool checkRayTermination(const MatrixXd &tableu, const int &pivotCol);\r\nint minRatioTest(const MatrixXd &tableau, const int &pivotCol);\r\nMatrixXd extractSolution(const MatrixXd &tableau);\r\n\r\n// Solve LCP by Lemke's Method.\r\nLCP LCPSolve(MatrixXd M, VectorXd q) {\r\n const int dim = q.size();\r\n\r\n // Initialize LCP data structure.\r\n LCP solution {};\r\n solution.M = M;\r\n solution.q = q;\r\n\r\n // Check that inputs are compatable.\r\n bool compatable = checkCompatability(M, dim);\r\n if (!compatable) {\r\n solution.exitCond = 2;\r\n return solution;\r\n }\r\n\r\n // Check for trivial solution.\r\n bool trivial = checkTrivialSol(q);\r\n if (trivial) {\r\n solution.z = VectorXd::Zero(dim);\r\n solution.w = q;\r\n solution.exitCond = 0;\r\n return solution;\r\n }\r\n\r\n // Construct & initialize tableau.\r\n MatrixXd tableau = constructTableau(M, q);\r\n VectorXd index = VectorXd::LinSpaced(dim, 0, dim-1);\r\n\r\n int pivotCol = initializeTableau(tableau);\r\n int pivotRow = pivotCol - dim;\r\n index(pivotRow) = 2*dim;\r\n\r\n // Now, the tableau is initialized with a feasible basis. Pivot until there is a feasible basis w/o z0.\r\n const int maxIter {pow(2, dim)};\r\n int iter {0};\r\n bool solFound = false;\r\n while ((!solFound) && (iter < maxIter)) {\r\n // Check for ray termination.\r\n bool rayTermination = checkRayTermination(tableau, pivotCol);\r\n if (rayTermination) {\r\n solFound = true;\r\n } else {\r\n // Minimum ratio test to determine the pivot row (blocked/dropped variable).\r\n pivotRow = minRatioTest(tableau, pivotCol);\r\n pivot(tableau, pivotRow, pivotCol);\r\n int drop = index(pivotRow);\r\n index(pivotRow) = pivotCol;\r\n \r\n // Find next entering variable (pivotCol). Dropped variable is pivotRow.\r\n if (drop > dim-1) {\r\n pivotCol = drop - dim;\r\n } else {\r\n pivotCol = drop + dim;\r\n }\r\n\r\n // Check for solution.\r\n solFound = checkSol(tableau);\r\n iter++;\r\n }\r\n }\r\n\r\n // Return solution.\r\n if (solFound) {\r\n MatrixXd sols = extractSolution(tableau);\r\n solution.z = sols.col(0);\r\n solution.w = sols.col(1);\r\n solution.exitCond = 0;\r\n } else {\r\n MatrixXd sols = extractSolution(tableau);\r\n solution.z = sols.col(0);\r\n solution.w = sols.col(1);\r\n solution.exitCond = 3;\r\n }\r\n \r\n return solution;\r\n}\r\n\r\n\r\n// Check that the inputs M and q are compatable.\r\nbool checkCompatability(const MatrixXd &M, const int &dim) {\r\n const int rows = M.rows();\r\n const int cols = M.cols();\r\n\r\n if (rows != cols)\r\n return false;\r\n else if (rows != dim)\r\n return false;\r\n else\r\n return true;\r\n}\r\n\r\n// Check for trivial solution where q is positive.\r\nbool checkTrivialSol(const VectorXd &q) {\r\n const int dim = q.size();\r\n for (int i = 0; i < dim; i++)\r\n if (q[i] <= 0)\r\n return false;\r\n return true;\r\n}\r\n\r\n// Construct Lemke tableau with auxilillary variable.\r\nMatrixXd constructTableau(const MatrixXd &M, const VectorXd &q) {\r\n const int dim = q.size();\r\n MatrixXd tableau = MatrixXd::Zero(dim, 2*dim + 2); // Initialize with zeros.\r\n VectorXd auxVar = -VectorXd::Ones(dim); // Auxillary variable z_0 = {-1, -1, ... -1}.\r\n tableau.topLeftCorner(dim, dim) = MatrixXd::Identity(dim, dim); // Enter identity matrix on left side (w_1, w_2, etc).\r\n tableau.middleCols(dim, dim) = -M; // Enter I-M (z_1, z_2, etc).\r\n tableau.col(2*dim) = auxVar; // Enter auxiliary variable.\r\n tableau.col(2*dim + 1) = q; // Enter q.\r\n return tableau;\r\n}\r\n\r\n// Pivot function.\r\nvoid pivot(MatrixXd &tableau, const int &row, const int &col) {\r\n const int dim = tableau.rows();\r\n double pivotElement = tableau(row, col);\r\n VectorXd newPivotRow = (1/pivotElement)*tableau.row(row);\r\n tableau.row(row) = newPivotRow;\r\n \r\n VectorXd newNonPivotRow {};\r\n for (int i = 0; i < dim; i++) {\r\n if (i != row) {\r\n newNonPivotRow = tableau.row(i) - tableau(i, col)*tableau.row(row);\r\n tableau.row(i) = newNonPivotRow;\r\n }\r\n }\r\n}\r\n\r\n// Initialize tableau.\r\nint initializeTableau(MatrixXd &tableau) {\r\n const int dim = tableau.rows();\r\n const int cols = 2*dim +2;\r\n\r\n // Pivot row of min element of q w.r.t. aux column.\r\n int minRow {0}; \r\n double minVal = tableau.coeff(minRow, cols-1);\r\n for (int i = 1; i < dim; i++) {\r\n if (tableau.coeff(i, cols-1) < minVal) {\r\n minRow = i;\r\n minVal = tableau(minRow, cols-1);\r\n }\r\n }\r\n\r\n pivot(tableau, minRow, cols-2);\r\n\r\n // Return the next entering variable, which is the complement to the non-basic variable.\r\n int newPivotCol = minRow + dim;\r\n return newPivotCol;\r\n}\r\n\r\n// Return which variables are basic.\r\nVectorXd basicVars(const MatrixXd &tableau) {\r\n int cols = tableau.cols();\r\n double varNorm {};\r\n VectorXd isBasic = VectorXd::Zero(cols - 1);\r\n\r\n double err {1e-8};\r\n for (int i = 0; i < cols - 1; i++) {\r\n varNorm = tableau.col(i).norm();\r\n if (abs(1 - varNorm) < err) {\r\n isBasic[i] = true;\r\n } else {\r\n isBasic[i] = false;\r\n }\r\n }\r\n\r\n return isBasic;\r\n}\r\n\r\n// Check for solution.\r\nbool checkSol(const MatrixXd &tableau) {\r\n\r\n // Determine basic variables.\r\n VectorXd isBasic = basicVars(tableau);\r\n\r\n // Size information and initialize q & z0.\r\n bool solFound {false};\r\n int dim = tableau.rows();\r\n int cols = 2*dim + 2;\r\n VectorXd q = tableau.col(cols-1);\r\n VectorXd z0 = tableau.col(cols-2);\r\n \r\n // No solution if any element of q is negative.\r\n for (int i = 0; i <= dim-1; i++) {\r\n if (q[i] < 0) {\r\n return solFound;\r\n }\r\n }\r\n \r\n // No solution if auxillary variable z0 is basic.\r\n if (isBasic[cols-2] == 1) {\r\n return solFound;\r\n }\r\n \r\n // If q is positive and z0 is non-basic, solution has been found.\r\n solFound = true;\r\n return solFound;\r\n}\r\n\r\n// Check for secondary ray termination.\r\nbool checkRayTermination(const MatrixXd &tableu, const int &pivotCol) {\r\n VectorXd column = tableu.col(pivotCol);\r\n int negTestSum {0};\r\n for (int i {0}; i < column.size(); i++) {\r\n if (column(i) <= 0) {\r\n negTestSum++;\r\n }\r\n }\r\n\r\n if (negTestSum == column.size()) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n}\r\n\r\n// Minimum ratio test to determine pivot row.\r\nint minRatioTest(const MatrixXd &tableau, const int &pivotCol) {\r\n const int dim = tableau.rows();\r\n\r\n VectorXd ratioTest = VectorXd::Zero(dim);\r\n for (int i = 0; i < dim; i++) {\r\n ratioTest[i] = tableau.coeff(i, 2*dim + 1) / tableau.coeff(i, pivotCol);\r\n if (ratioTest[i] < 0) {\r\n ratioTest[i] = 1e10;\r\n }\r\n }\r\n \r\n int pivotRow {0};\r\n double minRatio = ratioTest[0];\r\n for (int i = 1; i < dim; i++) {\r\n if (ratioTest[i] < minRatio) {\r\n minRatio = ratioTest[i];\r\n pivotRow = i;\r\n }\r\n }\r\n\r\n return pivotRow;\r\n}\r\n\r\n// Extract solution from tableau.\r\nMatrixXd extractSolution(const MatrixXd &tableau) {\r\n const int dim = tableau.rows();\r\n MatrixXd A = MatrixXd::Zero(dim, 2*dim);\r\n VectorXd z = VectorXd::Zero(dim);\r\n VectorXd w = VectorXd::Zero(dim);\r\n VectorXd isBasic = basicVars(tableau);\r\n \r\n for (int i = 0; i < 2*dim; i++)\r\n if (isBasic[i] == 1)\r\n A.col(i) = tableau.col(i);\r\n\r\n for (int i = 0; i < 2*dim; i++) {\r\n if (i < dim) {\r\n w[i] = A.col(i).dot(tableau.col(2*dim + 1));\r\n } else {\r\n z[i-dim] = A.col(i).dot(tableau.col(2*dim + 1));\r\n }\r\n }\r\n\r\n MatrixXd sols = MatrixXd::Zero(dim, 2);\r\n sols.col(0) = z;\r\n sols.col(1) = w;\r\n return sols;\r\n}\r\n", "meta": {"hexsha": "8f5da3404484ef0ff97fe8866d4dee62426d9740", "size": 8535, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/LCPSolve.cpp", "max_stars_repo_name": "Tom-Forsyth/LCPSolve", "max_stars_repo_head_hexsha": "046312adbc3dec07b9c58a65d54eea89aec89c12", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/LCPSolve.cpp", "max_issues_repo_name": "Tom-Forsyth/LCPSolve", "max_issues_repo_head_hexsha": "046312adbc3dec07b9c58a65d54eea89aec89c12", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/LCPSolve.cpp", "max_forks_repo_name": "Tom-Forsyth/LCPSolve", "max_forks_repo_head_hexsha": "046312adbc3dec07b9c58a65d54eea89aec89c12", "max_forks_repo_licenses": ["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.7386759582, "max_line_length": 123, "alphanum_fraction": 0.5681312244, "num_tokens": 2257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357666736772, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6443532441146725}} {"text": "\r\n// (C) Copyright John Maddock 2006.\r\n// Use, modification and distribution are subject to the\r\n// Boost Software License, Version 1.0. (See accompanying file\r\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\r\n\r\n#ifndef BOOST_MATH_SPECIAL_LEGENDRE_HPP\r\n#define BOOST_MATH_SPECIAL_LEGENDRE_HPP\r\n\r\n#ifdef _MSC_VER\r\n#pragma once\r\n#endif\r\n\r\n#include \r\n#include \r\n#include \r\n\r\nnamespace boost{\r\nnamespace math{\r\n\r\n// Recurrance relation for legendre P and Q polynomials:\r\ntemplate \r\ninline typename tools::promote_args::type\r\n legendre_next(unsigned l, T1 x, T2 Pl, T3 Plm1)\r\n{\r\n typedef typename tools::promote_args::type result_type;\r\n return ((2 * l + 1) * result_type(x) * result_type(Pl) - l * result_type(Plm1)) / (l + 1);\r\n}\r\n\r\nnamespace detail{\r\n\r\n// Implement Legendre P and Q polynomials via recurrance:\r\ntemplate \r\nT legendre_imp(unsigned l, T x, const Policy& pol, bool second = false)\r\n{\r\n static const char* function = \"boost::math::legrendre_p<%1%>(unsigned, %1%)\";\r\n // Error handling:\r\n if((x < -1) || (x > 1))\r\n return policies::raise_domain_error(\r\n function,\r\n \"The Legendre Polynomial is defined for\"\r\n \" -1 <= x <= 1, but got x = %1%.\", x, pol);\r\n\r\n T p0, p1;\r\n if(second)\r\n {\r\n // A solution of the second kind (Q):\r\n p0 = (boost::math::log1p(x, pol) - boost::math::log1p(-x, pol)) / 2;\r\n p1 = x * p0 - 1;\r\n }\r\n else\r\n {\r\n // A solution of the first kind (P):\r\n p0 = 1;\r\n p1 = x;\r\n }\r\n if(l == 0)\r\n return p0;\r\n\r\n unsigned n = 1;\r\n\r\n while(n < l)\r\n {\r\n std::swap(p0, p1);\r\n p1 = boost::math::legendre_next(n, x, p0, p1);\r\n ++n;\r\n }\r\n return p1;\r\n}\r\n\r\n} // namespace detail\r\n\r\ntemplate \r\ninline typename boost::enable_if_c::value, typename tools::promote_args::type>::type\r\n legendre_p(int l, T x, const Policy& pol)\r\n{\r\n typedef typename tools::promote_args::type result_type;\r\n typedef typename policies::evaluation::type value_type;\r\n static const char* function = \"boost::math::legendre_p<%1%>(unsigned, %1%)\";\r\n if(l < 0)\r\n return policies::checked_narrowing_cast(detail::legendre_imp(-l-1, static_cast(x), pol, false), function);\r\n return policies::checked_narrowing_cast(detail::legendre_imp(l, static_cast(x), pol, false), function);\r\n}\r\n\r\ntemplate \r\ninline typename tools::promote_args::type \r\n legendre_p(int l, T x)\r\n{\r\n return boost::math::legendre_p(l, x, policies::policy<>());\r\n}\r\n\r\ntemplate \r\ninline typename boost::enable_if_c::value, typename tools::promote_args::type>::type\r\n legendre_q(unsigned l, T x, const Policy& pol)\r\n{\r\n typedef typename tools::promote_args::type result_type;\r\n typedef typename policies::evaluation::type value_type;\r\n return policies::checked_narrowing_cast(detail::legendre_imp(l, static_cast(x), pol, true), \"boost::math::legendre_q<%1%>(unsigned, %1%)\");\r\n}\r\n\r\ntemplate \r\ninline typename tools::promote_args::type \r\n legendre_q(unsigned l, T x)\r\n{\r\n return boost::math::legendre_q(l, x, policies::policy<>());\r\n}\r\n\r\n// Recurrence for associated polynomials:\r\ntemplate \r\ninline typename tools::promote_args::type \r\n legendre_next(unsigned l, unsigned m, T1 x, T2 Pl, T3 Plm1)\r\n{\r\n typedef typename tools::promote_args::type result_type;\r\n return ((2 * l + 1) * result_type(x) * result_type(Pl) - (l + m) * result_type(Plm1)) / (l + 1 - m);\r\n}\r\n\r\nnamespace detail{\r\n// Legendre P associated polynomial:\r\ntemplate \r\nT legendre_p_imp(int l, int m, T x, T sin_theta_power, const Policy& pol)\r\n{\r\n // Error handling:\r\n if((x < -1) || (x > 1))\r\n return policies::raise_domain_error(\r\n \"boost::math::legendre_p<%1%>(int, int, %1%)\",\r\n \"The associated Legendre Polynomial is defined for\"\r\n \" -1 <= x <= 1, but got x = %1%.\", x, pol);\r\n // Handle negative arguments first:\r\n if(l < 0)\r\n return legendre_p_imp(-l-1, m, x, sin_theta_power, pol);\r\n if(m < 0)\r\n {\r\n int sign = (m&1) ? -1 : 1;\r\n return sign * boost::math::tgamma_ratio(static_cast(l+m+1), static_cast(l+1-m), pol) * legendre_p_imp(l, -m, x, sin_theta_power, pol);\r\n }\r\n // Special cases:\r\n if(m > l)\r\n return 0;\r\n if(m == 0)\r\n return boost::math::legendre_p(l, x, pol);\r\n\r\n T p0 = boost::math::double_factorial(2 * m - 1, pol) * sin_theta_power;\r\n\r\n if(m&1)\r\n p0 *= -1;\r\n if(m == l)\r\n return p0;\r\n\r\n T p1 = x * (2 * m + 1) * p0;\r\n\r\n int n = m + 1;\r\n\r\n while(n < l)\r\n {\r\n std::swap(p0, p1);\r\n p1 = boost::math::legendre_next(n, m, x, p0, p1);\r\n ++n;\r\n }\r\n return p1;\r\n}\r\n\r\ntemplate \r\ninline T legendre_p_imp(int l, int m, T x, const Policy& pol)\r\n{\r\n BOOST_MATH_STD_USING\r\n // TODO: we really could use that mythical \"pow1p\" function here:\r\n return legendre_p_imp(l, m, x, static_cast(pow(1 - x*x, T(abs(m))/2)), pol);\r\n}\r\n\r\n}\r\n\r\ntemplate \r\ninline typename tools::promote_args::type\r\n legendre_p(int l, int m, T x, const Policy& pol)\r\n{\r\n typedef typename tools::promote_args::type result_type;\r\n typedef typename policies::evaluation::type value_type;\r\n return policies::checked_narrowing_cast(detail::legendre_p_imp(l, m, static_cast(x), pol), \"bost::math::legendre_p<%1%>(int, int, %1%)\");\r\n}\r\n\r\ntemplate \r\ninline typename tools::promote_args::type\r\n legendre_p(int l, int m, T x)\r\n{\r\n return boost::math::legendre_p(l, m, x, policies::policy<>());\r\n}\r\n\r\n} // namespace math\r\n} // namespace boost\r\n\r\n#endif // BOOST_MATH_SPECIAL_LEGENDRE_HPP\r\n\r\n\r\n\r\n", "meta": {"hexsha": "dc0154238ab98a40cd89bbf535a8feea9bd92f33", "size": 6167, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/legendre.hpp", "max_stars_repo_name": "rudylee/expo", "max_stars_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_stars_repo_licenses": ["Apache-2.0", "MIT"], "max_stars_count": 8805.0, "max_stars_repo_stars_event_min_datetime": "2015-11-03T00:52:29.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T22:30:03.000Z", "max_issues_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/legendre.hpp", "max_issues_repo_name": "rudylee/expo", "max_issues_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_issues_repo_licenses": ["Apache-2.0", "MIT"], "max_issues_count": 14694.0, "max_issues_repo_issues_event_min_datetime": "2015-02-24T15:13:42.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T13:16:45.000Z", "max_forks_repo_path": "ios/Pods/boost-for-react-native/boost/math/special_functions/legendre.hpp", "max_forks_repo_name": "rudylee/expo", "max_forks_repo_head_hexsha": "b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc", "max_forks_repo_licenses": ["Apache-2.0", "MIT"], "max_forks_count": 1329.0, "max_forks_repo_forks_event_min_datetime": "2015-11-03T20:25:51.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T18:10:38.000Z", "avg_line_length": 31.6256410256, "max_line_length": 176, "alphanum_fraction": 0.6377493108, "num_tokens": 1821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8670357598021707, "lm_q2_score": 0.7431680086124811, "lm_q1q2_score": 0.6443532390079887}} {"text": "#include \"srrg_geometry/geometry3d.h\"\n#include \n#include \n#include \"srrg_autodiff/ad_multivariate.h\"\n\nusing namespace std;\nusing namespace srrg2_core;\nusing namespace srrg2_core::geometry3d;\n\nusing namespace Eigen;\n\ntypedef srrg2_core::Vector2ad Vector2adf;\ntypedef srrg2_core::Vector3ad Vector3adf;\ntypedef srrg2_core::Vector6ad Vector6adf;\ntypedef srrg2_core::Matrix3ad Matrix3adf;\ntypedef srrg2_core::DualValue_ DualValuef;\ntypedef srrg2_core::Isometry3ad Isometry3adf;\n\n\n\n \ntemplate \nclass TransformPoint: public MultivariateFunction{\npublic:\n void operator()(Scalar_* output, const Scalar_* input){\n\n // this maps the memory area in the input array to an\n // Eigen vector of dimension 6\n // if you feel uncomfy, you can\n // allocate an array\n // Vector6 robot_pose;\n // fill the elements with a for loop\n // for (int i=0; i<6; i++) robot_pose[i]=input[i];\n Eigen::Map > robot_pose(input);\n\n // this maps the memory area in the output array to an\n // Eigen vector of dimension 3\n // Changing the Eigen object would result\n // in doing side effect to the memory area\n Eigen::Map > projected_point(output);\n\n \n // compute the rotation matrix and translation vector\n // encoded in robot_pose\n Isometry3_ robot_pose_matrix=v2t(robot_pose);\n \n // compute the positionof the point w.r.t. the world,\n // by multiplying it by a transformation matrix \n projected_point=robot_pose_matrix*point;\n }\n\n // this is the parameter\n Eigen::Matrix point;\n};\n\n\n// this is our function that supports the multivariate autodiff\nADMultivariateFunction ad_project_point;\n\n\n \ntemplate \nclass TransformMovingPoint: public MultivariateFunction{\npublic:\n void operator()(Scalar_* output, const Scalar_* input){\n\n // this maps the memory area in the input array to an\n // Eigen vector of dimension 6\n // if you feel uncomfy, you can\n // allocate an array\n // Vector6 robot_pose;\n // fill the elements with a for loop\n // for (int i=0; i<6; i++) robot_pose[i]=input[i];\n Eigen::Map > robot_pose(input);\n Eigen::Map > point(input+6);\n\n \n // this maps the memory area in the output array to an\n // Eigen vector of dimension 3\n // Changing the Eigen object would result\n // in doing side effect to the memory area\n Eigen::Map > projected_point(output);\n\n \n // compute the rotation matrix and translation vector\n // encoded in robot_pose\n Isometry3_ robot_pose_matrix=v2t(robot_pose);\n \n // compute the positionof the point w.r.t. the world,\n // by multiplying it by a transformation matrix \n projected_point=robot_pose_matrix*point;\n }\n};\n\ntemplate \nclass TransformMovingPoint2: public MultivariateFunction{\npublic:\n void operator()(Scalar_* output, const Scalar_* input){\n\n // this maps the memory area in the input array to an\n // Eigen vector of dimension 6\n // if you feel uncomfy, you can\n // allocate an array\n // Vector6 robot_pose;\n // fill the elements with a for loop\n // for (int i=0; i<6; i++) robot_pose[i]=input[i];\n Eigen::Map > robot_pose_pert(input);\n Eigen::Map > point_pert(input+6);\n\n \n // this maps the memory area in the output array to an\n // Eigen vector of dimension 3\n // Changing the Eigen object would result\n // in doing side effect to the memory area\n Eigen::Map > projected_point(output);\n\n \n // compute the rotation matrix and translation vector\n // encoded in robot_pose\n Isometry3_ robot_pose_matrix=v2t(robot_pose_pert)*_robot_pose;\n \n // compute the positionof the point w.r.t. the world,\n // by multiplying it by a transformation matrix \n projected_point=robot_pose_matrix*(_point+point_pert);\n }\n Isometry3_ _robot_pose;\n Vector3_ _point;\n};\n\n\n\n// this is our function that supports the multivariate autodiff\nADMultivariateFunction ad_move_point;\n\nADMultivariateFunction ad_move_point_manifold;\n\nint main(int argc, char** argv){\n ad_project_point.point<<1,2,3;\n ad_project_point.point<<1,2,3;\n\n Eigen::Matrix v;\n v << 0,0,0,0,0,0;\n \n Eigen::Matrix output;\n Eigen::Matrix jacobian;\n \n ad_project_point(&output[0], &v[0]);\n jacobian=ad_project_point.jacobian(&v[0]);\n\n cerr << \"output: \" << endl;\n cerr << output.transpose() << endl;\n cerr << \"jacobian: \" << endl;\n cerr << jacobian << endl;\n\n cerr << endl << endl;\n Eigen::Matrix pose_and_point;\n Eigen::Matrix jacobian_move;\n pose_and_point.head<6>()=v;\n pose_and_point.tail<3>() << 1,2,3;\n cerr << \"pose_and_point: \" <\n\nusing namespace boost::math;\nusing namespace boost::math::tools; // for polynomial\n\nInfiniteRoots::InfiniteRoots(int L, int M) {\n _L = L;\n _M = M;\n _roots.resize(M);\n}\n\nstd::vector& InfiniteRoots::getRoot(int m)\n{\n if (_roots[m-1].size() == 0) {\n computeRoots(m);\n }\n \n return _roots[m-1];\n}\n\nstd::vector InfiniteRoots::equationSolver(std::vector &coefs, std::vector &out) {\n if (coefs.size() == 2) {\n return { -coefs[0]/coefs[1] };\n }\n if (coefs.size() <= 1) {\n return {};\n }\n \n PolynomialFunction target(coefs);\n UnityEquation start(1, coefs.size() - 1);\n \n SimpleHomotopy hom(&start, &target);\n hom.setSteps(coefs.size() * 300);\n hom.setRandSeed(coefs.size());\n SimpleHomotopyContinuation hc;\n \n std::vector ret;\n \n for (int i = 0; i < start.numberOfRoots(); i++) {\n Vector root = start.getRoot(i);\n Solution sol(root);\n hc.solve(hom, sol);\n bool found = false;\n for (int j = 0; j < ret.size(); j++) {\n if (std::abs(ret[j] - sol.get(0)) < EPS) {\n found = true;\n break;\n }\n }\n if (!found) {\n ret.push_back(sol.get(0));\n }\n }\n \n // it produced some duplicated roots\n if (ret.size() < start.numberOfRoots()) {\n polynomial eq(coefs.begin(), coefs.end());\n polynomial eq2 {{var_t(1.0L, 0.0L)}};\n for (int i = 0; i < ret.size(); i++) {\n polynomial solved {{-ret[i], var_t(1.0L, 0)}}; \n eq2 *= solved;\n }\n polynomial eq3 = eq / eq2;\n out = eq3.data();\n }\n return ret;\n}\n\nvoid InfiniteRoots::computeRoots(int m) {\n std::vector coefs(m + 1);\n elem_t r = 1.0L;\n int R = _L - 2 * _M + 2 * m;\n for (int i = 0; i <= m; i++) {\n coefs[i] = var_t(r, 0.0L);\n r *= -(m-i) * (2 * _L) / (elem_t)((R - i) * (i+1));\n }\n reverse(coefs.begin(), coefs.end());\n while (true) {\n std::vector remain;\n std::vector res = equationSolver(coefs, remain);\n _roots[m-1].insert(_roots[m-1].end(), res.begin(), res.end());\n// std::cout << \"roots=\" << _roots[m-1] << \" remain=\" << remain << std::endl;\n if (remain.size() <= 1) break;\n coefs = remain;\n }\n}\n", "meta": {"hexsha": "1dd49a8f91b5f7b28433b8b9d7ed253c37d05dfc", "size": 2482, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/InfiniteRoots.cpp", "max_stars_repo_name": "gaolichen/bethesolver", "max_stars_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/InfiniteRoots.cpp", "max_issues_repo_name": "gaolichen/bethesolver", "max_issues_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/InfiniteRoots.cpp", "max_forks_repo_name": "gaolichen/bethesolver", "max_forks_repo_head_hexsha": "1b4f0c097ed028e1a52f05fda034e2864eb37d24", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.8876404494, "max_line_length": 102, "alphanum_fraction": 0.5221595488, "num_tokens": 774, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8740772417253255, "lm_q2_score": 0.7371581684030623, "lm_q1q2_score": 0.6443331785530416}} {"text": "// Copyright (c) 2014 Max Planck Society\n\n#include \"math_tools.h\"\n#include \n#include \n#include \n#include \n#include \n\nnamespace math_tools {\n\n\nEigen::MatrixXd squareDistance(const Eigen::MatrixXd& a,\n const Eigen::MatrixXd& b) {\n int aRows = a.rows();\n int aCols = a.cols();\n int bCols = b.cols();\n\n Eigen::MatrixXd am(aRows, aCols); // mean-corrected a\n Eigen::MatrixXd bm(aRows, bCols); // mean-corrected b\n // final result, aCols x bCols\n Eigen::MatrixXd result(aCols, bCols);\n\n Eigen::VectorXd mean(aRows);\n\n /* If the two Matrices have the same address, it means the function was\n called from the overloaded version, and thus the mean only has to be\n computed once.\n */\n if (&a == &b) { // Same address?\n mean = a.rowwise().mean();\n am = a.colwise() - mean;\n bm = am;\n } else {\n if (aRows != b.rows()) {\n throw std::runtime_error(\"Matrix dimension incorrect.\");\n }\n\n mean = static_cast(aCols) / (aCols + bCols) * a.rowwise().mean() +\n static_cast(bCols) / (bCols + aCols) * b.rowwise().mean();\n\n // The mean of the two Matrices is subtracted beforehand, because the\n // squared error is independent of the mean and this makes the squares\n // smaller.\n am = a.colwise() - mean;\n bm = b.colwise() - mean;\n }\n\n Eigen::MatrixXd a_square =\n am.array().square().colwise()\n .sum().transpose().rowwise() .replicate(bCols);\n\n Eigen::MatrixXd b_square = bm.array().square().colwise().sum().colwise()\n .replicate(aCols);\n\n Eigen::MatrixXd twoab = 2 * (am.transpose()) * bm;\n\n return (a_square.matrix() + b_square.matrix()) - twoab;\n}\n\nEigen::MatrixXd squareDistance(const Eigen::MatrixXd& a) {\n return squareDistance(a, a);\n}\n\nEigen::MatrixXd generate_random_sequence(int d, int n) {\n // x = randn(d,1); % starting sample\n Eigen::VectorXd x = math_tools::generate_normal_random_matrix(d, 1);\n\n Eigen::VectorXd t = math_tools::generate_normal_random_matrix(d, 1);\n\n return generate_random_sequence(n, x, t);\n}\n\nEigen::MatrixXd generate_random_sequence(int n, Eigen::VectorXd x,\n Eigen::VectorXd t) {\n// function X = GPanimation(d,n)\n// % returns a matrix X of size [d,n], representing a grand circle on the\n// % unit d-sphere in n steps, starting at a random location. Given a kernel\n// % matrix K, this can be turned into a tour through the sample space, simply\n// % by calling chol(K)’ * X;\n// %\n// % Philipp Hennig, September 2012\n\n\n// r = sqrt(sum(x.^2));\n double r = std::sqrt(x.transpose() * x);\n\n// x = x ./ r; % project onto sphere\n x = x / r;\n\n// t = randn(d,1); % sample tangent direction\n\n// t = t - (t'*x) * x; % orthogonalise by Gram-Schmidt.\n double tmp = t.adjoint() * x;\n t = t - tmp * x;\n\n// t = t ./ sqrt(sum(t.^2)); % standardise\n t = t / std::sqrt(t.transpose() * t);\n\n// s = linspace(0,2*pi,n+1); s = s(1:end-1); % space to span\n Eigen::VectorXd s(n + 1);\n s.setLinSpaced(n + 1, 0, 2 * M_PI);\n s.conservativeResize(s.rows() - 1);\n\n// t = bsxfun(@times,s,t); % span linspace in direction of t\n// std::cout << (s.transpose().replicate(t.rows(),1)).format(OctaveFmt) <<\n// std::endl;\n// std::cout << (t.replicate(1,s.rows())).format(OctaveFmt) <<\n// std::endl;\n\n Eigen::MatrixXd T = s.transpose().replicate(t.rows(), 1)\n .cwiseProduct(t.replicate(1, s.rows()));\n\n// X = r.* exp_map(x,t); % project onto sphere, re-scale\n Eigen::MatrixXd X = r * exp_map(x, T);\n// end\n return X;\n}\n\nEigen::MatrixXd exp_map(const Eigen::VectorXd& mu, const Eigen::MatrixXd& E) {\n// D = size(E,1);\n int D = E.rows();\n\n// theta = sqrt(sum((E.^2)));\n Eigen::MatrixXd theta = E.array().pow(2).colwise().sum().sqrt();\n\n// M = mu * cos(theta) + E .* repmat(sin(theta)./theta, D, 1);\n Eigen::MatrixXd M = mu * theta.array().cos().matrix() +\n E.cwiseProduct(\n (theta.array().sin() / theta.array())\n .matrix().replicate(D, 1));\n\n// if (any (abs (theta) <= 1e-7))\n// for a = find (abs (theta) <= 1e-7)\n// M (:, a) = mu;\n// end % for\n// end % if\n for (int i = 0; i < theta.cols(); i++) {\n if (theta(0, i) < MINIMAL_THETA) {\n M.col(i) = mu;\n }\n }\n\n// end % function\n return M;\n}\n\nEigen::MatrixXd generate_uniform_random_matrix_0_1(\n const size_t n,\n const size_t m) {\n Eigen::MatrixXd result = Eigen::MatrixXd(n, m);\n result.setRandom();\n Eigen::MatrixXd temp = result.array() + 1;\n result = temp / 2.0;\n result = result.array().max(1e-10);\n result = result.array().min(1.0);\n return result;\n}\n\nEigen::MatrixXd box_muller(const Eigen::VectorXd &vRand) {\n size_t n = vRand.rows();\n size_t m = n / 2;\n\n Eigen::ArrayXd rand1 = vRand.head(m);\n Eigen::ArrayXd rand2 = vRand.tail(m);\n\n /* Implemented according to\n * http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform\n */\n\n rand1 = rand1.max(1e-10);\n rand1 = rand1.min(1.0);\n\n rand1 = -2 * rand1.log();\n rand1 = rand1.sqrt();\n\n rand2 = rand2 * 2 * M_PI;\n\n Eigen::MatrixXd result(2 * m, 1);\n Eigen::MatrixXd res1 = (rand1 * rand2.cos()).matrix();\n Eigen::MatrixXd res2 = (rand1 * rand2.sin()).matrix();\n result << res1, res2;\n\n return result;\n}\n\nEigen::MatrixXd generate_normal_random_matrix(\n const size_t n,\n const size_t m) {\n // if n*m is odd, we need one random number extra!\n // therefore, we have to round up here.\n size_t N = static_cast(std::ceil(n * m / 2.0));\n\n Eigen::MatrixXd result(2 * N, 1);\n // push random samples through the Box-Muller transform\n result = box_muller(generate_uniform_random_matrix_0_1(2 * N, 1));\n result.conservativeResize(n, m);\n return result;\n}\n\ndouble generate_normal_random_double() {\n Eigen::MatrixXd randomMatrix = generate_normal_random_matrix(1, 1);\n return randomMatrix(0,0);\n}\n\n} // namespace math_tools\n\n\n\n\n\n", "meta": {"hexsha": "887bb1f613a5a8b13b46f35045af943f0bcb3352", "size": 5885, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "contributions/MPI_IS_gaussian_process/tools/math_tools.cpp", "max_stars_repo_name": "iphantomsky/open-phd-guiding", "max_stars_repo_head_hexsha": "41f6f277cd2a2efd25dc198eae3206cf95102608", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "contributions/MPI_IS_gaussian_process/tools/math_tools.cpp", "max_issues_repo_name": "iphantomsky/open-phd-guiding", "max_issues_repo_head_hexsha": "41f6f277cd2a2efd25dc198eae3206cf95102608", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "contributions/MPI_IS_gaussian_process/tools/math_tools.cpp", "max_forks_repo_name": "iphantomsky/open-phd-guiding", "max_forks_repo_head_hexsha": "41f6f277cd2a2efd25dc198eae3206cf95102608", "max_forks_repo_licenses": ["BSD-3-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.7594339623, "max_line_length": 78, "alphanum_fraction": 0.6178419711, "num_tokens": 1733, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9005297941266014, "lm_q2_score": 0.7154239957834733, "lm_q1q2_score": 0.6442606236361217}} {"text": "#include \n#include \n#include \n#include \"jefflib.h\" \n#include \n\nusing namespace std;\n\nint getHundred(int x){\n string s = to_string(x);\n if(s.size()>= 3){\n return stoi(s.substr(s.size() - 3, 1));\n }\n else{\n return 0;\n }\n}\n\nint main()\n{\n int rack = 0;\n int pwr = 0;\n int maxPwr = 0;\n int maxX = 0;\n int maxY = 0;\n int serialNum = 2568;\n int grid[301][301];\n\n for(int x = 1; x <= 300; x++){\n for(int y = 1; y <= 300; y++){\n rack = x + 10;\n pwr = rack * y;\n pwr += serialNum;\n pwr *= rack;\n pwr = getHundred(pwr) - 5;\n grid[x][y] = pwr;\n }\n }\n\n for(int x = 1; x <= 298; x++){\n for(int y = 1; y <= 298; y++){\n pwr = grid[x][y] + grid[x+1][y] + grid[x+2][y];\n pwr = pwr + grid[x][y+1] + grid[x+1][y+1] + grid[x+2][y+1];\n pwr = pwr + grid[x][y+2] + grid[x+1][y+2] + grid[x+2][y+2];\n if(pwr > maxPwr){\n maxPwr = pwr;\n maxX = x;\n maxY = y;\n }\n }\n }\n cout << \"Part 1: Max power cell = \" << maxX << \", \" << maxY << endl; \n\n // Part 2\n maxPwr = 0;\n int maxSz = 0;\n for(int x = 1; x <= 300; x++){\n cout << x << \": \";\n for(int y = 1; y <= 300; y++){\n cout << y;\n // For each cell, calc power for all the valid square sizes\n int maxDim = 0;\n int maxXDim = 300 - x + 1;\n int maxYDim = 300 - y + 1;\n if(maxXDim > maxYDim){\n maxDim = maxYDim;\n } \n else{\n maxDim = maxXDim;\n }\n\n for(int sz = 1; sz <= maxDim; sz++){\n pwr = 0;\n for(int row = 0; row < sz; row++){\n for(int col = 0; col < sz; col++){\n pwr = pwr + grid[x+col][y+row];\n }\n }\n if(pwr > maxPwr){\n maxPwr = pwr;\n maxSz = sz;\n maxX = x;\n maxY = y;\n }\n }\n }\n cout << endl;\n }\n cout << \"Part 2: Max power cell = \" << maxX << \",\" << maxY << \",\" << maxSz << endl;\n}\n\n\n", "meta": {"hexsha": "cddcefa903d8120b94b3644836ceb05502fd9144", "size": 2317, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "jeff/day-11/part-1.cpp", "max_stars_repo_name": "jeffphi/advent-of-code-2018", "max_stars_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-23T01:40:07.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-23T01:40:07.000Z", "max_issues_repo_path": "jeff/day-11/part-1.cpp", "max_issues_repo_name": "jeffphi/advent-of-code-2018", "max_issues_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "jeff/day-11/part-1.cpp", "max_forks_repo_name": "jeffphi/advent-of-code-2018", "max_forks_repo_head_hexsha": "8e54bd23ebfe42fcbede315f0ab85db903551532", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.9139784946, "max_line_length": 87, "alphanum_fraction": 0.369011653, "num_tokens": 697, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587964389112, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6442348395116625}} {"text": "#include \"kak.hpp\"\n#include \"IRProvider.hpp\"\n#include \"xacc.hpp\"\n#include \"xacc_service.hpp\"\n#include \n#include \n#include \n#include \"PauliOperator.hpp\"\n\nnamespace {\nconstexpr std::complex I { 0.0, 1.0 };\nint getTempId()\n{\n static int tempIdCounter = 0;\n tempIdCounter++;\n return tempIdCounter;\n}\n\n// Define some special matrices\nconst Eigen::MatrixXcd& KAK_MAGIC() \n{\n static Eigen::MatrixXcd KAK_MAGIC(4, 4);\n static bool init = false;\n if (!init)\n {\n KAK_MAGIC << 1, 0, 0, I,\n 0, I, 1, 0,\n 0, I, -1, 0,\n 1, 0, 0, -I;\n KAK_MAGIC = KAK_MAGIC * std::sqrt(0.5); \n init = true;\n }\n\n return KAK_MAGIC;\n}\n\nconst Eigen::MatrixXcd& KAK_MAGIC_DAG() \n{\n static Eigen::MatrixXcd KAK_MAGIC_DAG = KAK_MAGIC().adjoint();\n return KAK_MAGIC_DAG;\n}\n \nconst Eigen::MatrixXcd& KAK_GAMMA()\n{\n static Eigen::MatrixXcd KAK_GAMMA(4, 4);\n static bool init = false;\n if (!init)\n {\n KAK_GAMMA << 1, 1, 1, 1,\n 1, 1, -1, -1,\n -1, 1, -1, 1,\n 1, -1, -1, 1;\n KAK_GAMMA = 0.25 * KAK_GAMMA;\n init = true;\n }\n\n return KAK_GAMMA;\n}\n\n// Splits i = 0...length into approximate equivalence classes\n// determine by the predicate\nstd::vector> contiguousGroups(int in_length, std::function in_predicate)\n{\n int start = 0;\n std::vector> result;\n while(start < in_length)\n {\n auto past = start + 1;\n while ((past < in_length) && in_predicate(start, past))\n {\n past++; \n }\n result.emplace_back(start, past);\n start = past;\n }\n return result;\n}\n\nEigen::MatrixXd blockDiag(const Eigen::MatrixXd& in_first, const Eigen::MatrixXd& in_second)\n{\n Eigen::MatrixXd bdm = Eigen::MatrixXd::Zero(in_first.rows() + in_second.rows(), in_first.cols() + in_second.cols());\n bdm.block(0, 0, in_first.rows(), in_first.cols()) = in_first;\n bdm.block(in_first.rows(), in_first.cols(), in_second.rows(), in_second.cols()) = in_second;\n return bdm;\n}\n\ninline bool isSquare(const Eigen::MatrixXcd& in_mat)\n{\n return in_mat.rows() == in_mat.cols();\n}\n\n// If the matrix is finite: no NaN elements\ntemplate\ninline bool isFinite(const Eigen::MatrixBase& x)\n{\n return ((x - x).array() == (x - x).array()).all();\n}\n\nbool isDiagonal(const Eigen::MatrixXcd& in_mat, double in_tol = 1e-9)\n{\n if (!isFinite(in_mat))\n {\n return false;\n }\n\n for (int i = 0; i < in_mat.rows(); ++i)\n {\n for (int j = 0; j < in_mat.cols(); ++j)\n {\n if (i != j)\n {\n if (std::abs(in_mat(i,j)) > in_tol)\n {\n return false;\n }\n }\n }\n }\n\n return true;\n}\n\nbool allClose(const Eigen::MatrixXcd& in_mat1, const Eigen::MatrixXcd& in_mat2, double in_tol = 1e-9)\n{\n if (!isFinite(in_mat1) || !isFinite(in_mat2))\n {\n return false;\n }\n\n if (in_mat1.rows() == in_mat2.rows() && in_mat1.cols() == in_mat2.cols())\n {\n for (int i = 0; i < in_mat1.rows(); ++i)\n {\n for (int j = 0; j < in_mat1.cols(); ++j)\n {\n if (std::abs(in_mat1(i,j) - in_mat2(i, j)) > in_tol)\n {\n return false;\n }\n }\n }\n\n return true;\n }\n return false;\n}\n\nbool isHermitian(const Eigen::MatrixXcd& in_mat)\n{\n if (!isSquare(in_mat) || !isFinite(in_mat))\n {\n return false;\n }\n return allClose(in_mat, in_mat.adjoint());\n}\n\nbool isUnitary(const Eigen::MatrixXcd& in_mat)\n{\n if (!isSquare(in_mat) || !isFinite(in_mat))\n {\n return false;\n }\n\n Eigen::MatrixXcd Id = Eigen::MatrixXcd::Identity(in_mat.rows(), in_mat.cols());\n\n return allClose(in_mat * in_mat.adjoint(), Id);\n}\n\nbool isOrthogonal(const Eigen::MatrixXcd& in_mat, double in_tol = 1e-9)\n{\n if (!isSquare(in_mat) || !isFinite(in_mat))\n {\n return false;\n }\n\n // Is real \n for (int i = 0; i < in_mat.rows(); ++i)\n {\n for (int j = 0; j < in_mat.cols(); ++j)\n {\n if (std::abs(in_mat(i,j).imag()) > in_tol)\n {\n return false;\n }\n }\n }\n // its transpose is its inverse\n return allClose(in_mat.inverse(), in_mat.transpose(), in_tol);\n}\n// Is Orthogonal and determinant == 1\nbool isSpecialOrthogonal(const Eigen::MatrixXcd& in_mat, double in_tol = 1e-9)\n{\n return isOrthogonal(in_mat, in_tol) && (std::abs(std::abs(in_mat.determinant()) - 1.0) < in_tol);\n}\n\nbool isCanonicalized(double x, double y, double z)\n{\n // 0 ≤ abs(z) ≤ y ≤ x ≤ pi/4\n // if x = pi/4, z >= 0\n const double TOL = 1e-9;\n if (std::abs(z) >= 0 && y >= std::abs(z) && x >= y && x <= M_PI_4 + TOL)\n {\n if (std::abs(x - M_PI_4) < TOL)\n {\n return (z >= 0);\n }\n return true;\n }\n return false;\n}\n// Compute exp(i(x XX + y YY + z ZZ)) matrix\nEigen::Matrix4cd interactionMatrixExp(double x, double y, double z)\n{\n Eigen::MatrixXcd X { Eigen::MatrixXcd::Zero(2, 2)}; \n Eigen::MatrixXcd Y { Eigen::MatrixXcd::Zero(2, 2)}; \n Eigen::MatrixXcd Z { Eigen::MatrixXcd::Zero(2, 2)}; \n X << 0, 1, 1, 0;\n Y << 0, -I, I, 0;\n Z << 1, 0, 0, -1;\n auto XX = Eigen::kroneckerProduct(X, X);\n auto YY = Eigen::kroneckerProduct(Y, Y);\n auto ZZ = Eigen::kroneckerProduct(Z, Z);\n Eigen::MatrixXcd herm = x*XX + y*YY + z*ZZ;\n herm = I*herm;\n Eigen::MatrixXcd unitary = herm.exp();\n return unitary;\n}\n\n// Simplify the Z-Y-Z decomposition:\n// i.e. combining rotations and removing trivial rotation\nstd::shared_ptr simplifySingleQubitSeq(double zAngleBefore, double yAngle, double zAngleAfter, size_t bitIdx)\n{\n auto zExpBefore = zAngleBefore / M_PI - 0.5;\n auto middleExp = yAngle / M_PI;\n std::string middlePauli = \"Rx\";\n auto zExpAfter = zAngleAfter / M_PI + 0.5;\n \n // Helper functions:\n const auto isNearZeroMod = [](double a, double period) -> bool {\n const auto halfPeriod = period / 2;\n const double TOL = 1e-8;\n return std::abs(fmod(a + halfPeriod, period) - halfPeriod) < TOL;\n };\n \n const auto toQuarterTurns = [](double in_exp) -> int {\n return static_cast(round(2 * in_exp)) % 4;\n }; \n\n const auto isCliffordRotation = [&](double in_exp) -> bool {\n return isNearZeroMod(in_exp, 0.5);\n };\n\n const auto isQuarterTurn = [&](double in_exp) -> bool {\n return (isCliffordRotation(in_exp) && toQuarterTurns(in_exp) % 2 == 1);\n };\n\n const auto isHalfTurn = [&](double in_exp) -> bool {\n return (isCliffordRotation(in_exp) && toQuarterTurns(in_exp) == 2);\n };\n\n const auto isNoTurn = [&](double in_exp) -> bool {\n return (isCliffordRotation(in_exp) && toQuarterTurns(in_exp) == 0);\n };\n\n // Clean up angles\n if (isCliffordRotation(zExpBefore)) \n {\n if ((isQuarterTurn(zExpBefore) || isQuarterTurn(zExpAfter)) != (isHalfTurn(middleExp) && isNoTurn(zExpBefore-zExpAfter)))\n {\n zExpBefore += 0.5;\n zExpAfter -= 0.5;\n middlePauli = \"Ry\";\n }\n if (isHalfTurn(zExpBefore) || isHalfTurn(zExpAfter))\n {\n zExpBefore -= 1;\n zExpAfter += 1;\n middleExp = -middleExp;\n } \n }\n if (isNoTurn(middleExp))\n {\n zExpBefore += zExpAfter;\n zExpAfter = 0;\n } \n else if (isHalfTurn(middleExp))\n {\n zExpAfter -= zExpBefore;\n zExpBefore = 0;\n }\n \n auto gateRegistry = xacc::getService(\"quantum\"); \n auto composite = gateRegistry->createComposite(\"__TEMP__COMPOSITE__\" + std::to_string(getTempId()));\n \n if (!isNoTurn(zExpBefore))\n {\n composite->addInstruction(gateRegistry->createInstruction(\"Rz\", { bitIdx }, { zExpBefore * M_PI }));\n }\n if (!isNoTurn(middleExp))\n {\n composite->addInstruction(gateRegistry->createInstruction(middlePauli, { bitIdx }, { middleExp * M_PI }));\n }\n if (!isNoTurn(zExpAfter))\n {\n composite->addInstruction(gateRegistry->createInstruction(\"Rz\", { bitIdx }, { zExpAfter * M_PI }));\n }\n\n return composite;\n}\n\n\nstd::shared_ptr singleQubitGateGen(const Eigen::Matrix2cd& in_mat, size_t in_bitIdx) \n{\n using GateMatrix = Eigen::Matrix2cd;\n auto gateRegistry = xacc::getService(\"quantum\");\n\n // Use Z-Y decomposition of Nielsen and Chuang (Theorem 4.1).\n // An arbitrary one qubit gate matrix can be written as\n // U = [ exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)\n // exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]\n // where a,b,c,d are real numbers.\n const auto singleQubitGateDecompose = [](const Eigen::Matrix2cd& matrix) -> std::tuple {\n if (allClose(matrix, GateMatrix::Identity()))\n {\n return std::make_tuple(0.0, 0.0, 0.0, 0.0);\n }\n const auto checkParams = [&matrix](double a, double bHalf, double cHalf, double dHalf) {\n GateMatrix U;\n U << std::exp(I*(a-bHalf-dHalf))*std::cos(cHalf),\n -std::exp(I*(a-bHalf+dHalf))*std::sin(cHalf),\n std::exp(I*(a+bHalf-dHalf))*std::sin(cHalf),\n std::exp(I*(a+bHalf+dHalf))*std::cos(cHalf);\n\n return allClose(U, matrix); \n };\n \n double a, bHalf, cHalf, dHalf;\n const double TOLERANCE = 1e-9;\n if (std::abs(matrix(0, 1)) < TOLERANCE)\n {\n auto two_a = fmod(std::arg(matrix(0, 0)*matrix(1, 1)), 2*M_PI);\n a = (std::abs(two_a) < TOLERANCE || std::abs(two_a) > 2*M_PI-TOLERANCE) ? 0 : two_a/2.0;\n auto dHalf = 0.0; \n auto b = std::arg(matrix(1, 1))-std::arg(matrix(0, 0));\n std::vector possibleBhalf { fmod(b/2.0, 2 * M_PI), fmod(b/2.0 + M_PI, 2.0 * M_PI) };\n std::vector possibleChalf { 0.0, M_PI };\n bool found = false;\n for (int i = 0; i < possibleBhalf.size(); ++i)\n {\n for (int j = 0; j < possibleChalf.size(); ++j)\n {\n bHalf = possibleBhalf[i];\n cHalf = possibleChalf[j];\n if (checkParams(a, bHalf, cHalf, dHalf))\n {\n found = true;\n break;\n }\n }\n if (found)\n {\n break;\n }\n }\n assert(found);\n }\n else if (std::abs(matrix(0, 0)) < TOLERANCE)\n {\n auto two_a = fmod(std::arg(-matrix(0, 1)*matrix(1, 0)), 2*M_PI);\n a = (std::abs(two_a) < TOLERANCE || std::abs(two_a) > 2*M_PI-TOLERANCE) ? 0 : two_a/2.0;\n dHalf = 0; \n auto b = std::arg(matrix(1, 0))-std::arg(matrix(0, 1)) + M_PI;\n std::vector possibleBhalf { fmod(b/2., 2*M_PI), fmod(b/2.+M_PI, 2*M_PI) };\n std::vector possibleChalf { M_PI/2., 3./2.*M_PI };\n bool found = false;\n for (int i = 0; i < possibleBhalf.size(); ++i)\n {\n for (int j = 0; j < possibleChalf.size(); ++j)\n {\n bHalf = possibleBhalf[i];\n cHalf = possibleChalf[j];\n if (checkParams(a, bHalf, cHalf, dHalf))\n {\n found = true;\n break;\n }\n }\n if (found)\n {\n break;\n }\n }\n assert(found);\n } \n else\n {\n auto two_a = fmod(std::arg(matrix(0, 0)*matrix(1, 1)), 2*M_PI);\n a = (std::abs(two_a) < TOLERANCE || std::abs(two_a) > 2*M_PI-TOLERANCE) ? 0 : two_a/2.0;\n auto two_d = 2.*std::arg(matrix(0, 1))-2.*std::arg(matrix(0, 0));\n std::vector possibleDhalf { fmod(two_d/4., 2*M_PI),\n fmod(two_d/4.+M_PI/2., 2*M_PI),\n fmod(two_d/4.+M_PI, 2*M_PI),\n fmod(two_d/4.+3./2.*M_PI, 2*M_PI) };\n auto two_b = 2.*std::arg(matrix(1, 0))-2.*std::arg(matrix(0, 0));\n std::vector possibleBhalf { fmod(two_b/4., 2*M_PI),\n fmod(two_b/4.+M_PI/2., 2*M_PI),\n fmod(two_b/4.+M_PI, 2*M_PI),\n fmod(two_b/4.+3./2.*M_PI, 2*M_PI) };\n auto tmp = std::acos(std::abs(matrix(1, 1)));\n std::vector possibleChalf { fmod(tmp, 2*M_PI),\n fmod(tmp+M_PI, 2*M_PI),\n fmod(-1.*tmp, 2*M_PI),\n fmod(-1.*tmp+M_PI, 2*M_PI) };\n bool found = false;\n for (int i = 0; i < possibleBhalf.size(); ++i)\n {\n for (int j = 0; j < possibleChalf.size(); ++j)\n {\n for (int k = 0; k < possibleDhalf.size(); ++k)\n {\n bHalf = possibleBhalf[i];\n cHalf = possibleChalf[j];\n dHalf = possibleDhalf[k];\n if (checkParams(a, bHalf, cHalf, dHalf))\n {\n found = true;\n break;\n }\n }\n if (found)\n {\n break;\n }\n }\n if (found)\n {\n break;\n }\n }\n assert(found);\n }\n \n // Final check:\n assert(checkParams(a, bHalf, cHalf, dHalf)); \n return std::make_tuple(a, bHalf, cHalf, dHalf);\n };\n // Use Z-Y decomposition of Nielsen and Chuang (Theorem 4.1).\n // An arbitrary one qubit gate matrix can be writen as\n // U = [ exp(j*(a-b/2-d/2))*cos(c/2), -exp(j*(a-b/2+d/2))*sin(c/2)\n // exp(j*(a+b/2-d/2))*sin(c/2), exp(j*(a+b/2+d/2))*cos(c/2)]\n // where a,b,c,d are real numbers.\n // Then U = exp(j*a) Rz(b) Ry(c) Rz(d).\n auto [a, bHalf, cHalf, dHalf] = singleQubitGateDecompose(in_mat);\n // Validate U = exp(j*a) Rz(b) Ry(c) Rz(d).\n const auto validate = [](const GateMatrix& in_mat, double a, double b, double c, double d) {\n GateMatrix Rz_b, Ry_c, Rz_d;\n Rz_b << std::exp(-I*b/2.0), 0, 0, std::exp(I*b/2.0);\n Rz_d << std::exp(-I*d/2.0), 0, 0, std::exp(I*d/2.0);\n Ry_c << std::cos(c/2), -std::sin(c/2), std::sin(c/2), std::cos(c/2);\n auto mat = std::exp(I*a)*Rz_b*Ry_c*Rz_d;\n return allClose(in_mat, mat);\n };\n // Validate the *raw* decomposition\n assert(validate(in_mat, a, 2*bHalf, 2*cHalf, 2*dHalf));\n \n // Simplify/optimize the sequence:\n auto composite = simplifySingleQubitSeq(2 * dHalf, 2 * cHalf, 2 * bHalf, in_bitIdx);\n\n // Validate the *simplified* sequence\n const auto validateSimplifiedSequence = [](const std::shared_ptr& in_composite, const GateMatrix& in_mat) {\n const auto Rx = [](double angle) {\n GateMatrix result;\n result << std::cos(angle/2.0), -I*std::sin(angle/2.0), -I*std::sin(angle/2.0), std::cos(angle/2.0);\n return result;\n };\n const auto Ry = [](double angle) {\n GateMatrix result;\n result << std::cos(angle/2), -std::sin(angle/2), std::sin(angle/2), std::cos(angle/2);\n return result;\n };\n const auto Rz = [](double angle) {\n GateMatrix result;\n result << std::exp(-I*angle/2.0), 0, 0, std::exp(I*angle/2.0);\n return result;\n };\n\n GateMatrix totalU = GateMatrix::Identity();\n for (size_t i = 0; i < in_composite->nInstructions(); ++i)\n {\n auto inst = in_composite->getInstruction(i);\n assert(inst->name() == \"Rx\" || inst->name() == \"Ry\" || inst->name() == \"Rz\");\n const auto angle = inst->getParameter(0).as();\n if (inst->name() == \"Rx\")\n {\n totalU = Rx(angle) * totalU;\n }\n if (inst->name() == \"Ry\")\n {\n totalU = Ry(angle) * totalU;\n }\n if (inst->name() == \"Rz\")\n {\n totalU = Rz(angle) * totalU;\n }\n }\n\n // Normalize the upto global phase:\n // Find index of the largest element:\n size_t colIdx = 0;\n size_t rowIdx = 0;\n double maxVal = std::abs(totalU(0,0));\n for (size_t i = 0; i < totalU.rows(); ++i)\n {\n for (size_t j = 0; j < totalU.cols(); ++j)\n {\n if (std::abs(totalU(i,j)) > maxVal)\n {\n maxVal = std::abs(totalU(i,j));\n colIdx = j;\n rowIdx = i;\n }\n }\n }\n\n const std::complex globalFactor = in_mat(rowIdx, colIdx) / totalU(rowIdx, colIdx);\n totalU = globalFactor * totalU;\n return allClose(in_mat, totalU, 1e-6);\n };\n\n assert(validateSimplifiedSequence(composite, in_mat));\n return composite; \n}\n}\n\nusing namespace xacc;\nusing namespace xacc::quantum;\n\nnamespace xacc {\nnamespace circuits {\nconst std::vector KAK::requiredKeys() \n{\n return { \"unitary\" };\n}\n\nbool KAK::expand(const HeterogeneousMap& parameters) \n{\n Eigen::Matrix4cd unitary;\n if (parameters.keyExists(\"unitary\"))\n {\n unitary = parameters.get(\"unitary\");\n }\n else if (parameters.keyExists>>(\"unitary\"))\n {\n auto matAsVec = parameters.get>>(\"unitary\");\n // Correct size: 4 x 4\n if (matAsVec.size() == 16)\n {\n for (int row = 0; row < 4; ++row)\n {\n for (int col = 0; col < 4; ++col)\n {\n // Expect row-by-row layout\n unitary(row, col) = matAsVec[4*row + col];\n }\n }\n }\n }\n \n if (!isUnitary(unitary))\n {\n xacc::error(\"Input matrix is not a 4x4 unitary matrix\");\n return false;\n }\n \n // Vector of qubits: \n // Default is {0, 1}\n // This can be specified if needed.\n std::vector bits {0, 1};\n if (parameters.keyExists>(\"qubits\"))\n {\n auto qubitVec = parameters.get>(\"qubits\");\n if (qubitVec.size() != 2)\n {\n xacc::error(\"Expected 2 qubits.\");\n return false;\n }\n bits[0] = qubitVec[0];\n bits[1] = qubitVec[1];\n }\n\n auto result = kakDecomposition(unitary);\n if (!result.has_value())\n {\n return false;\n }\n\n auto composite = result->toGates(bits[0], bits[1]);\n addInstructions(composite->getInstructions());\n return true;\n}\n\nstd::optional KAK::kakDecomposition(const InputMatrix& in_matrix) const\n{\n assert(isUnitary(in_matrix));\n Eigen::MatrixXcd mInMagicBasis = KAK_MAGIC_DAG() * in_matrix * KAK_MAGIC();\n auto [left, diag, right] = bidiagonalizeUnitary(mInMagicBasis);\n // Recover pieces.\n auto [a1, a0] = so4ToMagicSu2s(left.transpose()); \n auto [b1, b0] = so4ToMagicSu2s(right.transpose());\n assert(isUnitary(a0));\n assert(isUnitary(a1));\n assert(isUnitary(b0));\n assert(isUnitary(b1));\n\n Eigen::Vector4cd angles;\n for (size_t i = 0; i < 4; ++i)\n {\n angles(i) = std::arg(diag[i]);\n }\n auto factors = KAK_GAMMA() * angles;\n KakDecomposition result;\n {\n result.g = std::exp(I * factors(0));\n result.a0 = a0;\n result.a1 = a1;\n result.b0 = b0;\n result.b1 = b1;\n result.x = factors(1).real();\n assert(std::abs(factors(1).imag()) < 1e-9);\n result.y = factors(2).real();\n assert(std::abs(factors(2).imag()) < 1e-9);\n result.z = factors(3).real();\n assert(std::abs(factors(3).imag()) < 1e-9);\n }\n\n const bool validateMatrix = allClose(result.toMat(), in_matrix); \n // Failed to validate\n if (!validateMatrix)\n {\n return std::nullopt;\n }\n\n auto canonicalizedInteraction = canonicalizeInteraction(result.x, result.y, result.z);\n\n // Combine the single-qubit blocks:\n result.b1 = canonicalizedInteraction.b1 * result.b1;\n result.b0 = canonicalizedInteraction.b0 * result.b0;\n result.a1 = result.a1 * canonicalizedInteraction.a1;\n result.a0 = result.a0 * canonicalizedInteraction.a0;\n result.g = result.g * canonicalizedInteraction.g;\n result.x = canonicalizedInteraction.x;\n result.y = canonicalizedInteraction.y;\n result.z = canonicalizedInteraction.z;\n\n assert(isCanonicalized(result.x, result.y, result.z));\n assert(allClose(result.toMat(), in_matrix));\n\n return result;\n}\n\nEigen::MatrixXcd KAK::KakDecomposition::toMat() const\n{\n auto before = Eigen::kroneckerProduct(b1, b0);\n auto after = Eigen::kroneckerProduct(a1, a0);\n Eigen::MatrixXcd unitary = interactionMatrixExp(x, y, z);\n auto total = g * after * unitary * before;\n return total;\n}\n\nstd::shared_ptr KAK::KakDecomposition::toGates(size_t in_bit1, size_t in_bit2) const\n{\n auto gateRegistry = xacc::getService(\"quantum\");\n const auto generateInteractionComposite = [&](size_t bit1, size_t bit2, double x, double y, double z) {\n const double TOL = 1e-8;\n // Full decomposition is required\n if (std::abs(z) >= TOL)\n {\n const double xAngle = M_PI * (x * -2 / M_PI + 0.5);\n const double yAngle = M_PI * (y * -2 / M_PI + 0.5);\n const double zAngle = M_PI * (z * -2 / M_PI + 0.5);\n auto composite = gateRegistry->createComposite(\"__TEMP__INTERACTION_COMPOSITE__\" + std::to_string(getTempId()));\n \n composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit2, bit1 }));\n composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n composite->addInstruction(gateRegistry->createInstruction(\"Rz\", { bit1 }, { zAngle }));\n composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit1 }, { M_PI_2 }));\n composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit2 }));\n composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit1, bit2 }));\n composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit2 }));\n composite->addInstruction(gateRegistry->createInstruction(\"Ry\", { bit1 }, { yAngle }));\n composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit2 }, { xAngle }));\n composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit1, bit2 }));\n composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit2 }, { -M_PI_2 }));\n\n const auto validateGateSequence = [&](const Eigen::Matrix4cd& in_target){\n const auto H = []() {\n GateMatrix result;\n result << 1.0/std::sqrt(2), 1.0/std::sqrt(2), 1.0/std::sqrt(2), -1.0/std::sqrt(2);\n return result;\n };\n const auto Rx = [](double angle) {\n GateMatrix result;\n result << std::cos(angle/2.0), -I*std::sin(angle/2.0), -I*std::sin(angle/2.0), std::cos(angle/2.0);\n return result;\n };\n const auto Ry = [](double angle) {\n GateMatrix result;\n result << std::cos(angle/2), -std::sin(angle/2), std::sin(angle/2), std::cos(angle/2);\n return result;\n };\n const auto Rz = [](double angle) {\n GateMatrix result;\n result << std::exp(-I*angle/2.0), 0, 0, std::exp(I*angle/2.0);\n return result;\n };\n const auto CZ = []() {\n Eigen::Matrix4cd cz;\n cz << 1, 0, 0, 0, \n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, -1;\n return cz;\n };\n \n Eigen::Matrix2cd IdMat = Eigen::Matrix2cd::Identity();\n Eigen::Matrix4cd totalU = Eigen::Matrix4cd::Identity();\n totalU *= Eigen::kroneckerProduct(IdMat, Rx(-M_PI_2));\n totalU *= Eigen::kroneckerProduct(H(), IdMat);\n totalU *= CZ();\n totalU *= Eigen::kroneckerProduct(H(), IdMat);\n totalU *= Eigen::kroneckerProduct(IdMat, Rx(xAngle));\n totalU *= Eigen::kroneckerProduct(Ry(yAngle), IdMat);\n totalU *= Eigen::kroneckerProduct(IdMat, H());\n totalU *= CZ();\n totalU *= Eigen::kroneckerProduct(IdMat, H());\n totalU *= Eigen::kroneckerProduct(Rx(M_PI_2), IdMat);\n totalU *= Eigen::kroneckerProduct(Rz(zAngle), IdMat);\n totalU *= Eigen::kroneckerProduct(H(), IdMat);\n totalU *= CZ();\n totalU *= Eigen::kroneckerProduct(H(), IdMat); \n // Find index of the largest element:\n size_t colIdx = 0;\n size_t rowIdx = 0;\n double maxVal = std::abs(totalU(0,0));\n for (size_t i = 0; i < totalU.rows(); ++i)\n {\n for (size_t j = 0; j < totalU.cols(); ++j)\n {\n if (std::abs(totalU(i,j)) > maxVal)\n {\n maxVal = std::abs(totalU(i,j));\n colIdx = j;\n rowIdx = i;\n }\n }\n }\n\n const std::complex globalFactor = in_target(rowIdx, colIdx) / totalU(rowIdx, colIdx);\n totalU = globalFactor * totalU;\n return allClose(totalU, in_target);\n };\n \n assert(validateGateSequence(interactionMatrixExp(x, y, z)));\n return composite;\n }\n // ZZ interaction is near zero: only XX and YY\n else if (y >= TOL)\n {\n const double xAngle = -2 * x;\n const double yAngle = -2 * y;\n auto composite = gateRegistry->createComposite(\"__TEMP__INTERACTION_COMPOSITE__\" + std::to_string(getTempId())); \n composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit2 }, { M_PI_2 }));\n composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit2, bit1 }));\n composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n composite->addInstruction(gateRegistry->createInstruction(\"Ry\", { bit1 }, { yAngle }));\n composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit2 }, { xAngle }));\n composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit1, bit2 }));\n composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit2 }, { -M_PI_2 }));\n\n const auto validateGateSequence = [&](const Eigen::Matrix4cd& in_target){\n const auto H = []() {\n GateMatrix result;\n result << 1.0/std::sqrt(2), 1.0/std::sqrt(2), 1.0/std::sqrt(2), -1.0/std::sqrt(2);\n return result;\n };\n const auto Rx = [](double angle) {\n GateMatrix result;\n result << std::cos(angle/2.0), -I*std::sin(angle/2.0), -I*std::sin(angle/2.0), std::cos(angle/2.0);\n return result;\n };\n const auto Ry = [](double angle) {\n GateMatrix result;\n result << std::cos(angle/2), -std::sin(angle/2), std::sin(angle/2), std::cos(angle/2);\n return result;\n };\n const auto Rz = [](double angle) {\n GateMatrix result;\n result << std::exp(-I*angle/2.0), 0, 0, std::exp(I*angle/2.0);\n return result;\n };\n const auto CZ = []() {\n Eigen::Matrix4cd cz;\n cz << 1, 0, 0, 0, \n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, -1;\n return cz;\n };\n \n Eigen::Matrix2cd IdMat = Eigen::Matrix2cd::Identity();\n Eigen::Matrix4cd totalU = Eigen::Matrix4cd::Identity();\n totalU *= Eigen::kroneckerProduct(IdMat, Rx(-M_PI_2));\n totalU *= Eigen::kroneckerProduct(H(), IdMat);\n totalU *= CZ();\n totalU *= Eigen::kroneckerProduct(H(), IdMat);\n totalU *= Eigen::kroneckerProduct(IdMat, Rx(xAngle));\n totalU *= Eigen::kroneckerProduct(Ry(yAngle), IdMat);\n totalU *= Eigen::kroneckerProduct(H(), IdMat);\n totalU *= CZ();\n totalU *= Eigen::kroneckerProduct(H(), IdMat); \n totalU *= Eigen::kroneckerProduct(IdMat, Rx(M_PI_2));\n\n // Find index of the largest element:\n size_t colIdx = 0;\n size_t rowIdx = 0;\n double maxVal = std::abs(totalU(0,0));\n for (size_t i = 0; i < totalU.rows(); ++i)\n {\n for (size_t j = 0; j < totalU.cols(); ++j)\n {\n if (std::abs(totalU(i,j)) > maxVal)\n {\n maxVal = std::abs(totalU(i,j));\n colIdx = j;\n rowIdx = i;\n }\n }\n }\n\n const std::complex globalFactor = in_target(rowIdx, colIdx) / totalU(rowIdx, colIdx);\n totalU = globalFactor * totalU;\n return allClose(totalU, in_target);\n };\n \n assert(validateGateSequence(interactionMatrixExp(x, y, z)));\n return composite;\n }\n // only XX is significant\n else \n {\n const double xAngle = -2 * x;\n auto composite = gateRegistry->createComposite(\"__TEMP__INTERACTION_COMPOSITE__\" + std::to_string(getTempId()));\n composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit2, bit1 }));\n composite->addInstruction(gateRegistry->createInstruction(\"Rx\", { bit2 }, { xAngle }));\n composite->addInstruction(gateRegistry->createInstruction(\"CZ\", { bit1, bit2 }));\n composite->addInstruction(gateRegistry->createInstruction(\"H\", { bit1 }));\n \n const auto validateGateSequence = [&](const Eigen::Matrix4cd& in_target){\n const auto H = []() {\n GateMatrix result;\n result << 1.0/std::sqrt(2), 1.0/std::sqrt(2), 1.0/std::sqrt(2), -1.0/std::sqrt(2);\n return result;\n };\n const auto Rx = [](double angle) {\n GateMatrix result;\n result << std::cos(angle/2.0), -I*std::sin(angle/2.0), -I*std::sin(angle/2.0), std::cos(angle/2.0);\n return result;\n };\n const auto Ry = [](double angle) {\n GateMatrix result;\n result << std::cos(angle/2), -std::sin(angle/2), std::sin(angle/2), std::cos(angle/2);\n return result;\n };\n const auto Rz = [](double angle) {\n GateMatrix result;\n result << std::exp(-I*angle/2.0), 0, 0, std::exp(I*angle/2.0);\n return result;\n };\n const auto CZ = []() {\n Eigen::Matrix4cd cz;\n cz << 1, 0, 0, 0, \n 0, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, -1;\n return cz;\n };\n \n Eigen::Matrix2cd IdMat = Eigen::Matrix2cd::Identity();\n Eigen::Matrix4cd totalU = Eigen::Matrix4cd::Identity();\n \n totalU *= Eigen::kroneckerProduct(H(), IdMat);\n totalU *= CZ();\n totalU *= Eigen::kroneckerProduct(IdMat, Rx(xAngle));\n totalU *= CZ();\n totalU *= Eigen::kroneckerProduct(H(), IdMat); \n\n // Find index of the largest element:\n size_t colIdx = 0;\n size_t rowIdx = 0;\n double maxVal = std::abs(totalU(0,0));\n for (size_t i = 0; i < totalU.rows(); ++i)\n {\n for (size_t j = 0; j < totalU.cols(); ++j)\n {\n if (std::abs(totalU(i,j)) > maxVal)\n {\n maxVal = std::abs(totalU(i,j));\n colIdx = j;\n rowIdx = i;\n }\n }\n }\n\n const std::complex globalFactor = in_target(rowIdx, colIdx) / totalU(rowIdx, colIdx);\n totalU = globalFactor * totalU;\n return allClose(totalU, in_target);\n };\n \n assert(validateGateSequence(interactionMatrixExp(x, y, z)));\n return composite; \n }\n };\n\n auto a0Comp = singleQubitGateGen(a0, in_bit2);\n auto a1Comp = singleQubitGateGen(a1, in_bit1);\n auto b0Comp = singleQubitGateGen(b0, in_bit2);\n auto b1Comp = singleQubitGateGen(b1, in_bit1);\n auto interactionComp = generateInteractionComposite(in_bit2, in_bit1, x, y, z);\n auto totalComposite = gateRegistry->createComposite(\"__TEMP__KAK_COMPOSITE__\" + std::to_string(getTempId()));\n // U = g x (Gate A1 Gate A0) x exp(i(xXX + yYY + zZZ))x(Gate b1 Gate b0)\n // Before:\n totalComposite->addInstructions(b0Comp->getInstructions());\n totalComposite->addInstructions(b1Comp->getInstructions());\n // Interaction:\n totalComposite->addInstructions(interactionComp->getInstructions());\n // After:\n totalComposite->addInstructions(a0Comp->getInstructions());\n totalComposite->addInstructions(a1Comp->getInstructions());\n // Ignore global phase\n return totalComposite;\n}\n\nKAK::BidiagResult KAK::bidiagonalizeUnitary(const InputMatrix& in_matrix) const\n{\n Eigen::Matrix4d realMat;\n Eigen::Matrix4d imagMat;\n for (int row = 0; row < in_matrix.rows(); ++row)\n {\n for (int col = 0; col < in_matrix.cols(); ++col)\n {\n realMat(row, col) = in_matrix(row, col).real();\n imagMat(row, col) = in_matrix(row, col).imag();\n }\n }\n // Assert A X B.T and A.T X B are hermitian\n assert(isHermitian(realMat * imagMat.transpose()));\n assert(isHermitian(realMat.transpose() * imagMat));\n\n auto [left, right] = bidiagonalizeRealMatrixPairWithSymmetricProducts(realMat, imagMat);\n\n // Convert to special orthogonal w/o breaking diagonalization.\n if (left.determinant() < 0)\n {\n for (int i = 0; i < left.cols(); ++i)\n {\n left(0, i) = -left(0, i);\n }\n }\n if (right.determinant() < 0)\n {\n for (int i = 0; i < right.rows(); ++i)\n {\n right(i, 0) = -right(i, 0);\n }\n }\n\n auto diag = left * in_matrix * right;\n // Validate:\n assert(isDiagonal(diag));\n \n std::vector> diagVec;\n for (int i = 0; i < diag.rows(); ++i)\n {\n diagVec.emplace_back(diag(i, i));\n }\n\n return std::make_tuple(left, diagVec, right);\n}\n\nstd::tuple, KAK::GateMatrix, KAK::GateMatrix> KAK::kronFactor(const InputMatrix& in_matrix) const\n{\n KAK::GateMatrix f1 = KAK::GateMatrix::Zero();\n KAK::GateMatrix f2 = KAK::GateMatrix::Zero();\n \n // Get row and column of the max element\n size_t a = 0;\n size_t b = 0;\n double maxVal = std::abs(in_matrix(a, b));\n for (int row = 0; row < in_matrix.rows(); ++row)\n {\n for (int col = 0; col < in_matrix.cols(); ++col)\n {\n if (std::abs(in_matrix(row, col)) > maxVal)\n {\n a = row;\n b = col;\n maxVal = std::abs(in_matrix(a, b));\n }\n }\n }\n \n // Extract sub-factors touching the reference cell.\n for (int i = 0; i < 2; ++i)\n {\n for (int j = 0; j < 2; ++j)\n {\n f1((a >> 1) ^ i, (b >> 1) ^ j) = in_matrix(a ^ (i << 1), b ^ (j << 1));\n f2((a & 1) ^ i, (b & 1) ^ j) = in_matrix(a ^ i, b ^ j);\n }\n }\n\n // Rescale factors to have unit determinants.\n f1 /= (std::sqrt(f1.determinant()));\n f2 /= (std::sqrt(f2.determinant()));\n\n //Determine global phase.\n std::complex g = in_matrix(a, b) / (f1(a >> 1, b >> 1) * f2(a & 1, b & 1));\n if (g.real() < 0.0)\n {\n f1 *= -1;\n g = -g;\n }\n\n // Validate:\n Eigen::Matrix4cd testMat = g * Eigen::kroneckerProduct(f1, f2);\n assert(allClose(testMat, in_matrix));\n\n return std::make_tuple(g, f1, f2);\n}\n\nstd::pair KAK::so4ToMagicSu2s(const InputMatrix& in_matrix) const\n{\n assert(isSpecialOrthogonal(in_matrix));\n auto matInMagicBasis = KAK_MAGIC() * in_matrix * KAK_MAGIC_DAG();\n auto [g, f1, f2] = kronFactor(matInMagicBasis);\n return std::make_pair(f1, f2);\n}\n\nEigen::MatrixXd KAK::diagonalizeRealSymmetricMatrix(const Eigen::MatrixXd& in_mat) const\n{ \n assert(isHermitian(in_mat));\n Eigen::SelfAdjointEigenSolver solver(in_mat);\n Eigen::MatrixXd p = solver.eigenvectors();\n // Orthogonal basis (Hermitian/symmetric matrix) \n assert(isOrthogonal(p));\n // An orthogonal matrix P such that PT x matrix x P is diagonal.\n assert(isDiagonal(p.transpose() * in_mat * p));\n return p;\n}\n\nEigen::MatrixXd KAK::diagonalizeRealSymmetricAndSortedDiagonalMatrices(const Eigen::MatrixXd& in_symMat, const Eigen::MatrixXd& in_diagMat) const\n{\n assert(isDiagonal(in_diagMat));\n assert(isHermitian(in_symMat));\n const auto similarSingular = [&in_diagMat](int i, int j) {\n return std::abs(in_diagMat(i,i) - in_diagMat(j,j)) < 1e-5;\n };\n\n const auto ranges = contiguousGroups(in_diagMat.rows(), similarSingular);\n Eigen::MatrixXd p = Eigen::MatrixXd::Zero(in_symMat.rows(), in_symMat.cols());\n\n for (const auto& [start, end]: ranges)\n {\n const int blockSize = end - start;\n \n Eigen::MatrixXd block = Eigen::MatrixXd(blockSize, blockSize);\n for (int i = 0; i < blockSize; ++i)\n {\n for (int j = 0; j < blockSize; ++j)\n {\n block(i,j) = in_symMat(i + start, j + start);\n }\n }\n auto blockDiag = diagonalizeRealSymmetricMatrix(block);\n\n for (int i = 0; i < blockSize; ++i)\n {\n for (int j = 0; j < blockSize; ++j)\n {\n p(i + start, j + start) = blockDiag(i,j);\n }\n }\n }\n\n // P.T x symmetric_matrix x P is diagonal\n assert(isDiagonal(p.transpose() * in_symMat * p));\n // and P.T x diagonal_matrix x P = diagonal_matrix\n assert(allClose(p.transpose() * in_diagMat * p, in_diagMat));\n\n return p;\n}\n\nstd::pair KAK::bidiagonalizeRealMatrixPairWithSymmetricProducts(const Eigen::Matrix4d& in_mat1, const Eigen::Matrix4d& in_mat2) const\n{\n const auto svd = [](const Eigen::MatrixXd& in_mat) -> std::tuple {\n Eigen::JacobiSVD svd(in_mat, Eigen::ComputeThinU | Eigen::ComputeThinV);\n return std::make_tuple(svd.matrixU(), svd.singularValues(), svd.matrixV().adjoint());\n };\n // Use SVD to bi-diagonalize the first matrix.\n auto [baseLeft, baseDiagVec, baseRight] = svd(in_mat1);\n \n Eigen::MatrixXd baseDiag = Eigen::MatrixXd::Zero(baseDiagVec.size(), baseDiagVec.size());\n for (int i = 0; i < baseDiagVec.size(); ++i)\n {\n baseDiag(i, i) = baseDiagVec(i);\n }\n\n // Determine where we switch between diagonalization-fixup strategies.\n const auto dim = baseDiag.rows();\n auto rank = dim;\n while (rank > 0 && std::abs(baseDiag(rank - 1, rank - 1) < 1e-5))\n {\n rank--;\n } \n Eigen::MatrixXd baseDiagTrim = Eigen::MatrixXd::Zero(rank, rank);\n for (int i = 0; i < rank; ++i)\n {\n for (int j = 0; j < rank; ++j)\n {\n baseDiagTrim(i, j) = baseDiag(i, j);\n }\n }\n\n // Try diagonalizing the second matrix with the same factors as the first.\n auto semiCorrected = baseLeft.transpose() * in_mat2 * baseRight.transpose();\n \n Eigen::MatrixXd overlap = Eigen::MatrixXd::Zero(rank, rank);\n for (int i = 0; i < rank; ++i)\n {\n for (int j = 0; j < rank; ++j)\n {\n overlap(i, j) = semiCorrected(i, j);\n }\n }\n\n auto overlapAdjust = diagonalizeRealSymmetricAndSortedDiagonalMatrices(overlap, baseDiagTrim);\n \n const auto extraSize = dim - rank;\n Eigen::MatrixXd extra(extraSize, extraSize);\n for (int i = 0; i < extraSize; ++i)\n {\n for (int j = 0; j < extraSize; ++j)\n {\n extra(i, j) = semiCorrected(i + rank, j + rank);\n }\n } \n \n static const auto emptySvdResult = std::make_tuple(Eigen::MatrixXd::Zero(0,0), Eigen::VectorXd::Zero(0), Eigen::MatrixXd::Zero(0,0));\n auto [extraLeftAdjust, extraDiag, extraRightAdjust] = (dim > rank) ? svd(extra): emptySvdResult;\n \n auto leftAdjust = blockDiag(overlapAdjust, extraLeftAdjust);\n auto rightAdjust = blockDiag(overlapAdjust.transpose(), extraRightAdjust);\n auto left = leftAdjust.transpose() * baseLeft.transpose();\n auto right = baseRight.transpose() * rightAdjust.transpose(); \n // L x mat1 x R and L x mat2 x R are diagonal matrices.\n assert(isDiagonal(left * in_mat1 * right));\n assert(isDiagonal(left * in_mat2 * right));\n return std::make_pair(left, right);\n}\n\nKAK::KakDecomposition KAK::canonicalizeInteraction(double x, double y, double z) const\n{\n // Accumulated global phase.\n std::complex phase = 1.0; \n //Per-qubit left factors.\n std::vector left { GateMatrix::Identity(), GateMatrix::Identity() }; \n // Per-qubit right factors.\n std::vector right { GateMatrix::Identity(), GateMatrix::Identity() }; \n // Remaining XX/YY/ZZ interaction vector.\n std::vector v { x, y, z }; \n\n std::vector flippers {\n (GateMatrix() << 0, I, I, 0).finished(),\n (GateMatrix() << 0, 1, -1, 0).finished(),\n (GateMatrix() << I, 0, 0, -I).finished()\n };\n\n std::vector swappers {\n (GateMatrix() << I*M_SQRT1_2, M_SQRT1_2, -M_SQRT1_2, -I*M_SQRT1_2).finished(),\n (GateMatrix() << I*M_SQRT1_2, I*M_SQRT1_2, I*M_SQRT1_2, -I*M_SQRT1_2).finished(),\n (GateMatrix() << 0, I*M_SQRT1_2 + M_SQRT1_2, I*M_SQRT1_2 - M_SQRT1_2, 0).finished()\n };\n\n const auto shift = [&](int k, int step) {\n v[k] += step * M_PI_2;\n phase *= std::pow(I, step);\n const auto expFact = ((step % 4) + 4) % 4;\n const GateMatrix mat = flippers[k].array().pow(expFact); \n right[0] = mat * right[0];\n right[1] = mat * right[1];\n };\n\n const auto negate = [&](int k1, int k2) {\n v[k1] *= -1;\n v[k2] *= -1;\n phase *= -1;\n const auto& s = flippers[3 - k1 - k2]; \n left[1] = left[1] * s;\n right[1] = s * right[1];\n };\n\n const auto swap = [&](int k1, int k2) {\n std::iter_swap(v.begin() + k1, v.begin() + k2);\n const auto& s = swappers[3 - k1 - k2]; \n left[0] = left[0] * s;\n left[1] = left[1] * s;\n right[0] = s * right[0];\n right[1] = s * right[1];\n };\n\n const auto canonicalShift = [&](int k) {\n while (v[k] <= -M_PI_4)\n {\n shift(k, +1);\n }\n while (v[k] > M_PI_4)\n {\n shift(k, -1);\n }\n };\n\n const auto sort = [&](){\n if (std::abs(v[0]) < std::abs(v[1]))\n {\n swap(0, 1);\n }\n if (std::abs(v[1]) < std::abs(v[2]))\n {\n swap(1, 2);\n }\n if (std::abs(v[0]) < std::abs(v[1]))\n {\n swap(0, 1);\n }\n };\n\n canonicalShift(0);\n canonicalShift(1);\n canonicalShift(2);\n sort();\n\n if (v[0] < 0)\n {\n negate(0, 2);\n }\n if (v[1] < 0)\n {\n negate(1, 2);\n }\n canonicalShift(2);\n\n if ((v[0] > M_PI_4 - 1e-9) && (v[2] < 0))\n {\n shift(0, -1);\n negate(0, 2);\n }\n \n assert(isCanonicalized(v[0], v[1], v[2]));\n \n KakDecomposition result;\n {\n result.g = phase;\n result.a0 = left[1];\n result.a1 = left[0];\n result.b0 = right[1];\n result.b1 = right[0];\n result.x = v[0];\n result.y = v[1];\n result.z = v[2];\n }\n\n assert(allClose(result.toMat(), interactionMatrixExp(x, y, z)));\n return result;\n}\nbool ZYZ::expand(const xacc::HeterogeneousMap& runtimeOptions) \n{\n Eigen::Matrix2cd unitary;\n if (runtimeOptions.keyExists(\"unitary\"))\n {\n unitary = runtimeOptions.get(\"unitary\");\n }\n else if (runtimeOptions.keyExists>>(\"unitary\"))\n {\n auto matAsVec = runtimeOptions.get>>(\"unitary\");\n // Correct size: 2 x 2\n if (matAsVec.size() == 4)\n {\n for (int row = 0; row < 2; ++row)\n {\n for (int col = 0; col < 2; ++col)\n {\n // Expect row-by-row layout\n unitary(row, col) = matAsVec[2*row + col];\n }\n }\n }\n }\n else\n {\n xacc::error(\"unitary matrix is required.\");\n return false;\n }\n\n assert(isUnitary(unitary));\n auto decomposed = singleQubitGateGen(unitary, 0);\n addInstructions(decomposed->getInstructions());\n return true;\n}\n} // namespace circuits\n} // namespace xacc\n", "meta": {"hexsha": "320fac404782f4c867c4d201a9bfc2ea01db3fa6", "size": 42363, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "artifacts/old_dataset_versions/minimal_commits_v02/xacc/xacc#309_B/after/kak.cpp", "max_stars_repo_name": "MattePalte/Bugs-Quantum-Computing-Platforms", "max_stars_repo_head_hexsha": "0c1c805fd5dfce465a8955ee3faf81037023a23e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2021-11-08T11:46:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T10:13:38.000Z", "max_issues_repo_path": "artifacts/minimal_bugfixes/xacc/xacc#309_B/after/kak.cpp", "max_issues_repo_name": "MattePalte/Bugs-Quantum-Computing-Platforms", "max_issues_repo_head_hexsha": "0c1c805fd5dfce465a8955ee3faf81037023a23e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2.0, "max_issues_repo_issues_event_min_datetime": "2021-11-09T14:57:09.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-12T12:35:58.000Z", "max_forks_repo_path": "artifacts/old_dataset_versions/minimal_commits_v02/xacc/xacc#309_B/after/kak.cpp", "max_forks_repo_name": "MattePalte/Bugs-Quantum-Computing-Platforms", "max_forks_repo_head_hexsha": "0c1c805fd5dfce465a8955ee3faf81037023a23e", "max_forks_repo_licenses": ["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.8998493976, "max_line_length": 167, "alphanum_fraction": 0.5852512806, "num_tokens": 13117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587934924569, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6442348268110522}} {"text": "#ifndef CALIBRATOR_PROCESSES_GENERAL_HULLWHITEPROCESS_HPP\n#define CALIBRATOR_PROCESSES_GENERAL_HULLWHITEPROCESS_HPP\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace HJCALIBRATOR\n{\n\t//! Time-dependent Hull-White process class\n\t/*! This class describes the time-dependent Hull-White process governed by\n\t\\f[\n\tdr(t) = (\\theta(t) - a(t)r(t)) dt + \\sigma(t) dW_t.\n\t\\f]\n\n\tDerivation Reference, Eq. numbering quoted from SSRN-id1514192\n\n\t\\ingroup processes\n\t*/\n\tclass GeneralizedHullWhiteProcess : public StochasticProcess1D\n\t{\n\tpublic :\n\t\tGeneralizedHullWhiteProcess( const Handle& h,\n\t\t\t\t\t\t\t\t\t const IntegrableParameter& a, // must be an IntegrableParameter\n\t\t\t\t\t\t\t\t\t const Parameter& sigma );\n\t\t\n\t\t//! \\name StochasticProcess1D interface\n\t\t//@{\n\t\tReal x0() const override { return r0_; }\n\t\tReal drift( Time t, Rate r ) const override;\n\t\tReal diffusion( Time t, Rate r ) const override;\n\t\tReal variance( Time t0, Rate r0, Time dt ) const override;\n\t\tReal expectation( Time t0, Rate r0, Time dt ) const override;\n\t\tReal stdDeviation( Time t0, Rate r0, Time dt ) const override;\n\t\t//@}\n\n\t\tIntegrableParameter a() { return a_; }\n\t\tParameter sigma() { return sigma_; }\n\n\t\tReal a( Time t ) { return a_( t ); }\n\t\tReal sigma( Time t ) { return sigma_( t ); }\n\n\t\tReal bondPrice( Time t, Time T, Rate r )const;\n\n\tprivate :\n\t\tReal A( Time t, Time T ) const;\n\t\tReal B( Time t, Time T ) const;\n\n\t\tReal theta( Time t ) const;\n\t\tReal E( Time t, Real multiplier = 1. ) const;\n\t\tReal alpha( Time t ) const;\n\n\t\tReal DVIntegrand( Time u, Time t ) const;\n\t\tReal VrIntegrand( Time t ) const;\n\t\tReal alphaIntegrand( Time u, Time t ) const;\n\n\t\tHandle termStructure_;\n\t\tIntegrableParameter a_;\n\t\tParameter sigma_;\n\t\tReal r0_;\n\n\t\tSimpsonIntegral integrator_;\n\t\tboost::function Vrintegrand_; // variance integrand\n\t\tboost::function OneOverEintegrand_; // Eq. 31 integrand\n\n\t};\n\n\t//! Time-dependent Hull-White Forward-Rate process class\n\t/*\n\tDerivation Reference, Eq. numbering quoted from SSRN-id1514192\n\n\t\\ingroup processes\n\t*/\n\t/*\n\tclass GeneralizedHullwhiteForwardProcess : public ForwardMeasureProcess1D\n\t{\n\t\tGeneralizedHullwhiteForwardProcess( const Handle& h,\n\t\t\t\t\t\t\t\t\t\t\tconst IntegrableParameter& a, // must be an IntegrableParameter\n\t\t\t\t\t\t\t\t\t\t\tconst Parameter& sigma );\n\n\t\t//! \\name StochasticProcess1D interface\n\t\t//@{\n\t\tReal x0() const override;\n\t\tReal drift( Time t, Rate r ) const override;\n\t\tReal diffusion( Time t, Rate r ) const override;\n\t\tReal variance( Time t0, Rate r0, Time dt ) const override;\n\t\tReal expectation( Time t0, Rate r0, Time dt ) const override;\n\t\tReal stdDeviation( Time t0, Rate r0, Time dt ) const override;\n\t\t//@}\n\n\tprivate :\n\t\tboost::shared_ptr hwprocess_;\n\t};\n\t*/\n\n\t// inline definitions\n\n\tinline Real GeneralizedHullWhiteProcess::drift( Time t, Rate r ) const\n\t{\n\t\treturn theta( t ) - a_( t ) * r;\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::diffusion( Time t, Rate r ) const\n\t{\n\t\treturn sigma_( t );\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::variance( Time t0, Rate r0, Time dt ) const\n\t{\n\t\tReal Et = E( t0 + dt );\n\n\t\treturn integrator_( Vrintegrand_, t0, t0 + dt ) / (Et * Et);\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::stdDeviation( Time t0, Rate r0, Time dt ) const\n\t{\n\t\treturn sqrt( variance( t0, r0, dt ) );\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::expectation( Time t0, Rate r0, Time dt ) const\n\t{\n\t\t/* A part of eq.35 */\n\t\tTime s = t0;\n\t\tTime t = t0 + dt;\n\n\t\tReal RE = E( s ) / E( t );\n\n\t\treturn RE * r0 + alpha( t ) - RE * alpha( s );\n\t}\n\n\tReal GeneralizedHullWhiteProcess::bondPrice( Time t, Time T, Rate r) const\n\t{\n\t\treturn A( t, T ) * exp( -(B( t, T ) * r) );\n\t}\n\n\tReal GeneralizedHullWhiteProcess::A( Time t, Time T ) const\n\t{\n\t\t/* Modefication of the eq. 43 so that we have the general affine form P = Aexp(-Br)\n\t\t\\f[\n\t\tA(t,T) = \\frac{P(0,T)}{P(0,t)} + exp\\left{B(t,T)f(0,t) - \\frac{1}{2}B^2(t,T)V_r(0,t)\\right}\n\t\t\\f]\n\t\t*/\n\t\tReal discount_t = termStructure_->discount( t );\n\t\tReal discount_T = termStructure_->discount( T );\n\t\tReal forward = termStructure_->forwardRate( t, t, Continuous, NoFrequency );\n\n\t\tReal BtT = B( t, T );\n\t\tReal Vrt = variance( 0, 0, t );\n\n\t\treturn (discount_T / discount_t) * exp( BtT*forward - 0.5 * BtT * BtT * Vrt );\n\t}\n\n\tReal GeneralizedHullWhiteProcess::B( Time t, Time T ) const\n\t{\n\t\t/* eq. 31\n\t\t\\f[\n\t\tB(t,T) = E(t) \\int_t^T \\frac{du}{E(u)}\n\t\t\\f]\n\t\t*/\n\t\treturn E( t ) * integrator_( OneOverEintegrand_, t, T );\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::theta( Time t ) const\n\t{\n\t\tconst Real dt = 0.000001; // Should it be variable?\n\t\tReal f = termStructure_->forwardRate( t, t, Continuous, NoFrequency );\n\t\tReal fup = termStructure_->forwardRate( t + dt, t + dt, Continuous, NoFrequency );\n\t\tReal f_prime = (fup - f) / dt;\n\n\t\tboost::function integrand;\n\t\tintegrand = boost::bind( &GeneralizedHullWhiteProcess::DVIntegrand, this, _1, t );\n\t\tReal IntI = integrator_( integrand, 0, t );\n\n\t\tReal Et = E( t );\n\t\tReal at = a_( t );\n\n\t\tReal DV = (2. / Et) * IntI;\n\t\tReal D2V = 2.*variance( 0, 0, t ) - (2*at / Et) * IntI;\n\n\t\t/* eq. 39 */\n\t\treturn f_prime + a_( t ) * f + 0.5 * (D2V + at * DV);\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::E( Time t, Real multiplier ) const\n\t{\n\t\t/* eq. 30\n\t\t\\f[\n\t\tE(t) = exp(\\int_0^t{a(u)du})\n\t\t\\f]\n\n\t\t\n\t\tThe multiplier is given to deal with the integrand of the eq. 31 (\\f$ B(t,T) \\f$)\n\t\t*/\n\t\treturn exp( multiplier * a_.integral( 0, t ) );\n\t}\n\n\tinline Real GeneralizedHullWhiteProcess::DVIntegrand( Time u, Time t ) const\n\t{\n\t\t/* Integrand of \\f$ \\partial V(0,t) /\\partial t \\f$ in its derived form\n\t\t\\f[\n\t\t\\partial V(0,t) /\\partial t = \\frac{2}{E(t)\\int_0^t \\sigma(u,t)\\sigma(u)E(u)du\n\t\t\\f]\n\n\t\tHere, we takes \\f$ I(u,t) = \\sigma(u,t)\\sigma(u)E(u) \\f$\n\t\tso we have \n\t\t\\f[\n\t\t\\partial V(0,t) /\\partial t = \\frac{2}{E(t)\\int_0^t I(u,t)du\n\t\t\\partial^2 V(0,t) /\\partial t^2 = -\\frac{a(t)}{E(t)}\\int_0^t I(u,t)du + 2*V_r(0,t)\n\t\t\\f]\n\n\t\twhere \\f$ V_r(0,t \\f$ is the variance of the short rate.\n\t\t\\f]\n\t\t*/\n\n\t\tReal sigma_u = sigma_( u );\n\n\t\treturn (sigma_u * B( u, t )) * sigma_u * E( u );\n\t}\n\n\tReal GeneralizedHullWhiteProcess::VrIntegrand( Time t ) const\n\t{\n\t\t/* Integrand of eq. 37\n\t\t\\f[\n\t\tI(t) = E^2(t)\\sigam^2(t)\n\t\t\\f]\n\t\t*/\n\t\tReal Et = E( t );\n\t\tReal sigmat = sigma_( t );\n\n\t\treturn Et * Et * sigmat * sigmat;\n\t}\n\n\tReal GeneralizedHullWhiteProcess::alpha( Time t ) const\n\t{\n\t\t/* eq. 36 \n\t\t\\f[\n\t\t\\alpha = f(0,t) + \\frac{1}{E(t)}\\int_0^t E(u)\\sigma(u)B(u,t)du\n\t\t*/\n\t\tboost::function integrand;\n\t\tintegrand = boost::bind( &GeneralizedHullWhiteProcess::alphaIntegrand, this, _1, t );\n\t\tReal IntI = integrator_( integrand, 0, t );\n\t\tReal forward = termStructure_->forwardRate( t, t, Continuous, NoFrequency );\n\n\t\treturn forward + IntI / E( t );\n\t}\n\n\tReal GeneralizedHullWhiteProcess::alphaIntegrand( Time u, Time t ) const\n\t{\n\t\tReal sigma_t = sigma_( t );\n\t\t\n\t\treturn E( t ) * sigma_t * sigma_t * B( u, t );\n\t}\n}\n\n#endif // !CALIBRATOR_PROCESSES_GENERAL_HULLWHITEPROCESS_HPP\n\n", "meta": {"hexsha": "ab98f204d382506a27d8b1d4d4a89367735e699e", "size": 7280, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "calibrator/obsolete/generalhullwhiteprocess.hpp", "max_stars_repo_name": "hanjin-kim/gaussian-n-factor", "max_stars_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2019-02-25T05:59:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-27T04:10:19.000Z", "max_issues_repo_path": "calibrator/obsolete/generalhullwhiteprocess.hpp", "max_issues_repo_name": "hanjin-kim/gaussian-n-factor", "max_issues_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calibrator/obsolete/generalhullwhiteprocess.hpp", "max_forks_repo_name": "hanjin-kim/gaussian-n-factor", "max_forks_repo_head_hexsha": "0865fa115094e1f7f8e968eb8f7f123c2cc26c9f", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-07-27T04:10:42.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-27T04:10:42.000Z", "avg_line_length": 27.680608365, "max_line_length": 93, "alphanum_fraction": 0.6589285714, "num_tokens": 2471, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8887587846530937, "lm_q2_score": 0.7248702761768248, "lm_q1q2_score": 0.6442348256860672}} {"text": "#include \n#include \n\nint main () {\n using namespace boost::numeric::ublas;\n vector u(3), v(3);\n for (unsigned i = 0; i < v.size (); ++ i) {\n u(i) = 3*i + 1;\n v(i) = i;\n }\n std::cout << u << std::endl << v << std::endl;\n double t = inner_prod(u, v);\n std::cout << t << std::endl;\n return 0;\n}\n", "meta": {"hexsha": "c365035818cda892b59912992f107feb05a91fa1", "size": 398, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "source-code/Boost/Vector/boost_vector.cpp", "max_stars_repo_name": "gjbex/Scientific-C-", "max_stars_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 115.0, "max_stars_repo_stars_event_min_datetime": "2015-03-23T13:34:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T00:27:21.000Z", "max_issues_repo_path": "source-code/Boost/Vector/boost_vector.cpp", "max_issues_repo_name": "gjbex/Scientific-C-", "max_issues_repo_head_hexsha": "d7aeb88743ffa2a43b1df1569a9200b2447f401c", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 56.0, "max_issues_repo_issues_event_min_datetime": "2015-02-25T15:04:26.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-03T07:42:48.000Z", "max_forks_repo_path": "source-code/Boost/Vector/boost_vector.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": 24.875, "max_line_length": 50, "alphanum_fraction": 0.5226130653, "num_tokens": 131, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086178944582995, "lm_q2_score": 0.7090191399336402, "lm_q1q2_score": 0.6442274780571386}} {"text": "#include \n#include \n#include \n\ndouble calculate_anisotropy(const arma::mat &m) {\n\n const double iso = arma::mean(arma::eig_sym(m));\n double aniso = arma::accu(m % m);\n aniso = std::sqrt(std::abs(1.5*(aniso - (3.0*iso*iso))));\n\n return aniso;\n}\n\nint main() {\n\n arma::mat tensor(3, 3, arma::fill::zeros);\n\n tensor(0, 0) = 12;\n tensor(1, 1) = 12;\n tensor(2, 2) = -0;\n\n arma::vec principal_components;\n arma::mat orientation;\n\n arma::eig_sym(principal_components, orientation, tensor);\n\n principal_components.print(\"principal components (real)\");\n orientation.print(\"orientation (real)\");\n\n double isotropic = arma::mean(principal_components);\n std::cout << \"isotropic : \" << isotropic << std::endl;\n double anisotropic = calculate_anisotropy(tensor);\n std::cout << \"anisotropic: \" << anisotropic << std::endl;\n\n return 0;\n}\n", "meta": {"hexsha": "1dfbad98d231d56a3f8e55d65230d97eb62b6b75", "size": 904, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "cpp/armadillo/arma_diag.cpp", "max_stars_repo_name": "berquist/eg", "max_stars_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "cpp/armadillo/arma_diag.cpp", "max_issues_repo_name": "berquist/eg", "max_issues_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cpp/armadillo/arma_diag.cpp", "max_forks_repo_name": "berquist/eg", "max_forks_repo_head_hexsha": "4c368b12eaaffcf0af8032f10348cf8bc1c3957a", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.4324324324, "max_line_length": 62, "alphanum_fraction": 0.639380531, "num_tokens": 263, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9086179043564153, "lm_q2_score": 0.7090191276365463, "lm_q1q2_score": 0.6442274739017324}} {"text": "/*\n * (C) Copyright Nick Thompson 2018.\n * Use, modification and distribution are subject to the\n * Boost Software License, Version 1.0. (See accompanying file\n * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n */\n#ifndef BOOST_INTEGER_MOD_INVERSE_HPP\n#define BOOST_INTEGER_MOD_INVERSE_HPP\n#include \n#include \n#include \n\nnamespace boost { namespace integer {\n\n// From \"The Joy of Factoring\", Algorithm 2.7.\n// Here's some others names I've found for this function:\n// PowerMod[a, -1, m] (Mathematica)\n// mpz_invert (gmplib)\n// modinv (some dude on stackoverflow)\n// Would mod_inverse be sometimes mistaken as the modular *additive* inverse?\n// In any case, I think this is the best name we can get for this function without agonizing.\ntemplate\nZ mod_inverse(Z a, Z modulus)\n{\n if (modulus < Z(2))\n {\n BOOST_THROW_EXCEPTION(std::domain_error(\"mod_inverse: modulus must be > 1\"));\n }\n // make sure a < modulus:\n a = a % modulus;\n if (a == Z(0))\n {\n // a doesn't have a modular multiplicative inverse:\n return Z(0);\n }\n boost::integer::euclidean_result_t u = boost::integer::extended_euclidean(a, modulus);\n if (u.gcd > Z(1))\n {\n return Z(0);\n }\n // x might not be in the range 0 < x < m, let's fix that:\n while (u.x <= Z(0))\n {\n u.x += modulus;\n }\n // While indeed this is an inexpensive and comforting check,\n // the multiplication overflows and hence makes the check itself buggy.\n //BOOST_ASSERT(u.x*a % modulus == 1);\n return u.x;\n}\n\n}}\n#endif\n", "meta": {"hexsha": "04b6e819320f32c13014adea8eef36192c8a3f5e", "size": 1651, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "boost/integer/mod_inverse.hpp", "max_stars_repo_name": "cpp-pm/boost", "max_stars_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 12278.0, "max_stars_repo_stars_event_min_datetime": "2015-01-29T17:11:33.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:12:00.000Z", "max_issues_repo_path": "boost/integer/mod_inverse.hpp", "max_issues_repo_name": "cpp-pm/boost", "max_issues_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 9469.0, "max_issues_repo_issues_event_min_datetime": "2015-01-30T05:33:07.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T16:17:21.000Z", "max_forks_repo_path": "boost/integer/mod_inverse.hpp", "max_forks_repo_name": "cpp-pm/boost", "max_forks_repo_head_hexsha": "38c6c8c07f2fcc42d573b10807fef27ec14930f8", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 892.0, "max_forks_repo_forks_event_min_datetime": "2015-01-29T16:26:19.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-20T07:44:30.000Z", "avg_line_length": 30.5740740741, "max_line_length": 93, "alphanum_fraction": 0.6650514839, "num_tokens": 440, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8633916099737807, "lm_q2_score": 0.7461390043208003, "lm_q1q2_score": 0.6442101562047695}} {"text": "#include \r\n#include \r\n\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\r\n\r\nusing namespace Eigen;\r\n\r\n#include \"kshape.h\"\r\n\r\ntypedef Matrix MatrixXld;\r\ntypedef Matrix< std::complex< long double >, Dynamic, Dynamic > MatrixXcld;\r\ntypedef Matrix< long double, Dynamic, 1 > VectorXld;\r\ntypedef Matrix< std::complex< long double >, Dynamic, 1 > VectorXcld;\r\n\r\n\r\nVectorXld coefWiseDivision(VectorXld x, VectorXld y){\r\n VectorXld ans(x.size());\r\n for (int i=0;i 0) // shift right\r\n\t{\r\n\t\ty.head(shift) = vec.tail(shift);\r\n\t\ty.tail(n - shift) = vec.head(n - shift);\r\n\t}\r\n\r\n if(shift<0) // shift left\r\n\t{\r\n\t\ty.head(n + shift) = vec.tail(n + shift);\r\n\t\ty.tail(abs(shift)) = vec.head(abs(shift));\r\n\r\n\t}\r\n\r\n\treturn y;\r\n}\r\n\r\n\r\nVectorXld shiftWithZeors(VectorXld vec, int shift){\r\n int n = vec.size();\r\n VectorXld newvec(n);\r\n newvec.setZero();\r\n if (shift==0)\r\n\t{\r\n newvec.array() = vec.array();\r\n\t\treturn newvec;\r\n\t}\r\n\r\n if (std::abs(shift)>n){\r\n return newvec;\r\n }\r\n\r\n\t if (shift > 0) // shift right\r\n\t{\r\n\t\tnewvec.tail(n - shift) = vec.head(n - shift);\r\n //vec.head(shift).setZero();\r\n\t}\r\n\r\n if(shift<0) // shift left\r\n\t{\r\n\t\tnewvec.head(n + shift) = vec.tail(n + shift);\r\n\t\t//vec.tail(abs(shift)).setZero();\r\n\t}\r\n\r\n\treturn newvec;\r\n}\r\n\r\nVectorXld NCC(VectorXld x, VectorXld y){\r\n long double normed = x.norm()*y.norm();\r\n if (normed == 0){\r\n normed = 1000000000000.0 ;\r\n }\r\n\r\n int x_len = x.size();\r\n\r\n int fft_size = 1 << (int)ceil(log2((2*x_len - 1)));\r\n\r\n FFT fft;\r\n VectorXcld x_out;\r\n\r\n VectorXld transformed_x(fft_size);\r\n transformed_x.setZero();\r\n\r\n transformed_x.head(x_len) = x;\r\n fft.fwd(x_out, transformed_x);\r\n\r\n VectorXcld y_out;\r\n VectorXld transformed_y(fft_size);\r\n transformed_y.setZero();\r\n transformed_y.head(y.size()) = y;\r\n fft.fwd(y_out, transformed_y);\r\n\r\n VectorXld cc_out;\r\n VectorXcld inter = x_out.cwiseProduct( y_out.conjugate() );\r\n fft.inv(cc_out, inter);\r\n\r\n VectorXld cc(2*x_len - 1);\r\n cc.setZero();\r\n cc.head(x_len-1) = cc_out.tail(x_len-1);\r\n cc.tail(x_len) = cc_out.head(x_len);\r\n\r\n return cc.real() / normed;\r\n}\r\n\r\nstd::vector NCC3D(MatrixXld x, MatrixXld y){\r\n VectorXld x_norm = x.rowwise().norm();\r\n VectorXld y_norm = y.rowwise().norm();\r\n MatrixXld den(x_norm.size(),y_norm.size());\r\n for (int i = 0;i fft;\r\n\r\n MatrixXcld x_out;\r\n MatrixXcld y_out;\r\n\r\n std::vector cc(y.rows());\r\n\r\n for (int k=0;k SBD (VectorXld x, VectorXld y){\r\n VectorXld ncc = NCC(x, y);\r\n int idx;\r\n long double dist = 1.0 - ncc.maxCoeff(&idx);\r\n\r\n VectorXld yshift = shiftWithZeors(y, (idx+1)-std::max(x.size(),y.size()));\r\n\r\n return std::make_pair(dist, yshift);\r\n}\r\n\r\nMatrixXld z_norm(MatrixXld a, int axis = 0,int ddof=0){\r\n VectorXld means;\r\n VectorXld sstd;\r\n if (axis == 0){\r\n means = a.colwise().mean();\r\n int n = means.size();\r\n\r\n VectorXld sstd = VectorXld(n);\r\n for (int i=0;i eigensolver(m);\r\n MatrixXcld eigenVectors = eigensolver.eigenvectors();\r\n int cols = eigenVectors.cols();\r\n VectorXcld eigenvalues = eigensolver.eigenvalues();\r\n\r\n VectorXld centroid = eigenVectors.col(cols-1).real();\r\n\r\n long double dist1 = (cluster.row(0)-centroid.transpose()).array().pow(2).sum();\r\n long double dist2 = (cluster.row(0)+centroid.transpose()).array().pow(2).sum();\r\n\r\n if (dist1>=dist2){\r\n centroid.array() *= -1.0;\r\n }\r\n\r\n return z_norm(centroid,0,1);\r\n\r\n }\r\n\r\n\r\nstd::pair, MatrixXld> kshape(MatrixXld x, int k, int runs_to_average_over){\r\n int m = x.rows();\r\n int n = x.cols();\r\n\r\n std::vector vidx(m);\r\n std::vector bestidx(m);\r\n\r\n MatrixXld bestcentroids(k,n);\r\n bestcentroids.setZero();\r\n\r\n int number_in_center[k];\r\n long double bestdist=0.0;\r\n\r\n for (int run=0;run x_corr = NCC3D(x, centroids);\r\n\r\n MatrixXld distances(m, k);\r\n\r\n for (int i=0;ibestdist){\r\n bestdist=dist;\r\n bestidx=vidx;\r\n bestcentroids = centroids;\r\n }\r\n break;\r\n }\r\n }\r\n\r\n if (changed){\r\n if (dist>bestdist){\r\n bestdist=dist;\r\n bestidx=vidx;\r\n bestcentroids = centroids;\r\n }\r\n }\r\n }\r\n\r\n return std::make_pair(bestidx, bestcentroids);\r\n}\r\n\r\nMatrixXld read_csv(std::string filename, int rows, int cols){\r\n std::ifstream file(filename);\r\n MatrixXld mat(rows,cols);\r\n\r\n std::string line;\r\n long double val; int row=0;\r\n\r\n while(std::getline(file, line))\r\n {\r\n std::stringstream ss(line);\r\n // Keep track of the current column index\r\n int col = 0;\r\n // Extract each integer\r\n while(ss >> val){\r\n // Add the current integer to the 'colIdx' column's values vector\r\n mat(row,col) = val;\r\n // If the next token is a comma, ignore it and move on\r\n if(ss.peek() == ',') ss.ignore();\r\n // Increment the column index\r\n col++;\r\n }\r\n row++;\r\n }\r\n\r\n file.close();\r\n\r\n return z_norm(mat,1,1);\r\n}\r\n\r\nvoid write_csv(std::string filename, MatrixXld mat){\r\n std::ofstream file(filename);\r\n\r\n for(int i = 0; i < mat.rows(); ++i)\r\n {\r\n for(int j = 0; j < mat.cols(); ++j)\r\n {\r\n file << mat(i,j);\r\n if(j != mat.cols() - 1) file << \",\";\r\n }\r\n file << \"\\n\";\r\n }\r\n file.close();\r\n\r\n}\r\n\r\nvoid write_csv(std::string filename, std::vector v){\r\n std::ofstream file(filename);\r\n\r\n for(int j = 0; j < v.size(); ++j){\r\n file << v[j];\r\n if(j != v.size() - 1) file << \",\";\r\n }\r\n file << \"\\n\";\r\n file.close();\r\n}\r\n\r\n\r\nint main(int argc, char* argv[]){\r\n\r\n if (argc < 6){\r\n std::cerr << \"Need to speficy a csv, and its number of rows and columns, as well as K and a number of runs\" << std::endl;\r\n return 1;\r\n }\r\n\r\n std::string csv_filename = std::string(argv[1]);\r\n int rows = atoi(argv[2]), cols = atoi(argv[3]), k = atoi(argv[4]), runs=atoi(argv[5]);\r\n\r\n MatrixXld mat = read_csv(csv_filename, rows, cols);\r\n mat = z_norm(mat, 1,1);\r\n std::pair, MatrixXld> result = kshape(mat, k, runs);\r\n write_csv(\"out_centroids.csv\", result.second);\r\n write_csv(\"out_indices.csv\", result.first);\r\n std::vector cluster_counts(k);\r\n for (auto i: result.first) cluster_counts[i]++;\r\n std::cout << std::endl;\r\n for (int i=0;i\n#include \n#include \n\n// References:\n//\n// [1] Eftychios Sifakis and Jernej Barbic. 2012. FEM simulation of 3D deformable solids: a practitioner's guide to\n// theory, discretization and model reduction. In ACM SIGGRAPH 2012 Courses (SIGGRAPH '12). Association for Computing\n// Machinery, New York, NY, USA, Article 20, 1–50. DOI:https://doi.org/10.1145/2343483.2343501\n//\n// [2] Theodore Kim and David Eberle. 2020. Dynamic deformables: implementation and production practicalities. In ACM\n// SIGGRAPH 2020 Courses (SIGGRAPH '20). Association for Computing Machinery, New York, NY, USA, Article 23, 1–182.\n// DOI:https://doi.org/10.1145/3388769.3407490\n\nnamespace elasty::fem\n{\n /// \\brief Extract the rotational part of the given square matrix by performing polar decomposion.\n ///\n /// \\details This implementation is based on SVD. It checks the determinant to avoid any reflection.\n template \n Eigen::Matrix\n extractRotation(const Eigen::MatrixBase& F)\n {\n const auto svd = F.jacobiSvd(Eigen::ComputeFullU | Eigen::ComputeFullV);\n const auto Sigma = svd.singularValues();\n const auto U = svd.matrixU();\n const auto V = svd.matrixV();\n const auto R = (U * V.transpose()).eval();\n\n assert(std::abs(std::abs(R.determinant()) - 1.0) < 1e-04);\n\n if constexpr (Derived::RowsAtCompileTime == 2)\n {\n // Just ignore reflection (if any)\n // TODO: Discuss whether this is a good strategy, or not\n return R;\n }\n else if constexpr (Derived::RowsAtCompileTime == 3)\n {\n // Correct reflection (if any)\n return (R.determinant() > 0) ? R : -R;\n }\n }\n\n /// \\brief Calculate the first Lame parameter, $\\lambda$.\n ///\n /// \\details Reference: [1]\n template constexpr Scalar calcFirstLame(const Scalar youngs_modulus, const Scalar poisson_ratio)\n {\n return youngs_modulus * poisson_ratio / ((1.0 + poisson_ratio) * (1.0 - 2.0 * poisson_ratio));\n }\n\n /// \\brief Calculate the second Lame parameter, $\\mu$.\n ///\n /// \\details Reference: [1]\n template constexpr Scalar calcSecondLame(const Scalar youngs_modulus, const Scalar poisson_ratio)\n {\n return youngs_modulus / (2.0 * (1.0 + poisson_ratio));\n }\n\n /// \\brief Calculate either the \"deformed\" shape matrix (D_s) or \"reference\" shape matrix (D_m) of a triangle.\n ///\n /// \\param x_0 A 2D vector.\n ///\n /// \\param x_1 A 2D vector.\n ///\n /// \\param x_2 A 2D vector.\n ///\n /// \\details Reference: [1]\n template \n Eigen::Matrix calc2dShapeMatrix(const Eigen::MatrixBase& x_0,\n const Eigen::MatrixBase& x_1,\n const Eigen::MatrixBase& x_2)\n {\n using Mat = Eigen::Matrix;\n\n Mat shape_matrix;\n shape_matrix.col(0) = x_1 - x_0;\n shape_matrix.col(1) = x_2 - x_0;\n\n return shape_matrix;\n }\n\n /// \\brief Calculate either the \"deformed\" shape matrix (D_s) or \"reference\" shape matrix (D_m) of a tetrahedron.\n ///\n /// \\param x_0 A 3D vector.\n ///\n /// \\param x_1 A 3D vector.\n ///\n /// \\param x_2 A 3D vector.\n ///\n /// \\param x_3 A 3D vector.\n ///\n /// \\details Reference: [1]\n template \n Eigen::Matrix calc3dShapeMatrix(const Eigen::MatrixBase& x_0,\n const Eigen::MatrixBase& x_1,\n const Eigen::MatrixBase& x_2,\n const Eigen::MatrixBase& x_3)\n {\n using Mat = Eigen::Matrix;\n\n Mat shape_matrix;\n shape_matrix.col(0) = x_1 - x_0;\n shape_matrix.col(1) = x_2 - x_0;\n shape_matrix.col(2) = x_3 - x_0;\n\n return shape_matrix;\n }\n\n /// \\brief Calculate the area of a triangle in 2D\n template \n typename Derived::Scalar calc2dTriangleArea(const Eigen::MatrixBase& x_0,\n const Eigen::MatrixBase& x_1,\n const Eigen::MatrixBase& x_2)\n {\n const auto r_1 = x_1 - x_0;\n const auto r_2 = x_2 - x_0;\n\n return 0.5 * std::abs(r_1(0) * r_2(1) - r_2(0) * r_1(1));\n }\n\n /// \\brief Calculate the volume of a tetrahedron\n template \n typename Derived::Scalar calcTetrahedronVolume(const Eigen::MatrixBase& x_0,\n const Eigen::MatrixBase& x_1,\n const Eigen::MatrixBase& x_2,\n const Eigen::MatrixBase& x_3)\n {\n const auto r_1 = x_1 - x_0;\n const auto r_2 = x_2 - x_0;\n const auto r_3 = x_3 - x_0;\n\n return std::abs(r_1.dot(r_2.cross(r_3))) / 6.0;\n }\n\n /// \\brief Calculate the diagonal elements of the lumped mass matrix.\n ///\n /// \\details This function takes the \"barycentric\" approach. See https://www.alecjacobson.com/weblog/?p=1146 .\n template \n Eigen::Matrix\n calcTriangleMeshLumpedMass(const Eigen::MatrixBase& verts,\n const Eigen::MatrixBase& elems,\n const typename DerivedV::Scalar total_mass)\n {\n using Scalar = typename DerivedV::Scalar;\n using Vec = Eigen::Matrix;\n\n assert(verts.cols() == 1);\n assert(verts.size() % 2 == 0);\n assert(elems.rows() == 3);\n\n const auto num_verts = verts.size() / 2;\n\n Scalar total_area = 0;\n Vec masses = Vec::Zero(verts.size());\n\n for (std::size_t elem_index = 0; elem_index < elems.cols(); ++elem_index)\n {\n const auto& indices = elems.col(elem_index);\n\n const Scalar area = calc2dTriangleArea(verts.template segment<2>(2 * indices[0]),\n verts.template segment<2>(2 * indices[1]),\n verts.template segment<2>(2 * indices[2]));\n\n const Scalar one_third_area = (1.0 / 3.0) * area;\n\n masses(2 * indices[0] + 0) += one_third_area;\n masses(2 * indices[0] + 1) += one_third_area;\n masses(2 * indices[1] + 0) += one_third_area;\n masses(2 * indices[1] + 1) += one_third_area;\n masses(2 * indices[2] + 0) += one_third_area;\n masses(2 * indices[2] + 1) += one_third_area;\n\n total_area += area;\n }\n\n assert(total_mass > 0);\n assert(total_area > 0);\n\n return (total_mass / total_area) * masses;\n }\n\n /// \\brief Calculate the diagonal elements of the lumped mass matrix.\n template \n Eigen::Matrix\n calcTetraMeshLumpedMass(const Eigen::MatrixBase& verts,\n const Eigen::MatrixBase& elems,\n const typename DerivedV::Scalar total_mass)\n {\n using Scalar = typename DerivedV::Scalar;\n using Vec = Eigen::Matrix;\n\n assert(verts.cols() == 1);\n assert(verts.size() % 3 == 0);\n assert(elems.rows() == 4);\n\n const auto num_verts = verts.size() / 3;\n const auto num_elems = elems.cols();\n\n Scalar total_vol = 0;\n Vec masses = Vec::Zero(verts.size());\n\n for (std::size_t elem_index = 0; elem_index < num_elems; ++elem_index)\n {\n const auto& indices = elems.col(elem_index);\n\n const Scalar vol = calcTetrahedronVolume(verts.template segment<3>(3 * indices[0]),\n verts.template segment<3>(3 * indices[1]),\n verts.template segment<3>(3 * indices[2]),\n verts.template segment<3>(3 * indices[3]));\n\n const Scalar one_fourth_vol = (1.0 / 4.0) * vol;\n\n masses.template segment<3>(3 * indices[0]) += one_fourth_vol * Eigen::Vector3d::Ones();\n masses.template segment<3>(3 * indices[1]) += one_fourth_vol * Eigen::Vector3d::Ones();\n masses.template segment<3>(3 * indices[2]) += one_fourth_vol * Eigen::Vector3d::Ones();\n masses.template segment<3>(3 * indices[3]) += one_fourth_vol * Eigen::Vector3d::Ones();\n\n total_vol += vol;\n }\n\n assert(total_mass > 0);\n assert(total_vol > 0);\n assert(masses.minCoeff() > 0.0);\n\n return (total_mass / total_vol) * masses;\n }\n\n /// \\brief Calculate the Green strain tensor for a finite element.\n ///\n /// \\param deform_grad The deformation gradient matrix, which should be either 2-by-2 (2D element in 2D), 3-by-3 (3D\n /// element in 3D), or 3-by-2 (2D element in 3D).\n template \n Eigen::Matrix\n calcGreenStrain(const Eigen::MatrixBase& deform_grad)\n {\n using Mat = Eigen::Matrix;\n\n return 0.5 * (deform_grad.transpose() * deform_grad - Mat::Identity());\n }\n\n /// \\details Eq. 3.4 in [1]\n template \n typename Derived::Scalar calcCoRotationalEnergyDensity(const Eigen::MatrixBase& deform_grad,\n const typename Derived::Scalar first_lame,\n const typename Derived::Scalar second_lame)\n {\n using Mat = Eigen::Matrix;\n\n const auto R = extractRotation(deform_grad);\n const auto S = R.transpose() * deform_grad;\n const auto I = Mat::Identity();\n const auto trace = (S - I).trace();\n\n assert(deform_grad.isApprox(R * S));\n\n return second_lame * (deform_grad - R).squaredNorm() + 0.5 * first_lame * trace * trace;\n }\n\n /// \\details Eq. 3.5 in [1]\n template \n Eigen::Matrix\n calcCoRotationalPiolaStress(const Eigen::MatrixBase& deform_grad,\n const typename Derived::Scalar first_lame,\n const typename Derived::Scalar second_lame)\n {\n using Mat = Eigen::Matrix;\n\n const auto R = extractRotation(deform_grad);\n const auto S = R.transpose() * deform_grad;\n const auto I = Mat::Identity();\n const auto trace = (S - I).trace();\n\n assert(deform_grad.isApprox(R * S));\n\n return 2.0 * second_lame * (deform_grad - R) + first_lame * trace * R;\n }\n\n /// \\details The first equation in Sec. 3.3 in [1]\n template \n typename Derived::Scalar calcStVenantKirchhoffEnergyDensity(const Eigen::MatrixBase& deform_grad,\n const typename Derived::Scalar first_lame,\n const typename Derived::Scalar second_lame)\n {\n const auto E = calcGreenStrain(deform_grad);\n const auto trace = E.trace();\n\n return second_lame * E.squaredNorm() + 0.5 * first_lame * trace * trace;\n }\n\n /// \\details Eq. 3.3 in [1]\n template \n Eigen::Matrix\n calcStVenantKirchhoffPiolaStress(const Eigen::MatrixBase& deform_grad,\n const typename Derived::Scalar first_lame,\n const typename Derived::Scalar second_lame)\n {\n const auto E = calcGreenStrain(deform_grad);\n\n return 2.0 * second_lame * deform_grad * E + first_lame * E.trace() * deform_grad;\n }\n\n template \n Eigen::Matrix\n calc2dTriangleDeformGrad(const Eigen::MatrixBase& x_0,\n const Eigen::MatrixBase& x_1,\n const Eigen::MatrixBase& x_2,\n const Eigen::MatrixBase& rest_shape_mat_inv)\n {\n const auto D_s = elasty::fem::calc2dShapeMatrix(x_0, x_1, x_2);\n const auto F = D_s * rest_shape_mat_inv;\n\n return F;\n }\n\n template \n Eigen::Matrix\n calcTetrahedronDeformGrad(const Eigen::MatrixBase& x_0,\n const Eigen::MatrixBase& x_1,\n const Eigen::MatrixBase& x_2,\n const Eigen::MatrixBase& x_3,\n const Eigen::MatrixBase& rest_shape_mat_inv)\n {\n const auto D_s = elasty::fem::calc3dShapeMatrix(x_0, x_1, x_2, x_3);\n const auto F = D_s * rest_shape_mat_inv;\n\n return F;\n }\n\n /// \\brief Calculate analytic partial derivatives of the deformation gradient $\\mathbf{F}$ with respect to the\n /// vertex positions $\\mathbf{x}$ (i.e., $\\frac{\\partial \\mathbf{F}}{\\partial \\mathbf{x}}$) and return it in the\n /// \"flattened\" format.\n ///\n /// \\details The result is a 2-by-2-by-6 third-order tensor but flattened into a 4-by-6 matrix.\n ///\n /// Reference: [2, Appendix D]\n template \n Eigen::Matrix\n calcVecTrianglePartDeformGradPartPos(const Eigen::MatrixBase& rest_shape_mat_inv)\n {\n using Scalar = typename Derived::Scalar;\n\n // Analytics partial derivatives $\\frac{\\partial \\mathbf{D}_\\text{s}{\\partial x_{i}}$\n Eigen::Matrix PDsPx[6];\n\n // x[0] (= x_0)\n PDsPx[0] << -1.0, -1.0, 0.0, 0.0;\n\n // x[1] (= y_0)\n PDsPx[1] << 0.0, 0.0, -1.0, -1.0;\n\n // x[2] (= x_1)\n PDsPx[2] << 1.0, 0.0, 0.0, 0.0;\n\n // x[3] (= y_1)\n PDsPx[3] << 0.0, 0.0, 1.0, 0.0;\n\n // x[4] (= x_2)\n PDsPx[4] << 0.0, 1.0, 0.0, 0.0;\n\n // x[5] (= y_2)\n PDsPx[5] << 0.0, 0.0, 0.0, 1.0;\n\n Eigen::Matrix vec_PFPx;\n for (std::size_t i = 0; i < 6; ++i)\n {\n const Eigen::Matrix PFPx_i = PDsPx[i] * rest_shape_mat_inv;\n\n vec_PFPx.col(i) = Eigen::Map>(PFPx_i.data(), PFPx_i.size());\n }\n\n return vec_PFPx;\n }\n\n /// \\brief Calculate analytic partial derivatives of the deformation gradient $\\mathbf{F}$ with respect to the\n /// vertex positions $\\mathbf{x}$ (i.e., $\\frac{\\partial \\mathbf{F}}{\\partial \\mathbf{x}}$) and return it in the\n /// \"flattened\" format.\n ///\n /// \\details The result is a 3-by-3-by-12 third-order tensor but flattened into a 9-by-12 matrix.\n ///\n /// Reference: [2, Appendix D]\n template \n Eigen::Matrix\n calcVecTetrahedronPartDeformGradPartPos(const Eigen::MatrixBase& rest_shape_mat_inv)\n {\n using Scalar = typename Derived::Scalar;\n\n // Analytics partial derivatives $\\frac{\\partial \\mathbf{D}_\\text{s}{\\partial x_{i}}$\n Eigen::Matrix PDsPx[12];\n\n PDsPx[0] << -1.0, -1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n PDsPx[1] << 0.0, 0.0, 0.0, -1.0, -1.0, -1.0, 0.0, 0.0, 0.0;\n PDsPx[2] << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, -1.0, -1.0;\n\n PDsPx[3] << 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n PDsPx[4] << 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n PDsPx[5] << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0;\n\n PDsPx[6] << 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n PDsPx[7] << 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0;\n PDsPx[8] << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0;\n\n PDsPx[9] << 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0;\n PDsPx[10] << 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0;\n PDsPx[11] << 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0;\n\n Eigen::Matrix vec_PFPx;\n for (std::size_t i = 0; i < 12; ++i)\n {\n const Eigen::Matrix PFPx_i = PDsPx[i] * rest_shape_mat_inv;\n\n vec_PFPx.col(i) = Eigen::Map>(PFPx_i.data(), PFPx_i.size());\n }\n\n return vec_PFPx;\n }\n} // namespace elasty::fem\n\n#endif // ELASTY_FEM_HPP\n", "meta": {"hexsha": "490fe43c4dd012e0a88db58697f7b7300c715373", "size": 17749, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/elasty/fem.hpp", "max_stars_repo_name": "yuki-koyama/elasty", "max_stars_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 176.0, "max_stars_repo_stars_event_min_datetime": "2019-04-27T00:45:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-26T03:15:45.000Z", "max_issues_repo_path": "include/elasty/fem.hpp", "max_issues_repo_name": "yuki-koyama/elasty", "max_issues_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 28.0, "max_issues_repo_issues_event_min_datetime": "2019-04-27T00:00:49.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-30T07:01:12.000Z", "max_forks_repo_path": "include/elasty/fem.hpp", "max_forks_repo_name": "yuki-koyama/elasty", "max_forks_repo_head_hexsha": "67c7a15c1483fe1979b8b3af64be4f34e110c760", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 15.0, "max_forks_repo_forks_event_min_datetime": "2019-04-27T01:09:58.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-09T13:30:41.000Z", "avg_line_length": 41.8608490566, "max_line_length": 120, "alphanum_fraction": 0.5649895769, "num_tokens": 5055, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767842777551, "lm_q2_score": 0.7341195385342971, "lm_q1q2_score": 0.6441728519485446}} {"text": "\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\ntypedef boost::numeric::ublas::vector Vector3;\r\ntypedef boost::numeric::ublas::matrix Matrix44;\r\n\r\n\r\nint main()\r\n{\r\n\tVector3 vector(4);\r\n\tMatrix44 matrix(4, 4);\r\n\tD3DXVECTOR3 dVector3;\r\n\tD3DXMATRIX dMatrix44;\r\n\r\n\tfor (int i = 0; i < vector.size(); ++i) {\r\n\t\tvector(i) = i;\r\n\t}\r\n\r\n\tfor (int i = 0; i < 4; ++i) {\r\n\t\tfor (int j = 0; j < 4; ++j) {\r\n\t\t\tmatrix(i, j) = 4 * i + j;\r\n\t\t\tdMatrix44.m[i][j] = matrix(i, j);\r\n\t\t}\r\n\t}\r\n\r\n\tstd::cout << vector << std::endl;\r\n\tstd::cout << matrix << std::endl;\r\n\t//std::cout << dMatrix44 << std::endl;\r\n\tfor (int i = 0; i < 4; ++i) {\r\n\t\tfor (int j = 0; j < 4; ++j) {\r\n\t\t\tstd::cout << dMatrix44.m[i][j] << \" \";\r\n\t\t}\r\n\t}\r\n\tstd::cout << std::endl;\r\n\r\n\tVector3 multipul = boost::numeric::ublas::prod(matrix, vector);\r\n\t//Vector3 multipul = boost::numeric::ublas::prod(vector, matrix);\r\n\r\n\tstd::cout << multipul << std::endl;\r\n\r\n\r\n\treturn 0;\r\n}\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "2a24215e9b358e6edcb12064677a3b4adfb205f4", "size": 1095, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "c++/MatrixTest/AxisTest.cpp", "max_stars_repo_name": "taku-xhift/labo", "max_stars_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "c++/MatrixTest/AxisTest.cpp", "max_issues_repo_name": "taku-xhift/labo", "max_issues_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "c++/MatrixTest/AxisTest.cpp", "max_forks_repo_name": "taku-xhift/labo", "max_forks_repo_head_hexsha": "89dc28fdb602c7992c6f31920714225f83a11218", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 19.5535714286, "max_line_length": 67, "alphanum_fraction": 0.5652968037, "num_tokens": 367, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8774767746654974, "lm_q2_score": 0.7341195327172402, "lm_q1q2_score": 0.644172839787666}} {"text": "/*\nCopyright (c) 2018 Inverse Palindrome\nApophis - Conversions.hpp\nInversePalindrome.com\n*/\n\n\n#pragma once\n\n#include \n\n\nnamespace Conversions\n{\n template\n T degreesToRadians(T degrees)\n {\n return degrees * boost::math::constants::pi() / (T)180;\n }\n\n template\n T radiansToDegrees(T radians)\n {\n return radians * (T)180 / boost::math::constants::pi();\n }\n}", "meta": {"hexsha": "291de7886c60d3a926643f47187b4e01d9020ea1", "size": 458, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Classes/Conversions.hpp", "max_stars_repo_name": "InversePalindrome/Apophis", "max_stars_repo_head_hexsha": "c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 7.0, "max_stars_repo_stars_event_min_datetime": "2018-08-20T17:28:29.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-05T15:19:31.000Z", "max_issues_repo_path": "Classes/Conversions.hpp", "max_issues_repo_name": "InversePalindrome/JATR66", "max_issues_repo_head_hexsha": "c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Classes/Conversions.hpp", "max_forks_repo_name": "InversePalindrome/JATR66", "max_forks_repo_head_hexsha": "c2bb39e87d63cb51bc67f8e3682d84b3b4f970c8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2019-12-25T12:02:03.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-25T12:02:03.000Z", "avg_line_length": 17.6153846154, "max_line_length": 66, "alphanum_fraction": 0.6528384279, "num_tokens": 114, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8499711832583695, "lm_q2_score": 0.757794360334681, "lm_q1q2_score": 0.644103369120188}} {"text": "//\n// GrowthHelper.hpp\n// Elasticity\n//\n// Created by Wim van Rees on 8/17/16.\n// Copyright © 2016 Wim van Rees. All rights reserved.\n//\n\n#ifndef GrowthHelper_hpp\n#define GrowthHelper_hpp\n\n#include \"common.hpp\"\n#include \"TriangleInfo.hpp\"\n\n#include \n#include \n\n\nclass DecomposedGrowthState\n{\nprotected:\n Real s1, s2;\n Eigen::Vector3d v1, v2;\n \n void decompose_metric(const Eigen::MatrixXd & rxy, const Eigen::Matrix2d & metric)\n {\n // decompute metric\n const Eigen::Matrix2d a_i = rxy.transpose() * rxy;\n \n // compute delta_metric\n const Eigen::Matrix2d delta_a = a_i.inverse() * metric;\n \n // eigensolver\n Eigen::EigenSolver es(delta_a);\n const Eigen::Vector2d evals = es.eigenvalues().real();\n const Eigen::Matrix2d evecs = es.eigenvectors().real();\n \n // evecs is the V-matrix (generalized eigen-vectors) but not appropriately normalized yet -- normalize\n // const Eigen::Matrix2d shouldBeI = evecs.transpose() * a_i * evecs;\n // const Eigen::Matrix2d V = evecs * shouldBeI.inverse().sqrt();\n \n const Eigen::MatrixXd v12_evec = rxy * evecs;\n Eigen::Vector3d v1_evec = v12_evec.col(0).normalized();\n Eigen::Vector3d v2_evec = v12_evec.col(1).normalized();\n \n // note: for everything else here we assume that v1 and v2 are orthogonal\n // however if s1==s2 --> the values of v1 and v2 are arbitrary and so from whatever we do above, they might turn out to not be orthogonal\n // so, in this case we orthogonalize them by hand (they are already normalized)\n // but since we can still have them equal, instead we set them equal to rxy_1 and rxy_2 first and orthogonalize second\n if(std::abs(evals(0) - evals(1)) < 1e-12)\n {\n v1_evec = rxy.col(0);\n v2_evec = rxy.col(1);\n \n v1_evec.normalize();\n v2_evec = v2_evec - v1_evec.dot(v2_evec)*v1_evec;\n v2_evec.normalize();\n }\n \n // finally we assign\n s1 = std::sqrt(evals(0));\n s2 = std::sqrt(evals(1));\n v1 = v1_evec;\n v2 = v2_evec;\n \n if(s2 > s1) // make sure that s1 is the biggest (does not matter really, just convention -- will still give the same matrix)\n {\n std::swap(s1,s2);\n v1.swap(v2);\n }\n#ifndef NDEBUG\n if(not checkVectorValidity())\n {\n std::cout << \"decomposition is not valid : the eigenvectors are not unit length and/or not orthogonal\" << std::endl;\n print();\n printf(\"computed eigenvalues are %10.10e \\t %10.10e\\n\", evals(0), evals(1));\n printf(\"computed evec1 is %10.10e \\t %10.10e\\n\", evecs(0,0), evecs(1,0));\n printf(\"computed evec2 is %10.10e \\t %10.10e\\n\", evecs(0,1), evecs(1,1));\n printf(\"input rxy_1 is %10.10e \\t %10.10e \\t %10.10e\\n\", rxy(0,0), rxy(1,0), rxy(2,0));\n printf(\"input rxy_2 is %10.10e \\t %10.10e \\t %10.10e\\n\", rxy(0,1), rxy(1,1), rxy(2,1));\n printf(\"input metric is %10.10e \\t %10.10e \\t %10.10e\\n\", metric(0,0), metric(0,1), metric(1,1));\n \n assert(checkVectorValidity());\n }\n#endif\n }\n \npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW // https://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html\n \n DecomposedGrowthState(const Real s1_in, const Real s2_in, const Eigen::Vector3d & v1_in, const Eigen::Vector3d & v2_in):\n s1(s1_in),\n s2(s2_in),\n v1(v1_in),\n v2(v2_in)\n {}\n \n DecomposedGrowthState(const Eigen::MatrixXd & rxy, const Eigen::Matrix2d & metric)\n {\n decompose_metric(rxy, metric);\n }\n \n void changeMetric(const Eigen::MatrixXd & rxy, const Eigen::Matrix2d & metric)\n {\n decompose_metric(rxy, metric);\n }\n \n bool checkVectorValidity(const Real tol = 1e-9) const\n {\n const bool unit_v1 = std::abs(v1.dot(v1) - 1) < tol;\n const bool unit_v2 = std::abs(v2.dot(v2) - 1) < tol;\n const bool ortho = std::abs(v1.dot(v2)) < tol;\n return (unit_v1 and unit_v2 and ortho);\n }\n \n void print() const\n {\n printf(\"s1/s2 : %10.10e \\t %10.10e \\t\\t v1 : %10.10e, %10.10e, %10.10e \\t v2 : %10.10e, %10.10e, %10.10e\\n\",s1,s2,v1(0),v1(1),v1(2),v2(0),v2(1),v2(2));\n }\n \n Eigen::Matrix2d computeMetric(const Eigen::MatrixXd & rxy) const\n {\n const Eigen::Matrix2d a_i = rxy.transpose() * rxy;\n const Eigen::Matrix2d Lsq = (Eigen::Matrix2d() << s1*s1,0,0,s2*s2).finished();\n Eigen::MatrixXd v12(3,2);\n v12 << v1,v2;\n const Eigen::Matrix2d V = (v12.transpose() * rxy).inverse();\n const Eigen::Matrix2d a_f = a_i * V * Lsq * V.transpose() * a_i;\n return a_f;\n }\n \n Real get_s1() const {return s1;}\n Real get_s2() const {return s2;}\n Eigen::Vector3d get_v1() const {return v1;}\n Eigen::Vector3d get_v2() const {return v2;}\n};\n\nclass GrowthState\n{\nprotected:\n const Eigen::MatrixXd rxy_base;\n const Eigen::Matrix2d a_final;\n const DecomposedGrowthState decomposed_final;\n Eigen::Matrix2d a_init;\n DecomposedGrowthState decomposed_init;\n \npublic:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW // https://eigen.tuxfamily.org/dox/group__TopicStructHavingEigenMembers.html\n \n GrowthState(const Eigen::MatrixXd & rxy_base_in, const Eigen::Matrix2d & a_final_in):\n rxy_base(rxy_base_in),\n a_final(a_final_in),\n decomposed_final(rxy_base, a_final),\n a_init(rxy_base.transpose() * rxy_base),\n decomposed_init(rxy_base, a_init)\n {\n }\n \n GrowthState(const Eigen::MatrixXd & rxy_base_in, const Eigen::Matrix2d & a_init_in, const Eigen::Matrix2d & a_final_in):\n rxy_base(rxy_base_in),\n a_final(a_final_in),\n decomposed_final(rxy_base, a_final),\n a_init(a_init_in),\n decomposed_init(rxy_base, a_init)\n {\n }\n \n \n void changeInitialState(const Eigen::Matrix2d & a_init_in)\n {\n a_init = a_init_in;\n decomposed_init.changeMetric(rxy_base, a_init);\n }\n \n Eigen::Matrix2d interpolate_from_iso(const Real t) const\n {\n // we start from isotropic : just interpolate the growth factors\n const Real s1_interp = (1.0 - t) * decomposed_init.get_s1() + t*decomposed_final.get_s1();\n const Real s2_interp = (1.0 - t) * decomposed_init.get_s2() + t*decomposed_final.get_s2();\n \n const DecomposedGrowthState decomposed_intermediate(s1_interp, s2_interp, decomposed_final.get_v1(), decomposed_final.get_v2());\n return decomposed_intermediate.computeMetric(rxy_base);\n }\n \n Eigen::Matrix2d interpolate_from_iso_logeucl(const Real t) const\n {\n // we start from isotropic : just interpolate the growth factors\n const Real s1_interp = std::exp( (1.0 - t) * std::log(decomposed_init.get_s1()) + t*std::log(decomposed_final.get_s1()) );\n const Real s2_interp = std::exp( (1.0 - t) * std::log(decomposed_init.get_s2()) + t*std::log(decomposed_final.get_s2()) );\n \n const DecomposedGrowthState decomposed_intermediate(s1_interp, s2_interp, decomposed_final.get_v1(), decomposed_final.get_v2());\n return decomposed_intermediate.computeMetric(rxy_base);\n }\n \n Eigen::Matrix2d interpolate(const Real t) const\n {\n if(std::abs(decomposed_init.get_s1() - decomposed_init.get_s2()) < 1e-12) return interpolate_from_iso(t);\n \n // t between 0 and 1\n return (1.0 - t)*a_init + t*a_final;\n }\n \n Eigen::Matrix2d interpolateLogEucl(const Real t) const\n {\n if(std::abs(decomposed_init.get_s1() - decomposed_init.get_s2()) < 1e-12) return interpolate_from_iso_logeucl(t);\n \n // t between 0 and 1\n return ((1.0 - t)*a_init.log() + t * a_final.log()).exp();\n }\n \n Eigen::Matrix2d getInitGrowthMetric() const\n {\n return a_init;\n }\n \n Eigen::Matrix2d getFinalGrowthMetric() const\n {\n return a_final;\n }\n \n const DecomposedGrowthState & getDecomposedInitState() const\n {\n return decomposed_init;\n }\n \n const DecomposedGrowthState & getDecomposedFinalState() const\n {\n return decomposed_final;\n }\n};\n\n\n\ntemplate\nstruct GrowthHelper\n{\n static void anglesToVectors(const Eigen::Ref angles, Eigen::Ref vectors, const Real phase = 0)\n {\n const int nFaces = angles.rows();\n for(int i=0;i angles, const Eigen::Ref lengths, Eigen::Ref vectors, const Real phase = 0)\n {\n const int nFaces = angles.rows();\n for(int i=0;i dir1, const Eigen::Ref dir2, Eigen::Ref angles, Eigen::Ref growthRates1, Eigen::Ref growthRates2)\n {\n const int nFaces = dir1.rows();\n for(int i=0;i growthRates, tVecMat2d & aforms)\n {\n const int nFaces = mesh.getNumberOfFaces();\n const auto & topo = mesh.getTopology();\n const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n \n aforms.resize(nFaces);\n \n for(int i=0;i growthRates, const Eigen::Ref gradEng_abar, Eigen::Ref gradEng_rate)\n {\n // compute gradient abar wrt growth\n const int nFaces = mesh.getNumberOfFaces();\n const auto & topo = mesh.getTopology();\n const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n \n for(int i=0;i growthAngles, const Eigen::Ref growthRates_p, const Eigen::Ref growthRates_o, tVecMat2d & aforms)\n {\n const int nFaces = mesh.getNumberOfFaces();\n const auto & topo = mesh.getTopology();\n const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n \n aforms.resize(nFaces);\n \n for(int i=0;i growthAngles, const Eigen::Ref growthRates_p, const Eigen::Ref growthRates_o, const Eigen::Ref gradEng_abar, Eigen::Ref gradEng_angle, Eigen::Ref gradEng_rate_p, Eigen::Ref gradEng_rate_o)\n {\n // compute gradient abar wrt growth\n const int nFaces = mesh.getNumberOfFaces();\n const auto & topo = mesh.getTopology();\n const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n \n for(int i=0;i growthAngles, const Eigen::Ref growthRates_p, const Eigen::Ref growthRates_o, const Eigen::Ref gradEng_abar, Eigen::Ref gradEng_verts)\n {\n // compute gradient abar wrt growth\n const int nFaces = mesh.getNumberOfFaces();\n const auto & topo = mesh.getTopology();\n const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n \n for(int i=0;i growthdirs_1, const Eigen::Ref growthRates_1, const Eigen::Ref growthRates_2, tVecMat2d & aforms)\n {\n const int nFaces = mesh.getNumberOfFaces();\n const auto & topo = mesh.getTopology();\n const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n \n aforms.resize(nFaces);\n \n for(int i=0;i growthRates, tVecMat2d & aforms)\n {\n // now the growth rates are prescribed per-edge\n const int nFaces = mesh.getNumberOfFaces();\n const auto & topo = mesh.getTopology();\n const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n \n aforms.resize(nFaces);\n \n for(int i=0;i growthRates, const Eigen::Ref gradEng_abar, Eigen::Ref gradEng_rate)\n {\n // compute gradient abar wrt growth\n const int nFaces = mesh.getNumberOfFaces();\n const auto & topo = mesh.getTopology();\n const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n \n for(int i=0;i growthRates, tVecMat2d & aforms)\n {\n // now the growth rates are prescribed per-edge\n const int nFaces = mesh.getNumberOfFaces();\n const auto & topo = mesh.getTopology();\n const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n \n aforms.resize(nFaces);\n \n for(int i=0;i growthRates, const Eigen::Ref gradEng_abar, Eigen::Ref gradEng_rate)\n {\n // compute gradient abar wrt growth\n const int nFaces = mesh.getNumberOfFaces();\n const auto & topo = mesh.getTopology();\n const auto & reststate = mesh.getRestConfiguration(); // does not matter which one at this point\n \n for(int i=0;i\n\n#include \n\n#include \n\nnamespace nobody {\n\nfloat kinetic_energy(const std::vector& particles) {\n float energy = 0.0f;\n for (const auto& p : particles) energy += p.mass * p.velocity.squaredNorm();\n return 0.5f * energy;\n}\n\nfloat potential_energy(const std::vector& particles) {\n float energy = 0.0f;\n for (std::size_t i = 0; i < particles.size(); ++i) {\n for (std::size_t j = 0; j < i; ++j) {\n energy += particles[i].mass * particles[j].mass /\n (particles[i].position - particles[j].position).norm();\n }\n }\n return -gravitation_const * energy;\n}\n\nEigen::Vector3f angular_momentum(const std::vector& particles) {\n Eigen::Vector3f result(0, 0, 0);\n for (const auto& particle : particles) {\n result += particle.mass * particle.position.cross(particle.velocity);\n }\n return result;\n}\n\n} // namespace nobody", "meta": {"hexsha": "911d320d38500bbfce86da9eb58ada9732358cab", "size": 943, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "nobody/energy.cpp", "max_stars_repo_name": "lyrahgames/nobody", "max_stars_repo_head_hexsha": "868b1a6c872f051f76c6ee852a977053e1ac35d4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-05-05T08:48:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-05-05T08:48:05.000Z", "max_issues_repo_path": "nobody/energy.cpp", "max_issues_repo_name": "lyrahgames/nobody", "max_issues_repo_head_hexsha": "868b1a6c872f051f76c6ee852a977053e1ac35d4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8.0, "max_issues_repo_issues_event_min_datetime": "2017-11-29T14:48:22.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-14T23:32:50.000Z", "max_forks_repo_path": "nobody/energy.cpp", "max_forks_repo_name": "lyrahgames/nobody", "max_forks_repo_head_hexsha": "868b1a6c872f051f76c6ee852a977053e1ac35d4", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 27.7352941176, "max_line_length": 78, "alphanum_fraction": 0.6638388123, "num_tokens": 257, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513731336204, "lm_q2_score": 0.7185944046238981, "lm_q1q2_score": 0.6440412218703051}} {"text": "//\n// ExtraCirProcesses.cpp\n// Master Thesis\n//\n// Created by Magnus Mencke on 25/05/2021.\n// Copyright © 2021 Magnus Mencke. All rights reserved.\n//\n\n#include \"ExtraCirProcesses.hpp\"\n\n\n#include \n#include \n\nnamespace QuantLib {\n Real CirProcess::x0() const {\n return x0_;\n }\n \n Real CirProcess::speed() const {\n return speed_;\n }\n \n Real CirProcess::volatility() const {\n return volatility_;\n }\n \n Real CirProcess::level() const {\n return level_;\n }\n \n Real CirProcess::drift(Time, Real x) const {\n return speed_ * (level_ - x);\n }\n \n Real CirProcess::diffusion(Time, Real) const {\n return volatility_;\n }\n \n Real CirProcess::expectation(Time, Real x0,\n Time dt) const {\n return level_ + (x0 - level_) * std::exp(-speed_*dt);\n }\n \n Real CirProcess::stdDeviation(Time t, Real x0,\n Time dt) const {\n return std::sqrt(variance(t,x0,dt));\n }\n\n //Full truncation scheme (as in Brigo, Morini and Pallavicini)\n //Inspired by Heston implementation\n // see Lord, R., R. Koekkoek and D. van Dijk (2006),\n // \"A Comparison of biased simulation schemes for\n // stochastic volatility models\",\n // Working Paper, Tinbergen Institute\n Real CirProcess::evolve (Time t0,\n Real x0,\n Time dt,\n Real dw) const {\n Real resultTrunc;\n switch (discretization_) {\n case None: {\n resultTrunc=apply(expectation(t0,x0,dt),stdDeviation(t0,x0,dt)*dw);\n break;\n }\n case FullTruncation: {\n Real x0_trunc = x0>0.0 ? x0 : 0.0;\n \n Real result = apply( expectation(t0, x0_trunc, dt),stdDeviation(t0,x0_trunc,dt)*dw);\n \n resultTrunc = result>0.0 ? result : 0.0;\n \n break;\n }\n case QuadraticExponential: {\n // for details of the quadratic exponential discretization scheme\n // see Leif Andersen,\n // Efficient Simulation of the Heston Stochastic Volatility Model\n const Real ex = std::exp(-speed_*dt);\n \n const Real m = level_+(x0-level_)*ex;\n const Real s2 = x0*volatility_*volatility_*ex/speed_*(1-ex)\n + level_*volatility_*volatility_/(2*speed_)*(1-ex)*(1-ex);\n const Real psi = s2/(m*m);\n \n if (psi <= 1.5) {\n const Real b2 = 2/psi-1+std::sqrt(2/psi*(2/psi-1));\n const Real b = std::sqrt(b2);\n const Real a = m/(1+b2);\n \n resultTrunc = a*(b+dw)*(b+dw);\n }\n else {\n const Real p = (psi-1)/(psi+1);\n const Real beta = (1-p)/m;\n \n const Real u = CumulativeNormalDistribution()(dw);\n \n resultTrunc = ((u <= p) ? 0.0 : std::log((1-p)/(1-u))/beta);\n }\n break;\n }\n case Exact: {\n CumulativeNormalDistribution dwDist; //despite the name, dw is standard normal\n Real uniform= dwDist(dw); //transforming normal to uniform\n \n Real c=(4*speed_)/(volatility_*volatility_*(1-std::exp(-speed_*dt)));\n Real nu=(4*speed_*level_)/(volatility_*volatility_);\n Real eta=c*x0*std::exp(-speed_*dt);\n \n //we had some strange errors using QuantLib's Chi2 distribution, so we use the one from boost\n boost::math::non_central_chi_squared_distribution> chi2(nu, eta);\n //InverseNonCentralCumulativeChiSquareDistribution chi2(nu, eta);\n \n resultTrunc = quantile(chi2,uniform)/c;\n }\n }\n \n return resultTrunc;\n }\n \n \n CirProcess::CirProcess(Real speed,\n Volatility vol,\n Real x0,\n Real level,\n Discretization d)\n : x0_(x0), speed_(speed), level_(level), volatility_(vol), discretization_(d) {\n QL_REQUIRE(volatility_ >= 0.0, \"negative volatility given\");\n }\n \n Real CirProcess::variance(Time, Real, Time dt) const {\n Real exponent1 = std::exp(-speed_ * dt);\n Real exponent2 = std::exp(-2 * speed_ * dt);\n Real fraction = (volatility_ * volatility_) / speed_;\n \n return x0_ * fraction * (exponent1 - exponent2) + level_ * fraction * (1 - exponent1) * (1 - exponent1);\n }\n \n}\n", "meta": {"hexsha": "10bc2158ac47179121438e2ee34e5e1b3ec7a71e", "size": 5143, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "CppFiles/ExtraCirProcesses.cpp", "max_stars_repo_name": "mmencke/MasterThesis", "max_stars_repo_head_hexsha": "45b197b45ab452180109a66367dd9cf283b20aba", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "CppFiles/ExtraCirProcesses.cpp", "max_issues_repo_name": "mmencke/MasterThesis", "max_issues_repo_head_hexsha": "45b197b45ab452180109a66367dd9cf283b20aba", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "CppFiles/ExtraCirProcesses.cpp", "max_forks_repo_name": "mmencke/MasterThesis", "max_forks_repo_head_hexsha": "45b197b45ab452180109a66367dd9cf283b20aba", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-10-06T08:04:14.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-06T08:04:14.000Z", "avg_line_length": 36.475177305, "max_line_length": 122, "alphanum_fraction": 0.4921252187, "num_tokens": 1187, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513703624557, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6440412036751285}} {"text": "#include \n#include \n#include \n#include \n#include \n\nGraph createGraph(std::ifstream &fin){\n\tfacebook::Name name;\n\tfacebook::Data data = facebook::readFile(fin, name);\n\n\tfacebook::Map map = facebook::createMap(data);\n\n\tGraph g = facebook::createGraph(data, map);\n\t\n\treturn g;\n}\n\nWeightedGraph createWeightedGraph(Graph g){\n\tWeightedGraph wg(num_vertices(g));\n\t\n\tproperty_map::type weightmap = get(edge_weight, wg);\n\tEdgeIterator e, e_end;\n\tfor(tie(e, e_end) = edges(g); e != e_end; e++){\n\t\tWeightedEdgeDescriptor e1; bool inserted;\n\t\ttie(e1, inserted) = add_edge(source(*e, g), target(*e, g), wg);\n\t\tweightmap[e1] = 1;\n\t}\n\t\n\treturn wg;\n}\n\nMatrix createAllPairsShortestPaths(WeightedGraph wg){\n\tint V = num_vertices(wg);\n\tMatrix D(V, std::vector(V));\n\tjohnson_all_pairs_shortest_paths(wg, D);\n\t\n\treturn D;\n}\n\n//have to corresponding vertices\nEdges newEdgeList(Graph g, Graph g2){\n\tEdges edges;\n\tfor(int i=0; i temp(num_vertices(g), 0);\n\t\tmatrix[i] = temp;\n\t}\n\tfor(int i=0; i score(num_vertices(g), 0.0);\n\t\tscores[i] = score;\n\t}\n\treturn scores;\n}\n\nstd::vector sortDouble(std::vector scores){\n\tstd::vector temps;\n\tfor(int i=0; i 0)\n\t\t\ttemps.push_back(scores[i]);\n\t}\n\tstd::sort(temps.begin(), temps.end());\n\treturn temps;\n}\n\nbool comparisonSort(Score i, Score j){\n\tif(i.first < j.first) return false;\n\tif(j.first < i.first) return true;\n\treturn j.second.first < i.second.first;\n}\n\nScores SortScores(MatrixScore mscores){\n\tScores scores;\n\n\tfor(int i=0; i thresh)\n\t\t\t\t\tscores[x][y] = 1.0;\n\t\t\t\telse\n\t\t\t\t\tscores[x][y] = scores[x][y] / thresh;\n\t\t\t\tadd_edge(x,y,temp_g);\n\t\t\t}\n\t\t}\n\t}\n\twg = createWeightedGraph(temp_g);\n\tdistance = createAllPairsShortestPaths(wg);\n\n\t}\n\n\treturn scores;\n}\n\nMatrixScore AdamicAdar(Graph g){\n\tMatrix distance = createAllPairsShortestPaths(createWeightedGraph(g));\n\tMatrixScore scores = initializeScore(g);\n\n\tfor(int x=0; x 1){\n\t\t\t\t\t\tint d = distance[x][i] + distance[y][i];\n\t\t\t\t\t\tif(d == distance[x][y])\n\t\t\t\t\t\t\tscores[x][y] += (double)1/log(out_degree(i,g));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn scores;\n}\n\nvoid normalize(MatrixScore scores, Graph g){\n\t//mean\n\tint count=0;\n\tdouble avg=0.0;\n\tfor(int x=0; x score(num_vertices(g), 0.0);\n\t\tscores[i] = score;\n\t}\n\n\tstd::vector is_new(num_vertices(g), 0);\n\tfor(int i=0; i list(num_vertices(g));\n\t\tfor(int j=0; j list(A.size(), 0);\n\t\tfor(int j=0; j VertexBetweennessCentrality(Graph g, std::vector &v_centrality_vec, std::vector &e_centrality_vec){\n\tStdEdgeIndexMap my_e_index;\n\tEdgeIndexMap e_index(my_e_index);\n\tint i=0;\n\tBGL_FORALL_EDGES(edge, g, Graph){\n\t\tmy_e_index.insert(std::pair(edge,i));\n\t\t++i;\n\t}\n\n\t//std::vectore_centrality_vec(num_edges(g), 0.0);\n\titerator_property_map::iterator, EdgeIndexMap> e_centrality_map(e_centrality_vec.begin(), e_index);\n\n\tVertexIndexMap v_index = get(vertex_index, g);\n\t//std::vector v_centrality_vec(num_vertices(g), 0.0);\n\titerator_property_map::iterator, VertexIndexMap> v_centrality_map(v_centrality_vec.begin(), v_index);\n\tbrandes_betweenness_centrality(g, v_centrality_map, e_centrality_map);\n\t//relative_betweenness_centrality(g, v_centrality_map);\n\n\treturn v_centrality_vec;\n}\n\nMatrixScore BCBasedLP(Graph g, Matrix distance, std::vector v_centrality_vec, float beta){\n\tMatrixScore score = initializeScore(g);\n\t//Matrix distance = createAllPairsShortestPaths(createWeightedGraph(g));\n\n\t#pragma omp parallel for\n\tfor(int x=0; x z;\n\t\t\tdouble avg=0.0;\n\t\t\tfor(int i=0; i= 2)\n\t\t\t\tscore[x][y] *= pow(beta, distance[x][y]-2);\n\t\t}\n\t}\n\n\treturn score;\n}\n\nfloat BCBasedLPst(Graph g, Matrix distance, std::vector v_centrality_vec, float beta, int s, int t){\n\n\tfloat score=0.0;\n\tint count=0;\n\tstd::vector z;\n\tdouble avg=0.0;\n\tfor(int i=0; i 1 && distance[i][j] < num_vertices(g)){\n\t\t\t\twhile(distance[i][j] > ml.size())\n\t\t\t\t\tml.push_back(multiplyMatrix(ml[0], ml[ml.size()-1]));\n\n\t\t\t\tint num = ml[distance[i][j]-1][i][j];\n\n\t\t\t\tfor(int k=0; k(edge, i));\n\t\t++i;\n\t}\n\n\tstd::vectore_centrality_vec(num_edges(cg), 0.0);\n\titerator_property_map::iterator, EdgeIndexMap> e_centrality_map(e_centrality_vec.begin(), e_index);\n\n\tbc_clustering_thresholdterminate(max_centrality, cg, false);\n\tbetweenness_centrality_clustering(cg, terminate, e_centrality_map);\n\n\tfor(int i=0; i ebc){\n\tMatrixScore weights = initializeScore(g);\n\n\tint k=0;\n\tBGL_FORALL_EDGES(e, g, Graph){\n\t\tint s = source(e, g);\n\t\tint t = target(e, g);\n\t\tif(s < t)\n\t\t\tweights[s][t] += ebc[k];\n\t\telse if(t < s)\n\t\t\tweights[t][s] += ebc[k];\n\t\tk++;\n\t}\n\t\n\tfor(int i=0; i::type weightmap = get(edge_weight,ug);\n\n\tBGL_FORALL_EDGES(e, g, Graph){\n\t\tint s = source(e, g);\n\t\tint t = target(e, g);\n\t\tif(edge(s,t,ug).second != 1){\n\t\t\tUndirectedEdgeDescriptor ue;\n\t\t\tbool inserted;\n\t\t\ttie(ue, inserted) = add_edge(s,t,ug);\n\t\t\tweightmap[ue] = (size_t)weights[s][t];\n\t\t}\n\t}\n\n\tstd::vector spanning_tree;\n\tkruskal_minimum_spanning_tree(ug, std::back_inserter(spanning_tree));\n\n\tGraph tempg(num_vertices(g));\n\tfor(int i=0; i ebc){\n\tMatrixScore score = initializeScore(g);\n\n\tint k=0;\n\tBGL_FORALL_EDGES(e, g, Graph){\n\t\tint s = source(e, g);\n\t\tint t = target(e, g);\n\t\tscore[s][t] = ebc[k];\n\t\tscore[t][s] = ebc[k];\n\t\tk++;\n\t}\n\n\treturn score;\n}\n\nvoid NormalizePr(MatrixScore &scores, Matrix distance){\n\t//mean\n\tint count=0;\n\tdouble avg=0.0;\n\tfor(int x=0; x= 1.0)\n\t\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t}\n\tstd::cout << \"number of scores above 1: \" << count << std::endl;\n}\n", "meta": {"hexsha": "dbad6ba27b39999649f46eae6e8ab5f8ea8a5dfe", "size": 13472, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/graph.cpp", "max_stars_repo_name": "yishihara/Social-Network", "max_stars_repo_head_hexsha": "505c08f544a03bbd32ea1c48a437f5de63c51523", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/graph.cpp", "max_issues_repo_name": "yishihara/Social-Network", "max_issues_repo_head_hexsha": "505c08f544a03bbd32ea1c48a437f5de63c51523", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/graph.cpp", "max_forks_repo_name": "yishihara/Social-Network", "max_forks_repo_head_hexsha": "505c08f544a03bbd32ea1c48a437f5de63c51523", "max_forks_repo_licenses": ["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.4703832753, "max_line_length": 135, "alphanum_fraction": 0.6205463183, "num_tokens": 4366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8962513620489619, "lm_q2_score": 0.718594386544335, "lm_q1q2_score": 0.6440411977010986}} {"text": "\n#include \n#include \n\n\nclass Kalman {\n public:\n \n Kalman(){\n is_init = false;\n }\n\n ~Kalman(){\n ;\n }\n\n bool isInit(){\n return is_init;\n }\n\n // 初始化状态向量\n void init(Eigen::VectorXd x_in){\n x_ = x_in;\n is_init = true;\n }\n\n // 状态转移矩阵\n void setF(Eigen::MatrixXd F_in){\n F_ = F_in;\n }\n\n // 系统的不确定度\n void setP(Eigen::MatrixXd P_in){\n P_ = P_in;\n }\n\n // 过程噪声 (一般为单位矩阵)\n void setQ(Eigen::MatrixXd Q_in){\n Q_ = Q_in;\n }\n\n // 测量矩阵\n void setH(Eigen::MatrixXd H_in){\n H_ = H_in;\n }\n\n // 测量噪声矩阵(一般由传感器厂家提供)\n void setR(Eigen::MatrixXd R_in){\n R_ = R_in;\n }\n\n // 计算预测值\n void predict(){\n x_ = F_ * x_;\n // std::cout << x_ << std::endl;\n //printf(\"predict ok, x_ shape is %d %d\\n\", x_.rows(), x_.cols());\n P_ = F_*P_*F_.transpose();\n //printf(\"predict ok, P_ shape is %d %d\\n\", P_.rows(), P_.cols());\n }\n\n // 观测\n void measurement_update(const Eigen::VectorXd &z){\n // 观测值z与预测值x的差值y\n Eigen::VectorXd y = z - H_ * x_;\n //printf(\"update ok, y_ shape is %d %d\\n\", y.rows(), y.cols());\n // 求解卡尔曼增益k,差值y的权重\n Eigen::MatrixXd S_ = H_ * P_ * H_.transpose() + R_;\n //printf(\"update ok, S_ shape is %d %d\\n\", S_.rows(), S_.cols());\n Eigen::MatrixXd K_ = P_ * H_.transpose() * S_.inverse();\n //printf(\"update ok, K_ shape is %d %d\\n\", K_.rows(), K_.cols());\n // 更新状态向量,考虑了测量值,预测值,整个系统的噪声\n x_ = x_ + K_ * y;\n int size = x_.size();\n Eigen::MatrixXd I = Eigen::MatrixXd::Identity(size, size);\n P_ = (I - K_ * H_) * P_;\n }\n\n Eigen::VectorXd getX(){\n return x_;\n }\n\n private:\n bool is_init;\n Eigen::VectorXd x_;\n Eigen::MatrixXd F_, P_, Q_, H_, R_;\n};\n\n\nint main(int argc, char* argv[]){\n\n Kalman kalman;\n\n int iter=0;\n double mx = 1.0, my = 1.0, dt=0.1;\n while (iter++ < 1070)\n {\n \n if (!kalman.isInit())\n {\n Eigen::VectorXd x_in(4, 1);\n x_in << mx, my, 0.0, 0.0;\n kalman.init(x_in);\n\n Eigen::MatrixXd P_in(4, 4);\n P_in << 1.0, 0.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 0.0,\n 0.0, 0.0, 100.0, 0.0,\n 0.0, 0.0, 0.0, 100.0;\n kalman.setP(P_in);\n\n\n Eigen::MatrixXd Q_in(4, 4);\n Q_in << 1.0, 0.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 0.0,\n 0.0, 0.0, 1.0, 0.0,\n 0.0, 0.0, 0.0, 1.0;\n\n kalman.setQ(Q_in);\n\n Eigen::MatrixXd H_in(2, 4);\n H_in << 1.0, 0.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 0.0;\n\n kalman.setH(H_in);\n\n Eigen::MatrixXd R_in(2, 2);\n R_in << 0.0225, 0.0,\n 0.0, 0.0225;\n \n kalman.setR(R_in);\n continue;\n }\n \n Eigen::MatrixXd F_in(4, 4);\n F_in << 1.0, 0.0, dt, 0.0,\n 0.0, 1.0, 0.0, dt,\n 0.0, 0.0, 1.0, 0.0,\n 0.0, 0.0, 0.0, 1.0;\n\n kalman.setF(F_in);\n kalman.predict();\n\n Eigen::VectorXd z(2, 1);\n z << mx, my;\n kalman.measurement_update(z);\n\n\n Eigen::VectorXd x_out = kalman.getX();\n std::cout << \"x: \" << x_out(0) << \", y:\" << x_out(1) << std::endl;\n // std::cout << \"vx: \" << x_out(2) << \", vy:\" << x_out(3) << std::endl;\n\n std::cout << \"mx: \" << mx << \", my:\" << my << std::endl;\n \n\n // dt = 0.1;\n mx += 0.3;\n my += 0.4;\n\n if(iter == 998) mx = 1, my = 1;\n if(iter == 999) mx = 10, my = 10;\n }\n \n\n\n\n return 0;\n}", "meta": {"hexsha": "8cdb6c6f69d9f26b07ddb9a962769feae8bb8233", "size": 4009, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/algorithm/kalman.cpp", "max_stars_repo_name": "fulincao/algorithm-review", "max_stars_repo_head_hexsha": "601a5a4cfc3e40ba11a04e8e19b921491a75648a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/algorithm/kalman.cpp", "max_issues_repo_name": "fulincao/algorithm-review", "max_issues_repo_head_hexsha": "601a5a4cfc3e40ba11a04e8e19b921491a75648a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/algorithm/kalman.cpp", "max_forks_repo_name": "fulincao/algorithm-review", "max_forks_repo_head_hexsha": "601a5a4cfc3e40ba11a04e8e19b921491a75648a", "max_forks_repo_licenses": ["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.005988024, "max_line_length": 79, "alphanum_fraction": 0.3978548266, "num_tokens": 1409, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9124361557147439, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6439837719139898}} {"text": "\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"NumpySaver.hpp\"\n#include \"Timer.hpp\"\n#include \"YAMLUtils.hpp\"\n#include \"bsplines.hpp\"\n\nusing namespace Eigen;\nusing std::cout, std::endl, std::cerr;\n\nvoid test_bsplines(double x = .1, Index order = 3, Index nknots = 11) {\n std::vector std_knots(nknots);\n Map knots(std_knots.data(), std_knots.size());\n knots = ArrayXd::LinSpaced(nknots, 0, 1);\n\n auto [values, index] = bsplines::bsplines(x, std_knots, order);\n\n Map values_eigen(values.data(), values.size());\n auto sum = values_eigen.sum();\n if (std::abs(sum - 1) > 1e-15) {\n cerr << \"The knots are: \" << knots.transpose() << endl;\n cerr << \"The spline value at \" << x << \" is: \" << values_eigen.transpose()\n << endl;\n cerr << \"Summing all spline values (should be 1): \" << sum << endl;\n }\n}\n\nSparseMatrix build_matrix(const std::vector& knots,\n std::size_t order = 3) {\n auto n = knots.size();\n\n SparseMatrix matrix(n + 1, n + order - 2);\n matrix.reserve(order * (n + 1) - 2);\n\n auto [deriv_0, _index] = bsplines::ndx_bsplines(knots[0], knots, order, 2);\n for (int col = 0; col < int(order) - 1; col++)\n matrix.insert(0, col) = deriv_0[col + 1];\n\n for (int row = 1; row < int(n); row++) {\n auto [deriv, index] = bsplines::ndx_bsplines(knots[row], knots, order, 2);\n for (int col = row - 1; col < row - 1 + int(order); col++)\n matrix.insert(row, col) = deriv[col - row + 2];\n }\n\n auto [deriv_last, __index] =\n bsplines::ndx_bsplines(knots[n - 1], knots, order, 1);\n matrix.insert(n, n + order - 3) = deriv_last[order];\n matrix.insert(n, n + order - 4) = deriv_last[order - 1];\n\n return matrix;\n}\n\ndouble rho_uniform_sphere(double r, double R, double q) {\n if (r <= R) return q / (4. * M_PI / 3. * R * R * R);\n\n return 0;\n}\n\ndouble rho_uniform_shell(double r, double R1, double R2, double q) {\n if (r < R1) return 0;\n if (r <= R2) return q / (4. * M_PI / 3. * (R2 * R2 * R2 - R1 * R1 * R1));\n\n return 0;\n}\n\ndouble rho_hydrogen_ground_state(double r, double e, double r_bohr = 1) {\n return e / M_PI / (r_bohr * r_bohr * r_bohr) * std::exp(-2 * r / r_bohr);\n}\n\nVectorXd build_rhs(const std::vector& knots,\n std::function& rho) {\n auto n = knots.size();\n VectorXd rhs(n + 1);\n for (std::size_t i = 0; i < n; i++) {\n rhs[i] = -knots[i] * 4 * M_PI * rho(knots[i]);\n }\n\n rhs[n] = 0;\n\n return rhs;\n}\n\ndouble evaluate_spline(const double& x, const std::vector& knots,\n const VectorXd& weights, std::size_t order = 3) {\n auto n = knots.size();\n assert(int(n + order) - 1 == weights.size());\n\n auto [values, index] = bsplines::bsplines(x, knots, order);\n\n double sum = 0;\n for (std::size_t i = 0; i <= order; i++)\n sum += values[i] * weights[index + i];\n\n return sum;\n}\n\nVectorXd evaluate_spline(const VectorXd& x, const std::vector& knots,\n const VectorXd& weights, std::size_t order = 3) {\n auto n = x.size();\n VectorXd ret(n);\n for (Index i = 0; i < n; i++) {\n ret[i] = evaluate_spline(x[i], knots, weights, order);\n }\n return ret;\n}\n\nvoid solve_problem(YAML::Node node) {\n using namespace std::placeholders;\n\n auto name = node[\"name\"].as();\n auto R = node[\"R\"].as();\n auto R1 = node[\"R1\"].as();\n auto R2 = node[\"R2\"].as();\n auto q = node[\"q\"].as();\n auto e = node[\"e\"].as();\n auto r_bohr = node[\"r_bohr\"].as();\n\n YAML::Node knot_node = node[\"knots\"];\n auto knots = get_yaml_values(knot_node);\n\n auto matrix = build_matrix(knots);\n\n std::vector>> rhos = {\n {\"uniform_sphere\", std::bind(rho_uniform_sphere, _1, R, q)},\n {\"uniform_shell\", std::bind(rho_uniform_shell, _1, R1, R2, q)},\n {\"hydrogen\", std::bind(rho_hydrogen_ground_state, _1, e, r_bohr)},\n };\n\n if (knots.size() < 30) {\n cout << \"Knots = \";\n for (std::size_t i = 0; i < knots.size(); i++) cout << knots[i] << \", \";\n cout << \"\\n\";\n }\n\n // first do the (sparse) LU decomposition\n Eigen::SparseLU, Eigen::COLAMDOrdering>\n solver;\n solver.analyzePattern(matrix);\n solver.factorize(matrix);\n\n VectorXd x = VectorXd::LinSpaced(1000, knots[0], knots[knots.size() - 1]);\n\n for (std::size_t i = 0; i < rhos.size(); i++) {\n auto rho_name = std::get<0>(rhos[i]);\n auto rho = std::get<1>(rhos[i]);\n\n cout << \"\\nProblem = \" << rho_name << \"\\n\";\n\n auto rhs = build_rhs(knots, rho);\n auto solution = solver.solve(rhs);\n if (knots.size() < 30) {\n cout << \"rhs vector: \" << rhs.transpose() << \"\\n\";\n cout << \"solution vector: \" << solution.transpose() << \"\\n\";\n }\n\n VectorXd weights(solution.size() + 1);\n weights << 0, solution;\n\n VectorXd sol = evaluate_spline(x, knots, weights);\n\n NumpySaver(fmt::format(\"build/output/solution_{}_{}.npy\", name, rho_name))\n << x << sol;\n }\n cout << \"\\n\";\n}\n\nvoid plot_bsplines(std::size_t order = 3) {\n std::vector std_knots(11);\n Map knots(std_knots.data(), std_knots.size());\n knots = ArrayXd::LinSpaced(11, 0, 1);\n VectorXd xs = VectorXd::LinSpaced(1000, knots[0], knots[knots.size() - 1]);\n MatrixXd spline(xs.size(), order + 1);\n MatrixXd dspline(xs.size(), order + 1);\n MatrixXd ddspline(xs.size(), order + 1);\n\n for (Index i = 0; i < xs.size(); i++) {\n auto [x_spline, index_0] = bsplines::bsplines(xs[i], std_knots, order);\n auto [x_dspline, index_1] =\n bsplines::ndx_bsplines(xs[i], std_knots, order, 1);\n auto [x_ddspline, index_2] =\n bsplines::ndx_bsplines(xs[i], std_knots, order, 2);\n for (std::size_t j = 0; j < order + 1; j++) {\n spline(i, j) = x_spline[j];\n dspline(i, j) = x_dspline[j];\n ddspline(i, j) = x_ddspline[j];\n }\n }\n NumpySaver saver(\"build/output/plot_splines.npy\");\n saver << xs;\n for (std::size_t j = 0; j < order + 1; j++) saver << spline.col(j);\n for (std::size_t j = 0; j < order + 1; j++) saver << dspline.col(j);\n for (std::size_t j = 0; j < order + 1; j++) saver << ddspline.col(j);\n}\n\nint main() {\n cout << \"Testing if all spline values at each point sum to 1, no error means \"\n \"it worked.\"\n << endl;\n for (double x = 0; x <= 1; x += .001) {\n test_bsplines(x, 3, 11);\n }\n\n std::vector std_knots(11);\n Map knots(std_knots.data(), std_knots.size());\n knots = ArrayXd::LinSpaced(11, 0, 1);\n\n cout << \"Testing Matrix creation...\" << endl;\n auto matrix = build_matrix(std_knots);\n cout << \"Matrix size is \" << matrix.rows() << \"x\" << matrix.cols() << endl;\n cout << matrix << endl;\n\n YAML::Node config = YAML::LoadFile(\"config.yaml\");\n\n for (std::size_t i = 0; i < config.size(); i++) {\n cout << \"\\n\\n*****************************************\\n\"\n << fmt::format(\"Running simulation {}/{}\", i + 1, config.size())\n << endl;\n solve_problem(config[i]);\n }\n\n plot_bsplines();\n return 0;\n}\n", "meta": {"hexsha": "bc471bfa7c9f0c7cb4a05831e45bf2c1d89b62a7", "size": 7165, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Project04-BSplinesPoisson/bsplinespoisson.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": "Project04-BSplinesPoisson/bsplinespoisson.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": "Project04-BSplinesPoisson/bsplinespoisson.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": 31.0173160173, "max_line_length": 80, "alphanum_fraction": 0.5903698535, "num_tokens": 2313, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8596637612961506, "lm_q2_score": 0.7490872187162396, "lm_q1q2_score": 0.6439631359804748}} {"text": "// (C) Copyright Nick Thompson 2021.\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0. (See accompanying file\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#ifndef BOOST_MATH_TOOLS_QUARTIC_ROOTS_HPP\n#define BOOST_MATH_TOOLS_QUARTIC_ROOTS_HPP\n#include \n#include \n#include \n\nnamespace boost::math::tools {\n\nnamespace detail {\n\n// Make sure the nans are always at the back of the array:\ntemplate\nbool comparator(Real r1, Real r2) {\n using std::isnan;\n if (isnan(r2)) { return true; }\n return r1 < r2;\n}\n\ntemplate\nstd::array polish_and_sort(Real a, Real b, Real c, Real d, Real e, std::array& roots) {\n // Polish the roots with a Halley iterate.\n using std::fma;\n using std::abs;\n for (auto &r : roots) {\n Real df = fma(4*a, r, 3*b);\n df = fma(df, r, 2*c);\n df = fma(df, r, d);\n Real d2f = fma(12*a, r, 6*b);\n d2f = fma(d2f, r, 2*c);\n Real f = fma(a, r, b);\n f = fma(f,r,c);\n f = fma(f,r,d);\n f = fma(f,r,e);\n Real denom = 2*df*df - f*d2f;\n if (abs(denom) > (std::numeric_limits::min)())\n {\n r -= 2*f*df/denom;\n }\n }\n std::sort(roots.begin(), roots.end(), detail::comparator);\n return roots;\n}\n\n}\n// Solves ax^4 + bx^3 + cx^2 + dx + e = 0.\n// Only returns the real roots, as these are the only roots of interest in ray intersection problems.\n// Follows Graphics Gems V: https://github.com/erich666/GraphicsGems/blob/master/gems/Roots3And4.c\ntemplate\nstd::array quartic_roots(Real a, Real b, Real c, Real d, Real e) {\n using std::abs;\n using std::sqrt;\n auto nan = std::numeric_limits::quiet_NaN();\n std::array roots{nan, nan, nan, nan};\n if (abs(a) <= (std::numeric_limits::min)()) {\n auto cbrts = cubic_roots(b, c, d, e);\n roots[0] = cbrts[0];\n roots[1] = cbrts[1];\n roots[2] = cbrts[2];\n if (b == 0 && c == 0 && d == 0 && e == 0) {\n roots[3] = 0;\n }\n return detail::polish_and_sort(a, b, c, d, e, roots);\n }\n if (abs(e) <= (std::numeric_limits::min)()) {\n auto v = cubic_roots(a, b, c, d);\n roots[0] = v[0];\n roots[1] = v[1];\n roots[2] = v[2];\n roots[3] = 0;\n return detail::polish_and_sort(a, b, c, d, e, roots);\n }\n // Now solve x^4 + Ax^3 + Bx^2 + Cx + D = 0.\n Real A = b/a;\n Real B = c/a;\n Real C = d/a;\n Real D = e/a;\n Real Asq = A*A;\n // Let x = y - A/4:\n // Mathematica: Expand[(y - A/4)^4 + A*(y - A/4)^3 + B*(y - A/4)^2 + C*(y - A/4) + D]\n // We now solve the depressed quartic y^4 + py^2 + qy + r = 0.\n Real p = B - 3*Asq/8;\n Real q = C - A*B/2 + Asq*A/8;\n Real r = D - A*C/4 + Asq*B/16 - 3*Asq*Asq/256;\n if (abs(r) <= (std::numeric_limits::min)()) {\n auto [r1, r2, r3] = cubic_roots(Real(1), Real(0), p, q);\n r1 -= A/4;\n r2 -= A/4;\n r3 -= A/4;\n roots[0] = r1;\n roots[1] = r2;\n roots[2] = r3;\n roots[3] = -A/4;\n return detail::polish_and_sort(a, b, c, d, e, roots);\n }\n // Biquadratic case:\n if (abs(q) <= (std::numeric_limits::min)()) {\n auto [r1, r2] = quadratic_roots(Real(1), p, r);\n if (r1 >= 0) {\n Real rtr = sqrt(r1);\n roots[0] = rtr - A/4;\n roots[1] = -rtr - A/4;\n }\n if (r2 >= 0) {\n Real rtr = sqrt(r2);\n roots[2] = rtr - A/4;\n roots[3] = -rtr - A/4;\n }\n return detail::polish_and_sort(a, b, c, d, e, roots);\n }\n\n // Now split the depressed quartic into two quadratics:\n // y^4 + py^2 + qy + r = (y^2 + sy + u)(y^2 - sy + v) = y^4 + (v+u-s^2)y^2 + s(v - u)y + uv\n // So p = v+u-s^2, q = s(v - u), r = uv.\n // Then (v+u)^2 - (v-u)^2 = 4uv = 4r = (p+s^2)^2 - q^2/s^2.\n // Multiply through by s^2 to get s^2(p+s^2)^2 - q^2 - 4rs^2 = 0, which is a cubic in s^2.\n // Then we let z = s^2, to get\n // z^3 + 2pz^2 + (p^2 - 4r)z - q^2 = 0.\n auto z_roots = cubic_roots(Real(1), 2*p, p*p - 4*r, -q*q);\n // z = s^2, so s = sqrt(z).\n // No real roots:\n if (z_roots.back() <= 0) {\n return roots;\n }\n Real s = sqrt(z_roots.back());\n\n // s is nonzero, because we took care of the biquadratic case.\n Real v = (p + s*s + q/s)/2;\n Real u = v - q/s;\n // Now solve y^2 + sy + u = 0:\n auto [root0, root1] = quadratic_roots(Real(1), s, u);\n\n // Now solve y^2 - sy + v = 0:\n auto [root2, root3] = quadratic_roots(Real(1), -s, v);\n roots[0] = root0;\n roots[1] = root1;\n roots[2] = root2;\n roots[3] = root3;\n\n for (auto& r : roots) {\n r -= A/4;\n }\n return detail::polish_and_sort(a, b, c, d, e, roots);\n}\n\n}\n#endif\n", "meta": {"hexsha": "1394e7fae9db008138ab18db20b112e1c2d67267", "size": 4913, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/tools/quartic_roots.hpp", "max_stars_repo_name": "jamesfolberth/math", "max_stars_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "include/boost/math/tools/quartic_roots.hpp", "max_issues_repo_name": "jamesfolberth/math", "max_issues_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "include/boost/math/tools/quartic_roots.hpp", "max_forks_repo_name": "jamesfolberth/math", "max_forks_repo_head_hexsha": "a36f6a54a96006c3515ebf0acf17d180322042f2", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.5364238411, "max_line_length": 105, "alphanum_fraction": 0.5169957256, "num_tokens": 1801, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8807970842359877, "lm_q2_score": 0.7310585727705127, "lm_q1q2_score": 0.6439142593019902}} {"text": "#include \n#include \n#include \"uranus/Matrix.hpp\"\n#include \"uranus/un-constrained.hpp\"\n\nint main()\n{\n\tproblem<2> f;\t // f = x_1^2 + 4x_2^2\n\n\tf.matirx_Jacobian_ << 2, 0, 0, 8; \n\n uranus::Vector<2> x0; \n\tx0 << 1, 1; // 初始点\n\n\turanus::Vector<2> y = BFGS<2>(f,x0,0.001,true); // 用BFGS求解\n\n std::cout <<\"zuiyoujie:\\n\" << y <<\"\\n\";\n\n // dasds\n problem<2> f2;\n f2.matirx_Jacobian_ << 2, 0, 0, 2;\n uranus::Vector<2> x2;\n x2 << 5,5;\n\n double M_k = 0.1; // init M_k > 0\t\n uranus::Vector<2> x3;\n double a;\n\tdo{\n\t\tM_k = 10 * M_k; // update M_k\n\t\tf2.matirx_Jacobian_(1,1) = 2 + M_k; // update J mat\n cout << \"M_k=============================\\n\"< 0.01);\n\n std::cout <<\"x3: \\n\" << x3 <<\"\\n\";\n\n return 0;\n}", "meta": {"hexsha": "bce1822ffc51599140df48c56f74b0f67dfb4ba1", "size": 978, "ext": "cc", "lang": "C++", "max_stars_repo_path": "examples/BFGS.cc", "max_stars_repo_name": "hackath/Uranus", "max_stars_repo_head_hexsha": "415db5b23afdae52ed59c7d4ab08b671e2122485", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3.0, "max_stars_repo_stars_event_min_datetime": "2018-12-06T02:29:57.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-03T07:47:10.000Z", "max_issues_repo_path": "examples/BFGS.cc", "max_issues_repo_name": "hackath/Uranus", "max_issues_repo_head_hexsha": "415db5b23afdae52ed59c7d4ab08b671e2122485", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "examples/BFGS.cc", "max_forks_repo_name": "hackath/Uranus", "max_forks_repo_head_hexsha": "415db5b23afdae52ed59c7d4ab08b671e2122485", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.2857142857, "max_line_length": 64, "alphanum_fraction": 0.4560327198, "num_tokens": 396, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7310585786300048, "lm_q1q2_score": 0.6439142553129306}} {"text": "#pragma once\n\n#include \n\n#include \n#include \n\nnamespace polyfem\n{\n\n\t// Show some stats about the matrix M: det, singular values, condition number, etc\n\tvoid show_matrix_stats(const Eigen::MatrixXd &M);\n\n\ttemplate \n\tT determinant(const Eigen::Matrix &mat)\n\t{\n\t\tassert(mat.rows() == mat.cols());\n\n\t\tif (mat.rows() == 1)\n\t\t\treturn mat(0);\n\t\telse if (mat.rows() == 2)\n\t\t\treturn mat(0, 0) * mat(1, 1) - mat(0, 1) * mat(1, 0);\n\t\telse if (mat.rows() == 3)\n\t\t\treturn mat(0, 0) * (mat(1, 1) * mat(2, 2) - mat(1, 2) * mat(2, 1)) - mat(0, 1) * (mat(1, 0) * mat(2, 2) - mat(1, 2) * mat(2, 0)) + mat(0, 2) * (mat(1, 0) * mat(2, 1) - mat(1, 1) * mat(2, 0));\n\n\t\tassert(false);\n\t\treturn T(0);\n\t}\n\n\ttemplate \n\tbool read_matrix(const std::string &path, Eigen::Matrix &mat);\n\n\ttemplate \n\tbool read_matrix_binary(const std::string &path, Eigen::Matrix &mat);\n\n\ttemplate \n\tbool write_matrix_binary(const std::string &path, const Mat &mat);\n\n\tclass SpareMatrixCache\n\t{\n\tpublic:\n\t\tSpareMatrixCache() {}\n\t\tSpareMatrixCache(const size_t size);\n\t\tSpareMatrixCache(const size_t rows, const size_t cols);\n\t\tSpareMatrixCache(const SpareMatrixCache &other);\n\n\t\tvoid init(const size_t size);\n\t\tvoid init(const size_t rows, const size_t cols);\n\t\tvoid init(const SpareMatrixCache &other);\n\n\t\tvoid set_zero();\n\n\t\tinline void reserve(const size_t size) { entries_.reserve(size); }\n\t\tinline size_t entries_size() const { return entries_.size(); }\n\t\tinline size_t capacity() const { return entries_.capacity(); }\n\t\tinline size_t non_zeros() const { return mapping_.empty() ? mat_.nonZeros() : values_.size(); }\n\n\t\tvoid add_value(const int i, const int j, const double value);\n\t\tStiffnessMatrix get_matrix(const bool compute_mapping = true);\n\t\tvoid prune();\n\n\t\tSpareMatrixCache operator+(const SpareMatrixCache &a) const;\n\t\tvoid operator+=(const SpareMatrixCache &o);\n\n\tprivate:\n\t\tsize_t size_;\n\t\tStiffnessMatrix tmp_, mat_;\n\t\tstd::vector> entries_;\n\t\tstd::vector>> mapping_;\n\t\tstd::vector inner_index_, outer_index_;\n\t\tstd::vector values_;\n\t};\n\n} // namespace polyfem\n", "meta": {"hexsha": "dc5938415df62459f6548d348dd917c617feb879", "size": 2312, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "src/utils/MatrixUtils.hpp", "max_stars_repo_name": "Huangzizhou/polyfem", "max_stars_repo_head_hexsha": "db2bd4fb78848257f3d6cdb5241c9bca04165bf8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2020-04-09T12:30:08.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-30T07:16:46.000Z", "max_issues_repo_path": "src/utils/MatrixUtils.hpp", "max_issues_repo_name": "Huangzizhou/polyfem", "max_issues_repo_head_hexsha": "db2bd4fb78848257f3d6cdb5241c9bca04165bf8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/utils/MatrixUtils.hpp", "max_forks_repo_name": "Huangzizhou/polyfem", "max_forks_repo_head_hexsha": "db2bd4fb78848257f3d6cdb5241c9bca04165bf8", "max_forks_repo_licenses": ["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.8266666667, "max_line_length": 194, "alphanum_fraction": 0.6833910035, "num_tokens": 695, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.880797071719777, "lm_q2_score": 0.7310585727705126, "lm_q1q2_score": 0.643914250151907}} {"text": "/**\n * File: random_var.cpp\n * Date: Mon Nov 9 10:31:35 CET 2020\n * Author: Open Risk (www.openriskmanagement.com)\n *\n * Examples of using the tailRisk library to compute tail risk measures\n *\n */\n\n#include \n#include \"random_var.h\"\n\nint main(int argc, char *argv[]) {\n\n // Reading in some data for a type 0 representation (discrete distribution)\n int LossGrid = 1000;\n int DataType = 0;\n RandomVar L(LossGrid, DataType);\n L.ReadFromJSON(\"../../data/example5.json\");\n L.Print();\n\n // Calculate various measures\n double alpha = 0.8;\n int threshold = 0;\n\n std::cout << \"Mean Value: \" << L.Mean() << std::endl;\n std::cout << \"Median Value: \" << L.Median() << std::endl;\n std::cout << \"STD Value: \" << L.StandardDeviation() << std::endl;\n std::cout << \"Kurtosis: \" << L.Kurtosis() << std::endl;\n std::cout << \"Skeweness: \" << L.Skeweness() << std::endl;\n std::cout << \"Quantile @ \" << alpha << \": \" << L.Quantile(alpha) << std::endl;\n std::cout << \"Quantile Index @ \" << alpha << \": \" << L.Quantile_Index(alpha) << std::endl;\n std::cout << \"VaR @ \" << alpha << \": \" << L.VaR(alpha) << std::endl;\n std::cout << \"Expected Shortfall @ \" << alpha << \": \" << L.ExpectedShortFall(alpha) << std::endl;\n std::cout << \"Exceedance Probability: \" << L.ExceedanceProbability(threshold) << std::endl;\n std::cout << \"Mean Excess: \" << L.MeanExcess(threshold ) << std::endl;\n\n return 0;\n}", "meta": {"hexsha": "3ea3353c04d506e9e60b5953b14a2c6ddb0c921b", "size": 1444, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "main.cpp", "max_stars_repo_name": "open-risk/tailRisk", "max_stars_repo_head_hexsha": "209113f48b9d3ac0a98537b1b3eeea97e20bae17", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-02-26T07:25:15.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-26T07:25:15.000Z", "max_issues_repo_path": "main.cpp", "max_issues_repo_name": "open-risk/tailRisk", "max_issues_repo_head_hexsha": "209113f48b9d3ac0a98537b1b3eeea97e20bae17", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.cpp", "max_forks_repo_name": "open-risk/tailRisk", "max_forks_repo_head_hexsha": "209113f48b9d3ac0a98537b1b3eeea97e20bae17", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2020-12-05T11:47:13.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-05T11:47:13.000Z", "avg_line_length": 37.0256410256, "max_line_length": 101, "alphanum_fraction": 0.5921052632, "num_tokens": 434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8840392695254319, "lm_q2_score": 0.7279754430043072, "lm_q1q2_score": 0.6435588788659804}} {"text": "//=======================================================================\n// Copyright (c) 2014 Andrzej Pacuk\n//\n// Distributed under the Boost Software License, Version 1.0. (See\n// accompanying file LICENSE_1_0.txt or copy at\n// http://www.boost.org/LICENSE_1_0.txt)\n//=======================================================================\n/**\n * @file performance_measures.hpp\n * @brief\n * @author Andrzej Pacuk\n * @version 1.0\n * @date 2014-10-22\n */\n#ifndef PALL_PERFORMANCE_MEASURES_HPP\n#define PALL_PERFORMANCE_MEASURES_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace paal {\n\n/**\n * @brief\n *\n * @tparam FloatType\n * @tparam Probs\n * @tparam TestResults\n *\n * @param probs\n * @param test_results\n */\ntemplate\nFloatType log_loss(Probs &&probs, TestResults &&test_results) {\n assert(boost::size(probs) == boost::size(test_results));\n assert(!boost::empty(probs));\n\n FloatType loss{};\n static FloatType EPSILON{1e-6};\n for(auto prob_result : boost::combine(probs, test_results)) {\n FloatType prob, result;\n boost::tie(prob, result) = prob_result;\n loss -= std::log(std::max(result ? prob : 1 - prob,\n EPSILON));\n }\n\n return loss / boost::size(probs);\n}\n\n/**\n * @brief\n *\n * @tparam FloatType\n * @param log_loss\n *\n * @return\n */\ntemplate\nFloatType likelihood_from_log_loss(FloatType log_loss) {\n return std::exp(-log_loss);\n}\n\n/**\n * @brief\n *\n * @tparam FloatType\n * @tparam Probs\n * @tparam TestResults\n *\n * @param probs\n * @param test_results\n */\ntemplate\nFloatType likelihood(Probs &&probs, TestResults &&test_results) {\n return likelihood_from_log_loss(log_loss(std::forward(probs),\n std::forward(test_results)));\n}\n\n/**\n * @brief\n *\n * @tparam FloatType\n * @tparam Probs\n * @tparam TestResults\n *\n * @param probs\n * @param test_results\n */\ntemplate\nFloatType mean_absolute_error(Probs &&probs, TestResults &&test_results) {\n assert(boost::size(probs) == boost::size(test_results));\n assert(!boost::empty(probs));\n\n FloatType loss{};\n for(auto prob_result : boost::combine(probs, test_results)) {\n FloatType prob, result;\n boost::tie(prob, result) = prob_result;\n loss += std::abs(prob - result);\n }\n\n return loss / boost::size(probs);\n}\n\n} //! paal\n\n#endif /* PALL_PERFORMANCE_MEASURES_HPP */\n\n", "meta": {"hexsha": "ec609506ae2c7159f5e290cb8f3f2952b5b7ddff", "size": 2790, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/paal/utils/performance_measures.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/utils/performance_measures.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/utils/performance_measures.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": 23.8461538462, "max_line_length": 83, "alphanum_fraction": 0.6311827957, "num_tokens": 683, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891435927269, "lm_q2_score": 0.7826624789529376, "lm_q1q2_score": 0.6434965932924764}} {"text": "#pragma once\n\n#include \n#include \n\n#include \n#include \n\n#include \n\n//! \\file rkintegrator.hpp Solution for Problem 1, implementing RkIntegrator class\n\n//! \\brief Implements a Runge-Kutta explicit solver for a given Butcher tableau for autonomous ODEs\n//! \\tparam State a type representing the space in which the solution lies, e.g. R^d, represented by e.g. Eigen::VectorXd.\ntemplate \nclass RKIntegrator {\npublic:\n //! \\brief Constructor for the RK method.\n //! Performs size checks and copies A and b into internal storage\n //! \\param[in] A matrix containing coefficents of Butcher tableau, must be (strictly) lower triangular (no check)\n //! \\param[in] b vector containing coefficients of lower part of Butcher tableau\n RKIntegrator(const Eigen::MatrixXd & A, const Eigen::VectorXd & b)\n : A(A), b(b), s(b.size()) {\n assert( A.cols() == A.rows() && \"Matrix must be square.\");\n assert( A.cols() == b.size() && \"Incompatible matrix/vector size.\");\n }\n \n //! \\brief Perform the solution of the ODE\n //! Solve an autonomous ODE y' = f(y), y(0) = y0, using a RK scheme given in the Butcher tableau provided in the\n //! constructor. Performs N equidistant steps upto time T with initial data y0\n //! \\tparam Function type for function implementing the rhs function. Must have State operator()(State x)\n //! \\param[in] f function handle for rhs in y' = f(y), e.g. implemented using lambda funciton\n //! \\param[in] T final time T\n //! \\param[in] y0 initial data y(0) = y0 for y' = f(y)\n //! \\param[in] N number of steps to perform. Step size is h = T / N. Steps are equidistant.\n //! \\return vector containing all steps y^n (for each n) including initial and final value\n template \n std::vector solve(const Function &f, double T, const State & y0, unsigned int N) const {\n // Iniz step size\n double h = T / N;\n \n // Will contain all steps, reserve memory for efficiency\n std::vector res;\n res.reserve(N+1);\n \n // Store initial data\n res.push_back(y0);\n \n // Initialize some memory to store temporary values\n State ytemp1 = y0;\n State ytemp2 = y0;\n // Pointers to swap previous value\n State * yold = &ytemp1;\n State * ynew = &ytemp2;\n \n // Loop over all fixed steps\n for(unsigned int k = 0; k < N; ++k) {\n // Compute, save and swap next step\n step(f, h, *yold, *ynew);\n res.push_back(*ynew);\n std::swap(yold, ynew);\n }\n \n return res;\n }\n \nprivate:\n \n //! \\brief Perform a single step of the RK method for the solution of the autonomous ODE\n //! Compute a single explicit RK step y^{n+1} = y_n + \\sum ... starting from value y0 and storing next value in y1\n //! \\tparam Function type for function implementing the rhs. Must have State operator()(State x)\n //! \\param[in] f function handle for ths f, s.t. y' = f(y)\n //! \\param[in] h step size\n //! \\param[in] y0 initial state \n //! \\param[out] y1 next step y^{n+1} = y^n + ...\n template \n void step(const Function &f, double h, const State & y0, State & y1) const {\n // create vector holding next value\n y1 = y0;\n \n // Reserve space for increments\n std::vector k;\n k.reserve(s);\n \n // Loop over the size of RK\n for(unsigned int i = 0; i < s; ++i) {\n // Compute increments and save them to k\n State incr = y0;\n for(unsigned int j = 0; j < i; ++j) {\n incr += h*A(i,j)*k.at(j);\n }\n k.push_back( f( incr ) );\n y1 += h * b(i) * k.back();\n }\n }\n \n //! Matrix A in Butcher scheme\n const Eigen::MatrixXd A;\n //! Vector b in Butcher scheme\n const Eigen::VectorXd b;\n //! Size of Butcher matrix and vector A and b\n unsigned int s;\n};\n", "meta": {"hexsha": "d515801f82fc6269a01e623ab4e463c36bc34ef6", "size": 4064, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/rkintegrator.hpp", "max_stars_repo_name": "valentinjacot/backupETHZ", "max_stars_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2019-12-25T10:21:30.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-25T10:21:30.000Z", "max_issues_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/rkintegrator.hpp", "max_issues_repo_name": "valentinjacot/backupETHZ", "max_issues_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Nummerical Methods for CSE/PS13/solutions_ps13/rkintegrator.hpp", "max_forks_repo_name": "valentinjacot/backupETHZ", "max_forks_repo_head_hexsha": "36605c4f532eb65efb4a391ed0f17a07102f7d5b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.0769230769, "max_line_length": 122, "alphanum_fraction": 0.5971948819, "num_tokens": 1040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8221891130942472, "lm_q2_score": 0.782662489091802, "lm_q1q2_score": 0.6434965777585246}} {"text": "//---------------------------------------------------------------------------//\n//!\n//! \\file Utility_GaussRadauQuadratureSet.cpp\n//! \\author Luke Kersting\n//! \\brief Gauss-Radau quadrature set\n//!\n//---------------------------------------------------------------------------//\n\n// Boost Includes\n#include \n#include \n\n// FRENSIE Includes\n#include \"Utility_GaussRadauQuadratureSet.hpp\"\n#include \"Utility_GaussKronrodIntegrator.hpp\"\n#include \"Utility_ContractException.hpp\"\n\nnamespace Utility{\n\n// Constructor\nGaussRadauQuadratureSet::GaussRadauQuadratureSet( \n boost::function\n polynomial_expansion_function,\n const double error_tol,\n const int polynomial_order )\n : d_polynomial_expansion_function( polynomial_expansion_function ),\n d_error_tol( error_tol ),\n d_polynomial_order( polynomial_order )\n{\n // Make sure the error tolerances are valid\n testPrecondition( error_tol >= 0.0 );\n\n // Make sure the work space size is valid\n testPrecondition( polynomial_order > 0 );\n}\n\n// Caluclate the nth order Jacobi Polynomial at x\n/* \\details The Jacobi Polynomials can be calculated by the following recursion \n * relationship:\n * a1_n P_{n+1}^{\\alpha,\\beta}(x) = (a2_n + a3_n x)P_n^{\\alpha,\\beta}(x) - a4_n P_{n-1}^{\\alpha,\\beta}(x)\n * where: \n * a1_n = 2(n+1)(n+\\alpha+\\beta+1)(2n+\\alpha+\\beta)\n * a2_n = (2n+\\alpha+\\beta+1)(\\alpha^2-\\beta^2)\n * a3_n = (2n + \\alpha + \\beta)(2n + \\alpha + \\beta + 1)(2n + \\alpha +\\beta + 2)\n * a4_n = 2(n+\\alpha)(n+\\beta)(2n+\\alpha+\\beta+2)\n */\ndouble GaussRadauQuadratureSet::getJacobiPolynomial( \n double x,\n int n, \n int alpha,\n int beta ) const\n{\n // Calculate the first two polynomials\n double P_0 = 1.0;\n double P_1 = 0.5*( alpha - beta + ( alpha + beta + 2 )* x );\n\n if (n==0)\n {\n return P_0;\n }\n if (n==1)\n {\n return P_1;\n }\n else\n {\n int a_b = alpha + beta;\n int a_b_1 = a_b + 1;\n int a_b_2 = a_b + 2;\n\n double p_i_minus_2 = P_0;\n double p_i_minus_1 = P_1;\n double p_i;\n\n // Use recursion relation to calculate higher order Jacobi polynomials\n for (int i = 1; i < n; ++i)\n {\n int two_i = 2*i;\n\n // Calculate the Jacobi coefficients\n double a1_i = 2.0*( i + 1.0 )*( i + a_b_1 )*( two_i + a_b );\n double a2_i = ( two_i + a_b_1 )*( alpha*alpha - beta*beta );\n double a3_i = ( two_i + a_b )*( two_i + a_b_1 )*( two_i + a_b_2 );\n double a4_i = 2.0*( i + alpha )*( i + beta )*( two_i + a_b_2 );\n\n // Calculate new P_n value\n p_i = 1.0/a1_i*( ( a2_i + a3_i*x )*p_i_minus_1 - a4_i*p_i_minus_2 );\n\n // Update P_n_minus_1 and P_n_minus_2 for next value on n\n p_i_minus_2 = p_i_minus_1;\n p_i_minus_1 = p_i;\n }\n\n return p_i;\n }\n}\n\ndouble GaussRadauQuadratureSet::getLegendrePolynomial( \n double x,\n int n ) const\n{\n return getJacobiPolynomial( x, n, 0, 0 );\n}\n\n// Calculate the derivative of the nth order Jacobi Polynomial at x\n/* \\details The Jacobi Polynomials can be calculated by the following recursion \n * relationship:\n * 1/2( n + \\alpha + \\beta + 1 )P_{n-1}^{\\alpha + 1,\\beta + 1}(x) \n */\ndouble GaussRadauQuadratureSet::getJacobiPolynomialDerivative( \n double x,\n int n, \n int alpha,\n int beta ) const\n{\n\n if (n==0)\n {\n return 0.0;\n }\n if (n==1)\n {\n return 0.5*( alpha + beta + 2.0 );\n }\n else\n {\n return 0.5 * (alpha + beta + n + 1.0) * getJacobiPolynomial( x, \n n-1, \n alpha + 1, \n beta + 1 );\n }\n}\n\n// Estimate the roots of the Jacobi Polynomial\n/* \\details The roots of the Jacobi Polynomials can be estimated by the roots of \n * the Chebyshev Polynomials which are given by the relationship:\n * x_k = cos( (2k - 1)\\pi/2n ) , k = 1, ... , n \n */\nvoid GaussRadauQuadratureSet::getJacobiPolynomialRoots( \n Teuchos::Array& roots,\n const int n, \n int alpha,\n int beta ) const\n{\n // Max number of allowed iterations\n int max_iterations = 200;\n\n int iteration;\n double root_k, s, jacobi, jacobi_derivative, delta_root;\n\n // Iterate through all n roots ( 0 < k < n ) \n for (int k = 0; k < n; k++)\n {\n // Make an initial guess that the roots are equal to the roots of the Chebyshev Polynomial\n root_k = -cos( ( 2.0*k + 1.0 )/( 2.0 * n )* PhysicalConstants::pi );\n\n // Actual root is known to be inbetween roots of Chebyshev Polynomial\n if (k > 0)\n {\n root_k = ( root_k + roots[k-1] )/2.0;\n }\n\n iteration = 0;\n\n // Iterate until you converge on root\n do\n {\n s = 0;\n \n for (int i = 0; i < k; i++)\n {\n s += 1.0/( root_k - roots[i] );\n }\n \n // Get error\n jacobi = getJacobiPolynomial( root_k, n, alpha, beta );\n jacobi_derivative = \n getJacobiPolynomialDerivative( root_k, n, alpha, beta );\\\n \n delta_root = -jacobi/( jacobi_derivative - jacobi*s );\n\n // Update root value\n root_k += delta_root;\n \n // Update iteration\n ++iteration;\n \n if ( iteration > max_iterations )\n break;\n/* \n TEST_FOR_EXCEPTION( iteration > max_iterations, \n\t\t RadauQuadratueError, \n\t\t \"Error: the root of the Jacobi Polynomial \"\n \"did not converge\" );\n*/\n }\n while ( fabs(delta_root) > d_error_tol );\n\n roots[k] = root_k;\n }\n}\n\n// Find the Radau nodes and wieghts including at end point -1 or 1\nvoid GaussRadauQuadratureSet::findNodesAndWeights(\n double end_point, \n Teuchos::Array& nodes,\n Teuchos::Array& weights ) const\n{\n // Make sure end_point is either -1 or 1\n testPrecondition( fabs(end_point) == 1.0 );\n\n int n = d_polynomial_order;\n int alpha = 0;\n int beta = 1;\n double jacobi_derivative;\n\n Teuchos::Array roots( n );\n\n // Calculate the roots of the Jacobi Polynomial\n getJacobiPolynomialRoots( roots, n, alpha, beta );\n\n // Check to see if the end point is the first node\n if ( end_point < roots[0] )\n {\n nodes[0] = end_point;\n weights[0] = findWeightAtEndPoint( end_point, n );\n\n // Iterate through the all nodes and weights\n for ( int i = 0; i < n; ++i )\n {\n nodes[i+1] = roots[i];\n\n weights[i+1] = findWeightAtNode( roots[i], end_point, n );\n }\n }\n else\n {\n nodes[n] = end_point;\n weights[n] = findWeightAtEndPoint( end_point, n );\n\n // Iterate through all other nodes and weights\n for ( int i = 0; i < n; ++i )\n {\n nodes[i] = roots[i];\n \n weights[i] = findWeightAtNode( roots[i], end_point, n );\n }\n }\n}\n\n// Find the Radau nodes and wieghts including at end point -1 or 1\nvoid GaussRadauQuadratureSet::findNodesAndPositiveWeights(\n double end_point, \n Teuchos::Array& nodes,\n Teuchos::Array& weights ) const\n{\n // Make sure end_point is either -1 or 1\n testPrecondition( fabs(end_point) == 1.0 );\n\n int n = d_polynomial_order;\n int alpha = 0;\n int beta = 1;\n double jacobi_derivative;\n\n Teuchos::Array roots( n );\n\n // Calculate the roots of the Jacobi Polynomial\n getJacobiPolynomialRoots( roots, n, alpha, beta );\n\n // Check to see if the end point is the first node\n if ( end_point < roots[0] )\n {\n nodes[0] = end_point;\n weights[0] = findWeightAtEndPoint( end_point, n );\n\n // Iterate through the all nodes and weights\n for ( int i = 0; i < n; ++i )\n {\n nodes[i+1] = roots[i];\n\n jacobi_derivative = \n getJacobiPolynomialDerivative( nodes[i+1], n, alpha, beta );\n\n weights[i+1] = findWeightAtNode( roots[i], end_point, n );\n }\n }\n else\n {\n nodes[n] = end_point;\n weights[n] = findWeightAtEndPoint( -end_point, n );\n\n // Iterate through all other nodes and weights\n for ( int i = 0; i < n; ++i )\n {\n nodes[n-1-i] = -roots[i];\n\n // Get the derivative of the Jacobi Polynomial of order n\n jacobi_derivative = \n getJacobiPolynomialDerivative( roots[i], \n n, \n alpha, beta );\n \n weights[n-1-i] = findWeightAtNode( roots[i], -end_point, n );\n }\n }\n}\n\n// Create the integrand function for the weight at the end point -1 or 1\ndouble GaussRadauQuadratureSet::getFixedWeightIntegrand( \n double end_point,\n int n ) const\n{\n return d_polynomial_expansion_function( end_point, n )*getJacobiPolynomial( end_point, n );\n}\n\n// Create the integrand function for the weight at a given node with end point -1 or 1\ndouble GaussRadauQuadratureSet::getWeightIntegrand(\n double x,\n double node,\n double end_point, \n int n ) const\n{\n return getFixedWeightIntegrand( x, n )*( x - end_point )/( x - node );\n}\n\n// Find the Radau wieght for the function at the end point -1 or 1\ndouble GaussRadauQuadratureSet::findWeightAtEndPoint( double end_point,\n int n ) const\n{\n // Make sure end_point is either -1 or 1\n testPrecondition( fabs(end_point) == 1.0 );\n // Make sure n is positive\n testPrecondition( n > 0.0 );\n\n boost::function weight_function =\n boost::bind( &GaussRadauQuadratureSet::getFixedWeightIntegrand,\n\t\t\t boost::cref( *this ),\n\t\t\t _1,\n\t\t\t n );\n\n double abs_error, result;\n double precision = 1e-12;\n \n Utility::GaussKronrodIntegrator integrator( precision );\n\n integrator.integrateAdaptively<15>(\n\t\t\t\t\tweight_function,\n\t\t\t\t\t-1.0,\n\t\t\t\t\t1.0,\n\t\t\t\t\tresult,\n\t\t\t\t\tabs_error );\n\n return result/getJacobiPolynomial( end_point, n );\n\n}\n\n// Find the Radau wieght for the function at a given node\ndouble GaussRadauQuadratureSet::findWeightAtNode( double node,\n double end_point,\n int n ) const\n{\n // Make sure end_point is either -1 or 1\n testPrecondition( fabs(end_point) == 1.0 );\n // Make sure node is between -1 and 1\n testPrecondition( node < 1.0 );\n testPrecondition( node > -1.0 );\n // Make sure n is positive\n testPrecondition( n > 0.0 );\n\n boost::function weight_function =\n boost::bind( &GaussRadauQuadratureSet::getWeightIntegrand,\n\t\t\t boost::cref( *this ),\n\t\t\t _1,\n node,\n end_point,\n\t\t\t n );\n\n double abs_error, result;\n double precision = 1e-12;\n \n Utility::GaussKronrodIntegrator integrator( precision );\n\n integrator.integrateAdaptively<15>(\n\t\t\t\t\tweight_function,\n\t\t\t\t\t-1.0,\n\t\t\t\t\t1.0,\n\t\t\t\t\tresult,\n\t\t\t\t\tabs_error );\n return result/\n ( getJacobiPolynomialDerivative( node, n ) * ( node - end_point) );\n\n}\n\n} // end Utility namespace\n\n//---------------------------------------------------------------------------//\n// end Utility_GaussRadauQuadratureSet.cpp\n//---------------------------------------------------------------------------//\n", "meta": {"hexsha": "98e8cecc752ddef7df62fe9dc5c0758ef5389850", "size": 11798, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "packages/utility/integrator/src/Utility_GaussRadauQuadratureSet.cpp", "max_stars_repo_name": "lkersting/SCR-2123", "max_stars_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "packages/utility/integrator/src/Utility_GaussRadauQuadratureSet.cpp", "max_issues_repo_name": "lkersting/SCR-2123", "max_issues_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "packages/utility/integrator/src/Utility_GaussRadauQuadratureSet.cpp", "max_forks_repo_name": "lkersting/SCR-2123", "max_forks_repo_head_hexsha": "06ae3d92998664a520dc6a271809a5aeffe18f72", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.5689223058, "max_line_length": 105, "alphanum_fraction": 0.5475504323, "num_tokens": 3173, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8459424295406088, "lm_q2_score": 0.7606506526772884, "lm_q1q2_score": 0.6434666611574752}} {"text": "/* Implementation of the algorithm\n * \n D. Conte, L. Ixaru, B. Paternoster, G. Santomauro:\n Exponentially-fitted Gauss–Laguerre quadrature rule for integrals over an unbounded interval.\n \n https://hpcquantlib.wordpress.com/2020/05/17/optimized-heston-model-integration-exponentially-fitted-gauss-laguerre-quadrature-rule/\n \n \n Copyright (c) 2020, Klaus Spanderen\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 names of the copyright holders nor the names of the QuantLib \n Group and its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \n*/\n\n#include \n\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\nusing namespace boost::numeric::ublas;\n\n//typedef boost::multiprecision::number<\n// boost::multiprecision::cpp_dec_float<400> > Float;\n\ntypedef boost::multiprecision::number<\n boost::multiprecision::gmp_float<600> > Float;\n\n\ntemplate \nboost::numeric::ublas::vector lu(\n const boost::numeric::ublas::matrix& A,\n const boost::numeric::ublas::vector& b) {\n\n matrix A_fac = A;\n\n permutation_matrix piv(b.size());\n int singular = lu_factorize(A_fac, piv);\n\n if (singular) \n throw std::runtime_error(\"lu: A is singular.\");\n\n vector x = b;\n lu_substitute(A_fac, piv, x); \n\n return x;\n}\n\ntemplate \nboost::numeric::ublas::matrix inv(\n const boost::numeric::ublas::matrix& A) {\n \n using namespace boost::numeric::ublas;\n\n matrix A_fac = A;\n\n permutation_matrix piv(A.size1());\n int singular = lu_factorize(A_fac, piv);\n\n if (singular) \n throw std::runtime_error(\"lu: A is singular.\");\n \n matrix inverse = identity_matrix(A.size1());\n \n lu_substitute(A_fac, piv, inverse);\n \n return inverse;\n}\n\nFloat pow_c(const Float& x, int n) {\n\n if (n == 0)\n return Float(1.0);\n\n if (n == 1)\n return x;\n\n typedef std::pair key_type;\n\n typedef boost::unordered_map ResultMap;\n\n static boost::mutex mutex;\n\n static std::size_t maxCacheSize = 16384;\n\n static ResultMap results;\n static std::queue fifo;\n\n const key_type key(n, x);\n {\n boost::lock_guard lock(mutex);\n\n const typename ResultMap::const_iterator iter = results.find(key);\n\n if (iter != results.end())\n return iter->second;\n }\n\n const Float result = (n < 0)\n ? Float(1.0)/pow_c(x, -n)\n : Float(pow_c(x, n/2) * pow_c(x, n/2) * pow_c(x, n - 2*(n/2)));\n\n boost::lock_guard lock(mutex);\n\n results.emplace(key, result);\n fifo.push(key);\n\n while(fifo.size() > maxCacheSize) {\n results.erase(fifo.front());\n fifo.pop();\n }\n\n return result;\n}\n\nFloat pow_i(long n) {\n if (n < 0)\n return pow_c(Float(2), n);\n else if (n < 8*sizeof(unsigned long))\n return Float(1uL << n);\n else\n return pow_c(Float(2), n);\n}\n\n\ntemplate \nresult_type eta(int m, float_type Z) {\n \n typedef std::pair key_type;\n typedef boost::unordered_map ResultMap;\n\n static boost::mutex mutex;\n\n static std::size_t maxCacheSize = 16384;\n \n static ResultMap results;\n static std::queue fifo;\n\n const key_type key(m, Z);\n {\n boost::lock_guard lock(mutex);\n const typename ResultMap::const_iterator iter = results.find(key);\n\n if (iter != results.end()) {\n return iter->second;\n }\n }\n\n result_type result;\n\n if (m == 0) {\n if (Z < 0) {\n const result_type sz = sqrt(-Z);\n result = sin(sz)/sz;\n }\n else if (Z > 0) {\n const result_type sz = sqrt(Z);\n result = sinh(sz)/sz;\n }\n else\n result = result_type(1.0);\n }\n else if (m == -1)\n if (Z <= 0)\n result = cos(sqrt(-Z));\n else\n result = cosh(sqrt(Z));\n else\n result = (eta(m-2, Z) \n - (2*m-1)*eta(m-1, Z))/Z;\n \n boost::lock_guard lock(mutex);\n results.emplace(key, result);\n fifo.push(key);\n \n while(fifo.size() > maxCacheSize) {\n results.erase(fifo.front());\n fifo.pop();\n }\n \n return result; \n}\n\ntemplate \nreal factorial(std::size_t n) {\n static std::vector cache(1, real(1));\n\n if (cache.size() > n)\n return cache[n];\n \n const real val = real(n) * factorial(n-1);\n cache.resize(n+1);\n \n return cache[n] = val;\n}\n\n\ntemplate \nvector w_lin(const vector& x, const real& Z) {\n const int N = x.size();\n \n const int s = N/2;\n const int r = N-s;\n \n matrix A(N, N);\n int row = 0;\n \n vector b(x.size());\n \n for (int n=r+1; n <= N; ++n) {\n for (int k=0; k < N; ++k)\n A(row, k) = pow_c(x(k), 2*n-2)*eta(n-2, x(k)*x(k)*Z);\n \n b(row) = pow_i(n-1)*factorial(n-1)/pow_c(1.0-Z, n);\n ++row;\n }\n \n for (int n=s+1; n <= N; ++n) {\n for (int k=0; k < N; ++k)\n A(row, k) = pow_c(x(k), 2*n-1)*eta(n-1, x(k)*x(k)*Z);\n\n b(row) = pow_i(n-1)*factorial(n-1)/pow_c(1.0-Z, n);\n ++row;\n }\n \n return lu(A,b);\n}\n\n\nclass WorkerJxA {\n public:\n WorkerJxA(\n matrix& JxA, const vector& w,\n const vector& x, const Float& Z)\n : JxA_(JxA), w_(w), x_(x), Z_(Z) {}\n\n void run() const {\n const int N = JxA_.size1();\n const int s = N/2;\n const int r = N-s;\n\n for (int j=0; j < N; ++j) {\n const Float xxZ = x_(j)*x_(j)*Z_;\n\n for (int i=1; i <= N; ++i) {\n JxA_(i-1, j) = (i <= s)\n ? pow_c(x_(j), 2*(i+r)-3)*(\n 2*(i+r-1)*eta(i+r-2, xxZ)\n + xxZ*eta(i+r-1, xxZ))\n : pow_c(x_(j), 2*(i-1))*(\n (2*i-1)*eta(i-1, xxZ)\n + xxZ*eta(i, xxZ));\n JxA_(i-1, j) *= -w_(j);\n }\n }\n }\n\n private:\n matrix& JxA_;\n const vector& w_, x_;\n const Float& Z_;\n};\n\nclass WorkerInvA {\n public:\n WorkerInvA(matrix& A, const vector& x, const Float& Z)\n : A_(A), x_(x), Z_(Z) { }\n\n void run() const {\n const int N = A_.size1();\n const int s = N/2;\n const int r = N-s;\n\n for (int j=0; j < N; ++j) {\n const Float xxZ = x_(j)*x_(j)*Z_;\n for (int i=1; i <= N; ++i)\n A_(i-1, j) = (i <= s)\n ? pow_c(x_(j), 2*(i+r-1))*eta(i+r-2, xxZ)\n : pow_c(x_(j), 2*i-1 )*eta(i-1, xxZ);\n }\n\n A_ = inv(A_);\n }\n\n private:\n matrix& A_;\n const vector& x_;\n const Float& Z_;\n};\n\nclass WorkerC {\n public:\n WorkerC(matrix& C, const vector& w,\n const vector& x, const Float& Z)\n : C_(C), w_(w), x_(x), Z_(Z) {}\n\n void run() const {\n const int N = C_.size1();\n const int s = N/2;\n const int r = N-s;\n\n for (int k=0; k < N; ++k) {\n const Float xxZ = x_(k)*x_(k)*Z_;\n for (int i=1; i <= N; ++i) {\n C_(i-1, k) = (i <= r)\n ? pow_c(x_(k), 2*i-3)*( (2*i-2)*eta(i-2, xxZ)\n + xxZ*eta(i-1, xxZ) )\n : pow_c(x_(k), 2*(i-r-1))*( (2*(i-r)-1)*eta(i-r-1, xxZ)\n + xxZ*eta(i-r, xxZ) );\n C_(i-1, k) *= w_(k);\n }\n }\n }\n private:\n matrix& C_;\n const vector& w_, x_;\n const Float& Z_;\n};\n\nclass WorkerD {\n public:\n WorkerD(matrix& D, vector& dZ, const vector& x, const Float& Z)\n : D_(D), dZ_(dZ), x_(x), Z_(Z) {}\n\n void run() const {\n const int N = D_.size1();\n const int s = N/2;\n const int r = N-s;\n\n for (int k=0; k < N; ++k) {\n const Float xxZ = x_(k)*x_(k)*Z_;\n for (int i=1; i <= N; ++i)\n D_(i-1, k) = ( i <= r)\n ? pow_c(x_(k), 2*i-2) *eta(i-2, xxZ)\n : pow_c(x_(k), 2*(i-r)-1)*eta(i-r-1, xxZ);\n }\n\n const Float omz(1-Z_);\n\n for (int i=1; i <= N; ++i)\n dZ_(i-1) = (i <= r)\n ? pow_i(i-1)*factorial(i-1) / pow_c(omz, i)\n : pow_i(i-r-1)*factorial(i-r-1) / pow_c(omz, i-r);\n }\n\n private:\n matrix& D_;\n vector& dZ_;\n const vector& x_;\n const Float& Z_;\n};\n\n\ntemplate \nvector newton_iter(const vector& w, const vector& x, const real& Z) {\n const int N = x.size();\n const int s = N/2;\n const int r = N-s;\n \n matrix invA(N, N);\n WorkerInvA workerInvA(invA, x, Z);\n\n boost::thread invA_thread(&WorkerInvA::run, &workerInvA);\n\n matrix JxA(N, N);\n\n WorkerJxA workerJxA(JxA, w, x, Z);\n boost::thread JxA_thread(&WorkerJxA::run, &workerJxA);\n\n matrix C(N, N);\n WorkerC workerC(C, w, x, Z);\n boost::thread C_thread(&WorkerC::run, &workerC);\n\n matrix D(N, N);\n vector dZ(N);\n WorkerD workerD(D, dZ, x, Z);\n boost::thread D_thread(&WorkerD::run, &workerD);\n\n\n JxA_thread.join();\n invA_thread.join();\n const matrix JxW = prod(invA, JxA);\n\n C_thread.join();\n D_thread.join();\n \n const matrix B = C + prod(D, JxW);\n\n return lu(B, vector(prod(D, w) - dZ));\n}\n \n \ntemplate \nvector newton(vector& x, real Z) {\n const static real eps = Float(1e-300);\n\n const std::size_t N = x.size();\n \n vector w(N), dx;\n\n do {\n w = w_lin(x, Z);\n\n dx = newton_iter(w, x, Z); \n\n x = x - dx;\n \n std::cout << norm_2(dx) << std::endl;\n\n for (std::size_t i=0; i < N; ++i)\n if (x(i) < 0.0) {\n return vector();\n }\n }\n while (norm_2(dx) > eps);\n \n return w;\n}\n\n\nbool greaterThan(vector& x, vector& y) {\n bool f = false;\n \n for (std::size_t i=0; i < x.size(); ++i) {\n if (x[i] >= y[i]) {\n f = true;\n }\n }\n return f;\n}\n\n\nint main() {\n \n const std::size_t n = 64;\n const std::size_t maxOrder = 45;\n \n const QuantLib::Array x_laguerre = \n QuantLib::GaussLaguerreIntegration(n).x();\n const QuantLib::Array w_laguerre = \n QuantLib::GaussLaguerreIntegration(n).weights();\n \n std::vector > x(maxOrder, vector(n));\n std::copy(x_laguerre.begin(), x_laguerre.end(), x[0].begin());\n\n std::ofstream f(\"values.txt\");\n f << std::setprecision(std::numeric_limits::digits10 + 1)\n << \"{ 0.0\";\n for (std::size_t i = 0; i < n; ++i)\n f << \", \" << x_laguerre[i];\n for (std::size_t i = 0; i < n; ++i)\n f << \", \" << w_laguerre[i];\n f << \" },\" << std::endl; \n f.flush();\n\n \n vector xGuess;\n std::vector o(maxOrder, Float(0.0));\n o[0] = 0.01;\n \n std::size_t iter = 0;\n \n vector w;\n w = newton(x[0], Float(-o[0]*o[0]));\n \n while (o[0] < 50.0) {\n\n ++iter;\n const std::size_t order = std::min(maxOrder, iter);\n \n vector xTest(n);\n \n const Float m1 = o[0] + Float(0.01);\n const Float m2 = o[0]*(1 + 0.0075);\n \n Float nomega = (m1 > m2)? m1 : m2;\n \n do {\n const Float z = -nomega*nomega;\n \n for (std::size_t i=0; i < order; ++i) {\n Float l=1.0;\n for (std::size_t j=0; j < order; ++j) \n if (i != j)\n l *= (nomega-o[j])/(o[i]-o[j]);\n \n xTest += x[i]*l;\n }\n \n xGuess = xTest;\n\n w = newton(xTest, z); \n \n if (w.size() == 0) {\n std::cout << \"opps, monotocity violation \" << nomega;\n nomega = o[0] + 0.5*(nomega - o[0]);\n std::cout << \" new \" << nomega << std::endl;\n }\n } while (w.size() == 0);\n \n std::cout << \"start norm \" << nomega << \" \" << norm_2(xGuess - xTest) << std::endl;\n \n if (greaterThan(xTest, x[0]))\n std::cout << \"wrong direction\" << std::endl;\n \n for (int i=std::min(maxOrder-1, order); i > 0; --i) {\n x[i] = x[i-1];\n o[i] = o[i-1];\n }\n \n x[0] = xTest;\n o[0] = nomega;\n \n Float s=0;\n for (std::size_t i=0; i < n; ++i)\n s+=w(i)*(x[0](i)*cos(o[0]*x[0](i)) + x[0](i)*sin(o[0]*x[0](i)));\n\n const Float expected = (1+2*o[0]-o[0]*o[0])/(1+o[0]*o[0])/(1+o[0]*o[0]);\n if (abs(s - expected) > 1e-16) {\n std::cout << \"integration error \" << abs(s - expected) << std::endl;\n exit(-1);\n }\n \n f << std::setprecision(std::numeric_limits::digits10 + 1)\n << \"{ \" << o[0];\n for (std::size_t i = 0; i < n; ++i)\n f << \", \" << x[0](i);\n for (std::size_t i = 0; i < n; ++i)\n f << \", \" << exp(x[0](i))*w(i);\n f << \" },\" << std::endl; \n f.flush();\n }\n f.close();\n}\n", "meta": {"hexsha": "a61ba9e2f2cd7d44e32042c2866811e4f78201d9", "size": 15537, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "exponential_fitting/ef_laguerre.cpp", "max_stars_repo_name": "klausspanderen/HestonExponentialFitting", "max_stars_repo_head_hexsha": "a06e596340820b181699eb105c90b854246c26b8", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "exponential_fitting/ef_laguerre.cpp", "max_issues_repo_name": "klausspanderen/HestonExponentialFitting", "max_issues_repo_head_hexsha": "a06e596340820b181699eb105c90b854246c26b8", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "exponential_fitting/ef_laguerre.cpp", "max_forks_repo_name": "klausspanderen/HestonExponentialFitting", "max_forks_repo_head_hexsha": "a06e596340820b181699eb105c90b854246c26b8", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2022-03-28T10:57:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:57:06.000Z", "avg_line_length": 27.3538732394, "max_line_length": 134, "alphanum_fraction": 0.519727103, "num_tokens": 4627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9032942041005327, "lm_q2_score": 0.7122321781307375, "lm_q1q2_score": 0.6433551984793934}} {"text": "#pragma once\n#include \n#include \"datatypes.hpp\"\n#include \n#include \"profile.hpp\"\n#include \"integration.hpp\"\n#include \"transformation.hpp\"\n\nnamespace gd {\n\nusing namespace std;\nUSING_PART_OF_NAMESPACE_EIGEN\n\nclass Mesh1d {\npublic:\n\tvirtual int findindex(double) { return 0; }\n\tvirtual double indexto_x(int) { return 0; }\n\t//virtual void indexto_x(int) { return 0; }\n\tvirtual bool inrange(double) { return false; }\n\tvirtual int length() {return 0;}\n};\n\ntemplate\nclass Mesh1dRegular : public Base {\npublic:\n\tMesh1dRegular(double x1, double x2, int length) : x1(x1), x2(x2), _length(length) {}\n\tint findindex(double x) {\n\t\treturn x < x1 ? 0 :\n\t\t\t(x >= x2 ? _length-1 : (int)((x-x1)/(x2-x1)*(_length)));\n\t}\n\tdouble indexto_x(int i) {\n\t\treturn x1 + (x2-x1)/length()*i;\n\t}\n\tbool inrange(double r) {\n\t\treturn (r >= x1) && (r < x2); \n\t}\n\tint length() { return _length; }\n\tdouble x1, x2;\n\tint _length;\n};\n\ntemplate\nclass BasisTriLeft {\npublic:\n\tT operator()(T x) {\n\t\treturn x >= -1 ? (x < 0 ? (x+1) : 0) : 0;\n\t}\n};\n\ntemplate\nclass BasisTriRight {\npublic:\n\tT operator()(T x) {\n\t\treturn x >= 0 ? (x < 1 ? (1-x) : 0) : 0;\n\t}\n};\n\n\t\n\ntemplate\nclass BasisTriMesh1dRegular {\npublic:\n\tBasisTriMesh1dRegular(T _x1, T _x2, int _n_nodes) : x1(_x1), x2(_x2), n_nodes(_n_nodes), mesh(_x1, _x2, _n_nodes), ctrans(_n_nodes+1,_n_nodes+1) {\n\t\tMatrixXd m = MatrixXd::Zero(_n_nodes+1,_n_nodes+1);\n\t\t//m.setZero();\n\t\tm(0,0) = 1./3;\n\t\tm(_n_nodes,_n_nodes) = 1./3;\n\t\tfor(int i = 1; i < (_n_nodes+1); i++) {\n\t\t\tm(i, i-1) = 1./6;\n\t\t\tm(i-1, i) = 1./6;\n\t\t} \n\t\tfor(int i = 1; i < (_n_nodes); i++) {\n\t\t\tm(i, i) = 2./3;\n\t\t} \n\t\tT scale = (x2-x1)/n_nodes;\n\t\tm = m * scale;\n\t\t//cout << m << endl;\n\t\tctrans = m.inverse();\n\t\t//cout << ctrans << endl;\n\t}\n\tvoid testprofile(Profile* profile, double_vector v, bool dotrans) {\n\t\tdouble* vp = v.data().begin();\n\t\tdouble* array = vp;\n\t\t//int size = x.size();\n\t\t//double scale = 1./size;\n\t\t//cout << \"size = \" << size << endl;\n\t\tfor(int i = 0; i < n_nodes; i++) {\n\t\t\tdouble integral = 0;\n\t\t\tT xleft = mesh.indexto_x(i);\n\t\t\tT xright = mesh.indexto_x(i+1);\n\t\t\tT dx = (xright-xleft);\n\t\t\t{\n\t\t\t\tBasisTriRight triright;\n\t\t\t\tauto f = [&](double x) { return triright((x-xleft)/dx) * profile->densityr(x); };\n\t\t\t\tIntegratorGSL<> integratorGSL(f); // the integrator\n\t\t\t\tintegral = integratorGSL.integrate(xleft, xright);\n\t\t\t\tarray[i] += integral;\n\t\t\t}\n\t\t\t{\n\t\t\t\tBasisTriLeft trileft;\n\t\t\t\tauto f = [&](double x) { return trileft((x-xleft)/dx-1) * profile->densityr(x); };\n\t\t\t\tIntegratorGSL<> integratorGSL(f); // the integrator\n\t\t\t\tintegral = integratorGSL.integrate(xleft, xright);\n\t\t\t\tarray[i+1] += integral;\n\t\t\t}\n\t\t}\n\t\tif(dotrans) {\n\t\t\tVectorXd v_alias = VectorXd::Map(v.data().begin(), v.size());\n\t\t\tVectorXd vtrans = ctrans * v_alias;\n\t\t\tVectorXd::Map(v.data().begin(), v.size()) = vtrans;\n\t\t}\n\t}\n\n\tvoid test(double_vector x, double_vector y, double_vector v, bool dotrans) {\n\t\tdouble* xp = x.data().begin();\n\t\tdouble* yp = y.data().begin();\n\t\tdouble* vp = v.data().begin();\n\t\tint size = x.size();\n\t\tdouble scale = 1./size * (x2-x1);\n\t\t//cout << \"size = \" << size << endl;\n\t\tfor(int i = 0; i < size; i++) {\n\t\t\t//cout << \"i = \" << i << endl;\n\t\t\tthis->operator()(xp[i], yp[i]*scale, vp);\n\t\t\t\n\t\t}\n\t\tif(dotrans) {\n\t\t\tVectorXd v_alias = VectorXd::Map(v.data().begin(), v.size());\n\t\t\tVectorXd vtrans = ctrans * v_alias;\n\t\t\tVectorXd::Map(v.data().begin(), v.size()) = vtrans;\n\t\t}\n\t}\n\n\n\ttemplate\n\tT operator()(T x, T y, A array) {\n\t\tif(mesh.inrange(x)) {\n\t\t\tint indexleft = mesh.findindex(x);\n\t\t\tT xleft = mesh.indexto_x(indexleft);\n\t\t\tT xright = mesh.indexto_x(indexleft+1);\n\t\t\tT fraction = (x-xleft)/(xright-xleft);\n\t\t\t//cout << \"x = \" << x << \" xleft = \" << xleft << \" xright = \" << xright << \" fraction = \" << fraction << endl;\n\t\t\tBasisTriLeft trileft;\n\t\t\tBasisTriRight triright;\n\t\t\t//cout << \"y = \" << y << \" triright(fraction) = \" << triright(fraction) << \" trileft (fraction-1) = \" << trileft (fraction-1) << endl;\n\t\t\tarray[indexleft] += triright(fraction) * y;\n\t\t\tarray[indexleft+1] += trileft (fraction-1) * y;\n\t\t\t// TODO: use trileft(fraction) + triright(fraction) == 1\n\t\t}\n\t\treturn 0; // TODO: not finished.., remove code? \n\t}\n\t\n\tT x1, x2;\n\tint n_nodes;\n\tMesh1dRegular<> mesh;\n\tMatrixXd ctrans;\n};\n\ntemplate\nclass MeshRegularNodal1d {\npublic:\n\ttypedef Basis basis_type;\n\tT x1, x2;\n\tint n_cells;\n\tMesh1dRegular<> mesh;\n\tMatrixXd ctrans;\n\tTransformation1d_in_3d* transformation;\n\tint dof;\n\tenum { dof_per_cell = Basis::degree+1 };\n\n\tint get_dof() { return dof;}\n\tint get_n_cells() { return n_cells;}\n\tint dof_index(int cell_index, int local_index) {\n\t\treturn cell_index*(dof_per_cell-1)+local_index;\n\t}\n\n\n\ttemplate\n\tstruct util {\n\t\ttypedef util next_type;\n\t\tnext_type next;\n\t\tT integrate(int i, double xleft, double xright, double dx, Profile* profile) {\n\t\t\tif(i == I) { \n\t\t\t\tB basis;\n\t\t\t\tauto f = [&](double x) { return basis((x-xleft)/dx) * profile->densityr(x); };\n\t\t\t\tIntegratorGSL<> integratorGSL(f); // the integrator\n\t\t\t\treturn integratorGSL.integrate(xleft, xright);\n\t\t\t} else {\n\t\t\t\treturn next.integrate(i, xleft, xright, dx, profile);\n\t\t\t}\n\t\t}\n\t\ttemplate\n\t\tT integrate2(int i, double xleft, double xright, double dx, F f) {\n\t\t\tif(i == I) { \n\t\t\t\tB basis;\n\t\t\t\tauto f2 = [&](double x) { return basis((x-xleft)/dx) * f(x); };\n\t\t\t\tIntegratorGSL<> integratorGSL(f2); // the integrator\n\t\t\t\treturn integratorGSL.integrate(xleft, xright);\n\t\t\t} else {\n\t\t\t\treturn next.integrate2(i, xleft, xright, dx, f);\n\t\t\t}\n\t\t}\n\t\ttemplate\n\t\tT eval(Array& array, int index, double xleft, double dx, double x) {\n\t\t\tB basis;\n\t\t\t//cout << \"eval: \" << index << \" \" << xleft << \" \" << dx << \" \" << x << \" u=\" << ((x-xleft)/dx) << \" \" << basis((x-xleft)/dx) << \" \" << array(index) << endl;\n\t\t\treturn basis((x-xleft)/dx) * array(index) + next.eval(array, index-1, xleft, dx, x);\n\t\t}\n\t\ttemplate\n\t\tT gradient(Array& array, int index, double xleft, double dx, double x) {\n\t\t\tB basis;\n\t\t\t//cout << \"grad: \" << index << \" \" << xleft << \" \" << dx << \" \" << x << \" u=\" << ((x-xleft)/dx) << \" \" << basis((x-xleft)/dx) << \" \" << basis.dfdx((x-xleft)/dx) << \" \" << array(index) << endl;\n\t\t\treturn basis.dfdx((x-xleft)/dx)/dx * array(index) + next.gradient(array, index-1, xleft, dx, x);\n\t\t}\n\t};\n\ttemplate\n\tstruct util<-1, B> {\n\t\tT integrate(int, double, double, double, Profile*) {\n\t\t\treturn 0;\n\t\t}\n\t\ttemplate\n\t\tT integrate2(int, double, double, double, F) {\n\t\t\treturn 0;\n\t\t}\n\t\ttemplate\n\t\tT eval(Array&, int, double, double, double) {\n\t\t\treturn 0;\n\t\t}\n\t\ttemplate\n\t\tT gradient(Array&, int, double, double, double) {\n\t\t\treturn 0;\n\t\t}\n\t};\n\n\ttemplate\n\tstruct selfintegrator {\n\t\ttypedef selfintegrator next_typeI;\n\t\ttypedef selfintegrator next_typeJ;\n\t\tnext_typeI nextI;\n\t\tnext_typeJ nextJ;\n\t\tT integrate(int i, int j) {\n\t\t\tif((i == I)) { // first search for right i\n\t\t\t\tif(j == J) { // then right j\n\t\t\t\t\tB1 basis1;\n\t\t\t\t\tB2 basis2;\n\t\t\t\t\tauto f = [&](double x) { return basis1(x) * basis2(x); };\n\t\t\t\t\tIntegratorGSL<> integratorGSL(f);\n\t\t\t\t\treturn integratorGSL.integrate(0, 1);\n\t\t\t\t} else {\n\t\t\t\t\treturn nextJ.integrate(i, j);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn nextI.integrate(i, j);\n\t\t\t}\n\t\t}\n\t\tT integrate_grad(int i, int j, double xleft, double xright, double dx, Transformation1d_in_3d* transformation) {\n\t\t\tif((i == I)) { // first search for right i\n\t\t\t\tif(j == J) { // then right j\n\t\t\t\t\tB1 basis1;\n\t\t\t\t\tB2 basis2;\n\t\t\t\t\t//auto f = [&](double x) { return basis1.dfdx((x-xleft)/dx) / dx * basis2.dfdx((x-xleft)/dx) / dx * x * x;}; //*/; };\n\t\t\t\t\tauto f = [&](double x) -> double {\n\t\t\t\t\t\t//double r = tan(u*M_PI/2);\n\t\t\t\t\t\tdouble u = x;\n\t\t\t\t\t\t//double t = tan(u*M_PI/2);\n\t\t\t\t\t\t//double c = cos(u*M_PI/2);\n\t\t\t\t\t\t//return 16./2 * basis1.dfdx((x-xleft)/dx) / dx * basis2.dfdx((x-xleft)/dx) / dx * t * t * c * c;\n\t\t\t\t\t\treturn basis1.dfdx((x-xleft)/dx) / dx * basis2.dfdx((x-xleft)/dx) / dx * transformation->laplace_u1_1_times_d3xdu(u) * transformation->laplace_u1_2(u);\n\t\t\t\t\t}; //*/; };\n\t\t\t\t\tIntegratorGSL<> integratorGSL(f);\n\t\t\t\t\treturn integratorGSL.integrate(xleft, xright);\n\t\t\t\t} else {\n\t\t\t\t\treturn nextJ.integrate_grad(i, j, xleft, xright, dx, transformation);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\treturn nextI.integrate_grad(i, j, xleft, xright, dx, transformation);\n\t\t\t}\n\t\t}\n\t};\n\ttemplate\n\tstruct selfintegrator {\n\t\tT integrate(int, int) {\n\t\t\treturn 0;\n\t\t}\n\t\tT integrate_grad(int, int, double, double, double, Transformation1d_in_3d*) {\n\t\t\treturn 0;\n\t\t}\n\t};\n\ttemplate\n\tstruct selfintegrator<-1, J, B1, B2> {\n\t\tT integrate(int, int) {\n\t\t\treturn 0;\n\t\t}\n\t\tT integrate_grad(int, int, double, double, double, Transformation1d_in_3d* ) {\n\t\t\treturn 0;\n\t\t}\n\t};\n\n\tdouble integrate_gradshape(int cell_index, int i, int j) {\n\t\ttypedef selfintegrator selfintegrator_type;\n\t\tselfintegrator_type si; \n\t\tT xleft = mesh.indexto_x(cell_index);\n\t\tT xright = mesh.indexto_x(cell_index+1);\n\t\tT dx = (xright-xleft);\n\t\t//cout << \"integrate: \" << cell_index << \" i \" << i << \" \" << xleft << \" to \" << xright << endl;\n\t\treturn si.integrate_grad(i, j, xleft, xright, dx, transformation);\n\t}\n\n\ttemplate\n\tdouble integrate_shape(int cell_index, int i, F f) {\n\t\tT xleft = mesh.indexto_x(cell_index);\n\t\tT xright = mesh.indexto_x(cell_index+1);\n\t\tT dx = (xright-xleft);\n\t\tutil integrator;\n\t\t//cout << \"integrate shape: \" << cell_index << \" i \" << i << \" \" << xleft << \" to \" << xright << endl;\n\t\treturn integrator.integrate2(i, xleft, xright, dx, f);\n\t\t//return -integrator.integrate2(dof_per_cell-1-i, xright, xleft, dx, f);\n\t}\n\n\tdouble eval(VectorXd& solution, double x) {\n\t\tint cell_index = mesh.findindex(x);\n\t\tT xleft = mesh.indexto_x(cell_index);\n\t\tT xright = mesh.indexto_x(cell_index+1);\n\t\tT dx = xright-xleft;\n\t\tdouble v = 0;\n\t\tutil util;\n\t\tif(mesh.inrange(x))\n\t\t\tv = util.eval(solution, dof_index(cell_index, dof_per_cell-1), xleft, dx, x);\n\t\t//cout << \"eval: \" << v << endl;\n\t\treturn v;\n\t\t/*for(int i = 0; i < dof_per_cell; i++) {\n\t\t\tev\n\t\t}*/\n\t}\n\n\tdouble gradient(VectorXd& solution, double x) {\n\t\tint cell_index = mesh.findindex(x);\n\t\tT xleft = mesh.indexto_x(cell_index);\n\t\tT xright = mesh.indexto_x(cell_index+1);\n\t\tT dx = xright-xleft;\n\t\tdouble v = 0;\n\t\tutil util;\n\t\tif(mesh.inrange(x))\n\t\t\tv = util.gradient(solution, dof_index(cell_index, dof_per_cell-1), xleft, dx, x);\n\t\t//cout << \"grad: \" << \" \" << cell_index << \" \" << n_cells << \" \" << v << endl;\n\t\treturn v;\n\t\t/*for(int i = 0; i < dof_per_cell; i++) {\n\t\t\tev\n\t\t}*/\n\t}\n\n\n\tMeshRegularNodal1d(T _x1, T _x2, int n_cells, Transformation1d_in_3d* transformation) : x1(_x1), x2(_x2), n_cells(n_cells), mesh(_x1, _x2, n_cells), ctrans(1, 1), transformation(transformation) {\n\t\tif(Basis::degree == 0) {\n\t\t\t//dof_per_cell = 1;\n\t\t\tdof = n_cells;\n\t\t} else {\n\t\t\tdof = 1 + n_cells + (dof_per_cell-2)*n_cells; // 1 dof per border + dofs inside the cel\n\t\t}\n\t\t//cout << \"n_cells = \" << n_cells << \" dof = \" << dof << \" dof_per_cell = \" << dof_per_cell << endl;\n\t\tMatrixXd m = MatrixXd::Zero(dof, dof);\n\t\tctrans.resize(dof, dof);\n\t\tT scale = (x2-x1)/n_cells;\n\n\t\tT integrals[dof_per_cell][dof_per_cell];\n\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\tfor(int k = 0; k < (j+1); k++) {\n\t\t\t\ttypedef selfintegrator selfintegrator_type;\n\t\t\t\tselfintegrator_type si; \n\t\t\t\tdouble integral = si.integrate(j,k);\n\t\t\t\t//cout << j << \" \" << k << \" \" << integral << endl;\n\t\t\t\tintegrals[j][k] = integral;\n\t\t\t\tintegrals[k][j] = integral;\n\t\t\t}\n\t\t}\n\t\tfor(int i = 0; i < n_cells; i++) {\n\t\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\t\tfor(int k = 0; k < dof_per_cell; k++) {\n\t\t\t\t\tint i1 = i*(dof_per_cell-1)+j;\n\t\t\t\t\tint i2 = i*(dof_per_cell-1)+k;\n\t\t\t\t\tm(i1, i2) = m(i1, i2) + integrals[j][k];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t//cout << m << endl;\n\t\tm = m * scale;\n\t\tctrans = m.inverse();\n\t}\n\tvoid testprofile(Profile* profile, double_vector v, bool dotrans) {\n\t\tdouble* vp = v.data().begin();\n\t\tassert((int)v.size() == dof);\n\t\tdouble* array = vp;\n\t\t//int size = x.size();\n\t\t//double scale = 1./size;\n\t\t//cout << \"size = \" << size << endl;\n\t\tfor(int i = 0; i < n_cells; i++) {\n\t\t\tfor(int j = 0; j < dof_per_cell; j++) {\n\t\t\t\tT xleft = mesh.indexto_x(i);\n\t\t\t\tT xright = mesh.indexto_x(i+1);\n\t\t\t\tT dx = (xright-xleft);\n\t\t\t\tutil integrator;\n\t\t\t\tdouble integral = integrator.integrate(j, xleft, xright, dx, profile);\n\t\t\t\t/**/\n\t\t\t\tcout << \"> \" << i << \" \" << j << \" \" << (i*(dof_per_cell-1)+j) << \" \" << integral << endl; \n\t\t\t\t//array[i*(dof_per_cell-1)+(dof_per_cell-1-j)] += integral;\n\t\t\t\tarray[i*(dof_per_cell-1)+j] += integral;\n\t\t\t\t\n\t\t\t} \n\t\t}\n\t\tif(dotrans) {\n\t\t\tVectorXd v_alias = VectorXd::Map(v.data().begin(), v.size());\n\t\t\tVectorXd vtrans = ctrans * v_alias;\n\t\t\tVectorXd::Map(v.data().begin(), v.size()) = vtrans;\n\t\t}\n\t}\n\n\tvoid test(double_vector x, double_vector y, double_vector v, bool dotrans) {\n\t\t/*double* xp = x.data().begin();\n\t\tdouble* yp = y.data().begin();\n\t\tdouble* vp = v.data().begin();\n\t\tint size = x.size();\n\t\tdouble scale = 1./size * (x2-x1);\n\t\t//cout << \"size = \" << size << endl;\n\t\tfor(int i = 0; i < size; i++) {\n\t\t\t//cout << \"i = \" << i << endl;\n\t\t\tthis->operator()(xp[i], yp[i]*scale, vp);\n\t\t\t\n\t\t}\n\t\tif(dotrans) {\n\t\t\tVectorXd v_alias = VectorXd::Map(v.data().begin(), v.size());\n\t\t\tVectorXd vtrans = ctrans * v_alias;\n\t\t\tVectorXd::Map(v.data().begin(), v.size()) = vtrans;\n\t\t}*/\n\t}\n\n\n\ttemplate\n\tT operator()(T x, T y, A array) {\n\t\t/*if(mesh.inrange(x)) {\n\t\t\tint indexleft = mesh.findindex(x);\n\t\t\tT xleft = mesh.indexto_x(indexleft);\n\t\t\tT xright = mesh.indexto_x(indexleft+1);\n\t\t\tT fraction = (x-xleft)/(xright-xleft);\n\t\t\t//cout << \"x = \" << x << \" xleft = \" << xleft << \" xright = \" << xright << \" fraction = \" << fraction << endl;\n\t\t\tBasisTriLeft trileft;\n\t\t\tBasisTriRight triright;\n\t\t\t//cout << \"y = \" << y << \" triright(fraction) = \" << triright(fraction) << \" trileft (fraction-1) = \" << trileft (fraction-1) << endl;\n\t\t\tarray[indexleft] += triright(fraction) * y;\n\t\t\tarray[indexleft+1] += trileft (fraction-1) * y;\n\t\t\t// TODO: use trileft(fraction) + triright(fraction) == 1\n\t\t}*/\n\t}\n\t\n};\n\n\n}", "meta": {"hexsha": "a8595ee923bc1e6bd120934f85b6263b336d784f", "size": 14389, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "gdfast/src/mesh.hpp", "max_stars_repo_name": "maartenbreddels/mab", "max_stars_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2018-12-01T04:10:34.000Z", "max_stars_repo_stars_event_max_datetime": "2018-12-01T04:10:34.000Z", "max_issues_repo_path": "gdfast/src/mesh.hpp", "max_issues_repo_name": "maartenbreddels/mab", "max_issues_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "gdfast/src/mesh.hpp", "max_forks_repo_name": "maartenbreddels/mab", "max_forks_repo_head_hexsha": "112dcfbc4a74b07aff13d489b3776bca58fe9bdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5548245614, "max_line_length": 196, "alphanum_fraction": 0.6010841615, "num_tokens": 4936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.907312226373181, "lm_q2_score": 0.7090191460821871, "lm_q1q2_score": 0.6433017399730409}} {"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_ATAN2D_HPP_INCLUDED\n#define BOOST_SIMD_FUNCTION_ATAN2D_HPP_INCLUDED\n\n#if defined(DOXYGEN_ONLY)\nnamespace boost { namespace simd\n{\n\n /*!\n\n @ingroup group-trigonometric\n Function object implementing atan2d capabilities\n\n atan2d function : atan2 in degrees.\n\n @par Semantic:\n\n For every parameters of same floating type\n\n @code\n auto r = atan2d(y, x);\n @endcode\n\n is similar to:\n\n @code\n T r = indeg(atan2(y, x));\n @endcode\n\n For any real arguments @c x and @c y not both equal to zero, atan2d(y, x)\n is the angle in degrees between the positive x-axis of a plane and the point\n given by the coordinates (x, yx).\n\n It is also the angle in \\f$[-180,180[\\f$ for which\n \\f$x/\\sqrt{x^2+y^2}\\f$ and \\f$y/\\sqrt{x^2+y^2}\\f$\n are respectively the sine and the cosine.\n\n @see atand, atan2, atan\n\n **/\n Value atan2d(Value const& x, Value const& y );\n} }\n#endif\n\n#include \n#include \n\n#endif\n", "meta": {"hexsha": "c5dff5470668c1720565fab5b2fa831b0cfd622a", "size": 1453, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "third_party/boost/simd/function/atan2d.hpp", "max_stars_repo_name": "xmar/pythran", "max_stars_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 5.0, "max_stars_repo_stars_event_min_datetime": "2018-02-20T11:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-12T13:45:09.000Z", "max_issues_repo_path": "third_party/boost/simd/function/atan2d.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/atan2d.hpp", "max_forks_repo_name": "xmar/pythran", "max_forks_repo_head_hexsha": "dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2.0, "max_forks_repo_forks_event_min_datetime": "2017-11-17T15:30:36.000Z", "max_forks_repo_forks_event_max_datetime": "2018-03-01T02:06:25.000Z", "avg_line_length": 25.0517241379, "max_line_length": 100, "alphanum_fraction": 0.5877494838, "num_tokens": 373, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8333246118695629, "lm_q2_score": 0.7718434925908525, "lm_q1q2_score": 0.64319617888732}} {"text": "/** @file SymmetricBetaDist.cpp\n * @author Mark J. Olah (mjo\\@cs.unm DOT edu)\n * @date 2017-2019\n * @brief SymmetricBetaDist class definition\n * \n */\n#include \"PriorHessian/SymmetricBetaDist.h\"\n#include \"PriorHessian/PriorHessianError.h\"\n\n#include \n#include \n#include \n\n#include \n\nnamespace prior_hessian {\n\nconst StringVecT SymmetricBetaDist::_param_names = { \"beta\" };\nconst SymmetricBetaDist::NparamsVecT SymmetricBetaDist::_param_lbound = { 0 }; //Lower bound on valid parameter values \nconst SymmetricBetaDist::NparamsVecT SymmetricBetaDist::_param_ubound = { INFINITY }; //Upper bound on valid parameter values\n\n/* Constructors */\nSymmetricBetaDist::SymmetricBetaDist(double beta) \n : UnivariateDist(),\n _beta(checked_beta(beta)),\n llh_const_initialized(false)\n{ }\n\n/* Non-static member functions */\nvoid SymmetricBetaDist::set_beta(double val) \n{ \n _beta = checked_beta(val); \n llh_const_initialized = false;\n}\n\ndouble SymmetricBetaDist::cdf(double x) const\n{\n if(x==0) return 0;\n if(x==1) return 1;\n return boost::math::ibeta(_beta, _beta, x);\n}\n\ndouble SymmetricBetaDist::icdf(double u) const\n{\n if(u==0) return 0;\n if(u==1) return 1;\n return boost::math::ibeta_inv(_beta, _beta, u);\n}\n\ndouble SymmetricBetaDist::pdf(double x) const\n{\n return boost::math::ibeta_derivative(_beta, _beta, x);\n}\n\ndouble SymmetricBetaDist::llh(double x) const \n{ \n if(!llh_const_initialized) initialize_llh_const();\n return rllh(x) + llh_const; \n}\n\nvoid SymmetricBetaDist::initialize_llh_const() const\n{\n llh_const = compute_llh_const(beta());\n llh_const_initialized = true;\n}\n\ndouble SymmetricBetaDist::compute_llh_const(double beta)\n{\n return -2*lgamma(beta) - lgamma(2*beta);//log(1/Beta(beta,beta))\n}\n\ndouble SymmetricBetaDist::checked_beta(double val)\n{\n if(val<=0 || !std::isfinite(val)) {\n std::ostringstream msg;\n msg<<\"SymmetricBetaDist: got bad beta value:\"<\n#include \n\n#include \n#include \n#include \n\nnamespace iglp\n{\n\ninline double linprog(const Eigen::VectorXd &c,\n const Eigen::MatrixXd &A,\n const Eigen::VectorXd &b,\n Eigen::VectorXd &x,\n bool ipm = false,\n bool verbose = false)\n// linprog:\n// min cTx s.t. Ax<=b\n// input:\n// c: d*1 objective coeffs\n// A: m*d constraint matrix\n// b: m*1 constraint bound\n// ipm: use interior point method\n// or simplex method\n// verbose: show details\n// output:\n// x: d*1 decision variables\n// return:\n// inf: No feasible solution or fail\n// -inf: Unbounded problem\n// real: minimum objective function\n{\n int d = c.size();\n int m = b.size();\n int dm = d * m;\n x = Eigen::VectorXd::Zero(d);\n\n glp_prob *lp;\n int *ia = new int[dm + 1];\n int *ja = new int[dm + 1];\n double *ar = new double[dm + 1];\n int s;\n double z;\n\n lp = glp_create_prob();\n glp_set_prob_name(lp, \"lp\");\n glp_set_obj_dir(lp, GLP_MIN);\n\n glp_add_rows(lp, m);\n for (int i = 1; i <= m; i++)\n {\n glp_set_row_name(lp, i, (std::to_string(i) + \"y\").c_str());\n glp_set_row_bnds(lp, i, GLP_UP, 0.0, b(i - 1));\n }\n\n glp_add_cols(lp, d);\n for (int i = 1; i <= d; i++)\n {\n glp_set_col_name(lp, i, (std::to_string(i) + \"x\").c_str());\n glp_set_col_bnds(lp, i, GLP_FR, 0.0, 0.0);\n glp_set_obj_coef(lp, i, c(i - 1));\n }\n\n int k = 1;\n for (int i = 1; i <= m; i++)\n {\n for (int j = 1; j <= d; j++)\n {\n ia[k] = i;\n ja[k] = j;\n ar[k] = A(i - 1, j - 1);\n k++;\n }\n }\n glp_load_matrix(lp, dm, ia, ja, ar);\n\n if (!ipm)\n {\n glp_smcp param;\n glp_init_smcp(¶m);\n param.msg_lev = verbose ? GLP_MSG_ALL : GLP_MSG_OFF;\n glp_simplex(lp, ¶m);\n s = glp_get_status(lp);\n z = INFINITY;\n if (s == GLP_OPT || s == GLP_UNBND)\n {\n z = (s == GLP_UNBND) ? -INFINITY : glp_get_obj_val(lp);\n for (int i = 1; i <= d; i++)\n {\n x(i - 1) = glp_get_col_prim(lp, i);\n }\n }\n }\n else\n {\n glp_iptcp param;\n glp_init_iptcp(¶m);\n param.msg_lev = verbose ? GLP_MSG_ALL : GLP_MSG_OFF;\n glp_interior(lp, ¶m);\n s = glp_ipt_status(lp);\n z = INFINITY;\n if (s == GLP_OPT)\n {\n z = glp_ipt_obj_val(lp);\n for (int i = 1; i <= d; i++)\n {\n x(i - 1) = glp_ipt_col_prim(lp, i);\n }\n }\n }\n\n glp_delete_prob(lp);\n delete[] ia;\n delete[] ja;\n delete[] ar;\n\n return z;\n}\n\n} // namespace iglp\n\n#endif", "meta": {"hexsha": "21a4dd778d36230306d6e4d32eb0521c27eca275", "size": 2932, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "iglp.hpp", "max_stars_repo_name": "ZJU-FAST-Lab/GLPK_Interface", "max_stars_repo_head_hexsha": "810eac17e67dff1a8a67251393900fb42a781481", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1.0, "max_stars_repo_stars_event_min_datetime": "2021-07-09T02:10:40.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-09T02:10:40.000Z", "max_issues_repo_path": "iglp.hpp", "max_issues_repo_name": "ZJU-FAST-Lab/GLPK_Interface", "max_issues_repo_head_hexsha": "810eac17e67dff1a8a67251393900fb42a781481", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "iglp.hpp", "max_forks_repo_name": "ZJU-FAST-Lab/GLPK_Interface", "max_forks_repo_head_hexsha": "810eac17e67dff1a8a67251393900fb42a781481", "max_forks_repo_licenses": ["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.456, "max_line_length": 67, "alphanum_fraction": 0.471691678, "num_tokens": 898, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.851952809486198, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6431519486827599}} {"text": "// (C) Copyright Christopher Kormanyos 1999 - 2021.\n// (C) Copyright Matt Borland 2021.\n// Use, modification and distribution are subject to the\n// Boost Software License, Version 1.0. (See accompanying file\n// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\n#ifndef BOOST_MATH_CCMATH_FREXP_HPP\n#define BOOST_MATH_CCMATH_FREXP_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace boost::math::ccmath {\n\nnamespace detail\n{\n\ntemplate \ninline constexpr Real frexp_zero_impl(Real arg, int* exp)\n{\n *exp = 0;\n return arg;\n}\n\ntemplate \ninline constexpr Real frexp_impl(Real arg, int* exp)\n{\n const bool negative_arg = (arg < Real(0));\n \n Real f = negative_arg ? -arg : arg;\n int e2 = 0;\n constexpr Real two_pow_32 = Real(4294967296);\n\n while (f >= two_pow_32)\n {\n f = f / two_pow_32;\n e2 += 32;\n }\n\n while(f >= Real(1))\n {\n f = f / Real(2);\n ++e2;\n }\n \n if(exp != nullptr)\n {\n *exp = e2;\n }\n\n return !negative_arg ? f : -f;\n}\n\n} // namespace detail\n\ntemplate , bool> = true>\ninline constexpr Real frexp(Real arg, int* exp)\n{\n if(BOOST_MATH_IS_CONSTANT_EVALUATED(arg))\n {\n return arg == Real(0) ? detail::frexp_zero_impl(arg, exp) : \n arg == Real(-0) ? detail::frexp_zero_impl(arg, exp) :\n boost::math::ccmath::isinf(arg) ? detail::frexp_zero_impl(arg, exp) : \n boost::math::ccmath::isnan(arg) ? detail::frexp_zero_impl(arg, exp) :\n boost::math::ccmath::detail::frexp_impl(arg, exp);\n }\n else\n {\n using std::frexp;\n return frexp(arg, exp);\n }\n}\n\ntemplate , bool> = true>\ninline constexpr double frexp(Z arg, int* exp)\n{\n return boost::math::ccmath::frexp(static_cast(arg), exp);\n}\n\ninline constexpr float frexpf(float arg, int* exp)\n{\n return boost::math::ccmath::frexp(arg, exp);\n}\n\n#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS\ninline constexpr long double frexpl(long double arg, int* exp)\n{\n return boost::math::ccmath::frexp(arg, exp);\n}\n#endif\n\n}\n\n#endif // BOOST_MATH_CCMATH_FREXP_HPP\n", "meta": {"hexsha": "88b520c1ec193d3b299178788635fd2cdb10b409", "size": 2393, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/boost/math/ccmath/frexp.hpp", "max_stars_repo_name": "oleg-alexandrov/math", "max_stars_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_stars_repo_licenses": ["BSL-1.0"], "max_stars_count": 233.0, "max_stars_repo_stars_event_min_datetime": "2015-01-12T19:26:01.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T09:21:47.000Z", "max_issues_repo_path": "include/boost/math/ccmath/frexp.hpp", "max_issues_repo_name": "oleg-alexandrov/math", "max_issues_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_issues_repo_licenses": ["BSL-1.0"], "max_issues_count": 626.0, "max_issues_repo_issues_event_min_datetime": "2015-02-05T18:12:27.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-20T13:19:18.000Z", "max_forks_repo_path": "include/boost/math/ccmath/frexp.hpp", "max_forks_repo_name": "oleg-alexandrov/math", "max_forks_repo_head_hexsha": "2137c31eb8e52129d997a76b893f71c1da0ccc5f", "max_forks_repo_licenses": ["BSL-1.0"], "max_forks_count": 243.0, "max_forks_repo_forks_event_min_datetime": "2015-01-17T17:46:32.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-07T12:56:26.000Z", "avg_line_length": 24.1717171717, "max_line_length": 85, "alphanum_fraction": 0.647722524, "num_tokens": 676, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683106, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.643151943007394}} {"text": "#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\nclass Array2D\n{\nprivate:\n\tvector m_data;\n\tsize_t m_Nx, m_Ny;\n\npublic:\n\tArray2D(size_t nx, size_t ny, double val = 0.0) : m_Nx(nx), m_Ny(ny), m_data(nx*ny, val) {}\n\n\t// 0-based indexing\n\tdouble &at(int i, int j)\n\t{\n\t\tint idx = i + m_Nx * j;\n\t\treturn m_data[idx];\n\t}\n\n\tdouble at(int i, int j) const\n\t{\n\t\tint idx = i + m_Nx * j;\n\t\treturn m_data[idx];\n\t}\n\n\t// 1-based indexing\n\tdouble &operator()(int i, int j)\n\t{\n\t\treturn at(i - 1, j - 1);\n\t}\n\n\tdouble operator()(int i, int j) const\n\t{\n\t\treturn at(i - 1, j - 1);\n\t}\n};\n\nconst size_t WIDTH = 16;\nconst size_t DIGITS = 7;\n\nconst double L = 0.5; // m\nconst double D = 0.01; // m\nconst double Ue = 1.0; // m/s\nconst double Pe = 0.0;\nconst double rho = 1.225; // Kg/m3\nconst double mu = 3.737e-5; // Kg/m/s\n\nconst int Nx = 21, Ny = 11;\nconst double dx = L / (Nx - 1), dy = D / (Ny - 1);\nconst double dx2 = 2 * dx, dy2 = 2 * dy;\nconst double dxdx = dx * dx, dydy = dy * dy;\nvector x(Nx, 0.0), y(Ny, 0.0);\n\nconst double dt = 0.001;\ndouble t = 0.0;\nint iter_cnt = 0;\nconst int MAX_ITER_NUM = 2000;\n\nconst double a = 2 * (dt / dxdx + dt / dydy);\nconst double b = -dt / dxdx;\nconst double c = -dt / dydy;\ndouble d_min = numeric_limits::max(), d_max = numeric_limits::min(), d_15_5 = 0.0;\n\nArray2D p(Nx, Ny, Pe), p_star(Nx, Ny, Pe), p_prime(Nx, Ny, 0.0);\nArray2D u(Nx + 1, Ny, 0.0), u_wedge(Nx + 1, Ny, 0.0), u_star(Nx + 1, Ny, 0.0), u_prime(Nx + 1, Ny, 0.0);\nArray2D v(Nx + 2, Ny + 1, 0.0), v_wedge(Nx + 2, Ny + 1, 0.0), v_star(Nx + 2, Ny + 1, 0.0), v_prime(Nx + 2, Ny + 1, 0.0);\n\n// Full flowfield in TECPLOT ASCII Format.\nvoid output1(void)\n{\n\tArray2D u_interp(Nx, Ny, 0.0);\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tu_interp(i, 1) = 0.0; // Bottom\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 1; i <= Nx; ++i)\n\t\t\tu_interp(i, j) = (u(i, j) + u(i + 1, j)) / 2; // Inner\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tu_interp(i, Ny) = Ue; // Top\n\n\tArray2D v_interp(Nx, Ny, 0.0);\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tv_interp(i, 1) = 0.0; // Bottom\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t{\n\t\tv_interp(1, j) = 0.0; // Left\n\t\tfor (int i = 3; i <= Nx + 1; ++i)\n\t\t\tv_interp(i - 1, j) = (v(i, j) + v(i, j + 1)) / 2; // Inner and Right\n\t}\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tv_interp(i, Ny) = 0.0; // Top\n\n\t// Create Tecplot data file.\n\tofstream result(\"flow\" + to_string(iter_cnt) + \".dat\");\n\tif (!result)\n\t\tthrow(\"Failed to create data file!\");\n\n\t// Header\n\tresult << \"TITLE = \\\"t=\" << t << \"\\\"\" << endl;\n\tresult << \"VARIABLES = \\\"X\\\", \\\"Y\\\", \\\"P\\\", \\\"U\\\", \\\"V\\\"\" << endl;\n\tresult << \"ZONE I=\" << Nx << \", J=\" << Ny << \", F=POINT\" << endl;\n\n\t// Flowfield data\n\tfor (int j = 1; j <= Ny; ++j)\n\t\tfor (int i = 1; i <= Nx; ++i)\n\t\t{\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << x[i - 1];\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << y[j - 1];\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << p(i, j);\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << u_interp(i, j);\n\t\t\tresult << setw(WIDTH) << setprecision(DIGITS) << v_interp(i, j);\n\t\t\tresult << endl;\n\t\t}\n\n\t// Finalize\n\tresult.close();\n}\n\n// Statistics at (15, 5) and i=15\nvoid output2(int iter)\n{\n\tstatic const string fn(\"history_at_15_5.txt\");\n\n\tofstream fout;\n\tif (iter == 0)\n\t{\n\t\tfout.open(fn, ios::out);\n\t\tif (!fout)\n\t\t\tthrow(\"Failed to open history file.\");\n\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t\tfout << setw(WIDTH) << setprecision(DIGITS) << y[j];\n\t\tfout << endl;\n\t}\n\telse\n\t{\n\t\tfout.open(fn, ios::app);\n\t\tif (!fout)\n\t\t\tthrow(\"Failed to open history file.\");\n\t}\n\n\tfor (int j = 1; j <= Ny; ++j)\n\t\tfout << setw(WIDTH) << setprecision(DIGITS) << u(15, j);\n\tfout << endl;\n\tfor (int j = 1; j <= Ny; ++j)\n\t\tfout << setw(WIDTH) << setprecision(DIGITS) << v(15, j);\n\tfout << endl;\n\tfout << d_15_5 << endl;\n\n\tfout.close();\n}\n\nvoid init(void)\n{\n\tcout << \"mu=\" << mu << endl;\n\tcout << \"dt=\" << dt << endl;\n\n\t// Init\n\tfor (int i = 1; i < Nx; ++i)\n\t\tx[i] = L * i / (Nx - 1); // X-Coordinates\n\tfor (int j = 1; j < Ny; ++j)\n\t\ty[j] = D * j / (Ny - 1); // Y-Coordinates\n\n\tfor (int i = 1; i <= Nx + 1; ++i)\n\t\tu(i, Ny) = u_wedge(i, Ny) = u_star(i, Ny) = Ue; // U at top\n\tv(15, 5) = v_wedge(15, 5) = v_star(15, 5) = 0.5; // Initial peak to ensure 2D flow structure\n}\n\n// Solve the pressure equation.\nvoid ImplicitMethod1()\n{\n\ttypedef Eigen::SparseMatrix SpMat;\n\ttypedef Eigen::Triplet T;\n\n\tconst int m = Nx * Ny;\n\tvector coef;\n\tEigen::VectorXd rhs(m);\n\tSpMat A(m, m);\n\n\t// Calculating coefficients\n\tfor (int i = 0; i < Nx; ++i)\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t{\n\t\t\tconst int id = j * Nx + i;\n\t\t\tconst int id_w = id - 1;\n\t\t\tconst int id_e = id + 1;\n\t\t\tconst int id_n = id + Nx;\n\t\t\tconst int id_s = id - Nx;\n\n\t\t\tif (i == 0 || i == Nx - 1) // Inlet and Outlet\n\t\t\t{\n\t\t\t\tcoef.push_back(T(id, id, 1.0));\n\t\t\t\trhs(id) = Pe;\n\t\t\t}\n\t\t\telse if (j == 0) // Bottom\n\t\t\t{\n\t\t\t\tcoef.push_back(T(id, id_n, 1.0));\n\t\t\t\tcoef.push_back(T(id, id, -1.0));\n\t\t\t\tconst double ddvddx = 0.0;\n\t\t\t\t//const double ddvddy = 4.0 / 3 * (v_wedge.at(i + 1, j + 2) - 3 * v_wedge.at(i + 1, j + 1)) / dydy; \n\t\t\t\tconst double ddvddy = 0.0;\n\t\t\t\trhs(id) = mu * (ddvddx + ddvddy) * dy;\n\t\t\t}\n\t\t\telse if (j == Ny - 1) // Top\n\t\t\t{\n\t\t\t\tcoef.push_back(T(id, id, 1.0));\n\t\t\t\tcoef.push_back(T(id, id_s, -1.0));\n\t\t\t\tconst double ddvddx = 0.0;\n\t\t\t\t//const double ddvddy = 4.0 / 3 * (v_wedge.at(i + 1, j - 1) - 3 * v_wedge.at(i + 1, j)) / dydy;\n\t\t\t\tconst double ddvddy = 0.0;\n\t\t\t\trhs(id) = mu * (ddvddx + ddvddy) * dy;\n\t\t\t}\n\t\t\telse // Inner\n\t\t\t{\n\t\t\t\t// Use 0-based interface\n\t\t\t\tconst double d = (rho*u_wedge.at(i + 1, j) - rho * u_wedge.at(i, j)) / dx + (rho*v_wedge.at(i + 1, j + 1) - rho * v_wedge.at(i + 1, j)) / dy;\n\n\t\t\t\tcoef.push_back(T(id, id, a));\n\t\t\t\tcoef.push_back(T(id, id_w, b));\n\t\t\t\tcoef.push_back(T(id, id_e, b));\n\t\t\t\tcoef.push_back(T(id, id_n, c));\n\t\t\t\tcoef.push_back(T(id, id_s, c));\n\t\t\t\trhs(id) = -d;\n\t\t\t}\n\t\t}\n\n\t// Construct sparse matrix\n\tA.setFromTriplets(coef.begin(), coef.end());\n\n\t// Solve the linear system: Ax = rhs\n\tEigen::SimplicialCholesky chol(A);\n\tEigen::VectorXd x = chol.solve(rhs);\n\n\t// Update p\n\tfor (int i = 0; i < Nx; ++i)\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t{\n\t\t\tconst int id = j * Nx + i;\n\t\t\tp.at(i, j) = x(id);\n\t\t}\n}\n\n// Solve the pressure-correction equation\nvoid ImplicitMethod2()\n{\n\ttypedef Eigen::SparseMatrix SpMat;\n\ttypedef Eigen::Triplet T;\n\n\tconst int m = Nx * Ny;\n\tvector coef;\n\tEigen::VectorXd rhs(m);\n\tSpMat A(m, m);\n\n\t// Calculating coefficients\n\tfor (int i = 0; i < Nx; ++i)\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t{\n\t\t\tconst int id = j * Nx + i;\n\t\t\tconst int id_w = id - 1;\n\t\t\tconst int id_e = id + 1;\n\t\t\tconst int id_n = id + Nx;\n\t\t\tconst int id_s = id - Nx;\n\n\t\t\tif (i == 0 || i == Nx - 1) // Inlet and Outlet\n\t\t\t{\n\t\t\t\tcoef.push_back(T(id, id, 1.0));\n\t\t\t\trhs(id) = 0.0;\n\t\t\t}\n\t\t\telse if (j == 0) // Bottom\n\t\t\t{\n\t\t\t\tcoef.push_back(T(id, id, 1.0));\n\t\t\t\tcoef.push_back(T(id, id_n, -1.0));\n\t\t\t\trhs(id) = 0.0;\n\t\t\t}\n\t\t\telse if (j == Ny - 1) // Top\n\t\t\t{\n\t\t\t\tcoef.push_back(T(id, id, 1.0));\n\t\t\t\tcoef.push_back(T(id, id_s, -1.0));\n\t\t\t\trhs(id) = 0.0;\n\t\t\t}\n\t\t\telse // Inner\n\t\t\t{\n\t\t\t\t// Use 0-based interface\n\t\t\t\tconst double d = (rho*u_star.at(i + 1, j) - rho * u_star.at(i, j)) / dx + (rho * v_star.at(i + 1, j + 1) - rho * v_star.at(i + 1, j)) / dy;\n\t\t\t\tif (d > d_max)\n\t\t\t\t\td_max = d;\n\t\t\t\tif (d < d_min)\n\t\t\t\t\td_min = d;\n\t\t\t\tif (i == 15 && j == 5)\n\t\t\t\t\td_15_5 = d;\n\n\t\t\t\tcoef.push_back(T(id, id, a));\n\t\t\t\tcoef.push_back(T(id, id_w, b));\n\t\t\t\tcoef.push_back(T(id, id_e, b));\n\t\t\t\tcoef.push_back(T(id, id_n, c));\n\t\t\t\tcoef.push_back(T(id, id_s, c));\n\t\t\t\trhs(id) = -d;\n\t\t\t}\n\t\t}\n\n\t// Construct sparse matrix\n\tA.setFromTriplets(coef.begin(), coef.end());\n\n\t// Solve the linear system: Ax = rhs\n\tEigen::SimplicialCholesky chol(A);\n\tEigen::VectorXd x = chol.solve(rhs);\n\n\t// Update p_prime\n\tfor (int i = 0; i < Nx; ++i)\n\t\tfor (int j = 0; j < Ny; ++j)\n\t\t{\n\t\t\tconst int id = j * Nx + i;\n\t\t\tp_prime.at(i, j) = x(id);\n\t\t}\n}\n\nvoid SIMPLER(void)\n{\n\t// u_wedge at inner points\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 2; i <= Nx; ++i)\n\t\t{\n\t\t\tdouble v_bar1 = 0.5*(v(i, j + 1) + v(i + 1, j + 1));\n\t\t\tdouble v_bar2 = 0.5*(v(i, j) + v(i + 1, j));\n\n\t\t\tdouble t11 = rho * pow(u(i + 1, j), 2) - rho * pow(u(i - 1, j), 2);\n\t\t\tdouble t12 = rho * u(i, j + 1)*v_bar1 - rho * u(i, j - 1)*v_bar2;\n\t\t\tdouble t21 = u(i + 1, j) - 2 * u(i, j) + u(i - 1, j);\n\t\t\tdouble t22 = u(i, j + 1) - 2 * u(i, j) + u(i, j - 1);\n\t\t\tdouble A = -(t11 / dx2 + t12 / dy2) + mu * (t21 / dxdx + t22 / dydy);\n\n\t\t\tu_wedge(i, j) = (rho * u(i, j) + A * dt) / rho;\n\t\t}\n\n\t// v_wedge at inner points\n\tfor (int i = 3; i <= Nx; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tdouble u_bar1 = 0.5 *(u(i, j - 1) + u(i, j));\n\t\t\tdouble u_bar2 = 0.5 *(u(i - 1, j - 1) + u(i - 1, j));\n\n\t\t\tdouble t11 = rho * v(i + 1, j) * u_bar1 - rho * v(i - 1, j) * u_bar2;\n\t\t\tdouble t12 = rho * pow(v(i, j + 1), 2) - rho * pow(v(i, j - 1), 2);\n\t\t\tdouble t21 = v(i + 1, j) - 2 * v(i, j) + v(i - 1, j);\n\t\t\tdouble t22 = v(i, j + 1) - 2 * v(i, j) + v(i, j - 1);\n\t\t\tdouble B = -(t11 / dx2 + t12 / dy2) + mu * (t21 / dxdx + t22 / dydy);\n\n\t\t\tv_wedge(i, j) = (rho * v(i, j) + B * dt) / rho;\n\t\t}\n\n\t// Solve p\n\tImplicitMethod1();\n\n\t// Set p_star to p\n\tfor (int j = 1; j <= Ny; ++j)\n\t\tfor (int i = 1; i <= Nx; ++i)\n\t\t\tp_star(i, j) = p(i, j);\n\n\t// u_star at inner points\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 2; i <= Nx; ++i)\n\t\t{\n\t\t\tdouble v_bar1 = 0.5*(v(i, j + 1) + v(i + 1, j + 1));\n\t\t\tdouble v_bar2 = 0.5*(v(i, j) + v(i + 1, j));\n\n\t\t\tdouble t11 = rho * pow(u(i + 1, j), 2) - rho * pow(u(i - 1, j), 2);\n\t\t\tdouble t12 = rho * u(i, j + 1)*v_bar1 - rho * u(i, j - 1)*v_bar2;\n\t\t\tdouble t21 = u(i + 1, j) - 2 * u(i, j) + u(i - 1, j);\n\t\t\tdouble t22 = u(i, j + 1) - 2 * u(i, j) + u(i, j - 1);\n\t\t\tdouble A = -(t11 / dx2 + t12 / dy2) + mu * (t21 / dxdx + t22 / dydy);\n\n\t\t\tu_star(i, j) = (rho * u(i, j) + A * dt - dt / dx * (p_star(i, j) - p_star(i - 1, j))) / rho;\n\t\t}\n\n\t// v_star at inner points\n\tfor (int i = 3; i <= Nx + 1; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tdouble u_bar1 = 0.5 *(u(i, j - 1) + u(i, j));\n\t\t\tdouble u_bar2 = 0.5 *(u(i - 1, j - 1) + u(i - 1, j));\n\n\t\t\tdouble t11 = rho * v(i + 1, j) * u_bar1 - rho * v(i - 1, j) * u_bar2;\n\t\t\tdouble t12 = rho * pow(v(i, j + 1), 2) - rho * pow(v(i, j - 1), 2);\n\t\t\tdouble t21 = v(i + 1, j) - 2 * v(i, j) + v(i - 1, j);\n\t\t\tdouble t22 = v(i, j + 1) - 2 * v(i, j) + v(i, j - 1);\n\t\t\tdouble B = -(t11 / dx2 + t12 / dy2) + mu * (t21 / dxdx + t22 / dydy);\n\n\t\t\tv_star(i, j) = (rho * v(i, j) + B * dt - dy / dy * (p_star(i - 1, j) - p_star(i - 1, j - 1))) / rho;\n\t\t}\n\n\td_min = numeric_limits::max();\n\td_max = numeric_limits::min();\n\tImplicitMethod2();\n\n\t// Correct u at inner nodes\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t\tfor (int i = 2; i <= Nx; ++i)\n\t\t{\n\t\t\tu_prime(i, j) = -dt / dx * (p_prime(i, j) - p_prime(i - 1, j)) / rho; // u_prime\n\t\t\tu(i, j) = u_star(i, j) + u_prime(i, j);\n\t\t}\n\n\t// Linear extrapolation of u at virtual nodes\n\tfor (int j = 2; j <= Ny - 1; ++j)\n\t{\n\t\tu(1, j) = 2 * u(2, j) - u(3, j);\n\t\tu(Nx + 1, j) = 2 * u(Nx, j) - u(Nx - 1, j);\n\t}\n\n\t// Correct v at inner nodes\n\tfor (int i = 3; i <= Nx + 1; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tv_prime(i, j) = -dt / dy * (p_prime(i - 1, j) - p_prime(i - 1, j - 1)) / rho; // v_prime\n\t\t\tv(i, j) = v_star(i, j) + v_prime(i, j);\n\t\t}\n\n\t// Linear extrapolation of v at both top and bottom virtual nodes\n\t// No-Penetration at both top and bottom\n\tfor (int i = 2; i <= Nx + 1; ++i)\n\t{\n\t\tv(i, 1) = -v(i, 2);\n\t\tv(i, Ny + 1) = -v(i, Ny);\n\t}\n\n\t// Linear extrapolation of v at right virtual nodes\n\tfor (int j = 2; j <= Ny; ++j)\n\t\tv(Nx + 2, j) = 2 * v(Nx + 1, j) - v(Nx, j);\n}\n\nbool check_convergence(void)\n{\n\t// Statistics of the mass flux residue\n\tcout << \"Max(d)=\" << d_max << \" Min(d)=\" << d_min << endl;\n\n\t// Statistics of u\n\tdouble u_max = numeric_limits::min();\n\tdouble u_min = numeric_limits::max();\n\tfor (int i = 2; i <= Nx; ++i)\n\t\tfor (int j = 1; j <= Ny; ++j)\n\t\t{\n\t\t\tu_max = max(u_max, u(i, j));\n\t\t\tu_min = min(u_min, u(i, j));\n\t\t}\n\tcout << \"Max(u)=\" << u_max << \" Min(u)=\" << u_min << endl;\n\n\t// Statistics of v\n\tdouble v_max = numeric_limits::min();\n\tdouble v_min = numeric_limits::max();\n\tfor (int i = 2; i <= Nx + 1; ++i)\n\t\tfor (int j = 2; j <= Ny; ++j)\n\t\t{\n\t\t\tv_max = max(v_max, v(i, j));\n\t\t\tv_min = min(v_min, v(i, j));\n\t\t}\n\tcout << \"Max(v)=\" << v_max << \" Min(v)=\" << v_min << endl;\n\n\t// Statistics of p\n\tdouble p_max = numeric_limits::min();\n\tdouble p_min = numeric_limits::max();\n\tfor (int i = 1; i <= Nx; ++i)\n\t\tfor (int j = 1; j <= Ny; ++j)\n\t\t{\n\t\t\tp_max = max(p_max, p(i, j));\n\t\t\tp_min = min(p_min, p(i, j));\n\t\t}\n\tcout << \"Max(p)=\" << p_max << \" Min(p)=\" << p_min << endl;\n\n\treturn iter_cnt > MAX_ITER_NUM || max(abs(d_max), abs(d_min)) < 1e-4;\n}\n\nvoid loop(void)\n{\n\tbool converged = false;\n\twhile (!converged)\n\t{\n\t\t++iter_cnt;\n\t\tcout << \"Iter\" << iter_cnt << \":\" << endl;\n\n\t\tSIMPLER();\n\t\tt += dt;\n\n\t\toutput1();\n\t\toutput2(iter_cnt);\n\n\t\tconverged = check_convergence();\n\t}\n}\n\nint main(int argc, char *argv[])\n{\n\t// Initialize\n\tinit();\n\n\t// Output I.C.\n\toutput1();\n\toutput2(0);\n\n\t// Solve\n\tloop();\n\n\treturn 0;\n}\n", "meta": {"hexsha": "0711d69018c9ad2fd00576850398e869c31aecdd", "size": 13262, "ext": "cc", "lang": "C++", "max_stars_repo_path": "Couette/2D/SIMPLER/main.cc", "max_stars_repo_name": "cangyu/CFD-book-of-Anderson", "max_stars_repo_head_hexsha": "cd8bd49b5e169c360d789054abe58c7139a3a9e9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 8.0, "max_stars_repo_stars_event_min_datetime": "2019-07-22T14:20:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-16T10:36:38.000Z", "max_issues_repo_path": "Couette/2D/SIMPLER/main.cc", "max_issues_repo_name": "cangyu/CFD-book-of-Anderson", "max_issues_repo_head_hexsha": "cd8bd49b5e169c360d789054abe58c7139a3a9e9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Couette/2D/SIMPLER/main.cc", "max_forks_repo_name": "cangyu/CFD-book-of-Anderson", "max_forks_repo_head_hexsha": "cd8bd49b5e169c360d789054abe58c7139a3a9e9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1.0, "max_forks_repo_forks_event_min_datetime": "2021-05-04T06:54:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-04T06:54:56.000Z", "avg_line_length": 25.8015564202, "max_line_length": 145, "alphanum_fraction": 0.5200573066, "num_tokens": 5434, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8519528019683105, "lm_q2_score": 0.7549149923816048, "lm_q1q2_score": 0.6431519430073939}} {"text": "#include \n#include \n#include \n\nusing namespace std;\nusing namespace boost;\n\nnamespace GaussianElimination\n{\n ///------------------------------------------------------------\n constexpr int MAX_EQ = 500;\n constexpr int MAX_VAR = 500;\n\n using T = boost::multiprecision::cpp_int;\n\n rational A[MAX_EQ + 1][MAX_VAR + 1];\n rational B[MAX_EQ + 1][MAX_VAR + 1];\n\n rational solutions[MAX_VAR + 1];\n\n int N, M;\n ///------------------------------------------------------------\n\n ///------------------------------------------------------------\n void clear()\n {\n for (int i = 0; i <= MAX_EQ; ++i)\n for (int j = 0; j <= MAX_VAR; ++j)\n A[i][j] = B[i][j] = 0;\n\n for (int j = 0; j <= MAX_VAR; ++j)\n solutions[j] = 0;\n }\n\n void makeIdentity()\n {\n for (int i = 1; i <= N; ++i)\n B[i][i] = 1;\n }\n\n bool checkIfInvertible()\n {\n assert(N == M);\n\n for (int i = 1; i <= N; ++i)\n if (A[i][i] != 1)\n return false;\n\n return true;\n }\n ///------------------------------------------------------------\n\n ///------------------------------------------------------------\n void swapLines(int x, int y) /// swap(X, Y)\n {\n swap(A[x], A[y]);\n swap(B[x], B[y]);\n\n cerr << \"SWAP LINES : \" << x << \" \" << y << endl;\n }\n\n void divideLine(int line, rational rat) /// X = X / rat\n {\n assert(rat != 0);\n\n for (int j = 1; j <= M; ++j)\n A[line][j] /= rat;\n\n for (int j = 1; j <= M; ++j)\n B[line][j] /= rat;\n\n cerr << \"DIVIDE LINE_\" << line << \" BY \" << rat << endl;\n }\n\n void changeLines(int x, int y, rational rat) /// X = X - rat * Y\n {\n for (int i = 1; i <= M; ++i)\n A[x][i] -= rat * A[y][i];\n\n for (int i = 1; i <= M; ++i)\n B[x][i] -= rat * B[y][i];\n\n cerr << \"ADD TO LINE_\" << x << \" => LINE_\" << y << \" x \" << -rat << endl;\n }\n ///------------------------------------------------------------\n\n void rowEchelonForm()\n {\n cerr << \"START ROW ECHELON\" << endl;\n\n int i = 1, j = 1;\n\n while (i <= N && j <= M)\n {\n int k = i;\n\n while (k <= N && A[k][j] == 0)\n k++;\n\n if (k == N + 1)\n {\n j++;\n continue;\n }\n\n if (k != i)\n swapLines(k, i);\n\n assert(A[i][j] != 0);\n divideLine(i, A[i][j]);\n\n for (int l = i + 1; l <= N; ++l)\n changeLines(l, i, A[l][j]);\n\n i++;\n j++;\n }\n\n cerr << \"FINISH ROW ECHELON\" << endl << endl;\n }\n\n void reducedRowEchelonForm()\n {\n cerr << \"START REDUCED ROW ECHELON\" << endl;\n\n for (int i = N; i >= 1; i--)\n {\n int j = 1;\n\n while (j <= M && A[i][j] == 0)\n j++;\n\n if (j <= M)\n {\n for (int k = i - 1; k >= 1; k--)\n changeLines(k, i, A[k][j]);\n }\n }\n\n cerr << \"FINISH REDUCED ROW ECHELON\" << endl << endl;\n }\n\n vector> getInverse(const vector> &coef, ostream &out = cout)\n {\n assert(coef.size() >= 1);\n assert(coef[0].size() >= 1);\n\n GaussianElimination::N = coef.size();\n GaussianElimination::M = coef[0].size();\n\n if (N != M)\n {\n out << \"Matrix not invertible : N != M (non-square)\\n\";\n return {};\n }\n\n clear();\n\n for (int i = 0; i < N; ++i)\n for (int j = 0; j < M; ++j)\n A[i + 1][j + 1] = coef[i][j];\n\n makeIdentity();\n rowEchelonForm();\n\n if (checkIfInvertible() == false)\n {\n out << \"Matrix not invertible\\n\";\n return {};\n }\n\n reducedRowEchelonForm();\n\n vector> inverse(N + 2);\n\n for (int i = 1; i <= N; ++i)\n {\n inverse[i - 1].resize(M + 1);\n\n for (int j = 1; j <= M; ++j)\n {\n inverse[i - 1][j - 1] = boost::rational_cast(B[i][j]);\n out << B[i][j] << \" \";\n }\n\n out << endl;\n }\n\n return inverse;\n }\n\n vector solveSystemEquations(const vector> &coef, const vector &bs, ostream &out = cout)\n {\n assert(coef.size() >= 1);\n assert(coef[0].size() >= 1);\n\n GaussianElimination::N = coef.size();\n GaussianElimination::M = coef[0].size();\n\n assert(static_cast(bs.size()) == GaussianElimination::N);\n\n clear();\n\n for (int i = 0; i < N; ++i)\n for (int j = 0; j < M; ++j)\n A[i + 1][j + 1] = coef[i][j];\n\n for (int i = 0; i < N; ++i)\n B[i + 1][1] = bs[i];\n\n rowEchelonForm();\n reducedRowEchelonForm();\n\n for (int i = N; i >= 1; i--)\n {\n int j = 1;\n\n while (j <= M && A[i][j] == 0)\n j++;\n\n if (j == M + 1)\n {\n if (B[i][1] != 0)\n {\n out << \"Impossible!\" << endl;\n return {};\n }\n }\n else\n {\n solutions[i] = B[i][1];\n\n for (int p = j + 1; p <= M; ++p)\n solutions[i] -= A[i][p] * solutions[p];\n }\n }\n\n vector solution(M);\n\n for (int j = 0; j < M; ++j)\n solution[j] = boost::rational_cast(solutions[j + 1]);\n\n for (int j = 1; j <= M; ++j)\n out << solutions[j] << \" \";\n\n out << endl;\n\n return solution;\n }\n}\n\nint main()\n{\n ifstream in(\"data.in\");\n\n assert(in.is_open());\n\n vector> A;\n int n, m;\n\n in >> n >> m;\n A.resize(n);\n vector bs(n);\n\n for (int i = 0; i < n; ++i)\n {\n A[i].resize(m);\n\n for (int j = 0; j < m; ++j)\n in >> A[i][j];\n\n in >> bs[i];\n }\n\n vector xs = GaussianElimination::solveSystemEquations(A, bs);\n\n return 0;\n}\n", "meta": {"hexsha": "cf439eb9d3c36d8dac0e9ccc16315f8f42f621af", "size": 6311, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "Number-Theory/Gaussian elimination (namespace).cpp", "max_stars_repo_name": "Fresher001/Competitive-Programming-2", "max_stars_repo_head_hexsha": "e1e953bb1d4ade46cc670b2d0432f68504538ed2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 86.0, "max_stars_repo_stars_event_min_datetime": "2016-10-18T23:30:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T21:57:34.000Z", "max_issues_repo_path": "Number-Theory/Gaussian elimination (namespace).cpp", "max_issues_repo_name": "Fresher001/Competitive-Programming-2", "max_issues_repo_head_hexsha": "e1e953bb1d4ade46cc670b2d0432f68504538ed2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2018-04-13T09:38:36.000Z", "max_issues_repo_issues_event_max_datetime": "2018-04-13T09:38:36.000Z", "max_forks_repo_path": "Number-Theory/Gaussian elimination (namespace).cpp", "max_forks_repo_name": "Fresher001/Competitive-Programming-2", "max_forks_repo_head_hexsha": "e1e953bb1d4ade46cc670b2d0432f68504538ed2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 39.0, "max_forks_repo_forks_event_min_datetime": "2017-03-02T07:25:40.000Z", "max_forks_repo_forks_event_max_datetime": "2020-12-14T12:13:50.000Z", "avg_line_length": 22.6200716846, "max_line_length": 116, "alphanum_fraction": 0.363175408, "num_tokens": 1755, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872046056466901, "lm_q2_score": 0.724870282120402, "lm_q1q2_score": 0.6431082527936364}} {"text": "#include \"Gaussian.h\"\n#include \n\nBaseDistributionGaussian::BaseDistributionGaussian(const Options& iOptions, const Data& iData) : BaseDistribution(iOptions, iData) {\n\n}\nfloat BaseDistributionGaussian::getCdf(float iX, const std::vector& iMoments) const {\n assert(iMoments.size() == 2);\n float mean = iMoments[0];\n float variance = iMoments[1];\n if(variance == 0) {\n return Global::MV;\n }\n boost::math::normal dist(mean, sqrt(variance));\n return boost::math::cdf(dist, iX);\n}\nfloat BaseDistributionGaussian::getPdf(float iX, const std::vector& iMoments) const {\n assert(iMoments.size() == 2);\n float mean = iMoments[0];\n float variance = iMoments[1];\n if(variance == 0) {\n return Global::MV;\n }\n boost::math::normal dist(mean, sqrt(variance));\n return boost::math::pdf(dist, iX);\n}\nfloat BaseDistributionGaussian::getInv(float iCdf, const std::vector& iMoments) const {\n assert(iMoments.size() == 2);\n float mean = iMoments[0];\n float variance = iMoments[1];\n if(variance == 0) {\n return Global::MV;\n }\n boost::math::normal dist(mean, sqrt(variance));\n return boost::math::quantile(dist, iCdf);\n\n}\nint BaseDistributionGaussian::getNumMoments() const {\n return 2;\n}\n", "meta": {"hexsha": "bff52fe8de9c1e56d00238de9e1498234f01cc33", "size": 1293, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/BaseDistributions/Gaussian.cpp", "max_stars_repo_name": "dsiuta/Comps", "max_stars_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/BaseDistributions/Gaussian.cpp", "max_issues_repo_name": "dsiuta/Comps", "max_issues_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/BaseDistributions/Gaussian.cpp", "max_forks_repo_name": "dsiuta/Comps", "max_forks_repo_head_hexsha": "2071279280d33946e975de25deedc60f1881eda0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.5365853659, "max_line_length": 132, "alphanum_fraction": 0.6782675947, "num_tokens": 366, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.8872045937171068, "lm_q2_score": 0.7248702702332475, "lm_q1q2_score": 0.6431082335998978}} {"text": "/**\n * ravg.hpp\n *\n * 2021 Gabriel A. Moreira\n *\n * gmoreira at isr.tecnico.ulisboa.pt\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\n#ifndef RAVG_HPP\n#define RAVG_HPP\n\n#include \n#include \n\n\n/**\n * Cycle Solver in SO(3).\n *\n * Closed-form cycle graph rotation averaging solver in SO(3).\n *\n * @param pairwise (input) Eigen::MatrixXd - 3 x 3n Eigen matrix with SO(3) blocks.\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 Eigen::Ref pairwise,\n int num_nodes,\n Eigen::Ref R);\n\n\n/**\n * Rotation averaging Primal-Dual method in SO(3).\n *\n * Primal-dual update method for averaging rotations in SO(3).\n *\n * @param Rtilde (input) Eigen::SparseMatrix - 3n x 3n sparse rotation adjacency matrix.\n * @param R (output) Eigen::MatrixXd - 3n x 3 solution.\n * @param A (input/output) Eigen::SparseMatrix - 3n x 3n symmetric and sparse graph adjacency matrix.\n * @param num_nodes (input) Int - number of variables.\n * @param maxiter (input) int - maxiter.\n * @param dual (output) Double - dual problem.\n * @param eta (input) Double - minimum eigenvalue stopping criterion.\n * @param sigma (input) Double - spectral shift.\n */\nvoid primalDualSO3(const Eigen::SparseMatrix& Rtilde,\n const Eigen::SparseMatrix& A,\n Eigen::Ref R,\n int num_nodes,\n int maxiter,\n double& dual,\n double eta,\n double sigma);\n\n\n#endif /* RAVG_HPP */\n", "meta": {"hexsha": "8cf2028e3442801b73f17b2b11344e545a6badd6", "size": 1886, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/ravg.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/ravg.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/ravg.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": 31.4333333333, "max_line_length": 109, "alphanum_fraction": 0.6463414634, "num_tokens": 474, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797124237605, "lm_q2_score": 0.705785040214066, "lm_q1q2_score": 0.6430970099752449}} {"text": "// MIT License\n//\n// Copyright (c) 2020 Lennart Braun\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 \"linear_algebra.h\"\n\n#include \n\n#include \n#include \n\n#include \"tensor/tensor_op.h\"\n\nnamespace MOTION {\n\ntemplate \nvoid matrix_multiply(std::size_t dim_l, std::size_t dim_m, std::size_t dim_n, const T* A,\n const T* B, T* output) {\n using MatrixType = Eigen::Matrix;\n Eigen::Map matrix_output(output, dim_l, dim_n);\n Eigen::Map matrix_A(A, dim_l, dim_m);\n Eigen::Map matrix_B(B, dim_m, dim_n);\n matrix_output = matrix_A * matrix_B;\n}\n\ntemplate \nstd::vector matrix_multiply(std::size_t dim_l, std::size_t dim_m, std::size_t dim_n,\n const std::vector& A, const std::vector& B) {\n assert(A.size() == dim_l * dim_m);\n assert(B.size() == dim_m * dim_n);\n std::vector output(dim_l * dim_n);\n matrix_multiply(dim_l, dim_m, dim_n, A.data(), B.data(), output.data());\n return output;\n}\n\ntemplate \nvoid matrix_multiply(const tensor::GemmOp& gemm_op, const T* A, const T* B, T* output) {\n using MatrixType = Eigen::Matrix;\n assert(gemm_op.verify());\n Eigen::Map matrix_output(output, gemm_op.output_shape_[0], gemm_op.output_shape_[1]);\n Eigen::Map matrix_A(A, gemm_op.input_A_shape_[0], gemm_op.input_A_shape_[1]);\n Eigen::Map matrix_B(B, gemm_op.input_B_shape_[0], gemm_op.input_B_shape_[1]);\n\n if (gemm_op.transA_ && gemm_op.transB_) {\n matrix_output = matrix_A.transpose() * matrix_B.transpose();\n } else if (gemm_op.transA_) {\n matrix_output = matrix_A.transpose() * matrix_B;\n } else if (gemm_op.transB_) {\n matrix_output = matrix_A * matrix_B.transpose();\n } else {\n matrix_output = matrix_A * matrix_B;\n }\n}\n\ntemplate void matrix_multiply(std::size_t, std::size_t, std::size_t, const std::uint8_t*,\n const std::uint8_t*, std::uint8_t*);\ntemplate void matrix_multiply(std::size_t, std::size_t, std::size_t, const std::uint16_t*,\n const std::uint16_t*, std::uint16_t*);\ntemplate void matrix_multiply(std::size_t, std::size_t, std::size_t, const std::uint32_t*,\n const std::uint32_t*, std::uint32_t*);\ntemplate void matrix_multiply(std::size_t, std::size_t, std::size_t, const std::uint64_t*,\n const std::uint64_t*, std::uint64_t*);\ntemplate std::vector matrix_multiply(std::size_t, std::size_t, std::size_t,\n const std::vector&,\n const std::vector&);\ntemplate std::vector matrix_multiply(std::size_t, std::size_t, std::size_t,\n const std::vector&,\n const std::vector&);\ntemplate std::vector matrix_multiply(std::size_t, std::size_t, std::size_t,\n const std::vector&,\n const std::vector&);\ntemplate std::vector matrix_multiply(std::size_t, std::size_t, std::size_t,\n const std::vector&,\n const std::vector&);\ntemplate std::vector<__uint128_t> matrix_multiply(std::size_t, std::size_t, std::size_t,\n const std::vector<__uint128_t>&,\n const std::vector<__uint128_t>&);\ntemplate void matrix_multiply(const tensor::GemmOp&, const std::uint8_t*, const std::uint8_t*,\n std::uint8_t*);\ntemplate void matrix_multiply(const tensor::GemmOp&, const std::uint16_t*, const std::uint16_t*,\n std::uint16_t*);\ntemplate void matrix_multiply(const tensor::GemmOp&, const std::uint32_t*, const std::uint32_t*,\n std::uint32_t*);\ntemplate void matrix_multiply(const tensor::GemmOp&, const std::uint64_t*, const std::uint64_t*,\n std::uint64_t*);\ntemplate void matrix_multiply(const tensor::GemmOp&, const __uint128_t*, const __uint128_t*,\n __uint128_t*);\n\ntemplate \nvoid convolution(const tensor::Conv2DOp& conv_op, const T* input_buffer, const T* kernel_buffer,\n T* output_buffer) {\n using TensorType3 = Eigen::Tensor;\n using CTensorType3 = Eigen::Tensor;\n using CTensorType4 = Eigen::Tensor;\n assert(conv_op.verify());\n const auto& output_shape = conv_op.output_shape_;\n const auto& input_shape = conv_op.input_shape_;\n const auto& kernel_shape = conv_op.kernel_shape_;\n\n Eigen::TensorMap input(input_buffer, input_shape[0], input_shape[1],\n input_shape[2]);\n Eigen::TensorMap kernel(kernel_buffer, kernel_shape[0], kernel_shape[1],\n kernel_shape[2], kernel_shape[3]);\n Eigen::TensorMap output(output_buffer, output_shape[0], output_shape[1],\n output_shape[2]);\n const std::array kernel_matrix_dimensions = {\n static_cast(kernel_shape[1] * kernel_shape[2] * kernel_shape[3]),\n static_cast(kernel_shape[0])};\n const std::array input_matrix_dimensions = {\n static_cast(output_shape[1] * output_shape[2]),\n static_cast(kernel_shape[1] * kernel_shape[2] * kernel_shape[3])};\n\n auto kernel_matrix =\n kernel.shuffle(std::array{3, 2, 1, 0}).reshape(kernel_matrix_dimensions);\n\n auto input_matrix =\n input.shuffle(Eigen::array{2, 1, 0})\n .extract_image_patches(kernel_shape[2], kernel_shape[3], conv_op.strides_[0],\n conv_op.strides_[1], conv_op.dilations_[0], conv_op.dilations_[1],\n 1, 1, conv_op.pads_[0], conv_op.pads_[2], conv_op.pads_[1],\n conv_op.pads_[3], 0)\n .reshape(input_matrix_dimensions);\n\n const std::array, 1> contraction_dimensions = {\n Eigen::IndexPair(1, 0)};\n auto output_matrix =\n kernel_matrix.shuffle(std::array{1, 0})\n .contract(input_matrix.shuffle(std::array{1, 0}), contraction_dimensions)\n .shuffle(std::array{1, 0});\n\n const std::array rev_output_dimensions = {\n output.dimension(2), output.dimension(1), output.dimension(0)};\n output =\n output_matrix.reshape(rev_output_dimensions).shuffle(Eigen::array{2, 1, 0});\n}\n\ntemplate \nstd::vector convolution(const tensor::Conv2DOp& conv_op, const std::vector& input_buffer,\n const std::vector& kernel_buffer) {\n assert(conv_op.verify());\n assert(input_buffer.size() == conv_op.compute_input_size());\n assert(kernel_buffer.size() == conv_op.compute_kernel_size());\n std::vector output_buffer(conv_op.compute_output_size());\n convolution(conv_op, input_buffer.data(), kernel_buffer.data(), output_buffer.data());\n return output_buffer;\n}\n\nvoid convolution(const tensor::Conv2DOp&, const std::uint8_t*, const std::uint8_t*, std::uint8_t*);\nvoid convolution(const tensor::Conv2DOp&, const std::uint16_t*, const std::uint16_t*,\n std::uint16_t*);\nvoid convolution(const tensor::Conv2DOp&, const std::uint32_t*, const std::uint32_t*,\n std::uint32_t*);\nvoid convolution(const tensor::Conv2DOp&, const std::uint64_t*, const std::uint64_t*,\n std::uint64_t*);\ntemplate std::vector convolution(const tensor::Conv2DOp&,\n const std::vector&,\n const std::vector&);\ntemplate std::vector convolution(const tensor::Conv2DOp&,\n const std::vector&,\n const std::vector&);\ntemplate std::vector convolution(const tensor::Conv2DOp&,\n const std::vector&,\n const std::vector&);\ntemplate std::vector convolution(const tensor::Conv2DOp&,\n const std::vector&,\n const std::vector&);\ntemplate std::vector<__uint128_t> convolution(const tensor::Conv2DOp&,\n const std::vector<__uint128_t>&,\n const std::vector<__uint128_t>&);\n\ntemplate \nvoid sum_pool(const tensor::AveragePoolOp& avgpool_op, const T* input, T* output) {\n assert(avgpool_op.verify());\n using TensorType3C = Eigen::Tensor;\n using TensorType3 = Eigen::Tensor;\n const auto in_channels = static_cast(avgpool_op.input_shape_[0]);\n const auto in_rows = static_cast(avgpool_op.input_shape_[1]);\n const auto in_columns = static_cast(avgpool_op.input_shape_[2]);\n const auto out_channels = static_cast(avgpool_op.output_shape_[0]);\n const auto out_rows = static_cast(avgpool_op.output_shape_[1]);\n const auto out_columns = static_cast(avgpool_op.output_shape_[2]);\n const auto kernel_rows = static_cast(avgpool_op.kernel_shape_[0]);\n const auto kernel_columns = static_cast(avgpool_op.kernel_shape_[1]);\n const auto stride_rows = static_cast(avgpool_op.strides_[0]);\n const auto stride_columns = static_cast(avgpool_op.strides_[1]);\n\n Eigen::TensorMap tensor_src(input, in_channels, in_rows, in_columns);\n Eigen::TensorMap tensor_dst(output, out_channels, out_rows, out_columns);\n\n tensor_dst = tensor_src.shuffle(Eigen::array{2, 1, 0})\n .extract_image_patches(kernel_rows, kernel_columns, stride_rows, stride_columns,\n 1, 1, 1, 1, 0, 0, 0, 0, T(0))\n .sum(Eigen::array{1, 2})\n .reshape(Eigen::array{out_columns, out_rows, out_channels})\n .shuffle(Eigen::array{2, 1, 0});\n}\n\ntemplate void sum_pool(const tensor::AveragePoolOp&, const std::uint8_t*, std::uint8_t*);\ntemplate void sum_pool(const tensor::AveragePoolOp&, const std::uint16_t*, std::uint16_t*);\ntemplate void sum_pool(const tensor::AveragePoolOp&, const std::uint32_t*, std::uint32_t*);\ntemplate void sum_pool(const tensor::AveragePoolOp&, const std::uint64_t*, std::uint64_t*);\ntemplate void sum_pool(const tensor::AveragePoolOp&, const __uint128_t*, __uint128_t*);\n\n} // namespace MOTION\n", "meta": {"hexsha": "a1563aafabd8e35ef9f3ca510d90fece6389e2c7", "size": 12659, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/motioncore/utility/linear_algebra.cpp", "max_stars_repo_name": "Udbhavbisarya23/MOTION2NX", "max_stars_repo_head_hexsha": "eb26f639d8c1729cebfa85dd3bf41b770cebe92b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6.0, "max_stars_repo_stars_event_min_datetime": "2021-11-05T00:39:47.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-26T16:42:55.000Z", "max_issues_repo_path": "src/motioncore/utility/linear_algebra.cpp", "max_issues_repo_name": "Udbhavbisarya23/MOTION2NX", "max_issues_repo_head_hexsha": "eb26f639d8c1729cebfa85dd3bf41b770cebe92b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 7.0, "max_issues_repo_issues_event_min_datetime": "2021-11-07T06:53:00.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-23T11:46:40.000Z", "max_forks_repo_path": "src/motioncore/utility/linear_algebra.cpp", "max_forks_repo_name": "Udbhavbisarya23/MOTION2NX", "max_forks_repo_head_hexsha": "eb26f639d8c1729cebfa85dd3bf41b770cebe92b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7.0, "max_forks_repo_forks_event_min_datetime": "2021-11-04T12:01:07.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T12:15:23.000Z", "avg_line_length": 56.7668161435, "max_line_length": 100, "alphanum_fraction": 0.6376491034, "num_tokens": 3090, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797148356995, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6430969947609735}} {"text": "#include \n#include \n#include \n#include \n\n// Computes the energy terms into costs. The first part contains termes related to edge length variation,\n// and the second to angle variations.\ntemplate\nvoid ikLikeCosts(const Eigen::Matrix& curve, const Eigen::VectorXd& targetAngles, const Eigen::VectorXd& targetLengths, double beta,\n Eigen::Matrix& costs)\n{\n using namespace Eigen;\n using std::atan2;\n\n typedef Matrix Vec2;\n int nb = curve.size()/2;\n\n costs.setZero();\n for(int k=1;k(2*(k-1));\n Vec2 pk = curve.template segment<2>(2*k);\n Vec2 pk1 = curve.template segment<2>(2*(k+1));\n\n if(k+1\nstruct Functor\n{\n typedef _Scalar Scalar;\n enum {\n InputsAtCompileTime = Eigen::Dynamic,\n ValuesAtCompileTime = Eigen::Dynamic\n };\n typedef Eigen::Matrix InputType;\n typedef Eigen::Matrix ValueType;\n typedef Eigen::Matrix JacobianType;\n\n const int m_inputs, m_values;\n\n Functor() : m_inputs(InputsAtCompileTime), m_values(ValuesAtCompileTime) {}\n Functor(int inputs, int values) : m_inputs(inputs), m_values(values) {}\n\n int inputs() const { return m_inputs; } // number of degree of freedom (= 2*nb_vertices)\n int values() const { return m_values; } // number of energy terms (= nb_vertices + nb_edges)\n\n // you should define that in the subclass :\n // void operator() (const InputType& x, ValueType* v, JacobianType* _j=0) const;\n};\n\n// Specialized functor warping the ikLikeCosts function\nstruct iklike_functor : Functor\n{\n typedef Eigen::AutoDiffScalar > ADS;\n typedef Eigen::Matrix VectorXad;\n\n // pfirst and plast are the two extremities of the curve\n iklike_functor(const Eigen::VectorXd& targetAngles, const Eigen::VectorXd& targetLengths, double beta, const Eigen::Vector2d pfirst, const Eigen::Vector2d plast)\n : Functor(targetAngles.size()*2-4,targetAngles.size()*2-1),\n m_targetAngles(targetAngles), m_targetLengths(targetLengths), m_beta(beta),\n m_pfirst(pfirst), m_plast(plast)\n {}\n\n // input = x = { ..., x_i, y_i, ....}\n // output = fvec = the value of each term\n int operator()(const Eigen::VectorXd &x, Eigen::VectorXd &fvec)\n {\n using namespace Eigen;\n VectorXd curves(this->inputs()+8);\n\n curves.segment(4,this->inputs()) = x;\n\n Vector2d d(1,0);\n curves.segment<2>(0) = m_pfirst - d;\n curves.segment<2>(2) = m_pfirst;\n curves.segment<2>(this->inputs()+4) = m_plast;\n curves.segment<2>(this->inputs()+6) = m_plast + d;\n\n ikLikeCosts(curves, m_targetAngles, m_targetLengths, m_beta, fvec);\n return 0;\n }\n\n // Compute the jacobian into fjac for the current solution x\n int df(const Eigen::VectorXd &x, Eigen::MatrixXd &fjac)\n {\n using namespace Eigen;\n VectorXad curves(this->inputs()+8);\n\n // Compute the derivatives of each degree of freedom\n // -> grad( x_i ) = (0, ..., 0, 1, 0, ..., 0) ; 1 is in position i\n for(int i=0; iinputs();++i)\n curves(4+i) = ADS(x(i), this->inputs(), i);\n\n Vector2d d(1,0);\n curves.segment<2>(0) = (m_pfirst - d).cast();\n curves.segment<2>(2) = (m_pfirst).cast();\n curves.segment<2>(this->inputs()+4) = (m_plast).cast();\n curves.segment<2>(this->inputs()+6) = (m_plast + d).cast();\n\n VectorXad v(this->values());\n\n ikLikeCosts(curves, m_targetAngles, m_targetLengths, m_beta, v);\n\n // copy the gradient of each energy term into the Jacobian\n for(int i=0; ivalues();++i)\n fjac.row(i) = v(i).derivatives();\n\n return 0;\n }\n\n const Eigen::VectorXd& m_targetAngles;\n const Eigen::VectorXd& m_targetLengths;\n double m_beta;\n Eigen::Vector2d m_pfirst, m_plast;\n};\n\n\n\nvoid draw_vecX(const Eigen::VectorXd& res)\n{\n for( int i = 0; i < (res.size()/2) ; i++ )\n {\n std::cout << res.segment<2>(2*i).transpose() << \"\\n\";\n }\n}\n\n\nusing namespace Eigen;\n\nint main()\n{\n Eigen::Vector2d pfirst(-5., 0.);\n Eigen::Vector2d plast ( 5., 0.);\n\n // rest pose is a straight line starting between first and last point\n const int nb_points = 30;\n Eigen::VectorXd targetAngles (nb_points);\n targetAngles.fill(0);\n\n Eigen::VectorXd targetLengths(nb_points-1);\n double val = (pfirst-plast).norm() / (double)(nb_points-1);\n targetLengths.fill(val);\n\n\n // get initial solution\n Eigen::VectorXd x((nb_points-2)*2);\n for(int i = 1; i < (nb_points - 1); i++)\n {\n double s = (double)i / (double)(nb_points-1);\n x.segment<2>((i-1)*2) = plast * s + pfirst * (1. - s);\n }\n\n // move last point\n plast = Eigen::Vector2d(4., 1.);\n\n // Create the functor object\n iklike_functor func(targetAngles, targetLengths, 0.1, pfirst, plast);\n\n // construct the solver\n Eigen::LevenbergMarquardt lm(func);\n\n // adjust tolerance\n lm.parameters.ftol *= 1e-2;\n lm.parameters.xtol *= 1e-2;\n lm.parameters.maxfev = 2000;\n\n\n int a = lm.minimize(x);\n std::cerr << \"info = \" << a << \" \" << lm.nfev << \" \" << lm.njev << \" \" << \"\\n\";\n\n std::cout << pfirst.transpose() << \"\\n\";\n draw_vecX( x);\n std::cout << plast.transpose() << \"\\n\";\n}", "meta": {"hexsha": "7fe6ec4a499f22f20c75d0031b7ec8aba478f9f1", "size": 6153, "ext": "cpp", "lang": "C++", "max_stars_repo_path": "src/model/tools/solver/src/exampleDiff.cpp", "max_stars_repo_name": "chukhanhhoang/SorotokiCode", "max_stars_repo_head_hexsha": "e8c3c76c6768db1fcf9fce5235863b0ce3c6e6f8", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 12.0, "max_stars_repo_stars_event_min_datetime": "2020-01-29T11:56:32.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T08:21:59.000Z", "max_issues_repo_path": "src/model/tools/solver/src/exampleDiff.cpp", "max_issues_repo_name": "chukhanhhoang/SorotokiCode", "max_issues_repo_head_hexsha": "e8c3c76c6768db1fcf9fce5235863b0ce3c6e6f8", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1.0, "max_issues_repo_issues_event_min_datetime": "2022-01-02T09:09:17.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-02T09:09:17.000Z", "max_forks_repo_path": "src/model/tools/solver/src/exampleDiff.cpp", "max_forks_repo_name": "chukhanhhoang/SorotokiCode", "max_forks_repo_head_hexsha": "e8c3c76c6768db1fcf9fce5235863b0ce3c6e6f8", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3.0, "max_forks_repo_forks_event_min_datetime": "2022-01-10T11:40:10.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-15T09:38:17.000Z", "avg_line_length": 33.2594594595, "max_line_length": 165, "alphanum_fraction": 0.6078335771, "num_tokens": 1743, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797100118214, "lm_q2_score": 0.7057850216484838, "lm_q1q2_score": 0.6430969913563526}} {"text": "#ifndef TRIUMF_NMR_HEBEL_SLICHTER_HPP\n#define TRIUMF_NMR_HEBEL_SLICHTER_HPP\n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n// TRIUMF: Canada's particle accelerator centre\nnamespace triumf {\n\n// Nuclear Magnetic Resonance (NMR)\nnamespace nmr {\n\n// Hebel-Slichter\nnamespace hebel_slichter {\n\ntemplate \nT integrand(T energy, T temperature, T critical_temperature, T gap_meV, T alpha,\n T Gamma) {\n // alias some values\n T Delta = triumf::superconductivity::bcs::gap(\n temperature, critical_temperature, gap_meV);\n constexpr T E_0 = 0.0;\n constexpr T E_F = 0.0;\n //\n T E = energy;\n T E_p = E + alpha * gap_meV;\n\n // calculate the Fermi factors\n // Note: 1e-3 used to convert energyies from meV to eV\n T f_E = triumf::statistical_mechanics::fermi_dirac::distribution(\n temperature, E * 1e-3, E_0, E_F);\n T f_E_p = triumf::statistical_mechanics::fermi_dirac::distribution(\n temperature, E_p * 1e-3, E_0, E_F);\n\n //\n return (triumf::superconductivity::dynes::N(E, Gamma * gap_meV, Delta) *\n triumf::superconductivity::dynes::N(E_p, Gamma * gap_meV, Delta) +\n triumf::superconductivity::dynes::M(E, Gamma * gap_meV, Delta) *\n triumf::superconductivity::dynes::M(E_p, Gamma * gap_meV,\n Delta)) *\n f_E * (1.0 - f_E_p);\n}\n\n// ratio of SLR rates in the superconducting and normal states\ntemplate \nT slr_ratio(T temperature, T critical_temperature, T gap_meV, T alpha,\n T Gamma) {\n // define some convenience values\n T reduced_temperature = temperature / critical_temperature;\n constexpr T k_B =\n 1e3 *\n triumf::constants::codata_2018::Boltzmann_constant_in_eV_K::value();\n T beta = 1.0 / (k_B * temperature);\n // return limiting values...\n // if (temperature >= critical_temperature) {\n // return 1.0;\n // } else if (temperature <= 0.0) {\n // return 0.0;\n if (temperature <= 0.0) {\n return 0.0;\n // ...before attempting to evaluate the intergral!\n } else {\n // define the integrand\n auto hs_integrand = [&](T E) -> T {\n return integrand(E, temperature, critical_temperature, gap_meV, alpha,\n Gamma);\n };\n // setup values for numeric integration\n // const T tolerance = std::numeric_limits::epsilon();\n // const T tolerance = std::pow(std::numeric_limits::epsilon(), 2.0\n // / 3.0);\n const T tolerance = std::sqrt(std::numeric_limits::epsilon());\n\n const std::size_t max_refinements = 15;\n static boost::math::quadrature::exp_sinh hs_integrator(max_refinements);\n return 2.0 * beta *\n hs_integrator.integrate(hs_integrand, tolerance, nullptr, nullptr,\n nullptr);\n /*\n const unsigned max_depth = 15;\n return 2.0 * beta *\n boost::math::quadrature::gauss_kronrod::integrate(\n hs_integrand, 0.0, std::numeric_limits::infinity(), max_depth,\n tolerance, nullptr, nullptr);\n */\n }\n}\n\n} // namespace hebel_slichter\n\n} // namespace nmr\n\n} // namespace triumf\n\n#endif // TRIUMF_NMR_HEBEL_SLICHTER_HPP\n", "meta": {"hexsha": "5b8e2f17b298a30e3a9f1ec2b7bdc151cf26f29c", "size": 3466, "ext": "hpp", "lang": "C++", "max_stars_repo_path": "include/triumf/nmr/hebel_slichter.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/hebel_slichter.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/hebel_slichter.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.3269230769, "max_line_length": 80, "alphanum_fraction": 0.6532025389, "num_tokens": 988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.9111797075998823, "lm_q2_score": 0.7057850154599563, "lm_q1q2_score": 0.6430969840151814}} {"text": "//\n// Project: Delaunay\n// File: Delaunay.hpp\n//\n// Copyright (c) 2021 Miika 'Lehdari' Lehtimäki\n// You may use, distribute and modify this code under the terms\n// of the licence specified in file LICENSE which is distributed\n// with this source code package.\n//\n\n#ifndef DELAUNAY_DELAUNAY_HPP\n#define DELAUNAY_DELAUNAY_HPP\n\n\n#include \n#include \n\n\n#define DELAUNAY_BACKEND_EIGEN 1\n//#define DELAUNAY_BACKEND_OTHER 2 // add more enumerations for more supported backends\n\n// definitions for Eigen backend\n#if DELAUNAY_BACKEND == DELAUNAY_BACKEND_EIGEN\n #include \n\n #define DELAUNAY_VEC Eigen::Matrix\n #define DELAUNAY_VEC_ACCESS(V, D) V(D)\n #define DELAUNAY_DETERMINANT\n#endif\n\n// Check for macro definitions\n#ifndef DELAUNAY_VEC\n #error \"DELAUNAY_VEC not defined\"\n#endif\n#ifndef DELAUNAY_VEC_ACCESS\n #error \"DELAUNAY_VEC_ACCESS not defined\"\n#endif\n#ifndef DELAUNAY_DETERMINANT\n #error \"DELAUNAY_DETERMINANT not defined\"\n#endif\n\n#ifdef DELAUNAY_INLINE\n #error \"DELAUNAY_INLINE already defined\"\n#endif\n#define DELAUNAY_INLINE inline __attribute__((always_inline))\n\n\nnamespace delaunay {\n\nnamespace {\n\nstruct Triangle {\n int neighbours[3]; // indices of neighbouring triangles\n int vertices[3]; // indices of corner vertices\n\n Triangle(int t1, int t2, int t3, int v1, int v2, int v3) :\n neighbours {t1, t2, t3},\n vertices {v1, v2, v3}\n {}\n};\n\ntemplate \nDELAUNAY_INLINE bool ccw(\n const DELAUNAY_VEC& a,\n const DELAUNAY_VEC& b,\n const DELAUNAY_VEC& c)\n{\n#if DELAUNAY_BACKEND == DELAUNAY_BACKEND_EIGEN\n Eigen::Matrix m;\n m <<\n a.transpose(), 1.0,\n b.transpose(), 1.0,\n c.transpose(), 1.0;\n return m.determinant() > 0.0;\n#else\n return DELAUNAY_DETERMINANT(\n DELAUNAY_VEC_ACCESS(a,0), DELAUNAY_VEC_ACCESS(a,1), (T_Scalar)1.0,\n DELAUNAY_VEC_ACCESS(b,0), DELAUNAY_VEC_ACCESS(b,1), (T_Scalar)1.0,\n DELAUNAY_VEC_ACCESS(c,0), DELAUNAY_VEC_ACCESS(c,1), (T_Scalar)1.0) > 0.0;\n#endif\n}\n\n// is d inside of circumcircle of abc?\ntemplate \nDELAUNAY_INLINE bool inCircle(\n const DELAUNAY_VEC& a,\n const DELAUNAY_VEC& b,\n const DELAUNAY_VEC& c,\n const DELAUNAY_VEC& d)\n{\n T_Scalar dx2 = DELAUNAY_VEC_ACCESS(d,0)*DELAUNAY_VEC_ACCESS(d,0);\n T_Scalar dy2 = DELAUNAY_VEC_ACCESS(d,1)*DELAUNAY_VEC_ACCESS(d,1);\n#if DELAUNAY_BACKEND == DELAUNAY_BACKEND_EIGEN\n Eigen::Matrix m;\n m <<\n DELAUNAY_VEC_ACCESS(a,0)-DELAUNAY_VEC_ACCESS(d,0),\n DELAUNAY_VEC_ACCESS(a,1)-DELAUNAY_VEC_ACCESS(d,1),\n (DELAUNAY_VEC_ACCESS(a,0)*DELAUNAY_VEC_ACCESS(a,0)-dx2)+(DELAUNAY_VEC_ACCESS(a,1)*DELAUNAY_VEC_ACCESS(a,1)-dy2),\n DELAUNAY_VEC_ACCESS(b,0)-DELAUNAY_VEC_ACCESS(d,0),\n DELAUNAY_VEC_ACCESS(b,1)-DELAUNAY_VEC_ACCESS(d,1),\n (DELAUNAY_VEC_ACCESS(b,0)*DELAUNAY_VEC_ACCESS(b,0)-dx2)+(DELAUNAY_VEC_ACCESS(b,1)*DELAUNAY_VEC_ACCESS(b,1)-dy2),\n DELAUNAY_VEC_ACCESS(c,0)-DELAUNAY_VEC_ACCESS(d,0),\n DELAUNAY_VEC_ACCESS(c,1)-DELAUNAY_VEC_ACCESS(d,1),\n (DELAUNAY_VEC_ACCESS(c,0)*DELAUNAY_VEC_ACCESS(c,0)-dx2)+(DELAUNAY_VEC_ACCESS(c,1)*DELAUNAY_VEC_ACCESS(c,1)-dy2);\n return m.determinant() > 0.0;\n#else\n return DELAUNAY_DETERMINANT(\n DELAUNAY_VEC_ACCESS(a,0)-DELAUNAY_VEC_ACCESS(d,0),\n DELAUNAY_VEC_ACCESS(a,1)-DELAUNAY_VEC_ACCESS(d,1),\n (DELAUNAY_VEC_ACCESS(a,0)*DELAUNAY_VEC_ACCESS(a,0)-dx2)+(DELAUNAY_VEC_ACCESS(a,1)*DELAUNAY_VEC_ACCESS(a,1)-dy2),\n DELAUNAY_VEC_ACCESS(b,0)-DELAUNAY_VEC_ACCESS(d,0),\n DELAUNAY_VEC_ACCESS(b,1)-DELAUNAY_VEC_ACCESS(d,1),\n (DELAUNAY_VEC_ACCESS(b,0)*DELAUNAY_VEC_ACCESS(b,0)-dx2)+(DELAUNAY_VEC_ACCESS(b,1)*DELAUNAY_VEC_ACCESS(b,1)-dy2),\n DELAUNAY_VEC_ACCESS(c,0)-DELAUNAY_VEC_ACCESS(d,0),\n DELAUNAY_VEC_ACCESS(c,1)-DELAUNAY_VEC_ACCESS(d,1),\n (DELAUNAY_VEC_ACCESS(c,0)*DELAUNAY_VEC_ACCESS(c,0)-dx2)+(DELAUNAY_VEC_ACCESS(c,1)*DELAUNAY_VEC_ACCESS(c,1)-dy2))\n > 0.0;\n#endif\n}\n\n// initial primitive construction functions for edges and triangles\ntemplate